input_text
stringlengths
115
13.8k
output_text
stringlengths
24
15k
metadata
dict
Please answer the following Stack Overflow question: Title: Call child method from parent <p>I have two components:</p> <ol> <li>Parent component</li> <li>Child component</li> </ol> <p>I was trying to call Child's method from Parent, I tried this way but couldn't get a result:</p> <pre><code>class Parent extends Component { render() { return ( &lt;Child&gt; &lt;button onClick={Child.getAlert()}&gt;Click&lt;/button&gt; &lt;/Child&gt; ); } } class Child extends Component { getAlert() { alert('clicked'); } render() { return ( &lt;h1 ref=&quot;hello&quot;&gt;Hello&lt;/h1&gt; ); } } </code></pre> <p>Is there a way to call Child's method from Parent?</p> <p>Note: Child and Parent components are in two different files.</p>
<p>First off, let me express that this is generally <em>not</em> the way to go about things in React land. Usually what you want to do is pass down functionality to children in props, and pass up notifications from children in events (or better yet: <a href="https://reactjs.org/docs/hooks-reference.html#usereducer" rel="noreferrer"><code>dispatch</code></a>).</p> <p>But if you <em>must</em> expose an imperative method on a child component, you can use <a href="https://reactjs.org/docs/refs-and-the-dom.html" rel="noreferrer">refs</a>. Remember this is an escape hatch and usually indicates a better design is available.</p> <blockquote> <p>Previously, refs were only supported for Class-based components. With the advent of <a href="https://reactjs.org/docs/hooks-intro.html" rel="noreferrer">React Hooks</a>, that's no longer the case</p> </blockquote> <h2>Modern React with Hooks (<code>v16.8+</code>)</h2> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const { forwardRef, useRef, useImperativeHandle } = React; // We need to wrap component in `forwardRef` in order to gain // access to the ref object that is assigned using the `ref` prop. // This ref is passed as the second parameter to the function component. const Child = forwardRef((props, ref) =&gt; { // The component instance will be extended // with whatever you return from the callback passed // as the second argument useImperativeHandle(ref, () =&gt; ({ getAlert() { alert("getAlert from Child"); } })); return &lt;h1&gt;Hi&lt;/h1&gt;; }); const Parent = () =&gt; { // In order to gain access to the child component instance, // you need to assign it to a `ref`, so we call `useRef()` to get one const childRef = useRef(); return ( &lt;div&gt; &lt;Child ref={childRef} /&gt; &lt;button onClick={() =&gt; childRef.current.getAlert()}&gt;Click&lt;/button&gt; &lt;/div&gt; ); }; ReactDOM.render( &lt;Parent /&gt;, document.getElementById('root') );</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin&gt;&lt;/script&gt; &lt;script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin&gt;&lt;/script&gt; &lt;div id="root"&gt;&lt;/div&gt;</code></pre> </div> </div> </p> <p>Documentation for <code>useImperativeHandle()</code> is <a href="https://reactjs.org/docs/hooks-reference.html#useimperativehandle" rel="noreferrer">here</a>:</p> <blockquote> <p><code>useImperativeHandle</code> customizes the instance value that is exposed to parent components when using <code>ref</code>.</p> </blockquote> <h2>Legacy API using Class Components (<code>&gt;= [email protected]</code>)</h2> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const { Component } = React; class Parent extends Component { constructor(props) { super(props); this.child = React.createRef(); } onClick = () =&gt; { this.child.current.getAlert(); }; render() { return ( &lt;div&gt; &lt;Child ref={this.child} /&gt; &lt;button onClick={this.onClick}&gt;Click&lt;/button&gt; &lt;/div&gt; ); } } class Child extends Component { getAlert() { alert('getAlert from Child'); } render() { return &lt;h1&gt;Hello&lt;/h1&gt;; } } ReactDOM.render(&lt;Parent /&gt;, document.getElementById('root'));</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin&gt;&lt;/script&gt; &lt;script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin&gt;&lt;/script&gt; &lt;div id="root"&gt;&lt;/div&gt;</code></pre> </div> </div> </p> <h2>Callback Ref API</h2> <p>Callback-style refs are another approach to achieving this, although not quite as common in modern React:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const { Component } = React; const { render } = ReactDOM; class Parent extends Component { render() { return ( &lt;div&gt; &lt;Child ref={instance =&gt; { this.child = instance; }} /&gt; &lt;button onClick={() =&gt; { this.child.getAlert(); }}&gt;Click&lt;/button&gt; &lt;/div&gt; ); } } class Child extends Component { getAlert() { alert('clicked'); } render() { return ( &lt;h1&gt;Hello&lt;/h1&gt; ); } } render( &lt;Parent /&gt;, document.getElementById('app') );</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"&gt;&lt;/script&gt; &lt;div id="app"&gt;&lt;/div&gt;</code></pre> </div> </div> </p>
{ "question_id": 37949981, "question_date": "2016-06-21T16:34:48.777Z", "question_score": 852, "tags": "javascript|reactjs", "answer_id": 37950970, "answer_date": "2016-06-21T17:34:34.893Z", "answer_score": 1246 }
Please answer the following Stack Overflow question: Title: Does JavaScript guarantee object property order? <p>If I create an object like this:</p> <pre><code>var obj = {}; obj.prop1 = "Foo"; obj.prop2 = "Bar"; </code></pre> <p>Will the resulting object <em>always</em> look like this?</p> <pre><code>{ prop1 : "Foo", prop2 : "Bar" } </code></pre> <p>That is, will the properties be in the same order that I added them?</p>
<p>The iteration order for objects follows <a href="https://stackoverflow.com/a/38218582/292500">a certain set of rules</a> since ES2015, but <strong>it does not (always) follow the insertion order</strong>. Simply put, the iteration order is a combination of the insertion order for strings keys, and ascending order for number-like keys:</p> <pre><code>// key order: 1, foo, bar const obj = { &quot;foo&quot;: &quot;foo&quot;, &quot;1&quot;: &quot;1&quot;, &quot;bar&quot;: &quot;bar&quot; } </code></pre> <p>Using an array or a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map" rel="noreferrer"><code>Map</code> object</a> can be a better way to achieve this. <code>Map</code> shares some similarities with <code>Object</code> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Objects_and_maps_compared" rel="noreferrer">guarantees the keys to be iterated in order of insertion</a>, without exception:</p> <blockquote> <p>The keys in Map are ordered while keys added to object are not. Thus, when iterating over it, a Map object returns keys in order of insertion. (Note that in the ECMAScript 2015 spec objects do preserve creation order for string and Symbol keys, so traversal of an object with ie only string keys would yield keys in order of insertion)</p> </blockquote> <p>As a note, properties order in objects weren’t guaranteed at all before ES2015. Definition of an Object from <a href="http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%203rd%20edition,%20December%201999.pdf" rel="noreferrer">ECMAScript Third Edition (pdf)</a>:</p> <blockquote> <h3>4.3.3 Object</h3> <p>An object is a member of the type Object. <strong>It is an unordered collection of properties</strong> each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method.</p> </blockquote>
{ "question_id": 5525795, "question_date": "2011-04-02T20:54:12.467Z", "question_score": 851, "tags": "javascript|object", "answer_id": 5525820, "answer_date": "2011-04-02T20:56:53.343Z", "answer_score": 655 }
Please answer the following Stack Overflow question: Title: What is the simplest and most robust way to get the user's current location on Android? <p>The <code>LocationManager</code> API on Android seems like it's a bit of a pain to use for an application that only needs an occasional and rough approximation of the user's location.</p> <p>The app I'm working on isn't really a location app per se, but it does need to get the user's location in order to display a list of nearby businesses. It doesn't need to worry about if the user is moving around or anything like that.</p> <p>Here's what I'd like to do:</p> <ol> <li>Show the user a list of nearby locations.</li> <li>Preload the user's location so that by the time I need it in <code>Activity</code> X, it will be available.</li> <li>I don't particularly care about accuracy or frequency of update. Just grabbing one location is sufficient as long as it's not way off. Maybe if I want to be fancy I'll update the location once every few mins or so, but it's not a huge priority.</li> <li>Work for any device as long as it has either a GPS or a Network Location provider.</li> </ol> <p>It seems like it shouldn't be that hard, but it appears to me that I have to spin up two different location providers (GPS and NETWORK) and manage each's lifecycle. Not only that, but I have to duplicate the same code in multiple activities to satisfy #2. I've tried using <code>getBestProvider()</code> in the past to cut the solution down to just using one location provider, but that seems to only give you the best "theoretical" provider rather than the provider that's actually going to give you the best results.</p> <p>Is there a simpler way to accomplish this?</p>
<p>Here's what I do:</p> <ol> <li>First of all I check what providers are enabled. Some may be disabled on the device, some may be disabled in application manifest.</li> <li>If any provider is available I start location listeners and timeout timer. It's 20 seconds in my example, may not be enough for GPS so you can enlarge it.</li> <li>If I get update from location listener I use the provided value. I stop listeners and timer.</li> <li>If I don't get any updates and timer elapses I have to use last known values.</li> <li>I grab last known values from available providers and choose the most recent of them.</li> </ol> <p>Here's how I use my class:</p> <pre><code>LocationResult locationResult = new LocationResult(){ @Override public void gotLocation(Location location){ //Got the location! } }; MyLocation myLocation = new MyLocation(); myLocation.getLocation(this, locationResult); </code></pre> <p>And here's MyLocation class:</p> <pre><code>import java.util.Timer; import java.util.TimerTask; import android.content.Context; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; public class MyLocation { Timer timer1; LocationManager lm; LocationResult locationResult; boolean gps_enabled=false; boolean network_enabled=false; public boolean getLocation(Context context, LocationResult result) { //I use LocationResult callback class to pass location value from MyLocation to user code. locationResult=result; if(lm==null) lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); //exceptions will be thrown if provider is not permitted. try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){} try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){} //don't start listeners if no provider is enabled if(!gps_enabled &amp;&amp; !network_enabled) return false; if(gps_enabled) lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps); if(network_enabled) lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork); timer1=new Timer(); timer1.schedule(new GetLastLocation(), 20000); return true; } LocationListener locationListenerGps = new LocationListener() { public void onLocationChanged(Location location) { timer1.cancel(); locationResult.gotLocation(location); lm.removeUpdates(this); lm.removeUpdates(locationListenerNetwork); } public void onProviderDisabled(String provider) {} public void onProviderEnabled(String provider) {} public void onStatusChanged(String provider, int status, Bundle extras) {} }; LocationListener locationListenerNetwork = new LocationListener() { public void onLocationChanged(Location location) { timer1.cancel(); locationResult.gotLocation(location); lm.removeUpdates(this); lm.removeUpdates(locationListenerGps); } public void onProviderDisabled(String provider) {} public void onProviderEnabled(String provider) {} public void onStatusChanged(String provider, int status, Bundle extras) {} }; class GetLastLocation extends TimerTask { @Override public void run() { lm.removeUpdates(locationListenerGps); lm.removeUpdates(locationListenerNetwork); Location net_loc=null, gps_loc=null; if(gps_enabled) gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); if(network_enabled) net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); //if there are both values use the latest one if(gps_loc!=null &amp;&amp; net_loc!=null){ if(gps_loc.getTime()&gt;net_loc.getTime()) locationResult.gotLocation(gps_loc); else locationResult.gotLocation(net_loc); return; } if(gps_loc!=null){ locationResult.gotLocation(gps_loc); return; } if(net_loc!=null){ locationResult.gotLocation(net_loc); return; } locationResult.gotLocation(null); } } public static abstract class LocationResult{ public abstract void gotLocation(Location location); } } </code></pre> <p>Somebody may also want to modify my logic. For example if you get update from Network provider don't stop listeners but continue waiting. GPS gives more accurate data so it's worth waiting for it. If timer elapses and you've got update from Network but not from GPS then you can use value provided from Network.</p> <p>One more approach is to use LocationClient <a href="http://developer.android.com/training/location/retrieve-current.html" rel="noreferrer">http://developer.android.com/training/location/retrieve-current.html</a>. But it requires Google Play Services apk to be installed on user device.</p>
{ "question_id": 3145089, "question_date": "2010-06-29T21:59:25.793Z", "question_score": 851, "tags": "android|geolocation|location|latitude-longitude", "answer_id": 3145655, "answer_date": "2010-06-30T00:07:51.663Z", "answer_score": 968 }
Please answer the following Stack Overflow question: Title: Xcode 7 error: "Missing iOS Distribution signing identity for ..." <p>I tried to upload my App to iTunes Connect resp. AppStore and got the following error:</p> <blockquote> <p>Failed to locate or generate matching signing assets</p> <p>Xcode attempted to locate or generate matching signing assets and failed to do so because of the following issues.</p> </blockquote> <blockquote> <p>Missing iOS Distribution signing identity for ... Xcode can request one for you. </p> </blockquote> <p>Before I set up a new development machine, exported the developer accounts via Xcode 7 from the old to the new machine.</p> <p>What can I do to fix this?</p>
<p><a href="https://developer.apple.com/support/certificates/expiration/">From Apple</a> - </p> <blockquote> <p>Thanks for bringing this to the attention of the community and apologies for the issues you’ve been having. This issue stems from having a copy of the expired WWDR Intermediate certificate in both your System and Login keychains. To resolve the issue, you should first download and install the new <a href="https://developer.apple.com/certificationauthority/AppleWWDRCA.cer">WWDR intermediate certificate</a> (by double-clicking on the file). Next, in the Keychain Access application, select the System keychain. Make sure to select “Show Expired Certificates” in the View menu and then delete the expired version of the Apple Worldwide Developer Relations Certificate Authority Intermediate certificate (expired on February 14, 2016). Your certificates should now appear as valid in Keychain Access and be available to Xcode for submissions to the App Store.</p> </blockquote> <p>As noted in a comment below, the expired certificate also needs to be removed from the <code>login</code> section, as well:</p> <blockquote> <p>To all that cannot get it working despite the instructions... There are two expired WWDR certs. One is in login keychain, and the other one is in the System. You have to delete both of them in order to make things working</p> </blockquote>
{ "question_id": 32821189, "question_date": "2015-09-28T10:50:34.793Z", "question_score": 851, "tags": "ios|xcode|app-store-connect|code-signing|testflight", "answer_id": 35401483, "answer_date": "2016-02-15T04:26:39.227Z", "answer_score": 1953 }
Please answer the following Stack Overflow question: Title: How do I concatenate strings and variables in PowerShell? <p>Suppose I have the following snippet:</p> <pre class="lang-powershell prettyprint-override"><code>$assoc = New-Object PSObject -Property @{ Id = 42 Name = &quot;Slim Shady&quot; Owner = &quot;Eminem&quot; } Write-Host $assoc.Id + &quot; - &quot; + $assoc.Name + &quot; - &quot; + $assoc.Owner </code></pre> <p>I'd expect this snippet to show:</p> <blockquote> <p><code>42 - Slim Shady - Eminem</code></p> </blockquote> <p>But instead it shows:</p> <blockquote> <p><code>42 + - + Slim Shady + - + Eminem</code></p> </blockquote> <p>Which makes me think the <code>+</code> operator isn't appropriate for concatenating strings and variables.</p> <p>How should you approach this with PowerShell?</p>
<pre><code>Write-Host "$($assoc.Id) - $($assoc.Name) - $($assoc.Owner)" </code></pre> <p>See the <a href="https://www.microsoft.com/en-us/download/details.aspx?id=36389">Windows PowerShell Language Specification Version 3.0</a>, p34, sub-expressions expansion.</p>
{ "question_id": 15113413, "question_date": "2013-02-27T13:34:02.987Z", "question_score": 849, "tags": "powershell|string-concatenation", "answer_id": 15113467, "answer_date": "2013-02-27T13:37:03.240Z", "answer_score": 919 }
Please answer the following Stack Overflow question: Title: C# loop - break vs. continue <p>In a C# (feel free to answer for other languages) loop, what's the difference between <code>break</code> and <code>continue</code> as a means to leave the structure of the loop, and go to the next iteration?</p> <p>Example:</p> <pre><code>foreach (DataRow row in myTable.Rows) { if (someConditionEvalsToTrue) { break; //what's the difference between this and continue ? //continue; } } </code></pre>
<p><code>break</code> will exit the loop completely, <code>continue</code> will just <strong>skip</strong> the current iteration.</p> <p>For example:</p> <pre><code>for (int i = 0; i &lt; 10; i++) { if (i == 0) { break; } DoSomeThingWith(i); } </code></pre> <p>The break will cause the loop to exit on the first iteration - <code>DoSomeThingWith</code> will never be executed. This here:</p> <pre><code>for (int i = 0; i &lt; 10; i++) { if(i == 0) { continue; } DoSomeThingWith(i); } </code></pre> <p>Will not execute <code>DoSomeThingWith</code> for <code>i = 0</code>, but the loop will <strong>continue</strong> and <code>DoSomeThingWith</code> will be executed for <code>i = 1</code> to <code>i = 9</code>.</p>
{ "question_id": 6414, "question_date": "2008-08-08T21:49:01.127Z", "question_score": 849, "tags": "c#|loops|enumeration", "answer_id": 6417, "answer_date": "2008-08-08T21:51:35.397Z", "answer_score": 1578 }
Please answer the following Stack Overflow question: Title: How do I list all remote branches in Git 1.7+? <p>I've tried <code>git branch -r</code>, but that only lists remote branches that I've tracked locally. How do I find the list of those that I haven't? (It doesn't matter to me whether the command lists <em>all</em> remote branches or only those that are untracked.)</p>
<p><strong>For the vast majority<sup>[1]</sup> of visitors here, <a href="https://stackoverflow.com/questions/3471827/how-do-i-list-all-remote-branches-in-git-1-7#comment39347566_3472296">the correct and simplest answer to the question</a> "How do I list all remote branches in Git 1.7+?" is:</strong></p> <pre><code>git branch -r </code></pre> <p>For a small minority<sup>[1]</sup> <code>git branch -r</code> does not work. If <code>git branch -r</code> does not work try:</p> <pre><code>git ls-remote --heads &lt;remote-name&gt; </code></pre> <p>If <code>git branch -r</code> does not work, then maybe as <a href="https://stackoverflow.com/users/119963/cascabel">Cascabel</a> says <a href="https://stackoverflow.com/questions/3471827/how-do-i-list-all-remote-branches-in-git-1-7#comment3623773_3471827">"you've modified the default refspec, so that <code>git fetch</code> and <code>git remote update</code> don't fetch all the <code>remote</code>'s branches"</a>.</p> <hr> <p><sup>[1]</sup> As of the writing of this footnote 2018-Feb, I looked at the comments and see that the <code>git branch -r</code> works for the vast majority (about 90% or <a href="https://stackoverflow.com/questions/3471827/how-do-i-list-all-remote-branches-in-git-1-7#comment39347566_3472296">125</a> out of <a href="https://stackoverflow.com/questions/3471827/how-do-i-list-all-remote-branches-in-git-1-7#comment41488609_3472296">140</a>). </p> <p>If <code>git branch -r</code> does not work, check <code>git config --get remote.origin.fetch</code> contains a wildcard (<code>*</code>) as per <a href="https://stackoverflow.com/a/25941875/114770">this answer</a></p>
{ "question_id": 3471827, "question_date": "2010-08-12T20:37:33.540Z", "question_score": 849, "tags": "git|branch|git-branch|remote-branch", "answer_id": 3472296, "answer_date": "2010-08-12T21:44:00.903Z", "answer_score": 1091 }
Please answer the following Stack Overflow question: Title: How can I remove all CSS classes using jQuery/JavaScript? <p>Instead of individually calling <code>$("#item").removeClass()</code> for every single class an element might have, is there a single function which can be called which removes all CSS classes from the given element? </p> <p>Both jQuery and raw JavaScript will work.</p>
<pre><code>$(&quot;#item&quot;).removeClass(); </code></pre> <p>Calling <code>removeClass</code> with no parameters will remove all of the item's classes.</p> <hr /> <p>You can also use (but it is not necessarily recommended. The <em>correct</em> way is the one above):</p> <pre><code>$(&quot;#item&quot;).removeAttr('class'); $(&quot;#item&quot;).attr('class', ''); $('#item')[0].className = ''; </code></pre> <p>If you didn't have jQuery, then this would be pretty much your only option:</p> <pre><code>document.getElementById('item').className = ''; </code></pre>
{ "question_id": 1424981, "question_date": "2009-09-15T03:34:21.840Z", "question_score": 849, "tags": "javascript|jquery|dom", "answer_id": 1424991, "answer_date": "2009-09-15T03:37:27.503Z", "answer_score": 1646 }
Please answer the following Stack Overflow question: Title: Python: Find in list <p>I use the following to check if <code>item</code> is in <code>my_list</code>:</p> <pre><code>if item in my_list: print(&quot;Desired item is in list&quot;) </code></pre> <p>But sometimes, it doesn't find the item. Why is this?</p> <hr /> <p>Is &quot;<code>if item in my_list:</code>&quot; the most &quot;pythonic&quot; way of finding an item in a list?</p>
<p>As for your first question: &quot;<code>if item is in my_list:</code>&quot; is perfectly fine and should work if <code>item</code> equals one of the elements inside <code>my_list</code>. The item must <em>exactly</em> match an item in the list. For instance, <code>&quot;abc&quot;</code> and <code>&quot;ABC&quot;</code> do not match. Floating point values in particular may suffer from inaccuracy. For instance, <code>1 - 1/3 != 2/3</code>.</p> <p>As for your second question: There's actually several possible ways if &quot;finding&quot; things in lists.</p> <h3>Checking if something is inside</h3> <p>This is the use case you describe: Checking whether something is inside a list or not. As you know, you can use the <code>in</code> operator for that:</p> <pre><code>3 in [1, 2, 3] # =&gt; True </code></pre> <h3>Filtering a collection</h3> <p>That is, finding all elements in a sequence that meet a certain condition. You can use list comprehension or generator expressions for that:</p> <pre><code>matches = [x for x in lst if fulfills_some_condition(x)] matches = (x for x in lst if x &gt; 6) </code></pre> <p>The latter will return a <em>generator</em> which you can imagine as a sort of lazy list that will only be built as soon as you iterate through it. By the way, the first one is exactly equivalent to</p> <pre><code>matches = filter(fulfills_some_condition, lst) </code></pre> <p>in Python 2. Here you can see higher-order functions at work. In Python 3, <code>filter</code> doesn't return a list, but a generator-like object.</p> <h3>Finding the first occurrence</h3> <p>If you only want the first thing that matches a condition (but you don't know what it is yet), it's fine to use a for loop (possibly using the <code>else</code> clause as well, which is not really well-known). You can also use</p> <pre><code>next(x for x in lst if ...) </code></pre> <p>which will return the first match or raise a <code>StopIteration</code> if none is found. Alternatively, you can use</p> <pre><code>next((x for x in lst if ...), [default value]) </code></pre> <h3>Finding the location of an item</h3> <p>For lists, there's also the <code>index</code> method that can sometimes be useful if you want to know <em>where</em> a certain element is in the list:</p> <pre><code>[1,2,3].index(2) # =&gt; 1 [1,2,3].index(4) # =&gt; ValueError </code></pre> <p>However, note that if you have duplicates, <code>.index</code> always returns the lowest index:......</p> <pre><code>[1,2,3,2].index(2) # =&gt; 1 </code></pre> <p>If there are duplicates and you want all the indexes then you can use <code>enumerate()</code> instead:</p> <pre><code>[i for i,x in enumerate([1,2,3,2]) if x==2] # =&gt; [1, 3] </code></pre>
{ "question_id": 9542738, "question_date": "2012-03-03T02:03:34.150Z", "question_score": 848, "tags": "python|list|find", "answer_id": 9542768, "answer_date": "2012-03-03T02:10:21.073Z", "answer_score": 1602 }
Please answer the following Stack Overflow question: Title: Generate a Hash from string in Javascript <p>I need to convert strings to some form of hash. Is this possible in JavaScript?</p> <p>I'm not utilizing a server-side language so I can't do it that way.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i &lt; this.length; i++) { chr = this.charCodeAt(i); hash = ((hash &lt;&lt; 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; } const str = 'revenue' console.log(str, str.hashCode())</code></pre> </div> </div> </p> <p><a href="http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/" rel="nofollow noreferrer">Source</a></p>
{ "question_id": 7616461, "question_date": "2011-09-30T21:52:05.387Z", "question_score": 847, "tags": "javascript|hash", "answer_id": 7616484, "answer_date": "2011-09-30T21:55:20.147Z", "answer_score": 992 }
Please answer the following Stack Overflow question: Title: Creating a new DOM element from an HTML string using built-in DOM methods or Prototype <p>I have an HTML string representing an element: <code>'&lt;li&gt;text&lt;/li&gt;'</code>. I'd like to append it to an element in the DOM (a <code>ul</code> in my case). How can I do this with Prototype or with DOM methods?</p> <p>(I know i could do this easily in jQuery, but unfortunately we're not using jQuery.)</p>
<p><strong>Note:</strong> most current browsers support HTML <code>&lt;template&gt;</code> elements, which provide a more reliable way of turning creating elements from strings. See <a href="https://stackoverflow.com/a/35385518/1709587">Mark Amery's answer below for details</a>.</p> <p><strong>For older browsers, and node/jsdom</strong>: (which doesn't yet support <code>&lt;template&gt;</code> elements at the time of writing), use the following method. It's the same thing the libraries use to do to get DOM elements from an HTML string (<a href="https://stackoverflow.com/questions/1848588/why-does-html-work-and-not-innerhtml-or-appendchild/1849100#1849100">with some extra work for IE</a> to work around bugs with its implementation of <code>innerHTML</code>):</p> <pre><code>function createElementFromHTML(htmlString) { var div = document.createElement('div'); div.innerHTML = htmlString.trim(); // Change this to div.childNodes to support multiple top-level nodes. return div.firstChild; } </code></pre> <p>Note that unlike HTML templates this <em>won't</em> work for some elements that cannot legally be children of a <code>&lt;div&gt;</code>, such as <code>&lt;td&gt;</code>s.</p> <p>If you're already using a library, I would recommend you stick to the library-approved method of creating elements from HTML strings:</p> <ul> <li>Prototype has this feature built-into its <a href="http://prototypejs.org/doc/latest/dom/Element/update/" rel="noreferrer"><code>update()</code> method</a>.</li> <li>jQuery has it implemented in its <a href="https://api.jquery.com/jQuery/#jQuery2" rel="noreferrer"><code>jQuery(html)</code></a> and <a href="https://api.jquery.com/jQuery.parseHTML/" rel="noreferrer"><code>jQuery.parseHTML</code></a> methods.</li> </ul>
{ "question_id": 494143, "question_date": "2009-01-30T01:13:44.520Z", "question_score": 847, "tags": "javascript|dom|prototypejs", "answer_id": 494348, "answer_date": "2009-01-30T03:00:25.210Z", "answer_score": 1028 }
Please answer the following Stack Overflow question: Title: Is it possible to include one CSS file in another? <p>Is it possible to include one CSS file in another?</p>
<p>Yes:</p> <pre><code>@import url("base.css"); </code></pre> <p>Note:</p> <ul> <li>The <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/@import" rel="noreferrer"><code>@import</code></a> rule <a href="https://drafts.csswg.org/css-cascade-3/#at-import" rel="noreferrer">must precede</a> all other rules (except <code>@charset</code>).</li> <li>Additional <code>@import</code> statements require additional server requests. As an alternative, concatenate all CSS into one file to avoid multiple HTTP requests. For example, copy the contents of <code>base.css</code> and <code>special.css</code> into <code>base-special.css</code> and reference only <code>base-special.css</code>.</li> </ul>
{ "question_id": 147500, "question_date": "2008-09-29T04:23:10.667Z", "question_score": 847, "tags": "css", "answer_id": 147508, "answer_date": "2008-09-29T04:29:34.580Z", "answer_score": 1166 }
Please answer the following Stack Overflow question: Title: Designing function f(f(n)) == -n <p>A question I got on my last interview:</p> <blockquote> <p>Design a function <code>f</code>, such that:</p> <pre><code>f(f(n)) == -n </code></pre> <p>Where <code>n</code> is a 32 bit <strong>signed integer</strong>; you can't use complex numbers arithmetic.</p> <p>If you can't design such a function for the whole range of numbers, design it for the largest range possible.</p> </blockquote> <p>Any ideas?</p>
<p>How about:</p> <pre>f(n) = sign(n) - (-1)ⁿ * n</pre> <p>In Python:</p> <pre class="lang-py prettyprint-override"><code>def f(n): if n == 0: return 0 if n &gt;= 0: if n % 2 == 1: return n + 1 else: return -1 * (n - 1) else: if n % 2 == 1: return n - 1 else: return -1 * (n + 1) </code></pre> <p>Python automatically promotes integers to arbitrary length longs. In other languages the largest positive integer will overflow, so it will work for all integers except that one.</p> <hr /> <p>To make it work for real numbers you need to replace the <em>n</em> in (-1)ⁿ with <code>{ ceiling(n) if n&gt;0; floor(n) if n&lt;0 }</code>.</p> <p>In C# (works for any double, except in overflow situations):</p> <pre class="lang-cs prettyprint-override"><code>static double F(double n) { if (n == 0) return 0; if (n &lt; 0) return ((long)Math.Ceiling(n) % 2 == 0) ? (n + 1) : (-1 * (n - 1)); else return ((long)Math.Floor(n) % 2 == 0) ? (n - 1) : (-1 * (n + 1)); } </code></pre>
{ "question_id": 731832, "question_date": "2009-04-08T21:04:18.170Z", "question_score": 847, "tags": "math|integer", "answer_id": 731912, "answer_date": "2009-04-08T21:23:00.683Z", "answer_score": 378 }
Please answer the following Stack Overflow question: Title: window.onload vs document.onload <p>Which is more widely supported: <code>window.onload</code> or <code>document.onload</code>?</p>
<h2>When do they fire?</h2> <p><a href="https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers.onload" rel="noreferrer"><code>window.onload</code></a></p> <ul> <li>By default, it is fired when the entire page loads, <strong>including</strong> its content (images, CSS, scripts, etc.).</li> </ul> <p>In some browsers it now takes over the role of <code>document.onload</code> and fires when the DOM is ready as well.</p> <p><code>document.onload</code></p> <ul> <li>It is called when the DOM is ready which can be <strong>prior</strong> to images and other external content is loaded.</li> </ul> <h2>How well are they supported?</h2> <p><code>window.onload</code> appears to be the most widely supported. In fact, some of the most modern browsers have in a sense replaced <code>document.onload</code> with <code>window.onload</code>.</p> <p>Browser support issues are most likely the reason why many people are starting to use libraries such as <a href="http://jquery.com/" rel="noreferrer">jQuery</a> to handle the checking for the document being ready, like so:</p> <pre><code>$(document).ready(function() { /* code here */ }); $(function() { /* code here */ }); </code></pre> <hr> <p>For the purpose of history. <code>window.onload</code> vs <code>body.onload</code>:</p> <blockquote> <p>A similar question was asked on <a href="http://www.codingforums.com/archive/index.php/t-106229.html" rel="noreferrer">codingforums</a> a while back regarding the usage of <code>window.onload</code> over <code>body.onload</code>. The result seemed to be that you should use <code>window.onload</code> because it is good to separate your structure from the action.</p> </blockquote>
{ "question_id": 588040, "question_date": "2009-02-25T21:45:11.487Z", "question_score": 846, "tags": "javascript|event-handling|dom-events", "answer_id": 588048, "answer_date": "2009-02-25T21:46:45.787Z", "answer_score": 853 }
Please answer the following Stack Overflow question: Title: Download single files from GitHub <p>What are some tips on downloading a single file from a GitHub repo?</p> <p>I don't want the URL for displaying the raw file; in the case of binaries, there's nothing.</p> <p><a href="http://support.github.com/discussions/feature-requests/41-download-single-file" rel="noreferrer">http://support.github.com/discussions/feature-requests/41-download-single-file</a></p> <p>Is it even possible to use GitHub as a &quot;download server&quot;?</p> <p>If we decide to switch to Google Code, is the mentioned functionality presented there?</p> <p>Or is there any free-of-charge hosting and VCS for open-source projects?</p>
<p>Git does not support downloading parts of the repository. You have to download all of it. But you should be able to do this with GitHub.</p> <p>When you view a file it has a link to the &quot;raw&quot; version. The <a href="http://en.wikipedia.org/wiki/Uniform_resource_locator" rel="noreferrer">URL</a> is constructed like so</p> <pre><code>https://raw.githubusercontent.com/user/repository/branch/filename </code></pre> <p>By filling in the blanks in the URL, you can use <a href="http://en.wikipedia.org/wiki/Wget" rel="noreferrer">Wget</a> or <a href="http://en.wikipedia.org/wiki/CURL" rel="noreferrer">cURL</a> (with the <code>-L</code> option, see below) or whatever to download a single file. Again, you won't get any of the nice version control features used by Git by doing this.</p> <p>Update: I noticed you mention this doesn't work for binary files. You probably shouldn't use binary files in your Git repository, but GitHub has a download section for each repository that you can use to upload files. If you need more than one binary, you can use a .zip file. The URL to download an uploaded file is:</p> <pre><code>https://github.com/downloads/user/repository/filename </code></pre> <p>Note that the URLs given above, from the links on <code>github.com</code>, will redirect to <code>raw.githubusercontent.com</code>. You should not directly use the URL given by this HTTP 302 redirect because, per <a href="https://www.rfc-editor.org/rfc/rfc2616#section-10.3.3" rel="noreferrer">RFC 2616</a>: &quot;Since the redirection might be altered on occasion, the client SHOULD continue to use the Request-URI for future requests.&quot;</p>
{ "question_id": 4604663, "question_date": "2011-01-05T13:41:15.810Z", "question_score": 846, "tags": "git|github|url|download|version-control", "answer_id": 4605068, "answer_date": "2011-01-05T14:20:51.410Z", "answer_score": 720 }
Please answer the following Stack Overflow question: Title: What does the "at" (@) symbol do in Python? <p>What does the <code>@</code> symbol do in Python?</p>
<p>An <code>@</code> symbol at the <strong>beginning</strong> of a line is used for class and function <em>decorators</em>:</p> <ul> <li><a href="http://www.python.org/dev/peps/pep-0318/" rel="noreferrer">PEP 318: Decorators</a></li> <li><a href="http://wiki.python.org/moin/PythonDecorators" rel="noreferrer">Python Decorators</a></li> </ul> <p>The most common Python decorators are:</p> <ul> <li><a href="http://docs.python.org/library/functions.html#property" rel="noreferrer"><code>@property</code></a></li> <li><a href="http://docs.python.org/library/functions.html#classmethod" rel="noreferrer"><code>@classmethod</code></a></li> <li><a href="http://docs.python.org/library/functions.html#staticmethod" rel="noreferrer"><code>@staticmethod</code></a></li> </ul> <p>An <code>@</code> in the <strong>middle</strong> of a line is probably matrix multiplication:</p> <ul> <li><a href="https://stackoverflow.com/a/28997112/229792"><code>@</code> as a binary operator.</a></li> </ul>
{ "question_id": 6392739, "question_date": "2011-06-17T23:19:30.140Z", "question_score": 846, "tags": "python|syntax|python-decorators", "answer_id": 6392768, "answer_date": "2011-06-17T23:23:44.947Z", "answer_score": 491 }
Please answer the following Stack Overflow question: Title: Are double square brackets [[ ]] preferable over single square brackets [ ] in Bash? <p>A coworker claimed recently in a code review that the <code>[[ ]]</code> construct is to be preferred over <code>[ ]</code> in constructs like</p> <pre><code>if [ &quot;`id -nu`&quot; = &quot;$someuser&quot; ] ; then echo &quot;I love you madly, $someuser&quot; fi </code></pre> <p>He couldn't provide a rationale. Is there one?</p>
<p><code>[[</code> has fewer surprises and is generally safer to use. But it is not portable - POSIX doesn't specify what it does and only some shells support it (beside bash, I heard ksh supports it too). For example, you can do </p> <pre><code>[[ -e $b ]] </code></pre> <p>to test whether a file exists. But with <code>[</code>, you have to quote <code>$b</code>, because it splits the argument and expands things like <code>"a*"</code> (where <code>[[</code> takes it literally). That has also to do with how <code>[</code> can be an external program and receives its argument just normally like every other program (although it can also be a builtin, but then it still has not this special handling).</p> <p><code>[[</code> also has some other nice features, like regular expression matching with <code>=~</code> along with operators like they are known in C-like languages. Here is a good page about it: <a href="http://mywiki.wooledge.org/BashFAQ/031" rel="noreferrer">What is the difference between test, <code>[</code> and <code>[[</code> ?</a> and <a href="http://mywiki.wooledge.org/BashGuide/Practices#Bash_Tests" rel="noreferrer">Bash Tests</a></p>
{ "question_id": 669452, "question_date": "2009-03-21T15:28:45.137Z", "question_score": 846, "tags": "bash|if-statement|syntax", "answer_id": 669486, "answer_date": "2009-03-21T15:44:09.887Z", "answer_score": 821 }
Please answer the following Stack Overflow question: Title: What is an efficient way to implement a singleton pattern in Java? <p>What is an efficient way to implement a singleton design pattern in Java?</p>
<p>Use an enum:</p> <pre><code>public enum Foo { INSTANCE; } </code></pre> <p>Joshua Bloch explained this approach in his <a href="http://sites.google.com/site/io/effective-java-reloaded" rel="noreferrer">Effective Java Reloaded</a> talk at Google I/O 2008: <a href="http://www.youtube.com/watch?v=pi_I7oD_uGI#t=28m50s" rel="noreferrer">link to video</a>. Also see slides 30-32 of his presentation (<a href="https://14b1424d-a-62cb3a1a-s-sites.googlegroups.com/site/io/effective-java-reloaded/effective_java_reloaded.pdf?attachauth=ANoY7crKCOet2NEUGW7RV1XfM-Jn4z8YJhs0qJM11OhLRnFW_JbExkJtvJ3UJvTE40dhAciyWcRIeGJ-n3FLGnMOapHShHINh8IY05YViOJoZWzaohMtM-s4HCi5kjREagi8awWtcYD0_6G7GhKr2BndToeqLk5sBhZcQfcYIyAE5A4lGNosDCjODcBAkJn8EuO6572t2wU1LMSEUgjvqcf4I-Fp6VDhDvih_XUEmL9nuVJQynd2DRpxyuNH1SpJspEIdbLw-WWZ&amp;attredirects=0" rel="noreferrer">effective_java_reloaded.pdf</a>):</p> <blockquote> <h3>The Right Way to Implement a Serializable Singleton</h3> <pre><code>public enum Elvis { INSTANCE; private final String[] favoriteSongs = { "Hound Dog", "Heartbreak Hotel" }; public void printFavorites() { System.out.println(Arrays.toString(favoriteSongs)); } } </code></pre> </blockquote> <p><strong>Edit:</strong> An <a href="http://www.ddj.com/java/208403883?pgno=3" rel="noreferrer">online portion of "Effective Java"</a> says: </p> <blockquote> <p>"This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, <strong>a single-element enum type is the best way to implement a singleton</strong>."</p> </blockquote>
{ "question_id": 70689, "question_date": "2008-09-16T09:24:28.447Z", "question_score": 846, "tags": "java|singleton|design-patterns", "answer_id": 71399, "answer_date": "2008-09-16T11:31:57.173Z", "answer_score": 806 }
Please answer the following Stack Overflow question: Title: What is a "cache-friendly" code? <p>What is the difference between "<strong>cache unfriendly code</strong>" and the "<strong>cache friendly</strong>" code?</p> <p>How can I make sure I write cache-efficient code? </p>
<h2>Preliminaries</h2> <p>On modern computers, only the lowest level memory structures (the <strong>registers</strong>) can move data around in single clock cycles. However, registers are very expensive and most computer cores have less than a few dozen registers. At the other end of the memory spectrum (<strong>DRAM</strong>), the memory is very cheap (i.e. literally <em>millions of times cheaper</em>) but takes hundreds of cycles after a request to receive the data. To bridge this gap between super fast and expensive and super slow and cheap are the <strong>cache memories</strong>, named L1, L2, L3 in decreasing speed and cost. The idea is that most of the executing code will be hitting a small set of variables often, and the rest (a much larger set of variables) infrequently. If the processor can't find the data in L1 cache, then it looks in L2 cache. If not there, then L3 cache, and if not there, main memory. Each of these &quot;misses&quot; is expensive in time.</p> <p>(The analogy is cache memory is to system memory, as system memory is to hard disk storage. Hard disk storage is super cheap but very slow).</p> <p>Caching is one of the main methods to reduce the impact of <em>latency</em>. To paraphrase Herb Sutter (cfr. links below): <strong>increasing bandwidth is easy, but we can't buy our way out of latency</strong>.</p> <p>Data is always retrieved through the memory hierarchy (smallest == fastest to slowest). A <em>cache hit/miss</em> usually refers to a hit/miss in the highest level of cache in the CPU -- by highest level I mean the largest == slowest. The cache hit rate is crucial for performance since every cache miss results in fetching data from RAM (or worse ...) which takes <em><strong>a lot</strong></em> of time (hundreds of cycles for RAM, tens of millions of cycles for HDD). In comparison, reading data from the (highest level) cache typically takes only a handful of cycles.</p> <p>In modern computer architectures, the performance bottleneck is leaving the CPU die (e.g. accessing RAM or higher). This will only get worse over time. The increase in processor frequency is currently no longer relevant to increase performance. <strong>The problem is memory access.</strong> Hardware design efforts in CPUs therefore currently focus heavily on optimizing caches, prefetching, pipelines and concurrency. For instance, modern CPUs spend around 85% of die on caches and up to 99% for storing/moving data!</p> <p>There is quite a lot to be said on the subject. Here are a few great references about caches, memory hierarchies and proper programming:</p> <ul> <li><a href="http://www.agner.org/optimize/" rel="noreferrer">Agner Fog's page</a>. In his excellent documents, you can find detailed examples covering languages ranging from assembly to C++.</li> <li>If you are into videos, I strongly recommend to have a look at <a href="http://www.youtube.com/watch?v=L7zSU9HI-6I" rel="noreferrer">Herb Sutter's talk on machine architecture (youtube)</a> (specifically check 12:00 and onwards!).</li> <li><a href="https://web.archive.org/web/20160422113037/http://www.research.scea.com/research/pdfs/GDC2003_Memory_Optimization_18Mar03.pdf" rel="noreferrer">Slides about memory optimization by Christer Ericson</a> (director of technology @ Sony)</li> <li>LWN.net's article <a href="http://lwn.net/Articles/250967/" rel="noreferrer">&quot;<em>What every programmer should know about memory</em>&quot;</a></li> </ul> <h2>Main concepts for cache-friendly code</h2> <p>A very important aspect of cache-friendly code is all about <strong><a href="http://en.wikipedia.org/wiki/Locality_of_reference" rel="noreferrer">the principle of locality</a></strong>, the goal of which is to place related data close in memory to allow efficient caching. In terms of the CPU cache, it's important to be aware of cache lines to understand how this works: <a href="https://stackoverflow.com/questions/3928995/how-do-cache-lines-work">How do cache lines work?</a></p> <p>The following particular aspects are of high importance to optimize caching:</p> <ol> <li><strong>Temporal locality</strong>: when a given memory location was accessed, it is likely that the same location is accessed again in the near future. Ideally, this information will still be cached at that point.</li> <li><strong>Spatial locality</strong>: this refers to placing related data close to each other. Caching happens on many levels, not just in the CPU. For example, when you read from RAM, typically a larger chunk of memory is fetched than what was specifically asked for because very often the program will require that data soon. HDD caches follow the same line of thought. Specifically for CPU caches, the notion of <em>cache lines</em> is important.</li> </ol> <p><strong>Use appropriate <a href="/questions/tagged/c%2b%2b" class="post-tag" title="show questions tagged &#39;c++&#39;" rel="tag">c++</a> containers</strong></p> <p>A simple example of cache-friendly versus cache-unfriendly is <a href="/questions/tagged/c%2b%2b" class="post-tag" title="show questions tagged &#39;c++&#39;" rel="tag">c++</a>'s <code>std::vector</code> versus <code>std::list</code>. Elements of a <code>std::vector</code> are stored in contiguous memory, and as such accessing them is <em>much</em> more cache-friendly than accessing elements in a <code>std::list</code>, which stores its content all over the place. This is due to spatial locality.</p> <p>A very nice illustration of this is given by Bjarne Stroustrup in <a href="http://www.youtube.com/watch?v=YQs6IC-vgmo" rel="noreferrer">this youtube clip</a> (thanks to @Mohammad Ali Baydoun for the link!).</p> <p><strong>Don't neglect the cache in data structure and algorithm design</strong></p> <p>Whenever possible, try to adapt your data structures and order of computations in a way that allows maximum use of the cache. A common technique in this regard is <a href="http://www.cs.berkeley.edu/%7Erichie/cs267/mg/report/node35.html" rel="noreferrer">cache blocking</a> <a href="https://web.archive.org/web/20140113145619/http://www.cs.berkeley.edu/%7Erichie/cs267/mg/report/node35.html" rel="noreferrer">(Archive.org version)</a>, which is of extreme importance in high-performance computing (cfr. for example <a href="http://en.wikipedia.org/wiki/Automatically_Tuned_Linear_Algebra_Software" rel="noreferrer">ATLAS</a>).</p> <p><strong>Know and exploit the implicit structure of data</strong></p> <p>Another simple example, which many people in the field sometimes forget is column-major (ex. <a href="/questions/tagged/fortran" class="post-tag" title="show questions tagged &#39;fortran&#39;" rel="tag">fortran</a>,<a href="/questions/tagged/matlab" class="post-tag" title="show questions tagged &#39;matlab&#39;" rel="tag">matlab</a>) vs. row-major ordering (ex. <a href="/questions/tagged/c" class="post-tag" title="show questions tagged &#39;c&#39;" rel="tag">c</a>,<a href="/questions/tagged/c%2b%2b" class="post-tag" title="show questions tagged &#39;c++&#39;" rel="tag">c++</a>) for storing two dimensional arrays. For example, consider the following matrix:</p> <pre><code>1 2 3 4 </code></pre> <p>In row-major ordering, this is stored in memory as <code>1 2 3 4</code>; in column-major ordering, this would be stored as <code>1 3 2 4</code>. It is easy to see that implementations which do not exploit this ordering will quickly run into (easily avoidable!) cache issues. Unfortunately, I see stuff like this <em>very</em> often in my domain (machine learning). @MatteoItalia showed this example in more detail in his answer.</p> <p>When fetching a certain element of a matrix from memory, elements near it will be fetched as well and stored in a cache line. If the ordering is exploited, this will result in fewer memory accesses (because the next few values which are needed for subsequent computations are already in a cache line).</p> <p>For simplicity, assume the cache comprises a single cache line which can contain 2 matrix elements and that when a given element is fetched from memory, the next one is too. Say we want to take the sum over all elements in the example 2x2 matrix above (lets call it <code>M</code>):</p> <p>Exploiting the ordering (e.g. changing column index first in <a href="/questions/tagged/c%2b%2b" class="post-tag" title="show questions tagged &#39;c++&#39;" rel="tag">c++</a>):</p> <pre><code>M[0][0] (memory) + M[0][1] (cached) + M[1][0] (memory) + M[1][1] (cached) = 1 + 2 + 3 + 4 --&gt; 2 cache hits, 2 memory accesses </code></pre> <p>Not exploiting the ordering (e.g. changing row index first in <a href="/questions/tagged/c%2b%2b" class="post-tag" title="show questions tagged &#39;c++&#39;" rel="tag">c++</a>):</p> <pre><code>M[0][0] (memory) + M[1][0] (memory) + M[0][1] (memory) + M[1][1] (memory) = 1 + 3 + 2 + 4 --&gt; 0 cache hits, 4 memory accesses </code></pre> <p>In this simple example, exploiting the ordering approximately doubles execution speed (since memory access requires much more cycles than computing the sums). In practice, the performance difference can be <em>much</em> larger.</p> <p><strong>Avoid unpredictable branches</strong></p> <p>Modern architectures feature pipelines and compilers are becoming very good at reordering code to minimize delays due to memory access. When your critical code contains (unpredictable) branches, it is hard or impossible to prefetch data. This will indirectly lead to more cache misses.</p> <p>This is explained <em>very</em> well here (thanks to @0x90 for the link): <a href="https://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-an-unsorted-array">Why is processing a sorted array faster than processing an unsorted array?</a></p> <p><strong>Avoid virtual functions</strong></p> <p>In the context of <a href="/questions/tagged/c%2b%2b" class="post-tag" title="show questions tagged &#39;c++&#39;" rel="tag">c++</a>, <code>virtual</code> methods represent a controversial issue with regard to cache misses (a general consensus exists that they should be avoided when possible in terms of performance). Virtual functions can induce cache misses during look up, but this only happens <em>if</em> the specific function is not called often (otherwise it would likely be cached), so this is regarded as a non-issue by some. For reference about this issue, check out: <a href="https://stackoverflow.com/questions/667634/what-is-the-performance-cost-of-having-a-virtual-method-in-a-c-class">What is the performance cost of having a virtual method in a C++ class?</a></p> <h2>Common problems</h2> <p>A common problem in modern architectures with multiprocessor caches is called <a href="http://en.wikipedia.org/wiki/False_sharing" rel="noreferrer">false sharing</a>. This occurs when each individual processor is attempting to use data in another memory region and attempts to store it in the same <em>cache line</em>. This causes the cache line -- which contains data another processor can use -- to be overwritten again and again. Effectively, different threads make each other wait by inducing cache misses in this situation. See also (thanks to @Matt for the link): <a href="https://stackoverflow.com/questions/8469427/how-and-when-to-align-to-cache-line-size">How and when to align to cache line size?</a></p> <p>An extreme symptom of poor caching in RAM memory (which is probably not what you mean in this context) is so-called <a href="http://en.wikipedia.org/wiki/Thrashing_%28computer_science%29" rel="noreferrer">thrashing</a>. This occurs when the process continuously generates page faults (e.g. accesses memory which is not in the current page) which require disk access.</p>
{ "question_id": 16699247, "question_date": "2013-05-22T18:37:01.940Z", "question_score": 846, "tags": "c++|performance|caching|memory|cpu-cache", "answer_id": 16699282, "answer_date": "2013-05-22T18:39:16.423Z", "answer_score": 1110 }
Please answer the following Stack Overflow question: Title: Print string to text file <p>I'm using Python to open a text document:</p> <pre><code>text_file = open("Output.txt", "w") text_file.write("Purchase Amount: " 'TotalAmount') text_file.close() </code></pre> <p>I want to substitute the value of a string variable <code>TotalAmount</code> into the text document. Can someone please let me know how to do this?</p>
<p>It is strongly advised to use a context manager. As an advantage, it is made sure the file is always closed, no matter what:</p> <pre><code>with open(&quot;Output.txt&quot;, &quot;w&quot;) as text_file: text_file.write(&quot;Purchase Amount: %s&quot; % TotalAmount) </code></pre> <p>This is the explicit version (but always remember, the context manager version from above should be preferred):</p> <pre><code>text_file = open(&quot;Output.txt&quot;, &quot;w&quot;) text_file.write(&quot;Purchase Amount: %s&quot; % TotalAmount) text_file.close() </code></pre> <p>If you're using Python2.6 or higher, it's preferred to use <code>str.format()</code></p> <pre><code>with open(&quot;Output.txt&quot;, &quot;w&quot;) as text_file: text_file.write(&quot;Purchase Amount: {0}&quot;.format(TotalAmount)) </code></pre> <p>For python2.7 and higher you can use <code>{}</code> instead of <code>{0}</code></p> <p>In Python3, there is an optional <code>file</code> parameter to the <code>print</code> function</p> <pre><code>with open(&quot;Output.txt&quot;, &quot;w&quot;) as text_file: print(&quot;Purchase Amount: {}&quot;.format(TotalAmount), file=text_file) </code></pre> <p>Python3.6 introduced <a href="https://docs.python.org/3/whatsnew/3.6.html#pep-498-formatted-string-literals" rel="noreferrer">f-strings</a> for another alternative</p> <pre><code>with open(&quot;Output.txt&quot;, &quot;w&quot;) as text_file: print(f&quot;Purchase Amount: {TotalAmount}&quot;, file=text_file) </code></pre>
{ "question_id": 5214578, "question_date": "2011-03-07T00:31:57.730Z", "question_score": 845, "tags": "python|string|text|file-io", "answer_id": 5214587, "answer_date": "2011-03-07T00:34:38.527Z", "answer_score": 1518 }
Please answer the following Stack Overflow question: Title: How to un-commit last un-pushed git commit without losing the changes <p>Is there a way to revert a commit so that my local copy <em>keeps</em> the changes made in that commit, but they become non-committed changes in my working copy? Rolling back a commit takes you to the previous commit - I want to keep the changes made but I committed them to the wrong branch.</p> <p>This has not been pushed, only committed.</p>
<p>There are a lot of ways to do so, for example:</p> <p>in case you have <strong><em>not</em></strong> pushed the commit publicly yet:</p> <pre><code>git reset HEAD~1 --soft </code></pre> <p>That's it, your commit changes will be in your working directory, whereas the LAST commit will be removed from your current branch. See <a href="http://git-scm.com/docs/git-reset" rel="noreferrer">git reset man</a></p> <hr> <p>In case you <em>did</em> push publicly (on a branch called 'master'):</p> <pre><code>git checkout -b MyCommit //save your commit in a separate branch just in case (so you don't have to dig it from reflog in case you screw up :) ) </code></pre> <p>revert commit normally and push </p> <pre><code>git checkout master git revert a8172f36 #hash of the commit you want to destroy # this introduces a new commit (say, it's hash is 86b48ba) which removes changes, introduced in the commit in question (but those changes are still visible in the history) git push origin master </code></pre> <p>now if you want to have those changes as you local changes in your working copy ("so that your local copy keeps the changes made in that commit") - just revert the revert commit with <code>--no-commit</code> option:</p> <pre><code>git revert --no-commit 86b48ba (hash of the revert commit). </code></pre> <p>I've crafted a small example: <a href="https://github.com/Isantipov/git-revert/commits/master" rel="noreferrer">https://github.com/Isantipov/git-revert/commits/master</a></p>
{ "question_id": 19859486, "question_date": "2013-11-08T12:47:23.180Z", "question_score": 845, "tags": "git", "answer_id": 19859644, "answer_date": "2013-11-08T12:55:01.647Z", "answer_score": 1432 }
Please answer the following Stack Overflow question: Title: How do I get extra data from intent on Android? <p>How can I send data from one activity (intent) to another?</p> <p>I use this code to send data:</p> <pre><code>Intent i=new Intent(context,SendMessage.class); i.putExtra("id", user.getUserAccountId()+""); i.putExtra("name", user.getUserFullName()); context.startActivity(i); </code></pre>
<p>First, get the intent which has started your activity using the <code>getIntent()</code> method:</p> <pre><code>Intent intent = getIntent(); </code></pre> <p>If your extra data is represented as strings, then you can use <code>intent.getStringExtra(String name)</code> method. In your case:</p> <pre><code>String id = intent.getStringExtra("id"); String name = intent.getStringExtra("name"); </code></pre>
{ "question_id": 4233873, "question_date": "2010-11-20T16:59:59.500Z", "question_score": 844, "tags": "android|android-intent", "answer_id": 4233898, "answer_date": "2010-11-20T17:04:15.653Z", "answer_score": 1346 }
Please answer the following Stack Overflow question: Title: How to check whether a string contains a substring in Ruby <p>I have a string variable with content:</p> <pre><code>varMessage = "hi/thsid/sdfhsjdf/dfjsd/sdjfsdn\n" "/my/name/is/balaji.so\n" "call::myFunction(int const&amp;)\n" "void::secondFunction(char const&amp;)\n" . . . "this/is/last/line/liobrary.so" </code></pre> <p>In the string I have to find a sub-string:</p> <pre><code>"hi/thsid/sdfhsjdf/dfjsd/sdjfsdn\n" "/my/name/is/balaji.so\n" "call::myFunction(int const&amp;)\n" </code></pre> <p>How can I find it? I need to determine whether the sub-string is present or not.</p>
<p>You can use the <a href="https://ruby-doc.org/core-1.9.3/String.html#method-i-include-3F" rel="noreferrer"><code>include?</code></a> method:</p> <pre><code>my_string = "abcdefg" if my_string.include? "cde" puts "String includes 'cde'" end </code></pre>
{ "question_id": 8258517, "question_date": "2011-11-24T14:21:15.703Z", "question_score": 844, "tags": "ruby|string", "answer_id": 8258571, "answer_date": "2011-11-24T14:24:47.103Z", "answer_score": 1548 }
Please answer the following Stack Overflow question: Title: Docker Compose - How to execute multiple commands? <p>I want to do something like this where I can run multiple commands in following codes:</p> <pre class="lang-yaml prettyprint-override"><code>db: image: postgres web: build: . command: python manage.py migrate command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - &quot;8000:8000&quot; links: - db </code></pre> <p>How could I execute multiple commands?</p> <p>Thanks.</p>
<p>Figured it out, use <strong><code>bash -c</code></strong>.</p> <p>Example:</p> <pre><code>command: bash -c "python manage.py migrate &amp;&amp; python manage.py runserver 0.0.0.0:8000" </code></pre> <p>Same example in multilines:</p> <pre><code>command: &gt; bash -c "python manage.py migrate &amp;&amp; python manage.py runserver 0.0.0.0:8000" </code></pre> <p>Or:</p> <pre><code>command: bash -c " python manage.py migrate &amp;&amp; python manage.py runserver 0.0.0.0:8000 " </code></pre>
{ "question_id": 30063907, "question_date": "2015-05-05T21:53:37.160Z", "question_score": 844, "tags": "docker|docker-compose", "answer_id": 30064175, "answer_date": "2015-05-05T22:16:53.983Z", "answer_score": 1310 }
Please answer the following Stack Overflow question: Title: Addressing localhost from a VirtualBox virtual machine <p>I have a local test/development server (HTTP, of course), listening to port 8000.</p> <p>I'm working on Linux, so to test the page on Internet&nbsp;Explorer&nbsp;6, 7, 8, etc. I run a virtual machine using VirtualBox; I also need to see how it look on Firefox in a windows environment (fonts for instance are different).</p> <p>In my real machine, I open the website simply using the URL <code>http://localhost:8000</code>, how do I address this localhost from the virtual machine?</p> <p>Right now my workaround is to use the IP address. Any better ideas?</p>
<p>Googling turned this up: <a href="http://data.agaric.com/localhost-from-virtualbox-xp-install-ubuntu" rel="noreferrer">http://data.agaric.com/localhost-from-virtualbox-xp-install-ubuntu</a></p> <p>It suggests using IP: <code>http://10.0.2.2</code>, and it worked for me.</p> <p>So, I edited the hosts file, <code>C:\windows\system32\drivers\etc\hosts</code>, and added this entry:</p> <pre><code>10.0.2.2 outer </code></pre> <p>If you're testing on IE8, remember to put <code>http://</code> in the address bar. Just putting the ip directly will not work.</p> <p>For example:</p> <pre><code>http://10.0.2.2:3000/ </code></pre>
{ "question_id": 1261975, "question_date": "2009-08-11T17:57:55.797Z", "question_score": 844, "tags": "localhost|virtual-machine|virtualbox", "answer_id": 1262143, "answer_date": "2009-08-11T18:27:55.890Z", "answer_score": 993 }
Please answer the following Stack Overflow question: Title: Making a mocked method return an argument that was passed to it <p>Consider a method signature like:</p> <pre><code>public String myFunction(String abc); </code></pre> <p>Can Mockito help return the same string that the method received?</p>
<h2>Since Mockito 1.9.5+ and Java 8+</h2> <p>You can use a lambda expression, like:</p> <pre><code>when(myMock.myFunction(anyString())).thenAnswer(i -&gt; i.getArguments()[0]); </code></pre> <blockquote> <p>Where <code>i</code> is an instance of <code>InvocationOnMock</code>.</p> </blockquote> <h2>For older versions</h2> <p>You can create an Answer in Mockito. Let's assume, we have an interface named MyInterface with a method myFunction.</p> <pre class="lang-java prettyprint-override"><code>public interface MyInterface { public String myFunction(String abc); } </code></pre> <p>Here is the test method with a Mockito answer:</p> <pre class="lang-java prettyprint-override"><code>public void testMyFunction() throws Exception { MyInterface mock = mock(MyInterface.class); when(mock.myFunction(anyString())).thenAnswer(new Answer&lt;String&gt;() { @Override public String answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); return (String) args[0]; } }); assertEquals(&quot;someString&quot;,mock.myFunction(&quot;someString&quot;)); assertEquals(&quot;anotherString&quot;,mock.myFunction(&quot;anotherString&quot;)); } </code></pre>
{ "question_id": 2684630, "question_date": "2010-04-21T16:11:41.877Z", "question_score": 844, "tags": "java|mockito", "answer_id": 2711553, "answer_date": "2010-04-26T06:51:37.110Z", "answer_score": 1255 }
Please answer the following Stack Overflow question: Title: Func vs. Action vs. Predicate <p>With real examples and their use, can someone please help me understand:</p> <ol> <li>When do we need a <a href="https://docs.microsoft.com/en-us/dotnet/api/system.func-1?view=netcore-3.1" rel="noreferrer"><code>Func&lt;T, ..&gt;</code></a> delegate?</li> <li>When do we need an <a href="https://docs.microsoft.com/en-us/dotnet/api/system.action-1?view=netcore-3.1" rel="noreferrer"><code>Action&lt;T&gt;</code></a> delegate?</li> <li>When do we need a <a href="https://docs.microsoft.com/en-us/dotnet/api/system.predicate-1?view=netcore-3.1" rel="noreferrer"><code>Predicate&lt;T&gt;</code></a> delegate?</li> </ol>
<p>The difference between <code>Func</code> and <code>Action</code> is simply whether you want the delegate to return a value (use <code>Func</code>) or not (use <code>Action</code>).</p> <p><code>Func</code> is probably most commonly used in LINQ - for example in projections:</p> <pre><code> list.Select(x =&gt; x.SomeProperty) </code></pre> <p>or filtering:</p> <pre><code> list.Where(x =&gt; x.SomeValue == someOtherValue) </code></pre> <p>or key selection:</p> <pre><code> list.Join(otherList, x =&gt; x.FirstKey, y =&gt; y.SecondKey, ...) </code></pre> <p><code>Action</code> is more commonly used for things like <code>List&lt;T&gt;.ForEach</code>: execute the given action for each item in the list. I use this less often than <code>Func</code>, although I <em>do</em> sometimes use the parameterless version for things like <code>Control.BeginInvoke</code> and <code>Dispatcher.BeginInvoke</code>.</p> <p><code>Predicate</code> is just a special cased <code>Func&lt;T, bool&gt;</code> really, introduced before all of the <code>Func</code> and most of the <code>Action</code> delegates came along. I suspect that if we'd already had <code>Func</code> and <code>Action</code> in their various guises, <code>Predicate</code> wouldn't have been introduced... although it <em>does</em> impart a certain meaning to the use of the delegate, whereas <code>Func</code> and <code>Action</code> are used for widely disparate purposes.</p> <p><code>Predicate</code> is mostly used in <code>List&lt;T&gt;</code> for methods like <code>FindAll</code> and <code>RemoveAll</code>.</p>
{ "question_id": 4317479, "question_date": "2010-11-30T19:07:48.883Z", "question_score": 844, "tags": "c#|delegates|action|func", "answer_id": 4317512, "answer_date": "2010-11-30T19:11:43.050Z", "answer_score": 1049 }
Please answer the following Stack Overflow question: Title: Passing additional variables from command line to make <p>Can I pass variables to a GNU Makefile as command line arguments? In other words, I want to pass some arguments which will eventually become variables in the Makefile.</p>
<p>You have several options to set up variables from outside your makefile:</p> <ul> <li><p><strong>From environment</strong> - each environment variable is transformed into a makefile variable with the same name and value.</p> <p>You may also want to set <code>-e</code> option (aka <code>--environments-override</code>) on, and your environment variables will override assignments made into makefile (unless these assignments themselves use the <a href="http://www.gnu.org/software/make/manual/make.html#Override-Directive" rel="noreferrer"><code>override</code> directive</a> . However, it's not recommended, and it's much better and flexible to use <code>?=</code> assignment (the conditional variable assignment operator, it only has an effect if the variable is not yet defined):</p> <pre><code>FOO?=default_value_if_not_set_in_environment </code></pre> <p>Note that certain variables are not inherited from environment:</p> <ul> <li><code>MAKE</code> is gotten from name of the script</li> <li><code>SHELL</code> is either set within a makefile, or defaults to <code>/bin/sh</code> (rationale: commands are specified within the makefile, and they're shell-specific).</li> </ul></li> <li><p><strong>From command line</strong> - <code>make</code> can take variable assignments as part of his command line, mingled with targets:</p> <pre><code>make target FOO=bar </code></pre> <p>But then <em>all assignments to <code>FOO</code> variable within the makefile will be ignored</em> unless you use the <a href="http://www.gnu.org/software/make/manual/make.html#Override-Directive" rel="noreferrer"><code>override</code> directive</a> in assignment. (The effect is the same as with <code>-e</code> option for environment variables).</p></li> <li><p><strong>Exporting from the parent Make</strong> - if you call Make from a Makefile, you usually shouldn't explicitly write variable assignments like this:</p> <pre><code># Don't do this! target: $(MAKE) -C target CC=$(CC) CFLAGS=$(CFLAGS) </code></pre> <p>Instead, better solution might be to export these variables. Exporting a variable makes it into the environment of every shell invocation, and Make calls from these commands pick these environment variable as specified above.</p> <pre><code># Do like this CFLAGS=-g export CFLAGS target: $(MAKE) -C target </code></pre> <p>You can also export <em>all</em> variables by using <code>export</code> without arguments.</p></li> </ul>
{ "question_id": 2826029, "question_date": "2010-05-13T10:31:50.807Z", "question_score": 843, "tags": "makefile|gnu|command-line-arguments", "answer_id": 2826178, "answer_date": "2010-05-13T10:57:02.183Z", "answer_score": 952 }
Please answer the following Stack Overflow question: Title: Can I write a CSS selector selecting elements NOT having a certain class or attribute? <p>I would like to write a CSS selector rule that selects all elements that <em>don't</em> have a certain class. For example, given the following HTML:</p> <pre><code>&lt;html class="printable"&gt; &lt;body class="printable"&gt; &lt;h1 class="printable"&gt;Example&lt;/h1&gt; &lt;nav&gt; &lt;!-- Some menu links... --&gt; &lt;/nav&gt; &lt;a href="javascript:void(0)" onclick="javascript:self.print()"&gt;Print me!&lt;/a&gt; &lt;p class="printable"&gt; This page is super interresting and you should print it! &lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I would like to write a selector that selects all elements that don't have the "printable" class which, in this case, are the <em>nav</em> and <em>a</em> elements.</p> <p>Is this possible?</p> <p>NOTE: in the actual HTML where I would like to use this, there are going to be a lot more elements that <em>don't</em> have the "printable" class than do (I realize it's the other way around in the above example).</p>
<p>Typically you add a class selector to the <code>:not()</code> pseudo-class like so:</p> <pre class="lang-css prettyprint-override"><code>:not(.printable) { /* Styles */ } :not([attribute]) { /* Styles */ } </code></pre> <p>But if you need better browser support (IE8 and older don't support <code>:not()</code>), you're probably better off creating style rules for elements that <em>do</em> have the &quot;printable&quot; class. If even that isn't feasible despite what you say about your actual markup, you may have to work your markup around that limitation.</p> <p>Keep in mind that, depending on the properties you're setting in this rule, some of them may either be inherited by descendants that <em>are</em> <code>.printable</code>, or otherwise affect them one way or another. For example, although <code>display</code> is not inherited, setting <code>display: none</code> on a <code>:not(.printable)</code> will prevent it and all of its descendants from displaying, since it removes the element and its subtree from layout completely. You can often get around this by using <code>visibility: hidden</code> instead which will allow visible descendants to show, but the hidden elements will still affect layout as they originally did. In short, just be careful.</p>
{ "question_id": 9110300, "question_date": "2012-02-02T09:59:06.517Z", "question_score": 843, "tags": "html|css|css-selectors", "answer_id": 9110350, "answer_date": "2012-02-02T10:02:36.143Z", "answer_score": 1145 }
Please answer the following Stack Overflow question: Title: Creating a copy of a database in PostgreSQL <p>What's the correct way to copy entire database (its structure and data) to a new one in pgAdmin?</p>
<p>Postgres allows the use of any existing database on the server as a template when creating a new database. I'm not sure whether pgAdmin gives you the option on the create database dialog but you should be able to execute the following in a query window if it doesn't:</p> <pre><code>CREATE DATABASE newdb WITH TEMPLATE originaldb OWNER dbuser; </code></pre> <p>Still, you may get:</p> <pre><code>ERROR: source database "originaldb" is being accessed by other users </code></pre> <p>To disconnect all other users from the database, you can use this query:</p> <pre><code>SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = 'originaldb' AND pid &lt;&gt; pg_backend_pid(); </code></pre>
{ "question_id": 876522, "question_date": "2009-05-18T07:00:17.783Z", "question_score": 843, "tags": "postgresql", "answer_id": 876565, "answer_date": "2009-05-18T07:18:51.590Z", "answer_score": 1279 }
Please answer the following Stack Overflow question: Title: Test for existence of nested JavaScript object key <p>If I have a reference to an object:</p> <pre><code>var test = {}; </code></pre> <p>that will potentially (but not immediately) have nested objects, something like:</p> <pre><code>{level1: {level2: {level3: "level3"}}}; </code></pre> <p>What is the best way to check for the existence of property in deeply nested objects?</p> <p><code>alert(test.level1);</code> yields <code>undefined</code>, but <code>alert(test.level1.level2.level3);</code> fails.</p> <p>I’m currently doing something like this:</p> <pre><code>if(test.level1 &amp;&amp; test.level1.level2 &amp;&amp; test.level1.level2.level3) { alert(test.level1.level2.level3); } </code></pre> <p>but I was wondering if there’s a better way.</p>
<p>You have to do it step by step if you don't want a <code>TypeError</code> because if one of the members is <code>null</code> or <code>undefined</code>, and you try to access a member, an exception will be thrown.</p> <p>You can either simply <code>catch</code> the exception, or make a function to test the existence of multiple levels, something like this:</p> <pre><code>function checkNested(obj /*, level1, level2, ... levelN*/) { var args = Array.prototype.slice.call(arguments, 1); for (var i = 0; i &lt; args.length; i++) { if (!obj || !obj.hasOwnProperty(args[i])) { return false; } obj = obj[args[i]]; } return true; } var test = {level1:{level2:{level3:'level3'}} }; checkNested(test, 'level1', 'level2', 'level3'); // true checkNested(test, 'level1', 'level2', 'foo'); // false </code></pre> <p><strong>ES6 UPDATE:</strong></p> <p>Here is a shorter version of the original function, using ES6 features and recursion (it's also in <a href="https://webkit.org/blog/6240/ecmascript-6-proper-tail-calls-in-webkit/" rel="noreferrer">proper tail call</a> form):</p> <pre><code>function checkNested(obj, level, ...rest) { if (obj === undefined) return false if (rest.length == 0 &amp;&amp; obj.hasOwnProperty(level)) return true return checkNested(obj[level], ...rest) } </code></pre> <p>However, if you want to get the value of a nested property and not only check its existence, here is a simple one-line function:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function getNested(obj, ...args) { return args.reduce((obj, level) =&gt; obj &amp;&amp; obj[level], obj) } const test = { level1:{ level2:{ level3:'level3'} } }; console.log(getNested(test, 'level1', 'level2', 'level3')); // 'level3' console.log(getNested(test, 'level1', 'level2', 'level3', 'length')); // 6 console.log(getNested(test, 'level1', 'level2', 'foo')); // undefined console.log(getNested(test, 'a', 'b')); // undefined</code></pre> </div> </div> </p> <p>The above function allows you to get the value of nested properties, otherwise will return <code>undefined</code>.</p> <p><strong>UPDATE 2019-10-17:</strong></p> <p>The <a href="https://github.com/tc39/proposal-optional-chaining" rel="noreferrer">optional chaining proposal</a> reached Stage 3 on the <a href="https://tc39.es/process-document/" rel="noreferrer">ECMAScript committee process</a>, this will allow you to safely access deeply nested properties, by using the token <code>?.</code>, the new <em>optional chaining operator</em>:</p> <pre><code>const value = obj?.level1?.level2?.level3 </code></pre> <p>If any of the levels accessed is <code>null</code> or <code>undefined</code> the expression will resolve to <code>undefined</code> by itself.</p> <p>The proposal also allows you to handle method calls safely:</p> <pre><code>obj?.level1?.method(); </code></pre> <p>The above expression will produce <code>undefined</code> if <code>obj</code>, <code>obj.level1</code>, or <code>obj.level1.method</code> are <code>null</code> or <code>undefined</code>, otherwise it will call the function.</p> <p><s>You can start playing with this feature with Babel using the <a href="https://babeljs.io/docs/en/babel-plugin-proposal-optional-chaining" rel="noreferrer">optional chaining plugin</a>.</s></p> <p>Since <a href="https://babeljs.io/blog/2020/01/11/7.8.0" rel="noreferrer">Babel 7.8.0</a>, ES2020 is supported by default</p> <p>Check <a href="https://babeljs.io/repl/#?code_lz=MYewdgzgLgBCBGArGBeGBvANgUwG7cwEYAuDHfTAJlKzwIGZSAichpgX04G4AoH0SLFwBDTAFdsqOEgD8AOlZF5iysrqZ6vBIjUVC8gLbYoACxAATABQBKXkA&amp;version=7.8.4" rel="noreferrer">this example</a> on the Babel REPL.</p> <p><strong>UPDATE: December 2019 </strong></p> <p>The optional chaining proposal finally <a href="https://github.com/tc39/proposals/blob/master/finished-proposals.md" rel="noreferrer">reached Stage 4</a> in the December 2019 meeting of the TC39 committee. This means this feature will be part of the <strong>ECMAScript 2020</strong> Standard.</p>
{ "question_id": 2631001, "question_date": "2010-04-13T15:47:06.980Z", "question_score": 842, "tags": "javascript|object|properties|nested", "answer_id": 2631198, "answer_date": "2010-04-13T16:12:50.663Z", "answer_score": 692 }
Please answer the following Stack Overflow question: Title: Understanding "randomness" <p>I can't get my head around this, which is more random?</p> <pre><code>rand() </code></pre> <p><strong>OR</strong>:</p> <pre><code>rand() * rand() </code></pre> <p>I´m finding it a real brain teaser, could you help me out?</p> <hr> <p><strong>EDIT:</strong></p> <p>Intuitively I know that the mathematical answer will be that they are equally random, but I can't help but think that if you "run the random number algorithm" twice when you multiply the two together you'll create something more random than just doing it once.</p>
<h1>Just a clarification</h1> <p>Although the previous answers are right whenever you try to spot the randomness of a pseudo-random variable or its multiplication, you should be aware that while <strong>Random()</strong> is usually uniformly distributed, <strong>Random() * Random()</strong> is not. </p> <h2>Example</h2> <p>This is a <a href="http://en.wikipedia.org/wiki/Uniform_distribution_(continuous)" rel="noreferrer">uniform random distribution sample</a> simulated through a pseudo-random variable:</p> <p><img src="https://i.stack.imgur.com/M6XTU.png" alt="Histogram of Random()"> </p> <pre><code> BarChart[BinCounts[RandomReal[{0, 1}, 50000], 0.01]] </code></pre> <p>While this is the distribution you get after multiplying two random variables:</p> <p><img src="https://i.stack.imgur.com/S3Oaa.png" alt="Histogram of Random() * Random()"> </p> <pre><code> BarChart[BinCounts[Table[RandomReal[{0, 1}, 50000] * RandomReal[{0, 1}, 50000], {50000}], 0.01]] </code></pre> <p>So, both are “random”, but their distribution is very different.</p> <h2>Another example</h2> <p>While <strong>2 * Random()</strong> is uniformly distributed:</p> <p><img src="https://i.stack.imgur.com/XsFWW.png" alt="Histogram of 2 * Random()"></p> <pre><code> BarChart[BinCounts[2 * RandomReal[{0, 1}, 50000], 0.01]] </code></pre> <p><strong>Random() + Random() is not!</strong></p> <p><img src="https://i.stack.imgur.com/OyqWF.png" alt="Histogram of Random() + Random()"></p> <pre><code> BarChart[BinCounts[Table[RandomReal[{0, 1}, 50000] + RandomReal[{0, 1}, 50000], {50000}], 0.01]] </code></pre> <h2>The Central Limit Theorem</h2> <p><strong>The <a href="http://en.wikipedia.org/wiki/Central_limit_theorem" rel="noreferrer">Central Limit Theorem</a> states that the sum of <em>Random()</em> tends to a <a href="http://en.wikipedia.org/wiki/Normal_distribution" rel="noreferrer">normal distribution</a> as terms increase.</strong></p> <p>With just four terms you get:</p> <p><img src="https://i.stack.imgur.com/VWnJE.png" alt="Histogram of Random() + Random() + Random() + Random()"></p> <pre><code>BarChart[BinCounts[Table[RandomReal[{0, 1}, 50000] + RandomReal[{0, 1}, 50000] + Table[RandomReal[{0, 1}, 50000] + RandomReal[{0, 1}, 50000], {50000}], 0.01]] </code></pre> <p>And here you can see the road from a uniform to a normal distribution by adding up 1, 2, 4, 6, 10 and 20 uniformly distributed random variables:</p> <p><img src="https://i.stack.imgur.com/Apmgz.png" alt="Histogram of different numbers of random variables added"></p> <p><strong>Edit</strong></p> <p>A few credits</p> <p>Thanks to <a href="https://stackoverflow.com/users/205521/thomas-ahle">Thomas Ahle</a> for pointing out in the comments that the probability distributions shown in the last two images are known as the <a href="http://en.wikipedia.org/wiki/Irwin%E2%80%93Hall_distribution" rel="noreferrer">Irwin-Hall distribution</a> </p> <p>Thanks to <a href="https://mathematica.stackexchange.com/users/46/heike">Heike</a> for her wonderful <a href="https://mathematica.stackexchange.com/a/4155/193">torn[] function</a></p>
{ "question_id": 3956478, "question_date": "2010-10-18T03:40:52.267Z", "question_score": 842, "tags": "math|language-agnostic|random", "answer_id": 3956538, "answer_date": "2010-10-18T04:03:16.303Z", "answer_score": 1488 }
Please answer the following Stack Overflow question: Title: Rotating and spacing axis labels in ggplot2 <p>I have a plot where the x-axis is a factor whose labels are long. While probably not an ideal visualization, for now I'd like to simply rotate these labels to be vertical. I've figured this part out with the code below, but as you can see, the labels aren't totally visible.</p> <pre><code>data(diamonds) diamonds$cut &lt;- paste(&quot;Super Dee-Duper&quot;,as.character(diamonds$cut)) q &lt;- qplot(cut,carat,data=diamonds,geom=&quot;boxplot&quot;) q + opts(axis.text.x=theme_text(angle=-90)) </code></pre> <p><a href="https://i.stack.imgur.com/pcJr3l.png" rel="noreferrer"><img src="https://i.stack.imgur.com/pcJr3l.png" alt="enter image description here" /></a></p>
<p>Change the last line to </p> <pre><code>q + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) </code></pre> <p>By default, the axes are aligned at the center of the text, even when rotated. When you rotate +/- 90 degrees, you usually want it to be aligned at the edge instead:</p> <p><img src="https://learnr.files.wordpress.com/2009/03/immigration_b4.png?w=416&amp;h=415" alt="alt text"></p> <p>The image above is from <a href="http://learnr.wordpress.com/2009/03/17/ggplot2-barplots/" rel="noreferrer">this blog post</a>.</p>
{ "question_id": 1330989, "question_date": "2009-08-25T21:05:24.947Z", "question_score": 841, "tags": "r|ggplot2|label", "answer_id": 1331400, "answer_date": "2009-08-25T22:36:04.047Z", "answer_score": 1391 }
Please answer the following Stack Overflow question: Title: How do I get the day of week given a date? <p>I want to find out the following: given a date (<code>datetime</code> object), what is the corresponding day of the week?</p> <p>For instance, Sunday is the first day, Monday: second day.. and so on</p> <p>And then if the input is something like today's date.</p> <h2>Example</h2> <pre><code>&gt;&gt;&gt; today = datetime.datetime(2017, 10, 20) &gt;&gt;&gt; today.get_weekday() # what I look for </code></pre> <p>The output is maybe <code>6</code> (since it's Friday)</p>
<p>Use <code>weekday()</code>:</p> <pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; datetime.datetime.today() datetime.datetime(2012, 3, 23, 23, 24, 55, 173504) &gt;&gt;&gt; datetime.datetime.today().weekday() 4 </code></pre> <p>From the <a href="https://docs.python.org/3/library/datetime.html#datetime.datetime.weekday" rel="noreferrer">documentation</a>:</p> <blockquote> <p>Return the day of the week as an integer, where Monday is 0 and Sunday is 6.</p> </blockquote>
{ "question_id": 9847213, "question_date": "2012-03-23T22:21:18.923Z", "question_score": 841, "tags": "python|date|datetime|time|weekday", "answer_id": 9847269, "answer_date": "2012-03-23T22:26:41.767Z", "answer_score": 1312 }
Please answer the following Stack Overflow question: Title: How can I access the contents of an iframe with JavaScript/jQuery? <p>I would like to manipulate the HTML inside an iframe using jQuery.</p> <p>I thought I'd be able to do this by setting the context of the jQuery function to be the document of the iframe, something like:</p> <pre><code>$(function(){ //document ready $('some selector', frames['nameOfMyIframe'].document).doStuff() }); </code></pre> <p>However this doesn't seem to work. A bit of inspection shows me that the variables in <code>frames['nameOfMyIframe']</code> are <code>undefined</code> unless I wait a while for the iframe to load. However, when the iframe loads the variables are not accessible (I get <code>permission denied</code>-type errors).</p> <p>Does anyone know of a work-around to this?</p>
<p>I think what you are doing is subject to the <a href="http://en.wikipedia.org/wiki/Same_origin_policy" rel="noreferrer">same origin policy</a>. This should be the reason why you are getting <em>permission denied type</em> errors.</p>
{ "question_id": 364952, "question_date": "2008-12-13T07:20:34.733Z", "question_score": 841, "tags": "javascript|jquery|iframe|same-origin-policy", "answer_id": 364997, "answer_date": "2008-12-13T08:25:40.263Z", "answer_score": 402 }
Please answer the following Stack Overflow question: Title: Git asks for username every time I push <p>Whenever I try to push into my repo git asks for both <code>username &amp; password</code>. </p> <p>I have no problem in re-entering my password each time but the problem is in entering username. I use <code>https</code> to clone my repository.</p> <p>So, how can I configure git so that it doesn't asks for <code>username</code> on each <code>git push</code>.</p> <p>I am new to linux but IIRC in windows <code>git push</code> only asks for password.</p>
<p><em>Edit (by @dk14 as suggested by moderators and comments)</em></p> <p><strong>WARNING: If you use <code>credential.helper store</code> from the answer, your password is going to be stored completely unencrypted (&quot;as is&quot;) at <code>~/.git-credentials</code>. Please consult the comments section below or the answers from the &quot;Linked&quot; section, especially if your employer has zero tolerance for security issues.</strong></p> <p>Even though accepted, it doesn't answer the actual OP's question about omitting a username only (not password). For the readers with that exact problem @grawity's <a href="https://superuser.com/a/847183/367583">answer</a> might come in handy.</p> <hr /> <p><strong>Original answer (by @Alexander Zhu):</strong></p> <p>You can store your credentials using the following command</p> <pre><code>$ git config credential.helper store $ git push http://example.com/repo.git Username: &lt;type your username&gt; Password: &lt;type your password&gt; </code></pre> <p>Also I suggest you to read<br /> <a href="https://git-scm.com/docs/gitcredentials" rel="noreferrer"><code>$ git help credentials</code></a></p>
{ "question_id": 11403407, "question_date": "2012-07-09T21:25:38.203Z", "question_score": 841, "tags": "git|github", "answer_id": 17979600, "answer_date": "2013-07-31T19:49:48.157Z", "answer_score": 1145 }
Please answer the following Stack Overflow question: Title: How do I convert an existing callback API to promises? <p>I want to work with promises but I have a callback API in a format like:</p> <h3>1. DOM load or other one time event:</h3> <pre><code>window.onload; // set to callback ... window.onload = function() { }; </code></pre> <h3>2. Plain callback:</h3> <pre><code>function request(onChangeHandler) { ... } request(function() { // change happened ... }); </code></pre> <h3>3. Node style callback ("nodeback"):</h3> <pre><code>function getStuff(dat, callback) { ... } getStuff("dataParam", function(err, data) { ... }) </code></pre> <h3>4. A whole library with node style callbacks:</h3> <pre><code>API; API.one(function(err, data) { API.two(function(err, data2) { API.three(function(err, data3) { ... }); }); }); </code></pre> <h3>How do I work with the API in promises, how do I "promisify" it?</h3>
<p>Promises have state, they start as pending and can settle to:</p> <ul> <li><strong>fulfilled</strong> meaning that the computation completed successfully.</li> <li><strong>rejected</strong> meaning that the computation failed.</li> </ul> <p>Promise returning functions <a href="https://stackoverflow.com/q/21887856/1048572"><em>should never throw</em></a>, they should return rejections instead. Throwing from a promise returning function will force you to use both a <code>} catch {</code> <em>and</em> a <code>.catch</code>. People using promisified APIs do not expect promises to throw. If you're not sure how async APIs work in JS - please <a href="https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call/16825593#16825593">see this answer</a> first.</p> <h3>1. DOM load or other one time event:</h3> <p>So, creating promises generally means specifying when they settle - that means when they move to the fulfilled or rejected phase to indicate the data is available (and can be accessed with <code>.then</code>).</p> <p>With modern promise implementations that support the <code>Promise</code> constructor like native ES6 promises:</p> <pre><code>function load() { return new Promise(function(resolve, reject) { window.onload = resolve; }); } </code></pre> <p>You would then use the resulting promise like so:</p> <pre><code>load().then(function() { // Do things after onload }); </code></pre> <p>With libraries that support deferred (Let's use $q for this example here, but we'll also use jQuery later):</p> <pre><code>function load() { var d = $q.defer(); window.onload = function() { d.resolve(); }; return d.promise; } </code></pre> <p>Or with a jQuery like API, hooking on an event happening once:</p> <pre><code>function done() { var d = $.Deferred(); $("#myObject").once("click",function() { d.resolve(); }); return d.promise(); } </code></pre> <h3>2. Plain callback:</h3> <p>These APIs are rather common since well… callbacks are common in JS. Let's look at the common case of having <code>onSuccess</code> and <code>onFail</code>:</p> <pre><code>function getUserData(userId, onLoad, onFail) { … </code></pre> <p>With modern promise implementations that support the <code>Promise</code> constructor like native ES6 promises:</p> <pre><code>function getUserDataAsync(userId) { return new Promise(function(resolve, reject) { getUserData(userId, resolve, reject); }); } </code></pre> <p>With libraries that support deferred (Let's use jQuery for this example here, but we've also used $q above):</p> <pre><code>function getUserDataAsync(userId) { var d = $.Deferred(); getUserData(userId, function(res){ d.resolve(res); }, function(err){ d.reject(err); }); return d.promise(); } </code></pre> <p>jQuery also offers a <code>$.Deferred(fn)</code> form, which has the advantage of allowing us to write an expression that emulates very closely the <code>new Promise(fn)</code> form, as follows:</p> <pre><code>function getUserDataAsync(userId) { return $.Deferred(function(dfrd) { getUserData(userId, dfrd.resolve, dfrd.reject); }).promise(); } </code></pre> <p>Note: Here we exploit the fact that a jQuery deferred's <code>resolve</code> and <code>reject</code> methods are "detachable"; ie. they are bound to the <em>instance</em> of a jQuery.Deferred(). Not all libs offer this feature.</p> <h3>3. Node style callback ("nodeback"):</h3> <p>Node style callbacks (nodebacks) have a particular format where the callbacks is always the last argument and its first parameter is an error. Let's first promisify one manually:</p> <pre><code>getStuff("dataParam", function(err, data) { … </code></pre> <p>To:</p> <pre><code>function getStuffAsync(param) { return new Promise(function(resolve, reject) { getStuff(param, function(err, data) { if (err !== null) reject(err); else resolve(data); }); }); } </code></pre> <p>With deferreds you can do the following (let's use Q for this example, although Q now supports the new syntax <a href="https://stackoverflow.com/q/28687566/1048572">which you should prefer</a>): </p> <pre><code>function getStuffAsync(param) { var d = Q.defer(); getStuff(param, function(err, data) { if (err !== null) d.reject(err); else d.resolve(data); }); return d.promise; } </code></pre> <p>In general, you should not promisify things manually too much, most promise libraries that were designed with Node in mind as well as native promises in Node 8+ have a built in method for promisifying nodebacks. For example</p> <pre><code>var getStuffAsync = Promise.promisify(getStuff); // Bluebird var getStuffAsync = Q.denodeify(getStuff); // Q var getStuffAsync = util.promisify(getStuff); // Native promises, node only </code></pre> <h3>4. A whole library with node style callbacks:</h3> <p>There is no golden rule here, you promisify them one by one. However, some promise implementations allow you to do this in bulk, for example in Bluebird, converting a nodeback API to a promise API is as simple as:</p> <pre><code>Promise.promisifyAll(API); </code></pre> <p>Or with <em>native promises</em> in <strong>Node</strong>:</p> <pre><code>const { promisify } = require('util'); const promiseAPI = Object.entries(API).map(([key, v]) =&gt; ({key, fn: promisify(v)})) .reduce((o, p) =&gt; Object.assign(o, {[p.key]: p.fn}), {}); </code></pre> <p>Notes:</p> <ul> <li>Of course, when you are in a <code>.then</code> handler you do not need to promisify things. Returning a promise from a <code>.then</code> handler will resolve or reject with that promise's value. Throwing from a <code>.then</code> handler is also good practice and will reject the promise - this is the famous promise throw safety. </li> <li>In an actual <code>onload</code> case, you should use <code>addEventListener</code> rather than <code>onX</code>.</li> </ul>
{ "question_id": 22519784, "question_date": "2014-03-19T22:47:26.387Z", "question_score": 841, "tags": "javascript|node.js|callback|promise|bluebird", "answer_id": 22519785, "answer_date": "2014-03-19T22:47:26.387Z", "answer_score": 843 }
Please answer the following Stack Overflow question: Title: Functional programming vs Object Oriented programming <p>I've been mainly exposed to OO programming so far and am looking forward to learning a functional language. My questions are: </p> <ul> <li>When do you choose functional programming over object-oriented? </li> <li>What are the typical problem definitions where functional programming is a better choice?</li> </ul>
<blockquote> <p>When do you choose functional programming over object oriented?</p> </blockquote> <p>When you anticipate a different kind of software evolution:</p> <ul> <li><p>Object-oriented languages are good when you have a fixed set of <em>operations</em> on <em>things</em>, and as your code evolves, you primarily add new things. This can be accomplished by adding new classes which implement existing methods, and the existing classes are left alone.</p></li> <li><p>Functional languages are good when you have a fixed set of <em>things</em>, and as your code evolves, you primarily add new <em>operations</em> on existing things. This can be accomplished by adding new functions which compute with existing data types, and the existing functions are left alone.</p></li> </ul> <p>When evolution goes the wrong way, you have problems:</p> <ul> <li><p>Adding a new operation to an object-oriented program may require editing many class definitions to add a new method.</p></li> <li><p>Adding a new kind of thing to a functional program may require editing many function definitions to add a new case.</p></li> </ul> <p>This problem has been well known for many years; in 1998, <a href="http://www.daimi.au.dk/~madst/tool/papers/expression.txt" rel="noreferrer">Phil Wadler dubbed it the "expression problem"</a>. Although some researchers think that the expression problem can be addressed with such language features as mixins, a widely accepted solution has yet to hit the mainstream.</p> <blockquote> <p>What are the typical problem definitions where functional programming is a better choice?</p> </blockquote> <p>Functional languages excel at manipulating symbolic data in tree form. A&nbsp;favorite example is compilers, where source and intermediate languages change seldom (mostly the same <em>things</em>), but compiler writers are always adding new translations and code improvements or optimizations (new operations on things). Compilation and translation more generally are "killer apps" for functional languages.</p>
{ "question_id": 2078978, "question_date": "2010-01-16T21:35:48.817Z", "question_score": 841, "tags": "oop|functional-programming|paradigms", "answer_id": 2079678, "answer_date": "2010-01-17T01:47:29.927Z", "answer_score": 1287 }
Please answer the following Stack Overflow question: Title: jQuery Ajax File Upload <p>Can I use the following jQuery code to perform file upload using POST method of an ajax request ?</p> <pre><code>$.ajax({ type: "POST", timeout: 50000, url: url, data: dataString, success: function (data) { alert('success'); return false; } }); </code></pre> <p>If it is possible, do I need to fill <code>data</code> part? Is it the correct way? I only POST the file to the server side.</p> <p>I have been googling around, but what I found was a plugin while in my plan I do not want to use it. At least for the moment.</p>
<p>File upload is <strike>not</strike> possible through AJAX.<br> You can upload file, without refreshing page by using <code>IFrame</code>.<br> You can check further details <a href="http://www.ajaxf1.com/tutorial/ajax-file-upload-tutorial.html" rel="noreferrer">here</a>.</p> <hr> <h2>UPDATE</h2> <p>With XHR2, File upload through AJAX is supported. E.g. through <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects" rel="noreferrer"><code>FormData</code></a> object, but unfortunately it is not supported by all/old browsers.</p> <p><code>FormData</code> support starts from following desktop browsers versions.</p> <ul> <li>IE 10+</li> <li>Firefox 4.0+</li> <li>Chrome 7+</li> <li>Safari 5+</li> <li>Opera 12+</li> </ul> <p>For more detail, see <a href="https://developer.mozilla.org/en-US/docs/XMLHttpRequest/FormData" rel="noreferrer">MDN link</a>.</p>
{ "question_id": 2320069, "question_date": "2010-02-23T16:58:24.800Z", "question_score": 839, "tags": "javascript|jquery|ajax|post|file-upload", "answer_id": 2320097, "answer_date": "2010-02-23T17:03:33.960Z", "answer_score": 638 }
Please answer the following Stack Overflow question: Title: All possible array initialization syntaxes <p>What are all the array initialization syntaxes that are possible with C#?</p>
<p>These are the current declaration and initialization methods for a simple array.</p> <pre><code>string[] array = new string[2]; // creates array of length 2, default values string[] array = new string[] { "A", "B" }; // creates populated array of length 2 string[] array = { "A" , "B" }; // creates populated array of length 2 string[] array = new[] { "A", "B" }; // created populated array of length 2 </code></pre> <p>Note that other techniques of obtaining arrays exist, such as the Linq <code>ToArray()</code> extensions on <code>IEnumerable&lt;T&gt;</code>.</p> <p>Also note that in the declarations above, the first two could replace the <code>string[]</code> on the left with <code>var</code> (C# 3+), as the information on the right is enough to infer the proper type. The third line must be written as displayed, as array initialization syntax alone is not enough to satisfy the compiler's demands. The fourth could also use inference. So if you're into the whole brevity thing, the above could be written as</p> <pre><code>var array = new string[2]; // creates array of length 2, default values var array = new string[] { "A", "B" }; // creates populated array of length 2 string[] array = { "A" , "B" }; // creates populated array of length 2 var array = new[] { "A", "B" }; // created populated array of length 2 </code></pre>
{ "question_id": 5678216, "question_date": "2011-04-15T14:27:05.473Z", "question_score": 839, "tags": "c#|arrays|syntax|array-initialization", "answer_id": 5678244, "answer_date": "2011-04-15T14:29:21.300Z", "answer_score": 906 }
Please answer the following Stack Overflow question: Title: Sending an Intent to browser to open specific URL <p>I'm just wondering how to fire up an Intent to the phone's browser to open an specific URL and display it.</p> <p>Can someone please give me a hint?</p>
<p>To open a URL/website you do the following:</p> <pre><code>String url = "http://www.example.com"; Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); </code></pre> <p>Here's the <a href="http://developer.android.com/reference/android/content/Intent.html#ACTION_VIEW" rel="noreferrer">documentation of <code>Intent.ACTION_VIEW</code></a>.</p> <hr> <p>Source: <a href="http://programming.guide/java/open-url-in-androids-web-browser.html" rel="noreferrer">Opening a URL in Android's web browser from within application</a></p>
{ "question_id": 3004515, "question_date": "2010-06-09T09:21:57.657Z", "question_score": 839, "tags": "android|android-intent", "answer_id": 3004542, "answer_date": "2010-06-09T09:26:11.517Z", "answer_score": 1906 }
Please answer the following Stack Overflow question: Title: Best Practices for securing a REST API / web service <p>When designing a REST API or service are there any established best practices for dealing with security (Authentication, Authorization, Identity Management) ?</p> <p>When building a SOAP API you have WS-Security as a guide and much literature exists on the topic. I have found less information about securing REST endpoints.</p> <p>While I understand REST intentionally does not have specifications analogous to WS-* I am hoping best practices or recommended patterns have emerged.</p> <p>Any discussion or links to relevant documents would be very much appreciated. If it matters, we would be using WCF with POX/JSON serialized messages for our REST API's/Services built using v3.5 of the .NET Framework.</p>
<p>As tweakt said, Amazon S3 is a good model to work with. Their request signatures do have some features (such as incorporating a timestamp) that help guard against both accidental and malicious request replaying.</p> <p>The nice thing about HTTP Basic is that virtually all HTTP libraries support it. You will, of course, need to require SSL in this case because sending plaintext passwords over the net is almost universally a bad thing. Basic is preferable to Digest when using SSL because even if the caller already knows that credentials are required, Digest requires an extra roundtrip to exchange the nonce value. With Basic, the callers simply sends the credentials the first time.</p> <p>Once the identity of the client is established, authorization is really just an implementation problem. However, you could delegate the authorization to some other component with an existing authorization model. Again the nice thing about Basic here is your server ends up with a plaintext copy of the client's password that you can simply pass on to another component within your infrastructure as needed.</p>
{ "question_id": 7551, "question_date": "2008-08-11T05:44:42.803Z", "question_score": 839, "tags": "wcf|security|rest|authorization|rest-security", "answer_id": 7618, "answer_date": "2008-08-11T08:45:13.343Z", "answer_score": 303 }
Please answer the following Stack Overflow question: Title: How to select a radio button by default? <p>I have some radio buttons and I want one of them to be set as selected by default when the page is loaded. How can I do that?</p> <pre><code>&lt;input type="radio" name="imgsel" value="" /&gt; </code></pre>
<p>XHTML solution:</p> <pre><code>&lt;input type="radio" name="imgsel" value="" checked="checked" /&gt; </code></pre> <p>Please note, that the actual value of <code>checked</code> attribute does not actually matter; it's just a convention to assign <code>"checked"</code>. Most importantly, strings like <code>"true"</code> or <code>"false"</code> don't have any special meaning.</p> <p>If you don't aim for XHTML conformance, you can simplify the code to:</p> <pre><code>&lt;input type="radio" name="imgsel" value="" checked&gt; </code></pre>
{ "question_id": 5592345, "question_date": "2011-04-08T08:18:04.823Z", "question_score": 838, "tags": "html|radio-button", "answer_id": 5592370, "answer_date": "2011-04-08T08:19:44.323Z", "answer_score": 1330 }
Please answer the following Stack Overflow question: Title: Using boolean values in C <p>C doesn't have any built-in boolean types. What's the best way to use them in C?</p>
<p>From best to worse:</p> <p><strong>Option 1 (C99 and newer)</strong></p> <pre><code>#include &lt;stdbool.h&gt; </code></pre> <p><strong>Option 2</strong></p> <pre><code>typedef enum { false, true } bool; </code></pre> <p><strong>Option 3</strong></p> <pre><code>typedef int bool; enum { false, true }; </code></pre> <p><strong>Option 4</strong></p> <pre><code>typedef int bool; #define true 1 #define false 0 </code></pre> <h1>Explanation</h1> <ul> <li>Option 1 will work only if you use C99 (or newer) and it's the &quot;standard way&quot; to do it. Choose this if possible.</li> <li>Options 2, 3 and 4 will have in practice the same identical behavior. #2 and #3 don't use #defines though, which in my opinion is better.</li> </ul> <p>If you are undecided, go with #1!</p>
{ "question_id": 1921539, "question_date": "2009-12-17T12:46:49.130Z", "question_score": 838, "tags": "c|boolean", "answer_id": 1921557, "answer_date": "2009-12-17T12:49:28.687Z", "answer_score": 1238 }
Please answer the following Stack Overflow question: Title: Syntax for an async arrow function <p>I can mark a JavaScript function as &quot;async&quot; (i.e., returning a promise) with the <code>async</code> keyword. Like this:</p> <pre><code>async function foo() { // Do something } </code></pre> <p>What is the equivalent syntax for arrow functions?</p>
<p>Async <strong>arrow functions</strong> look like this:</p> <pre class="lang-js prettyprint-override"><code>const foo = async () =&gt; { // do something } </code></pre> <p>Async <strong>arrow functions</strong> look like this for a <em>single argument</em> passed to it:</p> <pre class="lang-js prettyprint-override"><code>const foo = async evt =&gt; { // do something with evt } </code></pre> <p>Async <strong>arrow functions</strong> look like this for <em>multiple arguments</em> passed to it:</p> <pre class="lang-js prettyprint-override"><code>const foo = async (evt, callback) =&gt; { // do something with evt // return response with callback } </code></pre> <p>The <strong>anonymous</strong> form works as well:</p> <pre class="lang-js prettyprint-override"><code>const foo = async function() { // do something } </code></pre> <p>An async function <strong>declaration</strong> looks like this:</p> <pre class="lang-js prettyprint-override"><code>async function foo() { // do something } </code></pre> <p>Using async function in a <strong>callback</strong>:</p> <pre class="lang-js prettyprint-override"><code>const foo = event.onCall(async () =&gt; { // do something }) </code></pre> <p>Using <a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await#asyncawait_class_methods" rel="noreferrer">async method</a> inside of a <strong>class</strong>:</p> <pre class="lang-js prettyprint-override"><code>async foo() { // do something } </code></pre>
{ "question_id": 42964102, "question_date": "2017-03-22T22:50:39.383Z", "question_score": 838, "tags": "javascript|promise|async-await|arrow-functions", "answer_id": 42964310, "answer_date": "2017-03-22T23:07:03.677Z", "answer_score": 1443 }
Please answer the following Stack Overflow question: Title: In JavaScript, how to conditionally add a member to an object? <p>I would like to create an object with a member added conditionally. The simple approach is:</p> <pre><code>var a = {}; if (someCondition) a.b = 5; </code></pre> <p>Now, I would like to write a more idiomatic code. I am trying:</p> <pre><code>a = { b: (someCondition? 5 : undefined) }; </code></pre> <p>But now, <code>b</code> is a member of <code>a</code> whose value is <code>undefined</code>. This is not the desired result.</p> <p>Is there a handy solution?</p> <p><strong>Update</strong></p> <p>I seek for a solution that could handle the general case with several members.</p> <pre><code>a = { b: (conditionB? 5 : undefined), c: (conditionC? 5 : undefined), d: (conditionD? 5 : undefined), e: (conditionE? 5 : undefined), f: (conditionF? 5 : undefined), g: (conditionG? 5 : undefined), }; </code></pre>
<p>In pure Javascript, I cannot think of anything more idiomatic than your first code snippet.</p> <p>If, however, using the jQuery library is not out of the question, then <a href="http://api.jquery.com/jQuery.extend/" rel="noreferrer">$.extend()</a> should meet your requirements because, as the documentation says:</p> <blockquote> <p>Undefined properties are not copied.</p> </blockquote> <p>Therefore, you can write:</p> <pre><code>var a = $.extend({}, { b: conditionB ? 5 : undefined, c: conditionC ? 5 : undefined, // and so on... }); </code></pre> <p>And obtain the results you expect (if <code>conditionB</code> is <code>false</code>, then <code>b</code> will not exist in <code>a</code>).</p>
{ "question_id": 11704267, "question_date": "2012-07-28T20:07:24.557Z", "question_score": 838, "tags": "javascript", "answer_id": 11704524, "answer_date": "2012-07-28T20:45:40.753Z", "answer_score": 139 }
Please answer the following Stack Overflow question: Title: Where is Java Installed on Mac OS X? <p>I just downloaded Java 7u17 on Mac OS 10.7.5 from <a href="http://www.java.com/en/download/mac_download.jsp?locale=en" rel="noreferrer">here</a> and then successfully installed it. In order to do some JNI programming, I need to know where Java installed on my Mac. </p> <p>I thought that inside the <code>/Library/Java/JavaVirtualMachines/</code> folder, there would be a folder called <code>1.7.0.jdk</code> or something, but then I found that the folder is empty. This was confirmed by running <code>ls /Library/Java/JavaVirtualMachines/</code> in the Terminal. I've tried searching for it to find out if it was installed somewhere else, but that doesn't seem to be turning anything up.</p> <p>Could someone please tell me where Java is installed on my Mac?</p>
<p>Use <code>/usr/libexec/java_home -v 1.8</code> command on a terminal shell to figure out where is your <strong>Java 1.8</strong> home directory</p> <p>If you just want to find out the home directory of your most recent version of Java, omit the version. e.g. <code>/usr/libexec/java_home</code></p>
{ "question_id": 15826202, "question_date": "2013-04-05T04:58:29.327Z", "question_score": 837, "tags": "java|macos", "answer_id": 15826712, "answer_date": "2013-04-05T05:40:34.220Z", "answer_score": 1584 }
Please answer the following Stack Overflow question: Title: How do I get a class instance of generic type T? <p>I have a generics class, <code>Foo&lt;T&gt;</code>. In a method of <code>Foo</code>, I want to get the class instance of type <code>T</code>, but I just can't call <code>T.class</code>.</p> <p>What is the preferred way to get around it using <code>T.class</code>?</p>
<p>The short answer is, that there is no way to find out the runtime type of generic type parameters in Java. I suggest reading the chapter about type erasure in the <a href="http://download.oracle.com/javase/tutorial/java/generics/erasure.html" rel="noreferrer">Java Tutorial</a> for more details.</p> <p>A popular solution to this is to pass the <code>Class</code> of the type parameter into the constructor of the generic type, e.g.</p> <pre><code>class Foo&lt;T&gt; { final Class&lt;T&gt; typeParameterClass; public Foo(Class&lt;T&gt; typeParameterClass) { this.typeParameterClass = typeParameterClass; } public void bar() { // you can access the typeParameterClass here and do whatever you like } } </code></pre>
{ "question_id": 3437897, "question_date": "2010-08-09T06:58:45.707Z", "question_score": 837, "tags": "java|generics", "answer_id": 3437930, "answer_date": "2010-08-09T07:03:15.970Z", "answer_score": 662 }
Please answer the following Stack Overflow question: Title: How to verify that a specific method was not called using Mockito? <p>How to verify that a method is <strong>not</strong> called on an object's dependency?</p> <p>For example:</p> <pre><code>public interface Dependency { void someMethod(); } public class Foo { public bar(final Dependency d) { ... } } </code></pre> <p>With the Foo test:</p> <pre><code>public class FooTest { @Test public void dependencyIsNotCalled() { final Foo foo = new Foo(...); final Dependency dependency = mock(Dependency.class); foo.bar(dependency); **// verify here that someMethod was not called??** } } </code></pre>
<p>Even more meaningful :</p> <pre><code>import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; // ... verify(dependency, never()).someMethod(); </code></pre> <p>The documentation of this feature is there <a href="https://static.javadoc.io/org.mockito/mockito-core/2.7.21/org/mockito/Mockito.html#4" rel="noreferrer">§4 "Verifying exact number of invocations / at least x / never"</a>, and the <code>never</code> javadoc is <a href="https://static.javadoc.io/org.mockito/mockito-core/2.7.21/org/mockito/Mockito.html#never_verification" rel="noreferrer">here</a>.</p>
{ "question_id": 12862659, "question_date": "2012-10-12T15:44:46.263Z", "question_score": 837, "tags": "java|unit-testing|junit|mockito|tdd", "answer_id": 12863072, "answer_date": "2012-10-12T16:08:03.190Z", "answer_score": 1403 }
Please answer the following Stack Overflow question: Title: Optimistic vs. Pessimistic locking <p>I understand the differences between optimistic and pessimistic locking. Now could someone explain to me when I would use either one in general?</p> <p>And does the answer to this question change depending on whether or not I'm using a stored procedure to perform the query?</p> <p>But just to check, optimistic means "don't lock the table while reading" and pessimistic means "lock the table while reading."</p>
<p><a href="http://en.wikipedia.org/wiki/Optimistic_locking" rel="noreferrer">Optimistic Locking</a> is a strategy where you read a record, take note of a version number (other methods to do this involve dates, timestamps or checksums/hashes) and check that the version hasn't changed before you write the record back. When you write the record back you filter the update on the version to make sure it's atomic. (i.e. hasn't been updated between when you check the version and write the record to the disk) and update the version in one hit.</p> <p>If the record is dirty (i.e. different version to yours) you abort the transaction and the user can re-start it.</p> <p>This strategy is most applicable to high-volume systems and three-tier architectures where you do not necessarily maintain a connection to the database for your session. In this situation the client cannot actually maintain database locks as the connections are taken from a pool and you may not be using the same connection from one access to the next.</p> <p><a href="http://en.wikipedia.org/wiki/Lock_(database)" rel="noreferrer">Pessimistic Locking</a> is when you lock the record for your exclusive use until you have finished with it. It has much better integrity than optimistic locking but requires you to be careful with your application design to avoid <a href="http://en.wikipedia.org/wiki/Deadlock" rel="noreferrer">Deadlocks</a>. To use pessimistic locking you need either a direct connection to the database (as would typically be the case in a <a href="http://en.wikipedia.org/wiki/Client-server" rel="noreferrer">two tier client server</a> application) or an externally available transaction ID that can be used independently of the connection. </p> <p>In the latter case you open the transaction with the TxID and then reconnect using that ID. The DBMS maintains the locks and allows you to pick the session back up through the TxID. This is how distributed transactions using two-phase commit protocols (such as <a href="http://www.opengroup.org/bookstore/catalog/c193.htm" rel="noreferrer">XA</a> or <a href="http://msdn.microsoft.com/en-us/library/ms687120(VS.85).aspx" rel="noreferrer">COM+ Transactions</a>) work. </p>
{ "question_id": 129329, "question_date": "2008-09-24T19:29:05.390Z", "question_score": 837, "tags": "sql-server|performance|locking|optimistic-locking|pessimistic-locking", "answer_id": 129397, "answer_date": "2008-09-24T19:40:58.670Z", "answer_score": 1120 }
Please answer the following Stack Overflow question: Title: Count(*) vs Count(1) - SQL Server <p>Just wondering if any of you people use <code>Count(1)</code> over <code>Count(*)</code> and if there is a noticeable difference in performance or if this is just a legacy habit that has been brought forward from days gone past?</p> <p>The specific database is <code>SQL Server 2005</code>.</p>
<p>There is no difference.</p> <p>Reason:</p> <blockquote> <p><a href="http://msdn.microsoft.com/en-us/library/ms175997.aspx" rel="noreferrer">Books on-line</a> says "<code>COUNT ( { [ [ ALL | DISTINCT ] expression ] | * } )</code>"</p> </blockquote> <p>"1" is a non-null expression: so it's the same as <code>COUNT(*)</code>. The optimizer recognizes it for what it is: trivial.</p> <p>The same as <code>EXISTS (SELECT * ...</code> or <code>EXISTS (SELECT 1 ...</code></p> <p>Example:</p> <pre><code>SELECT COUNT(1) FROM dbo.tab800krows SELECT COUNT(1),FKID FROM dbo.tab800krows GROUP BY FKID SELECT COUNT(*) FROM dbo.tab800krows SELECT COUNT(*),FKID FROM dbo.tab800krows GROUP BY FKID </code></pre> <p>Same IO, same plan, the works</p> <p>Edit, Aug 2011</p> <p><a href="https://dba.stackexchange.com/questions/2511/what-is-the-difference-between-select-count-and-select-countany-non-null-col/2512#2512">Similar question on DBA.SE</a>.</p> <p>Edit, Dec 2011</p> <p><code>COUNT(*)</code> is mentioned specifically in <a href="http://msdn.microsoft.com/en-us/library/ms175997.aspx" rel="noreferrer">ANSI-92</a> (look for "<code>Scalar expressions 125</code>")</p> <blockquote> <p>Case:</p> <p>a) If COUNT(*) is specified, then the result is the cardinality of T.</p> </blockquote> <p>That is, the ANSI standard recognizes it as bleeding obvious what you mean. <code>COUNT(1)</code> has been optimized out by RDBMS vendors <em>because</em> of this superstition. Otherwise it would be evaluated as per ANSI</p> <blockquote> <p>b) Otherwise, let TX be the single-column table that is the result of applying the &lt;value expression&gt; to each row of T and eliminating null values. If one or more null values are eliminated, then a completion condition is raised: warning-</p> </blockquote>
{ "question_id": 1221559, "question_date": "2009-08-03T10:15:10.700Z", "question_score": 837, "tags": "sql|sql-server|performance", "answer_id": 1221649, "answer_date": "2009-08-03T10:36:52.333Z", "answer_score": 663 }
Please answer the following Stack Overflow question: Title: Why em instead of px? <p>I heard you should define sizes and distances in your stylesheet with <code>em</code> instead of in pixels. So the question is why should I use <code>em</code> instead of <code>px</code> when defining styles in CSS? Is there a good example that illustrates this?</p>
<p>The reason I asked this question was that I forgot how to use em's as it was a while I was hacking happily in CSS. People didn't notice that I kept the question general as I wasn't talking about sizing fonts per se. I was more interested in how to define styles on <strong>any given block element</strong> on the page.</p> <p>As <a href="https://stackoverflow.com/questions/609517/why-em-instead-of-px/609541#609541">Henrik Paul</a> and others pointed out em is proportional to the font-size used in the element. It's a common practice to define sizes on block elements in px, however, sizing up fonts in browsers usually breaks this design. Resizing fonts is commonly done with the shortcut keys <kbd>Ctrl</kbd>+<kbd>+</kbd> or <kbd>Ctrl</kbd>+<kbd>-</kbd>. So a good practice is to use em's instead. </p> <h2>Using px to define the width</h2> <p>Here is an illustrating example. Say we have a div-tag that we want to turn into a stylish date box, we may have HTML-code that looks like this:</p> <pre><code>&lt;div class="date-box"&gt; &lt;p class="month"&gt;July&lt;/p&gt; &lt;p class="day"&gt;4&lt;/p&gt; &lt;/div&gt; </code></pre> <p>A simple implementation would defining the width of the <code>date-box</code> class in px:</p> <pre><code>* { margin: 0; padding: 0; } p.month { font-size: 10pt; } p.day { font-size: 24pt; font-weight: bold; } div.date-box { background-color: #DD2222; font-family: Arial, sans-serif; color: white; width: 50px; } </code></pre> <h2>The problem</h2> <p>However, if we want to size the text up in our browser the design will break. The text will also bleed outside the box which is almost the same what happens with SO's design as <a href="https://stackoverflow.com/questions/609517/why-em-instead-of-px/609543#609543">flodin</a> points out. This is because the box will remain the same size in width as it is locked to <code>50px</code>. </p> <h2>Using em instead</h2> <p>A smarter way is to define the width in ems instead:</p> <pre><code>div.date-box { background-color: #DD2222; font-family: Arial, sans-serif; color: white; width: 2.5em; } * { margin: 0; padding: 0; font-size: 10pt; } // Initial width of date-box = 10 pt x 2.5 em = 25 pt // Will also work if you used px instead of pt </code></pre> <p>That way you have a fluid design on the date-box, i.e. the box will size up together with the text in proportion to the font-size defined for the date-box. In this example, the font-size is defined in <code>*</code> as 10pt and will size up 2.5 times to that font size. So when you're sizing the fonts in the browser, the box will have 2.5 times the size of that font-size.</p>
{ "question_id": 609517, "question_date": "2009-03-04T07:08:11.910Z", "question_score": 837, "tags": "css|font-size", "answer_id": 657632, "answer_date": "2009-03-18T10:06:41.447Z", "answer_score": 108 }
Please answer the following Stack Overflow question: Title: How to 'grep' a continuous stream? <p>Is that possible to use <code>grep</code> on a continuous stream?</p> <p>What I mean is sort of a <code>tail -f &lt;file&gt;</code> command, but with <code>grep</code> on the output in order to keep only the lines that interest me.</p> <p>I've tried <code>tail -f &lt;file&gt; | grep pattern</code> but it seems that <code>grep</code> can only be executed once <code>tail</code> finishes, that is to say never.</p>
<p>Turn on <code>grep</code>'s line buffering mode when using BSD grep (FreeBSD, Mac OS X etc.)</p> <pre><code>tail -f file | grep --line-buffered my_pattern </code></pre> <p>It looks like a while ago <code>--line-buffered</code> didn't matter for GNU grep (used on pretty much any Linux) as it flushed by default (YMMV for other Unix-likes such as SmartOS, AIX or QNX). However, as of November 2020, <code>--line-buffered</code> is needed (at least with GNU grep 3.5 in openSUSE, but it seems generally needed based on comments below).</p>
{ "question_id": 7161821, "question_date": "2011-08-23T13:34:31.173Z", "question_score": 837, "tags": "linux|bash|shell|grep|tail", "answer_id": 7162898, "answer_date": "2011-08-23T14:44:59.690Z", "answer_score": 1497 }
Please answer the following Stack Overflow question: Title: How to avoid reverse engineering of an APK file <p>I am developing a <strong>payment processing app</strong> for Android, and I want to prevent a hacker from accessing any resources, assets or source code from the <a href="http://en.wikipedia.org/wiki/APK_%28file_format%29" rel="noreferrer">APK</a> file.</p> <p>If someone changes the .apk extension to .zip then they can unzip it and easily access all the app's resources and assets, and using <a href="http://code.google.com/p/dex2jar/wiki/Faq" rel="noreferrer">dex2jar</a> and a Java decompiler, they can also access the source code. It's very easy to reverse engineer an Android APK file - for more details see Stack Overflow question <em><a href="https://stackoverflow.com/questions/12732882/reverse-engineering-from-apk-to-project">Reverse engineering from an APK file to a project</a></em>.</p> <p>I have used the Proguard tool provided with the Android SDK. When I reverse engineer an APK file generated using a signed keystore and Proguard, I get obfuscated code.</p> <p>However, the names of Android components remain unchanged and some code, like key-values used in the app, remains unchanged. As per Proguard documentation the tool can't obfuscate components mentioned in the Manifest file.</p> <p>Now my questions are:</p> <ol> <li>How can I <strong>completely prevent</strong> reverse engineering of an Android APK? Is this possible?</li> <li>How can I protect all the app's resources, assets and source code so that hackers can't hack the APK file in any way?</li> <li><strong>Is there a way to make hacking more tough or even impossible?</strong> What more can I do to protect the source code in my APK file?</li> </ol>
<blockquote> <p>&nbsp;1. How can I completely avoid reverse engineering of an Android APK? Is this possible?</p> </blockquote> <p>AFAIK, there is not any trick for complete avoidance of reverse engineering.</p> <p>And also very well said by @inazaruk: <em>Whatever you do to your code, a potential attacker is able to change it in any way she or he finds it feasible</em>. You basically can't protect your application from being modified. And any protection you put in there can be disabled/removed.</p> <blockquote> <p>&nbsp;2. How can I protect all the app's resources, assets and source code so that hackers can't hack the APK file in any way?</p> </blockquote> <p>You can do different tricks to make hacking harder though. For example, use obfuscation (if it's Java code). This usually slows down reverse engineering significantly.</p> <blockquote> <p>&nbsp;3. Is there a way to make hacking more tough or even impossible? What more can I do to protect the source code in my APK file?</p> </blockquote> <p>As everyone says, and as you probably know, there's no 100% security. But the place to start for Android, that Google has built in, is ProGuard. If you have the option of including <strong>shared libraries</strong>, you can include the needed code in C++ to verify file sizes, integration, etc. If you need to add an external native library to your APK's library folder on every build, then you can use it by the below suggestion.</p> <p>Put the library in the native library path which defaults to "libs" in your project folder. If you built the native code for the <strong>'armeabi'</strong> target then put it under <strong>libs/armeabi</strong>. If it was built with <strong>armeabi-v7a</strong> then put it under <strong>libs/armeabi-v7a.</strong></p> <pre><code>&lt;project&gt;/libs/armeabi/libstuff.so </code></pre>
{ "question_id": 13854425, "question_date": "2012-12-13T06:42:14.893Z", "question_score": 837, "tags": "android|security|proguard|reverse-engineering", "answer_id": 13854693, "answer_date": "2012-12-13T07:03:12.323Z", "answer_score": 401 }
Please answer the following Stack Overflow question: Title: What's your favorite "programmer" cartoon? <p>Personally I like this one:</p> <p><img src="https://i.stack.imgur.com/ZNtvc.jpg" alt=""></p> <p>P.S. Do not hotlink the cartoon without the site's permission please. </p>
<p>Another one from <a href="http://xkcd.com/327/" rel="nofollow noreferrer">xkcd</a> <img src="https://imgs.xkcd.com/comics/exploits_of_a_mom.png" alt="Exploits of a Mom" title="Her daughter is named Help I&#39;m trapped in a driver&#39;s license factory."></p>
{ "question_id": 84556, "question_date": "2008-09-17T15:34:11.467Z", "question_score": 836, "tags": "language-agnostic", "answer_id": 84629, "answer_date": "2008-09-17T15:39:53.030Z", "answer_score": 1805 }
Please answer the following Stack Overflow question: Title: TypeError: a bytes-like object is required, not 'str' when writing to a file in Python 3 <p>I've very recently migrated to Python 3.5. This code was working properly in Python 2.7:</p> <pre><code>with open(fname, 'rb') as f: lines = [x.strip() for x in f.readlines()] for line in lines: tmp = line.strip().lower() if 'some-pattern' in tmp: continue # ... code </code></pre> <p>After upgrading to 3.5, I'm getting the:</p> <blockquote> <p>TypeError: a bytes-like object is required, not 'str'</p> </blockquote> <p>The error is on the last line (the pattern search code).</p> <p>I've tried using the <code>.decode()</code> function on either side of the statement and also tried:</p> <pre><code>if tmp.find('some-pattern') != -1: continue </code></pre> <p>- to no avail.</p> <p>I was able to resolve almost all Python 2-to-Python 3 issues quickly, but this little statement was bugging me.</p>
<p>You opened the file in binary mode:</p> <pre><code>with open(fname, 'rb') as f: </code></pre> <p>This means that all data read from the file is returned as <code>bytes</code> objects, not <code>str</code>. You cannot then use a string in a containment test:</p> <pre><code>if 'some-pattern' in tmp: continue </code></pre> <p>You'd have to use a <code>bytes</code> object to test against <code>tmp</code> instead:</p> <pre><code>if b'some-pattern' in tmp: continue </code></pre> <p>or open the file as a textfile instead by replacing the <code>'rb'</code> mode with <code>'r'</code>.</p>
{ "question_id": 33054527, "question_date": "2015-10-10T13:28:09.647Z", "question_score": 835, "tags": "python|python-3.x|string|file|byte", "answer_id": 33054552, "answer_date": "2015-10-10T13:30:57.907Z", "answer_score": 738 }
Please answer the following Stack Overflow question: Title: How can I measure the actual memory usage of an application or process? <p>How do you measure the memory usage of an application or process in Linux?</p> <p>From the blog article of <em><a href="http://virtualthreads.blogspot.com/2006/02/understanding-memory-usage-on-linux.html" rel="noreferrer">Understanding memory usage on Linux</a></em>, <code>ps</code> is not an accurate tool to use for this intent.</p> <blockquote> <p><strong>Why <code>ps</code> is &quot;wrong&quot;</strong></p> <p>Depending on how you look at it, <code>ps</code> is not reporting the real memory usage of processes. What it is really doing is showing how much real memory each process would take up <strong>if it were the only process running</strong>. Of course, a typical Linux machine has several dozen processes running at any given time, which means that the VSZ and RSS numbers reported by <code>ps</code> are almost definitely <em>wrong</em>.</p> </blockquote> <p><sub>(Note: This question is covered <a href="https://stackoverflow.com/q/63166/15161">here</a> in great detail.)</sub></p>
<p>With <code>ps</code> or similar tools you will only get the amount of memory pages allocated by that process. This number is correct, but:</p> <ul> <li><p>does not reflect the actual amount of memory used by the application, only the amount of memory reserved for it</p> </li> <li><p>can be misleading if pages are shared, for example by several threads or by using dynamically linked libraries</p> </li> </ul> <p>If you really want to know what amount of memory your application actually uses, you need to run it within a profiler. For example, <a href="https://en.wikipedia.org/wiki/Valgrind" rel="noreferrer">Valgrind</a> can give you insights about the amount of memory used, and, more importantly, about possible memory leaks in your program. The heap profiler tool of Valgrind is called 'massif':</p> <blockquote> </blockquote> <p>Massif is a heap profiler. It performs detailed heap profiling by taking regular snapshots of a program's heap. It produces a graph showing heap usage over time, including information about which parts of the program are responsible for the most memory allocations. The graph is supplemented by a text or HTML file that includes more information for determining where the most memory is being allocated. Massif runs programs about 20x slower than normal.</p> <p>As explained in the <a href="http://valgrind.org/docs/manual/ms-manual.html" rel="noreferrer">Valgrind documentation</a>, you need to run the program through Valgrind:</p> <pre><code>valgrind --tool=massif &lt;executable&gt; &lt;arguments&gt; </code></pre> <p>Massif writes a dump of memory usage snapshots (e.g. <code>massif.out.12345</code>). These provide, (1) a timeline of memory usage, (2) for each snapshot, a record of where in your program memory was allocated. A great graphical tool for analyzing these files is <a href="https://github.com/KDE/massif-visualizer" rel="noreferrer">massif-visualizer</a>. But I found <code>ms_print</code>, a simple text-based tool shipped with Valgrind, to be of great help already.</p> <p>To find memory leaks, use the (default) <code>memcheck</code> tool of valgrind.</p>
{ "question_id": 131303, "question_date": "2008-09-25T03:19:17.337Z", "question_score": 835, "tags": "linux|memory|process", "answer_id": 131346, "answer_date": "2008-09-25T03:33:27.753Z", "answer_score": 412 }
Please answer the following Stack Overflow question: Title: How to create a dialog with “Ok” and “Cancel” options <p>I am going to make a button to take an action and save the data into a database.</p> <p>Once the user clicks on the button, I want a JavaScript alert to offer “yes” and “cancel” options. If the user selects “yes”, the data will be inserted into the database, otherwise no action will be taken.</p> <p>How do I display such a dialog?</p>
<p>You’re probably looking for <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm" rel="noreferrer"><code>confirm()</code></a>, which displays a prompt and returns <code>true</code> or <code>false</code> based on what the user decided:</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>if (confirm('Are you sure you want to save this thing into the database?')) { // Save it! console.log('Thing was saved to the database.'); } else { // Do nothing! console.log('Thing was not saved to the database.'); }</code></pre> </div> </div> </p>
{ "question_id": 9334636, "question_date": "2012-02-17T20:03:21.583Z", "question_score": 835, "tags": "javascript|dialog", "answer_id": 9334684, "answer_date": "2012-02-17T20:06:59.287Z", "answer_score": 1561 }
Please answer the following Stack Overflow question: Title: Should I make HTML Anchors with 'name' or 'id'? <p>When one wants to refer to some part of a webpage with the "<code>http://example.com/#foo</code>" method, should one use</p> <pre><code>&lt;h1&gt;&lt;a name="foo"/&gt;Foo Title&lt;/h1&gt; </code></pre> <p>or</p> <pre><code>&lt;h1 id="foo"&gt;Foo Title&lt;/h1&gt; </code></pre> <p>They both work, but are they equal, or do they have semantic differences?</p>
<p>According to the HTML 5 specification, <a href="http://www.w3.org/html/wg/drafts/html/master/browsers.html#scroll-to-fragid" rel="noreferrer">5.9.8 Navigating to a fragment identifier</a>:</p> <blockquote> <p>For HTML documents (and the text/html MIME type), the following processing model must be followed to determine what the indicated part of the document is. </p> <ol> <li>Parse the URL, and let fragid be the &lt;fragment&gt; component of the URL. </li> <li>If fragid is the empty string, then the indicated part of the document is the top of the document. </li> <li>If there is an element in the DOM that has an ID exactly equal to fragid, then the first such element in tree order is the indicated part of the document; stop the algorithm here. </li> <li>If there is an <em>a</em> element in the DOM that has a name attribute whose value is exactly equal to fragid, then the first such element in tree order is the indicated part of the document; stop the algorithm here. </li> <li>Otherwise, there is no indicated part of the document. </li> </ol> </blockquote> <p><strong>So, it will look for <code>id="foo"</code>, and then will follow to <code>name="foo"</code></strong></p> <p>Edit: As pointed out by @hsivonen, in HTML5 the <code>a</code> element has no name attribute. However, the above rules still apply to other named elements.</p>
{ "question_id": 484719, "question_date": "2009-01-27T18:57:18.063Z", "question_score": 835, "tags": "html|hyperlink|fragment-identifier", "answer_id": 484781, "answer_date": "2009-01-27T19:10:54.667Z", "answer_score": 656 }
Please answer the following Stack Overflow question: Title: Android getResources().getDrawable() deprecated API 22 <p>With new android API 22 <code>getResources().getDrawable()</code> is now deprecated. Now the best approach is to use only <code>getDrawable()</code>.</p> <p>What changed? </p>
<p>You have some options to handle this deprecation the right (and <strong>future proof</strong>) way, depending on which kind of drawable you are loading:</p> <hr> <p><strong>A)</strong> drawables <em>with</em> theme attributes</p> <pre><code>ContextCompat.getDrawable(getActivity(), R.drawable.name); </code></pre> <p>You'll obtain a styled Drawable as your Activity theme instructs. This is probably what you need.</p> <hr> <p><strong>B)</strong> drawables <em>without</em> theme attributes</p> <pre><code>ResourcesCompat.getDrawable(getResources(), R.drawable.name, null); </code></pre> <p>You'll get your unstyled drawable the old way. Please note: <code>ResourcesCompat.getDrawable()</code> is <strong>not</strong> deprecated!</p> <hr> <p><strong>EXTRA)</strong> drawables <em>with</em> theme attributes from <em>another</em> theme</p> <pre><code>ResourcesCompat.getDrawable(getResources(), R.drawable.name, anotherTheme); </code></pre>
{ "question_id": 29041027, "question_date": "2015-03-13T20:05:02.260Z", "question_score": 835, "tags": "android|android-drawable|android-resources|android-5.1.1-lollipop", "answer_id": 29146895, "answer_date": "2015-03-19T14:13:35.820Z", "answer_score": 1276 }
Please answer the following Stack Overflow question: Title: How to sleep for five seconds in a batch file/cmd <p>Windows's Snipping tool can capture the screen, but sometimes I want to capture the screen after five seconds, such as taking an image being displayed by the webcam. (Run the script and smile at the camera, for example.)</p> <p>How do I sleep for 5 seconds in a batch file?</p>
<p>One hack is to (mis)use the ping command:</p> <pre><code>ping 127.0.0.1 -n 6 &gt; nul </code></pre> <p>Explanation:</p> <ul> <li><a href="https://ss64.com/nt/ping.html" rel="noreferrer"><code>ping</code></a> is a system utility that sends ping requests. <code>ping</code> is available on all versions of Windows.</li> <li><code>127.0.0.1</code> is the IP address of <a href="https://en.wikipedia.org/wiki/Localhost" rel="noreferrer">localhost</a>. This IP address is guaranteed to always resolve, be reachable, and immediately respond to pings.</li> <li><code>-n 6</code> specifies that there are to be 6 pings. There is a 1s delay between each ping, so for a 5s delay you need to send 6 pings.</li> <li><code>&gt; nul</code> suppress the output of <code>ping</code>, by <a href="https://ss64.com/nt/syntax-redirection.html" rel="noreferrer">redirecting</a> it to <a href="https://ss64.com/nt/nul.html" rel="noreferrer"><code>nul</code></a>.</li> </ul>
{ "question_id": 1672338, "question_date": "2009-11-04T08:13:31.563Z", "question_score": 834, "tags": "batch-file|timeout", "answer_id": 1672349, "answer_date": "2009-11-04T08:20:15.130Z", "answer_score": 959 }
Please answer the following Stack Overflow question: Title: Access restriction on class due to restriction on required library rt.jar? <p>I'm attempting to compile <strong>Java 1.4</strong> code that was created by <strong>IBM's</strong> <strong>WSDL2Java</strong> on <strong>Java5</strong> without recreating the stubs and saw this error in <strong>Eclipse</strong>.<br> I'm under the assumption that the stubs generated should just compile as long as the runtime <code>jars</code> are available (they are).</p> <p><code>Access restriction: The type QName is not accessible due to restriction on required library C:\Program Files\Java\jdk1.5.0_16\jre\lib\rt.jar</code></p> <p>The full class name is <code>javax.xml.namespace.QName</code></p> <blockquote> <p>What exactly is going on here? Is this a case where I am trying to refactor a pig from sausage? Am I better off recreating the stubs?</p> </blockquote>
<p>There's another solution that also works. </p> <ol> <li>Go to the <em>Build Path</em> settings in the project properties.</li> <li>Remove the <em>JRE System Library</em></li> <li>Add it back; Select <em>"Add Library"</em> and select the <em>JRE System Library</em>. The default worked for me.</li> </ol> <p>This works because you have multiple classes in different jar files. Removing and re-adding the JRE lib will make the right classes be first. If you want a fundamental solution make sure you exclude the jar files with the same classes.</p> <p>For me I have: <code>javax.xml.soap.SOAPPart</code> in three different jars: <code>axis-saaj-1.4.jar</code>, <code>saaj-api-1.3.jar</code> and the <code>rt.jar</code></p>
{ "question_id": 860187, "question_date": "2009-05-13T20:16:26.963Z", "question_score": 834, "tags": "java|eclipse|wsdl|stub|wsdl2java", "answer_id": 2174607, "answer_date": "2010-02-01T04:09:13.440Z", "answer_score": 1903 }
Please answer the following Stack Overflow question: Title: How do I delete everything in Redis? <p>I want to delete all keys. I want everything wiped out and give me a blank database. </p> <p>Is there a way to do this in <a href="http://en.wikipedia.org/wiki/Redis_%28data_store%29" rel="noreferrer">Redis</a> client?</p>
<p>With redis-cli:</p> <ul> <li><a href="http://redis.io/commands/flushdb" rel="noreferrer">FLUSHDB</a> – Deletes all keys from the connection's current database.</li> <li><a href="http://redis.io/commands/flushall" rel="noreferrer">FLUSHALL</a> – Deletes all keys from all databases.</li> </ul> <p>For example, in your shell: </p> <pre class="lang-none prettyprint-override"><code>redis-cli flushall </code></pre>
{ "question_id": 6851909, "question_date": "2011-07-27T22:15:01.410Z", "question_score": 834, "tags": "redis", "answer_id": 6851929, "answer_date": "2011-07-27T22:17:33.593Z", "answer_score": 1354 }
Please answer the following Stack Overflow question: Title: SQL multiple column ordering <p>How can I sort by multiple columns in SQL and in different directions. <code>column1</code> would be sorted descending, and <code>column2</code> ascending.</p>
<pre><code>ORDER BY column1 DESC, column2 </code></pre> <p>This sorts everything by <code>column1</code> (descending) first, and then by <code>column2</code> (ascending, which is the default) whenever the <code>column1</code> fields for two or more rows are equal.</p>
{ "question_id": 2051162, "question_date": "2010-01-12T18:02:09.567Z", "question_score": 833, "tags": "sql|sql-order-by", "answer_id": 2051176, "answer_date": "2010-01-12T18:03:53.650Z", "answer_score": 1307 }
Please answer the following Stack Overflow question: Title: LINQ equivalent of foreach for IEnumerable<T> <p>I'd like to do the equivalent of the following in LINQ, but I can't figure out how:</p> <pre><code>IEnumerable&lt;Item&gt; items = GetItems(); items.ForEach(i =&gt; i.DoStuff()); </code></pre> <p>What is the real syntax?</p>
<p>There is no ForEach extension for <code>IEnumerable</code>; only for <code>List&lt;T&gt;</code>. So you could do</p> <pre><code>items.ToList().ForEach(i =&gt; i.DoStuff()); </code></pre> <p>Alternatively, write your own ForEach extension method:</p> <pre><code>public static void ForEach&lt;T&gt;(this IEnumerable&lt;T&gt; enumeration, Action&lt;T&gt; action) { foreach(T item in enumeration) { action(item); } } </code></pre>
{ "question_id": 200574, "question_date": "2008-10-14T09:56:09.790Z", "question_score": 833, "tags": "linq|foreach|ienumerable", "answer_id": 200584, "answer_date": "2008-10-14T10:00:08.020Z", "answer_score": 1006 }
Please answer the following Stack Overflow question: Title: What is a 'workspace' in Visual Studio Code? <p>For example, Visual Studio Code talks about <a href="https://code.visualstudio.com/docs/getstarted/settings" rel="noreferrer">applying settings at the user level vs the workspace level</a>.</p> <p>On the one hand,</p> <ul> <li>it could refer to a project directory that you have opened; or</li> <li>it could refer to everything you have opened in a particular window.</li> </ul> <p>The page referenced above says</p> <blockquote> <p>&quot;Workspace: These settings are stored inside your workspace in a .vscode folder and only apply when the workspace is opened.&quot;</p> </blockquote>
<h2>What is a workspace?</h2> <p>A project that consists of one or more <a href="https://en.wikipedia.org/wiki/Root_directory" rel="noreferrer">root folders</a>, along with all of the Visual Studio Code configurations that belong to that project. These configurations include:</p> <ul> <li><a href="https://code.visualstudio.com/docs/getstarted/settings" rel="noreferrer">settings</a> that should be applied when that project is open</li> <li><a href="https://code.visualstudio.com/docs/editor/extension-gallery#_workspace-recommended-extensions" rel="noreferrer">recommended extensions</a> for the project (useful when sharing the configuration files with colleagues)</li> <li>project-specific <a href="https://code.visualstudio.com/docs/editor/multi-root-workspaces#_debugging" rel="noreferrer">debugging configurations</a></li> </ul> <h2>Why is a workspace so confusing?</h2> <p>Visual Studio Code does not use the term consistently across the UI (I've opened a <a href="https://github.com/microsoft/vscode/issues/77718" rel="noreferrer">GitHub issue</a> to address this). Sometimes it refers to a workspace as described above, and other times it refers to a workspace as a project that is specifically associated with a <code>.code-workspace</code> file.</p> <p>A good example being the <a href="https://code.visualstudio.com/docs/editor/multi-root-workspaces#_opening-workspace-files" rel="noreferrer">recent files widget</a>. Notice in the linked screenshot that all projects are grouped under the same &quot;workspaces&quot; heading, which would indicate that everything there is a workspace. But then projects with a <code>.code-workspace</code> file are given a &quot;Workspace&quot; suffix, contradicting the heading and indicating that only those files are actually workspaces.</p> <h2>What is a <code>.code-workspace</code> file?</h2> <p>It is a <a href="https://code.visualstudio.com/docs/languages/json#_json-with-comments" rel="noreferrer">JSON file with comments</a> that <a href="https://code.visualstudio.com/docs/editor/multi-root-workspaces#_settings" rel="noreferrer">stores all</a> of the configuration data mentioned above, in addition to the location of all root folders belonging to a workspace.</p> <h2>Do I need a <code>.code-workspace</code> file?</h2> <p>Only if you're creating a <a href="https://code.visualstudio.com/docs/editor/multi-root-workspaces" rel="noreferrer">multi-root workspace</a>, in which case you'll have a single <code>.code-workspace</code> file that automatically restores all of the workspace settings, in addition to all of the root folders that you want to be displayed in <a href="https://code.visualstudio.com/docs/getstarted/userinterface#_explorer" rel="noreferrer">the Explorer</a>.</p> <h2>What about single folder projects?</h2> <p>Everything is automated.</p> <p>When you open a folder in Visual Studio Code and start making modifications to the editor that are specifically related to the project you're currently working on, Visual Studio Code automatically creates a <code>.vscode</code> folder and stores it in the root of the project folder that you're working on. This <code>.vscode</code> folder has files that store the changes you made.</p> <p>For example, if you <a href="https://code.visualstudio.com/docs/getstarted/settings" rel="noreferrer">change Visual Studio Code settings</a> that you want to apply only to your current project, Visual Studio Code creates a <code>settings.json</code> file with those updates, and that file is stored in the <code>.vscode</code> folder.</p> <p>You can create a <code>.code-workspace</code> file that includes just a single root folder if you really want to. You'd then be able to either open the project folder directly, or open the workspace file. But I can't think of any reason why this would be beneficial.</p> <h2>How do I create a <code>.code-workspace</code> file?</h2> <p>Go to menu <em>File</em> → <em>Save Workspace As...</em></p> <h2>How do I add root folders to a workspace?</h2> <p>Go to menu <em>File</em> → <em>Add Folder to Workspace...</em>.</p> <h2>How do I open a workspace that is defined by a <code>.code-workspace</code> file?</h2> <p>Go to menu <em>File</em> → <em>Open Workspace...</em>.</p> <p>Alternatively, double click the <code>.code-workspace</code> file. Visual Studio Code won't open the actual file. Instead, it will read that file and open the folders that belong to that workspace.</p> <h2>How do I view the actual <code>.code-workspace</code> file?</h2> <p>Go to menu <em>File</em> → <em>Open...</em> and select the target <code>.code-workspace</code> file.</p> <p>Alternatively, open the workspace associated with that file. Then open the <a href="https://code.visualstudio.com/docs/getstarted/userinterface#_command-palette" rel="noreferrer">command palette</a>, search for, and select the <em>Workspaces: Open Workspace Configuration File</em> command.</p>
{ "question_id": 44629890, "question_date": "2017-06-19T11:53:36.503Z", "question_score": 833, "tags": "visual-studio-code", "answer_id": 57134632, "answer_date": "2019-07-21T15:36:15.233Z", "answer_score": 517 }
Please answer the following Stack Overflow question: Title: How do I prevent 'git diff' from using a pager? <p>Is there a command line switch to pass to <code>git diff</code> and other commands that use the <code>less</code> pager by default? I know these methods exist:</p> <ul> <li><code>git diff | cat</code>... removes all syntax highlighting</li> <li><code>git config --global core.pager cat</code> sets the pager in the global .gitconfig to <code>cat</code></li> <li><code>export GIT_PAGER=cat</code></li> </ul> <p>But I would prefer a command line switch.</p>
<p><code>--no-pager</code> to Git will tell it to not use a pager. Passing the option <code>-F</code> to <code>less</code> will tell it to not page if the output fits in a single screen.</p> <p>Usage:</p> <pre><code>git --no-pager diff </code></pre> <p>Other options from the comments include:</p> <pre><code># Set an evaporating environment variable to use 'cat' for your pager GIT_PAGER=cat git diff # Tells 'less' not to paginate if less than a page export LESS="-F -X $LESS" # ...then Git as usual git diff </code></pre>
{ "question_id": 2183900, "question_date": "2010-02-02T12:22:08.280Z", "question_score": 833, "tags": "git", "answer_id": 2183920, "answer_date": "2010-02-02T12:25:33.937Z", "answer_score": 916 }
Please answer the following Stack Overflow question: Title: How can I iterate over files in a given directory? <p>I need to iterate through all <code>.asm</code> files inside a given directory and do some actions on them. </p> <p>How can this be done in a efficient way?</p>
<p>Python 3.6 version of the above answer, using <a href="https://docs.python.org/3.6/library/os.html" rel="noreferrer"><code>os</code></a> - assuming that you have the directory path as a <code>str</code> object in a variable called <code>directory_in_str</code>:</p> <pre class="lang-py prettyprint-override"><code>import os directory = os.fsencode(directory_in_str) for file in os.listdir(directory): filename = os.fsdecode(file) if filename.endswith(&quot;.asm&quot;) or filename.endswith(&quot;.py&quot;): # print(os.path.join(directory, filename)) continue else: continue </code></pre> <p>Or recursively, using <a href="https://docs.python.org/3.6/library/pathlib.html" rel="noreferrer"><code>pathlib</code></a>:</p> <pre class="lang-py prettyprint-override"><code>from pathlib import Path pathlist = Path(directory_in_str).glob('**/*.asm') for path in pathlist: # because path is object not string path_in_str = str(path) # print(path_in_str) </code></pre> <ul> <li>Use <a href="https://docs.python.org/3/library/pathlib.html#pathlib.Path.rglob" rel="noreferrer"><code>rglob</code></a> to replace <code>glob('**/*.asm')</code> with <code>rglob('*.asm')</code> <ul> <li><em>This is like calling <a href="https://docs.python.org/3/library/pathlib.html#pathlib.Path.glob" rel="noreferrer"><code>Path.glob()</code></a> with <code>'**/'</code> added in front of the given relative pattern:</em></li> </ul> </li> </ul> <pre class="lang-py prettyprint-override"><code>from pathlib import Path pathlist = Path(directory_in_str).rglob('*.asm') for path in pathlist: # because path is object not string path_in_str = str(path) # print(path_in_str) </code></pre> <hr /> <p>Original answer:</p> <pre class="lang-py prettyprint-override"><code>import os for filename in os.listdir(&quot;/path/to/dir/&quot;): if filename.endswith(&quot;.asm&quot;) or filename.endswith(&quot;.py&quot;): # print(os.path.join(directory, filename)) continue else: continue </code></pre>
{ "question_id": 10377998, "question_date": "2012-04-30T02:58:01.280Z", "question_score": 832, "tags": "python|iterator|directory", "answer_id": 10378012, "answer_date": "2012-04-30T03:01:13.150Z", "answer_score": 1157 }
Please answer the following Stack Overflow question: Title: What is the purpose and use of **kwargs? <p>What are the uses for <code>**kwargs</code> in Python?</p> <p>I know you can do an <code>objects.filter</code> on a table and pass in a <code>**kwargs</code> argument.  </p> <p>Can I also do this for specifying time deltas i.e. <code>timedelta(hours = time1)</code>?</p> <p>How exactly does it work? Is it classified as 'unpacking'? Like <code>a,b=1,2</code>?</p>
<p>You can use <code>**kwargs</code> to let your functions take an arbitrary number of keyword arguments (&quot;kwargs&quot; means &quot;keyword arguments&quot;):</p> <pre><code>&gt;&gt;&gt; def print_keyword_args(**kwargs): ... # kwargs is a dict of the keyword args passed to the function ... for key, value in kwargs.iteritems(): ... print &quot;%s = %s&quot; % (key, value) ... &gt;&gt;&gt; print_keyword_args(first_name=&quot;John&quot;, last_name=&quot;Doe&quot;) first_name = John last_name = Doe </code></pre> <p>You can also use the <code>**kwargs</code> syntax when calling functions by constructing a dictionary of keyword arguments and passing it to your function:</p> <pre><code>&gt;&gt;&gt; kwargs = {'first_name': 'Bobby', 'last_name': 'Smith'} &gt;&gt;&gt; print_keyword_args(**kwargs) first_name = Bobby last_name = Smith </code></pre> <p>The <a href="http://docs.python.org/tutorial/controlflow.html#keyword-arguments" rel="noreferrer">Python Tutorial</a> contains a good explanation of how it works, along with some nice examples.</p> <h2>Python 3 update</h2> <p>For Python 3, instead of <code>iteritems()</code>, use <a href="https://docs.python.org/3/library/stdtypes.html#dict.items" rel="noreferrer"><code>items()</code></a></p>
{ "question_id": 1769403, "question_date": "2009-11-20T09:40:57.063Z", "question_score": 832, "tags": "python|keyword-argument", "answer_id": 1769475, "answer_date": "2009-11-20T09:58:18.500Z", "answer_score": 929 }
Please answer the following Stack Overflow question: Title: module.exports vs exports in Node.js <p>I've found the following contract in a Node.js module:</p> <pre><code>module.exports = exports = nano = function database_module(cfg) {...} </code></pre> <p>I wonder what's the difference between <code>module.exports</code> and <code>exports</code> and why both are used here.</p>
<p>Setting <code>module.exports</code> allows the <code>database_module</code> function to be called like a function when <code>required</code>. Simply setting <code>exports</code> wouldn't allow the function to be exported because node exports the object <code>module.exports</code> references. The following code wouldn't allow the user to call the function.</p> <h3>module.js</h3> <p><strong>The following won't work.</strong></p> <pre><code>exports = nano = function database_module(cfg) {return;} </code></pre> <p><strong>The following will work if <code>module.exports</code> is set.</strong></p> <pre><code>module.exports = exports = nano = function database_module(cfg) {return;} </code></pre> <p><strong>console</strong></p> <pre><code>var func = require('./module.js'); // the following line will **work** with module.exports func(); </code></pre> <p>Basically <strong>node.js</strong> doesn't export the object that <code>exports</code> currently references, but exports the properties of what <code>exports</code> originally references. Although <strong>Node.js</strong> does export the object <code>module.exports</code> references, allowing you to call it like a function.</p> <hr /> <h3>2nd least important reason</h3> <p>They set both <code>module.exports</code> and <code>exports</code> to ensure <code>exports</code> isn't referencing the prior exported object. By setting both you use <code>exports</code> as a shorthand and avoid potential bugs later on down the road.</p> <p>Using <code>exports.prop = true</code> instead of <code>module.exports.prop = true</code> saves characters and avoids confusion.</p>
{ "question_id": 7137397, "question_date": "2011-08-21T09:16:55.680Z", "question_score": 832, "tags": "javascript|node.js|commonjs", "answer_id": 7142924, "answer_date": "2011-08-22T03:38:53.303Z", "answer_score": 457 }
Please answer the following Stack Overflow question: Title: How to drop a table if it exists? <p>The table name is <code>Scores</code>.</p> <p>Is it correct to do the following?</p> <pre><code>IF EXISTS(SELECT * FROM dbo.Scores) DROP TABLE dbo.Scores </code></pre>
<blockquote> <p>Is it correct to do the following?</p> <pre><code>IF EXISTS(SELECT * FROM dbo.Scores) DROP TABLE dbo.Scores </code></pre> </blockquote> <p><strong>No.</strong> That will drop the table only if it contains any rows (and will raise an error if the table does not exist).</p> <p><strong>Instead, for a permanent table you can use</strong></p> <pre><code>IF OBJECT_ID('dbo.Scores', 'U') IS NOT NULL DROP TABLE dbo.Scores; </code></pre> <p><strong>Or, for a temporary table you can use</strong></p> <pre><code>IF OBJECT_ID('tempdb.dbo.#TempTableName', 'U') IS NOT NULL DROP TABLE #TempTableName; </code></pre> <p>SQL Server 2016+ has a better way, using <code>DROP TABLE IF EXISTS …</code>. See <a href="https://stackoverflow.com/a/33497857/73226">the answer by @Jovan</a>.</p>
{ "question_id": 7887011, "question_date": "2011-10-25T09:05:46.817Z", "question_score": 830, "tags": "sql-server|tsql", "answer_id": 7887033, "answer_date": "2011-10-25T09:07:20.793Z", "answer_score": 1533 }
Please answer the following Stack Overflow question: Title: Insert HTML into view from AngularJS controller <p>Is it possible to create an <strong>HTML</strong> fragment in an AngularJS controller and have this HTML shown in the view?</p> <p>This comes from a requirement to turn an inconsistent JSON blob into a nested list of <code>id: value</code> pairs. Therefore the <strong>HTML</strong> is created in the controller and I am now looking to display it.</p> <p>I have created a model property, but cannot render this in the view without it just printing the <strong>HTML</strong>.</p> <hr> <p>Update</p> <p>It appears that the problem arises from angular rendering the created HTML as a string within quotes. Will attempt to find a way around this.</p> <p>Example controller :</p> <pre><code>var SomeController = function () { this.customHtml = '&lt;ul&gt;&lt;li&gt;render me please&lt;/li&gt;&lt;/ul&gt;'; } </code></pre> <p>Example view :</p> <pre><code>&lt;div ng:bind="customHtml"&gt;&lt;/div&gt; </code></pre> <p>Gives :</p> <pre><code>&lt;div&gt; "&lt;ul&gt;&lt;li&gt;render me please&lt;/li&gt;&lt;/ul&gt;" &lt;/div&gt; </code></pre>
<p>For Angular 1.x, use <code>ng-bind-html</code> in the HTML:</p> <pre><code>&lt;div ng-bind-html=&quot;thisCanBeusedInsideNgBindHtml&quot;&gt;&lt;/div&gt; </code></pre> <p>At this point you would get a <code>attempting to use an unsafe value in a safe context</code> error so you need to either use <a href="https://docs.angularjs.org/api/ngSanitize/service/$sanitize" rel="noreferrer">ngSanitize</a> or <a href="https://docs.angularjs.org/api/ng/service/$sce" rel="noreferrer">$sce</a> to resolve that.</p> <h3>$sce</h3> <p>Use <code>$sce.trustAsHtml()</code> in the controller to convert the html string.</p> <pre><code> $scope.thisCanBeusedInsideNgBindHtml = $sce.trustAsHtml(someHtmlVar); </code></pre> <h3>ngSanitize</h3> <p>There are 2 steps:</p> <ol> <li><p>include the angular-sanitize.min.js resource, i.e.:</p> <pre><code>&lt;script src=&quot;lib/angular/angular-sanitize.min.js&quot;&gt;&lt;/script&gt; </code></pre> </li> <li><p>In a js file (controller or usually app.js), include ngSanitize, i.e.:</p> <pre><code>angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives', 'ngSanitize']) </code></pre> </li> </ol>
{ "question_id": 9381926, "question_date": "2012-02-21T17:12:12.177Z", "question_score": 830, "tags": "javascript|angularjs|escaping|html-sanitizing", "answer_id": 10971756, "answer_date": "2012-06-10T19:39:07.937Z", "answer_score": 1150 }
Please answer the following Stack Overflow question: Title: How can I get the assembly file version <p>In <code>AssemblyInfo</code> there are two assembly versions:</p> <ol> <li><code>AssemblyVersion</code>: Specify the version of the assembly being attributed.</li> <li><code>AssemblyFileVersion</code>: Instructs a compiler to use a specific version number for the Win32 file version resource. The Win32 file version is not required to be the same as the assembly's version number.</li> </ol> <p>I can get the <code>Assembly Version</code> with the following line of code:</p> <pre><code>Version version = Assembly.GetEntryAssembly().GetName().Version; </code></pre> <p>But how can I get the <code>Assembly File Version</code>?</p>
<p>See my comment above asking for clarification on what you really want. Hopefully this is it:</p> <pre><code>System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly(); System.Diagnostics.FileVersionInfo fvi = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location); string version = fvi.FileVersion; </code></pre>
{ "question_id": 909555, "question_date": "2009-05-26T08:19:03.553Z", "question_score": 830, "tags": "c#|.net|assemblies|version", "answer_id": 909583, "answer_date": "2009-05-26T08:26:47.110Z", "answer_score": 959 }
Please answer the following Stack Overflow question: Title: Make the current commit the only (initial) commit in a Git repository? <p>I currently have a local Git repository, which I push to a Github repository.</p> <p>The local repository has ~10 commits, and the Github repository is a synchronised duplicate of this.</p> <p>What I'd like to do is remove ALL the version history from the local Git repository, so the current contents of the repository appear as the only commit (and therefore older versions of files within the repository are not stored). </p> <p>I'd then like to push these changes to Github.</p> <p>I have investigated Git rebase, but this appears to be more suited to removing specific versions. Another potential solution is to delete the local repo, and create a new one - though this would probably create a lot of work!</p> <p>ETA: There are specific directories / files that are untracked - if possible I would like to maintain the untracking of these files.</p>
<p>Here's the brute-force approach. It also removes the configuration of the repository.</p> <p><strong>Note</strong>: This does NOT work if the repository has submodules! If you are using submodules, you should use e.g. <a href="https://www.atlassian.com/git/tutorials/rewriting-history/git-rebase-i" rel="noreferrer" title="interactive rebase">interactive rebase</a></p> <p>Step 1: remove all history (<strong>Make sure you have a backup, this cannot be reverted</strong>)</p> <pre><code>cat .git/config # note &lt;github-uri&gt; rm -rf .git </code></pre> <p>Step 2: reconstruct the Git repo with only the current content</p> <p>Before step 2 if you have not set up <code>init.defaultBranch</code> configuration then, please do it via <code>git config --global init.defaultBranch &lt;branch-name&gt;</code> you may choose <code>main</code> as <code>&lt;branch-name&gt;</code> in the current example</p> <pre><code>git init git add . git commit -m &quot;Initial commit&quot; </code></pre> <p>Step 3: push to GitHub.</p> <pre><code>git remote add origin &lt;github-uri&gt; git push -u --force origin main </code></pre>
{ "question_id": 9683279, "question_date": "2012-03-13T11:41:20.387Z", "question_score": 830, "tags": "git|github|git-commit", "answer_id": 9683337, "answer_date": "2012-03-13T11:44:55.310Z", "answer_score": 1103 }
Please answer the following Stack Overflow question: Title: What's the difference between unit, functional, acceptance, and integration tests? <p>What is the difference between unit, functional, acceptance, and integration testing (and any other types of tests that I failed to mention)?</p>
<p>Depending on where you look, you'll get slightly different answers. I've read about the subject a lot, and here's my distillation; again, these are slightly wooly and others may disagree.</p> <p><strong>Unit Tests</strong></p> <p>Tests the smallest unit of functionality, typically a method/function (e.g. given a class with a particular state, calling x method on the class should cause y to happen). Unit tests should be focussed on one particular feature (e.g., calling the pop method when the stack is empty should throw an <code>InvalidOperationException</code>). Everything it touches should be done in memory; this means that the test code <strong>and</strong> the code under test shouldn't:</p> <ul> <li>Call out into (non-trivial) collaborators</li> <li>Access the network </li> <li>Hit a database</li> <li>Use the file system</li> <li>Spin up a thread</li> <li>etc.</li> </ul> <p>Any kind of dependency that is slow / hard to understand / initialise / manipulate should be stubbed/mocked/whatevered using the appropriate techniques so you can focus on what the unit of code is doing, not what its dependencies do. </p> <p>In short, unit tests are as simple as possible, easy to debug, reliable (due to reduced external factors), fast to execute and help to prove that the smallest building blocks of your program function as intended before they're put together. The caveat is that, although you can prove they work perfectly in isolation, the units of code may blow up when combined which brings us to ...</p> <p><strong>Integration Tests</strong></p> <p>Integration tests build on unit tests by combining the units of code and testing that the resulting combination functions correctly. This can be either the innards of one system, or combining multiple systems together to do something useful. Also, another thing that differentiates integration tests from unit tests is the environment. Integration tests can and will use threads, access the database or do whatever is required to ensure that all of the code <strong>and</strong> the different environment changes will work correctly. </p> <p>If you've built some serialization code and unit tested its innards without touching the disk, how do you know that it'll work when you are loading and saving to disk? Maybe you forgot to flush and dispose filestreams. Maybe your file permissions are incorrect and you've tested the innards using in memory streams. The only way to find out for sure is to test it 'for real' using an environment that is closest to production.</p> <p>The main advantage is that they will find bugs that unit tests can't such as wiring bugs (e.g. an instance of class A unexpectedly receives a null instance of B) and environment bugs (it runs fine on my single-CPU machine, but my colleague's 4 core machine can't pass the tests). The main disadvantage is that integration tests touch more code, are less reliable, failures are harder to diagnose and the tests are harder to maintain.</p> <p>Also, integration tests don't necessarily prove that a complete feature works. The user may not care about the internal details of my programs, but I do!</p> <p><strong>Functional Tests</strong></p> <p>Functional tests check a particular feature for correctness by comparing the results for a given input against the specification. Functional tests don't concern themselves with intermediate results or side-effects, just the result (they don't care that after doing x, object y has state z). They are written to test part of the specification such as, "calling function Square(x) with the argument of 2 returns 4". </p> <p><strong>Acceptance Tests</strong></p> <p>Acceptance testing seems to be split into two types:</p> <p>Standard acceptance testing involves performing tests on the full system (e.g. using your web page via a web browser) to see whether the application's functionality satisfies the specification. E.g. "clicking a zoom icon should enlarge the document view by 25%." There is no real continuum of results, just a pass or fail outcome. </p> <p>The advantage is that the tests are described in plain English and ensures the software, as a whole, is feature complete. The disadvantage is that you've moved another level up the testing pyramid. Acceptance tests touch mountains of code, so tracking down a failure can be tricky. </p> <p>Also, in agile software development, user acceptance testing involves creating tests to mirror the user stories created by/for the software's customer during development. If the tests pass, it means the software should meet the customer's requirements and the stories can be considered complete. An acceptance test suite is basically an executable specification written in a domain specific language that describes the tests in the language used by the users of the system.</p> <p><strong>Conclusion</strong></p> <p>They're all complementary. Sometimes it's advantageous to focus on one type or to eschew them entirely. The main difference for me is that some of the tests look at things from a programmer's perspective, whereas others use a customer/end user focus.</p>
{ "question_id": 4904096, "question_date": "2011-02-04T23:59:14.517Z", "question_score": 830, "tags": "testing|terminology|definition", "answer_id": 4904533, "answer_date": "2011-02-05T01:32:28.327Z", "answer_score": 1392 }
Please answer the following Stack Overflow question: Title: CSS Background Opacity <p>I am using something similar to the following code: </p> <pre><code>&lt;div style="opacity:0.4; background-image:url(...);"&gt; &lt;div style="opacity:1.0;"&gt; Text &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I expected this to make the background have an opacity of 0.4 and the text to have 100% opacity. Instead they both have an opacity of 0.4. </p>
<p>Children inherit opacity. It'd be weird and inconvenient if they didn't.</p> <p>You can use a translucent PNG file for your background image, or use an RGBa (a for alpha) color for your background color.</p> <p>Example, 50% faded black background:</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-html lang-html prettyprint-override"><code>&lt;div style="background-color:rgba(0, 0, 0, 0.5);"&gt; &lt;div&gt; Text added. &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
{ "question_id": 10422949, "question_date": "2012-05-02T23:05:00.163Z", "question_score": 829, "tags": "html|css|opacity", "answer_id": 10422974, "answer_date": "2012-05-02T23:07:20.533Z", "answer_score": 1327 }
Please answer the following Stack Overflow question: Title: How do I set the figure title and axes labels font size in Matplotlib? <p>I am creating a figure in Matplotlib like this:</p> <pre><code>from matplotlib import pyplot as plt fig = plt.figure() plt.plot(data) fig.suptitle('test title') plt.xlabel('xlabel') plt.ylabel('ylabel') fig.savefig('test.jpg') </code></pre> <p>I want to specify font sizes for the figure title and the axis labels. I need all three to be different font sizes, so setting a global font size (<code>mpl.rcParams['font.size']=x</code>) is not what I want. How do I set font sizes for the figure title and the axis labels individually?</p>
<p>Functions dealing with text like <code>label</code>, <code>title</code>, etc. accept parameters same as <a href="http://matplotlib.org/users/text_props.html" rel="noreferrer"><code>matplotlib.text.Text</code></a>. For the font size you can use <code>size/fontsize</code>:</p> <pre><code>from matplotlib import pyplot as plt fig = plt.figure() plt.plot(data) fig.suptitle('test title', fontsize=20) plt.xlabel('xlabel', fontsize=18) plt.ylabel('ylabel', fontsize=16) fig.savefig('test.jpg') </code></pre> <p>For globally setting <code>title</code> and <code>label</code> sizes, <a href="http://matplotlib.org/users/customizing.html" rel="noreferrer"><code>mpl.rcParams</code></a> contains <code>axes.titlesize</code> and <code>axes.labelsize</code>. (From the page):</p> <pre><code>axes.titlesize : large # fontsize of the axes title axes.labelsize : medium # fontsize of the x any y labels </code></pre> <p>(As far as I can see, there is no way to set <code>x</code> and <code>y</code> label sizes separately.)</p> <p>And I see that <code>axes.titlesize</code> does not affect <code>suptitle</code>. I guess, you need to set that manually.</p>
{ "question_id": 12444716, "question_date": "2012-09-16T05:54:36.627Z", "question_score": 829, "tags": "python|matplotlib", "answer_id": 12444777, "answer_date": "2012-09-16T06:07:44.857Z", "answer_score": 1141 }
Please answer the following Stack Overflow question: Title: Most efficient method to groupby on an array of objects <p>What is the most efficient way to groupby objects in an array?</p> <p>For example, given this array of objects:</p> <pre><code>[ { Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" }, { Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" }, { Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15" }, { Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20" }, { Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" }, { Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30" }, { Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35" }, { Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40" } ] </code></pre> <p>I’m displaying this information in a table. I’d like to groupby different methods, but I want to sum the values.</p> <p>I’m using Underscore.js for its groupby function, which is helpful, but doesn’t do the whole trick, because I don’t want them “split up” but “merged”, more like the SQL <code>group by</code> method.</p> <p>What I’m looking for would be able to total specific values (if requested).</p> <p>So if I did groupby <code>Phase</code>, I’d want to receive:</p> <pre><code>[ { Phase: "Phase 1", Value: 50 }, { Phase: "Phase 2", Value: 130 } ] </code></pre> <p>And if I did groupy <code>Phase</code> / <code>Step</code>, I’d receive:</p> <pre><code>[ { Phase: "Phase 1", Step: "Step 1", Value: 15 }, { Phase: "Phase 1", Step: "Step 2", Value: 35 }, { Phase: "Phase 2", Step: "Step 1", Value: 55 }, { Phase: "Phase 2", Step: "Step 2", Value: 75 } ] </code></pre> <p>Is there a helpful script for this, or should I stick to using Underscore.js, and then looping through the resulting object to do the totals myself?</p>
<p>If you want to avoid external libraries, you can concisely implement a vanilla version of <code>groupBy()</code> like so:</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>var groupBy = function(xs, key) { return xs.reduce(function(rv, x) { (rv[x[key]] = rv[x[key]] || []).push(x); return rv; }, {}); }; console.log(groupBy(['one', 'two', 'three'], 'length')); // =&gt; {"3": ["one", "two"], "5": ["three"]}</code></pre> </div> </div> </p>
{ "question_id": 14446511, "question_date": "2013-01-21T20:18:24.187Z", "question_score": 829, "tags": "javascript|arrays|object|group-by|underscore.js", "answer_id": 34890276, "answer_date": "2016-01-20T02:02:24.373Z", "answer_score": 1181 }
Please answer the following Stack Overflow question: Title: Why isn't sizeof for a struct equal to the sum of sizeof of each member? <p>Why does the <code>sizeof</code> operator return a size larger for a structure than the total sizes of the structure's members?</p>
<p>This is because of padding added to satisfy alignment constraints. <a href="http://en.wikipedia.org/wiki/Data_structure_alignment" rel="noreferrer">Data structure alignment</a> impacts both performance and correctness of programs:</p> <ul> <li>Mis-aligned access might be a hard error (often <code>SIGBUS</code>).</li> <li>Mis-aligned access might be a soft error. <ul> <li>Either corrected in hardware, for a modest performance-degradation.</li> <li>Or corrected by emulation in software, for a severe performance-degradation.</li> <li>In addition, atomicity and other concurrency-guarantees might be broken, leading to subtle errors.</li> </ul></li> </ul> <p>Here's an example using typical settings for an x86 processor (all used 32 and 64 bit modes):</p> <pre><code>struct X { short s; /* 2 bytes */ /* 2 padding bytes */ int i; /* 4 bytes */ char c; /* 1 byte */ /* 3 padding bytes */ }; struct Y { int i; /* 4 bytes */ char c; /* 1 byte */ /* 1 padding byte */ short s; /* 2 bytes */ }; struct Z { int i; /* 4 bytes */ short s; /* 2 bytes */ char c; /* 1 byte */ /* 1 padding byte */ }; const int sizeX = sizeof(struct X); /* = 12 */ const int sizeY = sizeof(struct Y); /* = 8 */ const int sizeZ = sizeof(struct Z); /* = 8 */ </code></pre> <p>One can minimize the size of structures by sorting members by alignment (sorting by size suffices for that in basic types) (like structure <code>Z</code> in the example above).</p> <p>IMPORTANT NOTE: Both the C and C++ standards state that structure alignment is implementation-defined. Therefore each compiler may choose to align data differently, resulting in different and incompatible data layouts. For this reason, when dealing with libraries that will be used by different compilers, it is important to understand how the compilers align data. Some compilers have command-line settings and/or special <code>#pragma</code> statements to change the structure alignment settings.</p>
{ "question_id": 119123, "question_date": "2008-09-23T04:24:47.820Z", "question_score": 829, "tags": "c++|c|struct|sizeof|c++-faq", "answer_id": 119128, "answer_date": "2008-09-23T04:25:34.527Z", "answer_score": 763 }
Please answer the following Stack Overflow question: Title: ngFor with index as value in attribute <p>I have a simple <code>ngFor</code> loop which also keeps track of the current <code>index</code>. I want to store that <code>index</code> value in an attribute so I can print it. But I can't figure out how this works.</p> <p>I basically have this:</p> <pre><code>&lt;ul *ngFor="#item of items; #i = index" data-index="#i"&gt; &lt;li&gt;{{item}}&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>I want to store the value of <code>#i</code> in the attribute <code>data-index</code>. I tried several methods but none of them worked.</p> <p>I have a demo here: <a href="http://plnkr.co/edit/EXpOKAEIFlI9QwuRcZqp?p=preview" rel="noreferrer">http://plnkr.co/edit/EXpOKAEIFlI9QwuRcZqp?p=preview</a></p> <p>How can I store the <code>index</code> value in the <code>data-index</code> attribute?</p>
<p>I would use this syntax to set the index value into an attribute of the HTML element:</p> <h3>Angular >= 2</h3> <p>You have to use <code>let</code> to declare the value rather than <code>#</code>.</p> <pre class="lang-html prettyprint-override"><code>&lt;ul&gt; &lt;li *ngFor="let item of items; let i = index" [attr.data-index]="i"&gt; {{item}} &lt;/li&gt; &lt;/ul&gt; </code></pre> <h3>Angular = 1</h3> <pre class="lang-html prettyprint-override"><code>&lt;ul&gt; &lt;li *ngFor="#item of items; #i = index" [attr.data-index]="i"&gt; {{item}} &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Here is the updated plunkr: <a href="http://plnkr.co/edit/LiCeyKGUapS5JKkRWnUJ?p=preview" rel="noreferrer">http://plnkr.co/edit/LiCeyKGUapS5JKkRWnUJ?p=preview</a>.</p>
{ "question_id": 35405618, "question_date": "2016-02-15T09:27:57.367Z", "question_score": 828, "tags": "angular|ngfor", "answer_id": 35405648, "answer_date": "2016-02-15T09:29:22.653Z", "answer_score": 1413 }
Please answer the following Stack Overflow question: Title: How can I print a circular structure in a JSON-like format? <p>I have a big object I want to convert to JSON and send. However it has circular structure. I want to toss whatever circular references exist and send whatever can be stringified. How do I do that?</p> <p>Thanks.</p> <pre><code>var obj = { a: "foo", b: obj } </code></pre> <p>I want to stringify obj into:</p> <pre><code>{"a":"foo"} </code></pre>
<p>Use <code>JSON.stringify</code> with a custom replacer. For example:</p> <pre><code>// Demo: Circular reference var circ = {}; circ.circ = circ; // Note: cache should not be re-used by repeated calls to JSON.stringify. var cache = []; JSON.stringify(circ, (key, value) =&gt; { if (typeof value === 'object' &amp;&amp; value !== null) { // Duplicate reference found, discard key if (cache.includes(value)) return; // Store value in our collection cache.push(value); } return value; }); cache = null; // Enable garbage collection </code></pre> <p>The replacer in this example is not 100% correct (depending on your definition of "duplicate"). In the following case, a value is discarded:</p> <pre><code>var a = {b:1} var o = {}; o.one = a; o.two = a; // one and two point to the same object, but two is discarded: JSON.stringify(o, ...); </code></pre> <p>But the concept stands: Use a custom replacer, and keep track of the parsed object values.</p> <p>As a utility function written in es6:</p> <pre class="lang-js prettyprint-override"><code>// safely handles circular references JSON.safeStringify = (obj, indent = 2) =&gt; { let cache = []; const retVal = JSON.stringify( obj, (key, value) =&gt; typeof value === "object" &amp;&amp; value !== null ? cache.includes(value) ? undefined // Duplicate reference found, discard key : cache.push(value) &amp;&amp; value // Store value in our collection : value, indent ); cache = null; return retVal; }; // Example: console.log('options', JSON.safeStringify(options)) </code></pre>
{ "question_id": 11616630, "question_date": "2012-07-23T16:30:22.310Z", "question_score": 828, "tags": "javascript|json|node.js", "answer_id": 11616993, "answer_date": "2012-07-23T16:56:43.717Z", "answer_score": 722 }
Please answer the following Stack Overflow question: Title: How to get a file's extension in PHP? <p>This is a question you can read everywhere on the web with various answers:</p> <pre><code>$ext = end(explode('.', $filename)); $ext = substr(strrchr($filename, '.'), 1); $ext = substr($filename, strrpos($filename, '.') + 1); $ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $filename); $exts = split("[/\\.]", $filename); $n = count($exts)-1; $ext = $exts[$n]; </code></pre> <p>etc.</p> <p>However, there is always "the best way" and it should be on Stack Overflow.</p>
<p>People from other scripting languages always think theirs is better because they have a built-in function to do that and not PHP (I am looking at Pythonistas right now :-)).</p> <p>In fact, it does exist, but few people know it. Meet <a href="http://php.net/manual/en/function.pathinfo.php" rel="noreferrer"><code>pathinfo()</code></a>:</p> <pre><code>$ext = pathinfo($filename, PATHINFO_EXTENSION); </code></pre> <p>This is fast and built-in. <code>pathinfo()</code> can give you other information, such as canonical path, depending on the constant you pass to it.</p> <p>Remember that if you want to be able to deal with non ASCII characters, you need to set the locale first. E.G:</p> <pre><code>setlocale(LC_ALL,'en_US.UTF-8'); </code></pre> <p>Also, note this doesn't take into consideration the file content or mime-type, you only get the extension. But it's what you asked for.</p> <p>Lastly, note that this works only for a file path, not a URL resources path, which is covered using PARSE_URL.</p> <p>Enjoy</p>
{ "question_id": 173868, "question_date": "2008-10-06T11:00:02.957Z", "question_score": 828, "tags": "php|file-extension", "answer_id": 173876, "answer_date": "2008-10-06T11:03:24.493Z", "answer_score": 1912 }
Please answer the following Stack Overflow question: Title: Multi-Line Comments in Ruby? <p>How can I comment multiple lines in Ruby?</p>
<pre class="lang-ruby prettyprint-override"><code>#!/usr/bin/env ruby =begin Every body mentioned this way to have multiline comments. The =begin and =end must be at the beginning of the line or it will be a syntax error. =end puts &quot;Hello world!&quot; &lt;&lt;-DOC Also, you could create a docstring. which... DOC puts &quot;Hello world!&quot; &quot;..is kinda ugly and creates a String instance, but I know one guy with a Smalltalk background, who does this.&quot; puts &quot;Hello world!&quot; ## # most # people # do # this __END__ But all forgot there is another option. Only at the end of a file, of course. </code></pre> <ul> <li>This is how it looks (via screenshot) - otherwise it's hard to interpret how the above comments will look. <strong>Click to Zoom-in</strong>:</li> </ul> <p><a href="https://i.stack.imgur.com/AnchE.png" rel="noreferrer"><img src="https://i.stack.imgur.com/AnchE.png" alt="Comments in a text-editor" /></a></p>
{ "question_id": 2989762, "question_date": "2010-06-07T13:11:05.933Z", "question_score": 828, "tags": "ruby|comments|multiline|block-comments", "answer_id": 2991254, "answer_date": "2010-06-07T16:25:40.457Z", "answer_score": 1465 }
Please answer the following Stack Overflow question: Title: What does "connection reset by peer" mean? <p>What is the meaning of the "connection reset by peer" error on a TCP connection? Is it a fatal error or just a notification or related to the network failure?</p>
<p>It's fatal. The remote server has sent you a RST packet, which indicates an immediate dropping of the connection, rather than the usual handshake. This bypasses the normal half-closed state transition. I like <a href="http://everything2.com/title/Connection+reset+by+peer" rel="noreferrer">this description</a>:</p> <blockquote> <p>"Connection reset by peer" is the TCP/IP equivalent of slamming the phone back on the hook. It's more polite than merely not replying, leaving one hanging. But it's not the FIN-ACK expected of the truly polite TCP/IP converseur. </p> </blockquote>
{ "question_id": 1434451, "question_date": "2009-09-16T17:38:58.233Z", "question_score": 827, "tags": "sockets|tcp", "answer_id": 1434506, "answer_date": "2009-09-16T17:48:13.893Z", "answer_score": 977 }
Please answer the following Stack Overflow question: Title: Get the length of a String <p>How do you get the length of a <code>String</code>? For example, I have a variable defined like:</p> <pre><code>var test1: String = "Scott" </code></pre> <p>However, I can't seem to find a length method on the string.</p>
<p><strong>As of Swift 4+</strong></p> <p>It's just:</p> <pre><code>test1.count </code></pre> <p>for reasons.</p> <p>(Thanks to Martin R)</p> <p><strong>As of Swift 2:</strong></p> <p>With Swift 2, Apple has changed global functions to protocol extensions, extensions that match any type conforming to a protocol. Thus the new syntax is:</p> <pre><code>test1.characters.count </code></pre> <p>(Thanks to JohnDifool for the heads up)</p> <p><strong>As of Swift 1</strong></p> <p>Use the count characters method:</p> <pre><code>let unusualMenagerie = "Koala &amp;#128040;, Snail &amp;#128012;, Penguin &amp;#128039;, Dromedary &amp;#128042;" println("unusualMenagerie has \(count(unusualMenagerie)) characters") // prints "unusualMenagerie has 40 characters" </code></pre> <p>right from the Apple Swift Guide</p> <p>(note, for versions of Swift earlier than 1.2, this would be <code>countElements(unusualMenagerie)</code> instead)</p> <p>for your variable, it would be</p> <pre><code>length = count(test1) // was countElements in earlier versions of Swift </code></pre> <p>Or you can use test1.utf16count</p>
{ "question_id": 24037711, "question_date": "2014-06-04T12:40:01.927Z", "question_score": 827, "tags": "ios|swift|string|xcode|cocoa-touch", "answer_id": 24037756, "answer_date": "2014-06-04T12:41:48.953Z", "answer_score": 1353 }
Please answer the following Stack Overflow question: Title: How do I discover memory usage of my application in Android? <p>How can I find the memory used on my Android application, programmatically?</p> <p>I hope there is a way to do it. Plus, how do I get the free memory of the phone too?</p>
<p>Note that memory usage on modern operating systems like Linux is an <em>extremely</em> complicated and difficult to understand area. In fact the chances of you actually correctly interpreting whatever numbers you get is extremely low. (Pretty much every time I look at memory usage numbers with other engineers, there is always a long discussion about what they actually mean that only results in a vague conclusion.)</p> <p><strong>Note: we now have much more extensive documentation on <a href="http://developer.android.com/training/articles/memory.html" rel="noreferrer">Managing Your App's Memory</a> that covers much of the material here and is more up-to-date with the state of Android.</strong></p> <p>First thing is to probably read the last part of this article which has some discussion of how memory is managed on Android:</p> <p><a href="http://android-developers.blogspot.com/2010/02/service-api-changes-starting-with.html" rel="noreferrer">Service API changes starting with Android 2.0</a></p> <p>Now <code>ActivityManager.getMemoryInfo()</code> is our highest-level API for looking at overall memory usage. This is mostly there to help an application gauge how close the system is coming to having no more memory for background processes, thus needing to start killing needed processes like services. For pure Java applications, this should be of little use, since the Java heap limit is there in part to avoid one app from being able to stress the system to this point.</p> <p>Going lower-level, you can use the Debug API to get raw kernel-level information about memory usage: <a href="http://developer.android.com/intl/de/reference/android/os/Debug.html#getMemoryInfo" rel="noreferrer">android.os.Debug.MemoryInfo</a></p> <p>Note starting with 2.0 there is also an API, <code>ActivityManager.getProcessMemoryInfo</code>, to get this information about another process: <a href="http://developer.android.com/reference/android/app/ActivityManager.html#getProcessMemoryInfo(int[])" rel="noreferrer">ActivityManager.getProcessMemoryInfo(int[])</a></p> <p>This returns a low-level MemoryInfo structure with all of this data:</p> <pre><code> /** The proportional set size for dalvik. */ public int dalvikPss; /** The private dirty pages used by dalvik. */ public int dalvikPrivateDirty; /** The shared dirty pages used by dalvik. */ public int dalvikSharedDirty; /** The proportional set size for the native heap. */ public int nativePss; /** The private dirty pages used by the native heap. */ public int nativePrivateDirty; /** The shared dirty pages used by the native heap. */ public int nativeSharedDirty; /** The proportional set size for everything else. */ public int otherPss; /** The private dirty pages used by everything else. */ public int otherPrivateDirty; /** The shared dirty pages used by everything else. */ public int otherSharedDirty; </code></pre> <p>But as to what the difference is between <code>Pss</code>, <code>PrivateDirty</code>, and <code>SharedDirty</code>... well now the fun begins.</p> <p>A lot of memory in Android (and Linux systems in general) is actually shared across multiple processes. So how much memory a processes uses is really not clear. Add on top of that paging out to disk (let alone swap which we don't use on Android) and it is even less clear.</p> <p>Thus if you were to take all of the physical RAM actually mapped in to each process, and add up all of the processes, you would probably end up with a number much greater than the actual total RAM.</p> <p>The <code>Pss</code> number is a metric the kernel computes that takes into account memory sharing -- basically each page of RAM in a process is scaled by a ratio of the number of other processes also using that page. This way you can (in theory) add up the pss across all processes to see the total RAM they are using, and compare pss between processes to get a rough idea of their relative weight.</p> <p>The other interesting metric here is <code>PrivateDirty</code>, which is basically the amount of RAM inside the process that can not be paged to disk (it is not backed by the same data on disk), and is not shared with any other processes. Another way to look at this is the RAM that will become available to the system when that process goes away (and probably quickly subsumed into caches and other uses of it).</p> <p>That is pretty much the SDK APIs for this. However there is more you can do as a developer with your device.</p> <p>Using <code>adb</code>, there is a lot of information you can get about the memory use of a running system. A common one is the command <code>adb shell dumpsys meminfo</code> which will spit out a bunch of information about the memory use of each Java process, containing the above info as well as a variety of other things. You can also tack on the name or pid of a single process to see, for example <code>adb shell dumpsys meminfo system</code> give me the system process:</p> <pre> ** MEMINFO in pid 890 [system] ** native dalvik other total size: 10940 7047 N/A 17987 allocated: 8943 5516 N/A 14459 free: 336 1531 N/A 1867 (Pss): 4585 9282 11916 25783 (shared dirty): 2184 3596 916 6696 (priv dirty): 4504 5956 7456 17916 Objects Views: 149 ViewRoots: 4 AppContexts: 13 Activities: 0 Assets: 4 AssetManagers: 4 Local Binders: 141 Proxy Binders: 158 Death Recipients: 49 OpenSSL Sockets: 0 SQL heap: 205 dbFiles: 0 numPagers: 0 inactivePageKB: 0 activePageKB: 0 </pre> <p>The top section is the main one, where <code>size</code> is the total size in address space of a particular heap, <code>allocated</code> is the kb of actual allocations that heap thinks it has, <code>free</code> is the remaining kb free the heap has for additional allocations, and <code>pss</code> and <code>priv dirty</code> are the same as discussed before specific to pages associated with each of the heaps.</p> <p>If you just want to look at memory usage across all processes, you can use the command <code>adb shell procrank</code>. Output of this on the same system looks like:</p> <pre> PID Vss Rss Pss Uss cmdline 890 84456K 48668K 25850K 21284K system_server 1231 50748K 39088K 17587K 13792K com.android.launcher2 947 34488K 28528K 10834K 9308K com.android.wallpaper 987 26964K 26956K 8751K 7308K com.google.process.gapps 954 24300K 24296K 6249K 4824K com.android.phone 948 23020K 23016K 5864K 4748K com.android.inputmethod.latin 888 25728K 25724K 5774K 3668K zygote 977 24100K 24096K 5667K 4340K android.process.acore ... 59 336K 332K 99K 92K /system/bin/installd 60 396K 392K 93K 84K /system/bin/keystore 51 280K 276K 74K 68K /system/bin/servicemanager 54 256K 252K 69K 64K /system/bin/debuggerd </pre> <p>Here the <code>Vss</code> and <code>Rss</code> columns are basically noise (these are the straight-forward address space and RAM usage of a process, where if you add up the RAM usage across processes you get an ridiculously large number).</p> <p><code>Pss</code> is as we've seen before, and <code>Uss</code> is <code>Priv Dirty</code>.</p> <p>Interesting thing to note here: <code>Pss</code> and <code>Uss</code> are slightly (or more than slightly) different than what we saw in <code>meminfo</code>. Why is that? Well procrank uses a different kernel mechanism to collect its data than <code>meminfo</code> does, and they give slightly different results. Why is that? Honestly I haven't a clue. I believe <code>procrank</code> may be the more accurate one... but really, this just leave the point: "take any memory info you get with a grain of salt; often a very large grain."</p> <p>Finally there is the command <code>adb shell cat /proc/meminfo</code> that gives a summary of the overall memory usage of the system. There is a lot of data here, only the first few numbers worth discussing (and the remaining ones understood by few people, and my questions of those few people about them often resulting in conflicting explanations):</p> <pre> MemTotal: 395144 kB MemFree: 184936 kB Buffers: 880 kB Cached: 84104 kB SwapCached: 0 kB </pre> <p><code>MemTotal</code> is the total amount of memory available to the kernel and user space (often less than the actual physical RAM of the device, since some of that RAM is needed for the radio, DMA buffers, etc).</p> <p><code>MemFree</code> is the amount of RAM that is not being used at all. The number you see here is very high; typically on an Android system this would be only a few MB, since we try to use available memory to keep processes running</p> <p><code>Cached</code> is the RAM being used for filesystem caches and other such things. Typical systems will need to have 20MB or so for this to avoid getting into bad paging states; the Android out of memory killer is tuned for a particular system to make sure that background processes are killed before the cached RAM is consumed too much by them to result in such paging.</p>
{ "question_id": 2298208, "question_date": "2010-02-19T17:12:35.627Z", "question_score": 827, "tags": "java|android|memory|memory-management", "answer_id": 2299813, "answer_date": "2010-02-19T21:44:41.670Z", "answer_score": 1032 }
Please answer the following Stack Overflow question: Title: Pull a certain branch from the remote server <p>Say that someone created a branch <code>xyz</code>. How do I pull the branch <code>xyz</code> from the remote server (e.g. <a href="http://en.wikipedia.org/wiki/GitHub" rel="noreferrer">GitHub</a>) and merge it into an existing branch <code>xyz</code> in my local repo?</p> <p>The answer to <em><a href="https://stackoverflow.com/questions/1072261/push-and-pull-branches-in-git">Push branches to Git</a></em> gives me the error &quot;! [rejected]&quot; and mentions &quot;non fast forward&quot;.</p>
<blockquote> <p>But I get an error "! [rejected]" and something about "non fast forward"</p> </blockquote> <p>That's because Git can't merge the changes from the branches into your current master. Let's say you've checked out branch <code>master</code>, and you want to merge in the remote branch <code>other-branch</code>. When you do this:</p> <pre><code>$ git pull origin other-branch </code></pre> <p>Git is basically doing this:</p> <pre><code>$ git fetch origin other-branch &amp;&amp; git merge other-branch </code></pre> <p>That is, a <code>pull</code> is just a <code>fetch</code> followed by a <code>merge</code>. However, when <code>pull</code>-ing, Git will <em>only</em> merge <code>other-branch</code> <em>if</em> it can perform a <em>fast-forward</em> merge. A <em>fast-forward</em> merge is a merge in which the head of the branch you are trying to merge into is a <em>direct descendent</em> of the head of the branch you want to merge. For example, if you have this history tree, then merging <code>other-branch</code> would result in a fast-forward merge:</p> <pre><code>O-O-O-O-O-O ^ ^ master other-branch </code></pre> <p>However, this would <em>not</em> be a fast-forward merge:</p> <pre><code> v master O-O-O \ \-O-O-O-O ^ other-branch </code></pre> <p>To solve your problem, first <em>fetch</em> the remote branch:</p> <pre><code>$ git fetch origin other-branch </code></pre> <p>Then merge it into your current branch (I'll assume that's <code>master</code>), and fix any merge conflicts:</p> <pre><code>$ git merge origin/other-branch # Fix merge conflicts, if they occur # Add merge conflict fixes $ git commit # And commit the merge! </code></pre>
{ "question_id": 1709177, "question_date": "2009-11-10T16:18:21.753Z", "question_score": 826, "tags": "git|merge|branch|pull", "answer_id": 1710474, "answer_date": "2009-11-10T19:17:47.140Z", "answer_score": 965 }
Please answer the following Stack Overflow question: Title: Best way to find if an item is in a JavaScript array? <p>What is the best way to find if an object is in an array?</p> <p>This is the best way I know:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function include(arr, obj) { for (var i = 0; i &lt; arr.length; i++) { if (arr[i] == obj) return true; } } console.log(include([1, 2, 3, 4], 3)); // true console.log(include([1, 2, 3, 4], 6)); // undefined</code></pre> </div> </div> </p>
<p>As of ECMAScript 2016 you can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes" rel="noreferrer"><code>includes()</code></a></p> <pre><code>arr.includes(obj); </code></pre> <p>If you want to support IE or other older browsers:</p> <pre><code>function include(arr,obj) { return (arr.indexOf(obj) != -1); } </code></pre> <p>EDIT: This will not work on IE6, 7 or 8 though. The best workaround is to define it yourself if it's not present:</p> <ol> <li><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf" rel="noreferrer">Mozilla's</a> (ECMA-262) version:</p> <pre><code> if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(searchElement /*, fromIndex */) { &quot;use strict&quot;; if (this === void 0 || this === null) throw new TypeError(); var t = Object(this); var len = t.length &gt;&gt;&gt; 0; if (len === 0) return -1; var n = 0; if (arguments.length &gt; 0) { n = Number(arguments[1]); if (n !== n) n = 0; else if (n !== 0 &amp;&amp; n !== (1 / 0) &amp;&amp; n !== -(1 / 0)) n = (n &gt; 0 || -1) * Math.floor(Math.abs(n)); } if (n &gt;= len) return -1; var k = n &gt;= 0 ? n : Math.max(len - Math.abs(n), 0); for (; k &lt; len; k++) { if (k in t &amp;&amp; t[k] === searchElement) return k; } return -1; }; } </code></pre> </li> <li><p><a href="https://stackoverflow.com/questions/143847/best-way-to-find-an-item-in-a-javascript-array#144172">Daniel James</a>'s version:</p> <pre><code> if (!Array.prototype.indexOf) { Array.prototype.indexOf = function (obj, fromIndex) { if (fromIndex == null) { fromIndex = 0; } else if (fromIndex &lt; 0) { fromIndex = Math.max(0, this.length + fromIndex); } for (var i = fromIndex, j = this.length; i &lt; j; i++) { if (this[i] === obj) return i; } return -1; }; } </code></pre> </li> <li><p><a href="https://stackoverflow.com/questions/143847/best-way-to-find-an-item-in-a-javascript-array#144664">roosteronacid</a>'s version:</p> <pre><code> Array.prototype.hasObject = ( !Array.indexOf ? function (o) { var l = this.length + 1; while (l -= 1) { if (this[l - 1] === o) { return true; } } return false; } : function (o) { return (this.indexOf(o) !== -1); } ); </code></pre> </li> </ol>
{ "question_id": 143847, "question_date": "2008-09-27T15:41:12.783Z", "question_score": 826, "tags": "javascript|arrays", "answer_id": 143863, "answer_date": "2008-09-27T15:45:32.117Z", "answer_score": 761 }
Please answer the following Stack Overflow question: Title: Argparse optional positional arguments? <p>I have a script which is meant to be used like this: <code>usage: installer.py dir [-h] [-v]</code></p> <p><code>dir</code> is a positional argument which is defined like this:</p> <pre><code>parser.add_argument('dir', default=os.getcwd()) </code></pre> <p>I want the <code>dir</code> to be optional: when it's not specified it should just be <code>cwd</code>.</p> <p>Unfortunately when I don't specify the <code>dir</code> argument, I get <code>Error: Too few arguments</code>.</p>
<p>Use <a href="https://docs.python.org/3/library/argparse.html#nargs" rel="noreferrer"><code>nargs='?'</code></a> (or <code>nargs='*'</code> if you need more than one dir)</p> <pre><code>parser.add_argument('dir', nargs='?', default=os.getcwd()) </code></pre> <p>extended example:</p> <pre><code>&gt;&gt;&gt; import os, argparse &gt;&gt;&gt; parser = argparse.ArgumentParser() &gt;&gt;&gt; parser.add_argument('-v', action='store_true') _StoreTrueAction(option_strings=['-v'], dest='v', nargs=0, const=True, default=False, type=None, choices=None, help=None, metavar=None) &gt;&gt;&gt; parser.add_argument('dir', nargs='?', default=os.getcwd()) _StoreAction(option_strings=[], dest='dir', nargs='?', const=None, default='/home/vinay', type=None, choices=None, help=None, metavar=None) &gt;&gt;&gt; parser.parse_args('somedir -v'.split()) Namespace(dir='somedir', v=True) &gt;&gt;&gt; parser.parse_args('-v'.split()) Namespace(dir='/home/vinay', v=True) &gt;&gt;&gt; parser.parse_args(''.split()) Namespace(dir='/home/vinay', v=False) &gt;&gt;&gt; parser.parse_args(['somedir']) Namespace(dir='somedir', v=False) &gt;&gt;&gt; parser.parse_args('somedir -h -v'.split()) usage: [-h] [-v] [dir] positional arguments: dir optional arguments: -h, --help show this help message and exit -v </code></pre>
{ "question_id": 4480075, "question_date": "2010-12-18T20:45:35.500Z", "question_score": 826, "tags": "python|argparse", "answer_id": 4480202, "answer_date": "2010-12-18T21:15:47.263Z", "answer_score": 1055 }
Please answer the following Stack Overflow question: Title: Finding what branch a Git commit came from <p>Is there a way to find out what branch a commit comes from given its <a href="http://en.wikipedia.org/wiki/SHA-1" rel="noreferrer">SHA-1</a> hash value? </p> <p>Bonus points if you can tell me how to accomplish this using Ruby Grit.</p>
<p>While Dav is correct that the information isn't directly stored, that doesn't mean you can't ever find out. Here are a few things you can do.</p> <h1>Find branches the commit is on</h1> <pre><code>git branch -a --contains &lt;commit&gt; </code></pre> <p>This will tell you all branches which have the given commit in their history. Obviously this is less useful if the commit's already been merged.</p> <h1>Search the reflogs</h1> <p>If you are working in the repository in which the commit was made, you can search the reflogs for the line for that commit. Reflogs older than 90 days are pruned by git-gc, so if the commit's too old, you won't find it. That said, you can do this:</p> <pre><code>git reflog show --all | grep a871742 </code></pre> <p>to find commit a871742. Note that you MUST use the abbreviatd 7 first digits of the commit. The output should be something like this:</p> <pre><code>a871742 refs/heads/completion@{0}: commit (amend): mpc-completion: total rewrite </code></pre> <p>indicating that the commit was made on the branch "completion". The default output shows abbreviated commit hashes, so be sure not to search for the full hash or you won't find anything.</p> <p><code>git reflog show</code> is actually just an alias for <code>git log -g --abbrev-commit --pretty=oneline</code>, so if you want to fiddle with the output format to make different things available to grep for, that's your starting point!</p> <p>If you're not working in the repository where the commit was made, the best you can do in this case is examine the reflogs and find when the commit was first introduced to your repository; with any luck, you fetched the branch it was committed to. This is a bit more complex, because you can't walk both the commit tree and reflogs simultaneously. You'd want to parse the reflog output, examining each hash to see if it contains the desired commit or not.</p> <h1>Find a subsequent merge commit</h1> <p>This is workflow-dependent, but with good workflows, commits are made on development branches which are then merged in. You could do this:</p> <pre><code>git log --merges &lt;commit&gt;.. </code></pre> <p>to see merge commits that have the given commit as an ancestor. (If the commit was only merged once, the first one should be the merge you're after; otherwise you'll have to examine a few, I suppose.) The merge commit message should contain the branch name that was merged.</p> <p>If you want to be able to count on doing this, you may want to use the <code>--no-ff</code> option to <code>git merge</code> to force merge commit creation even in the fast-forward case. (Don't get too eager, though. That could become obfuscating if overused.) <a href="https://stackoverflow.com/questions/2850369/why-uses-git-fast-forward-merging-per-default/2850413#2850413">VonC's answer to a related question</a> helpfully elaborates on this topic.</p>
{ "question_id": 2706797, "question_date": "2010-04-25T01:23:33.343Z", "question_score": 826, "tags": "git", "answer_id": 2707110, "answer_date": "2010-04-25T04:07:22.920Z", "answer_score": 1085 }
Please answer the following Stack Overflow question: Title: Styling multi-line conditions in 'if' statements? <p>Sometimes I break long conditions in <code>if</code>s onto several lines. The most obvious way to do this is:</p> <pre><code> if (cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4'): do_something </code></pre> <p>Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.</p> <p>For the moment I'm using:</p> <pre><code> if ( cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4'): do_something </code></pre> <p>But this isn't very pretty. :-)</p> <p>Can you recommend an alternative way?</p>
<p>You don't need to use 4 spaces on your second conditional line. Maybe use:</p> <pre><code>if (cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4'): do_something </code></pre> <p>Also, don't forget the whitespace is more flexible than you might think:</p> <pre><code>if ( cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4' ): do_something if (cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4'): do_something </code></pre> <p>Both of those are fairly ugly though.</p> <p>Maybe lose the brackets (the <a href="https://www.python.org/dev/peps/pep-0008/#multiline-if-statements" rel="noreferrer">Style Guide</a> discourages this though)?</p> <pre><code>if cond1 == 'val1' and cond2 == 'val2' and \ cond3 == 'val3' and cond4 == 'val4': do_something </code></pre> <p>This at least gives you some differentiation.</p> <p>Or even:</p> <pre><code>if cond1 == 'val1' and cond2 == 'val2' and \ cond3 == 'val3' and \ cond4 == 'val4': do_something </code></pre> <p>I think I prefer:</p> <pre><code>if cond1 == 'val1' and \ cond2 == 'val2' and \ cond3 == 'val3' and \ cond4 == 'val4': do_something </code></pre> <p>Here's the <a href="https://www.python.org/dev/peps/pep-0008/#multiline-if-statements" rel="noreferrer">Style Guide</a>, which (since 2010) recommends using brackets.</p>
{ "question_id": 181530, "question_date": "2008-10-08T06:19:07.670Z", "question_score": 825, "tags": "python|coding-style|if-statement", "answer_id": 181557, "answer_date": "2008-10-08T06:34:25.267Z", "answer_score": 929 }
Please answer the following Stack Overflow question: Title: How do I check that a number is float or integer? <p>How to find that a number is <code>float</code> or <code>integer</code>?</p> <pre><code>1.25 --&gt; float 1 --&gt; integer 0 --&gt; integer 0.25 --&gt; float </code></pre>
<p>check for a remainder when dividing by 1:</p> <pre><code>function isInt(n) { return n % 1 === 0; } </code></pre> <p>If you don't know that the argument is a number you need two tests:</p> <pre><code>function isInt(n){ return Number(n) === n &amp;&amp; n % 1 === 0; } function isFloat(n){ return Number(n) === n &amp;&amp; n % 1 !== 0; } </code></pre> <p><strong>Update 2019</strong> 5 years after this answer was written, a solution was standardized in ECMA Script 2015. That solution is covered <a href="https://stackoverflow.com/a/20779354/1153227">in this answer</a>.</p>
{ "question_id": 3885817, "question_date": "2010-10-07T20:55:54.740Z", "question_score": 825, "tags": "javascript|types|numbers", "answer_id": 3886106, "answer_date": "2010-10-07T21:43:03.997Z", "answer_score": 1442 }
Please answer the following Stack Overflow question: Title: What is the shortcut to Auto import all in Android Studio? <p>Is there any way of auto importing in Android Studio. Something like the auto-import feature that <strong>Eclipse</strong> has when you use the keybinding: <strong><kbd>SHIFT</kbd> + <kbd>CTRL</kbd> + <kbd>O</kbd></strong> in <strong>Android Studio</strong>?</p> <p>Currently I have only found <kbd>CTRL</kbd> + <kbd>ALT</kbd> + <kbd>O</kbd>, which ask each individual thing, and I keep having to use the keybinding <kbd>ALT</kbd> + <kbd>ENTER</kbd> to accept.</p> <h5>Is there any way I can speed things up?</h5>
<p>For Windows/Linux, you can go to <code>File</code> -> <code>Settings</code> -> <code>Editor</code> -> <code>General</code> -> <code>Auto Import</code> -> <code>Java</code> and make the following changes:</p> <ul> <li><p>change <code>Insert imports on paste</code> value to <code>All</code></p></li> <li><p>mark<code>Add unambigious imports on the fly</code> option as checked</p></li> </ul> <p>On a Mac, do the same thing in <code>Android Studio</code> -> <code>Preferences</code></p> <p><img src="https://i.stack.imgur.com/YCJ3Z.png" alt="enter image description here"></p> <p>After this, all unambiguous imports will be added automatically.</p>
{ "question_id": 16615038, "question_date": "2013-05-17T17:45:35.850Z", "question_score": 825, "tags": "android-studio|ide|keyboard-shortcuts|auto-import", "answer_id": 16616085, "answer_date": "2013-05-17T18:56:33.083Z", "answer_score": 1305 }
Please answer the following Stack Overflow question: Title: What is a lambda (function)? <p>For a person without a comp-sci background, what is a lambda in the world of Computer Science?</p>
<p>Lambda comes from the <a href="http://en.wikipedia.org/wiki/Lambda_calculus" rel="noreferrer">Lambda Calculus</a> and refers to anonymous functions in programming.</p> <p>Why is this cool? It allows you to write quick throw away functions without naming them. It also provides a nice way to write closures. With that power you can do things like this.</p> <p><strong>Python</strong></p> <pre class="lang-py prettyprint-override"><code>def adder(x): return lambda y: x + y add5 = adder(5) add5(1) 6 </code></pre> <p>As you can see from the snippet of Python, the function adder takes in an argument x, and returns an anonymous function, or lambda, that takes another argument y. That anonymous function allows you to create functions from functions. This is a simple example, but it should convey the power lambdas and closures have.</p> <p><strong>Examples in other languages</strong></p> <p><strong>Perl 5</strong></p> <pre class="lang-pl prettyprint-override"><code>sub adder { my ($x) = @_; return sub { my ($y) = @_; $x + $y } } my $add5 = adder(5); print &amp;$add5(1) == 6 ? "ok\n" : "not ok\n"; </code></pre> <p><strong>JavaScript</strong></p> <pre class="lang-js prettyprint-override"><code>var adder = function (x) { return function (y) { return x + y; }; }; add5 = adder(5); add5(1) == 6 </code></pre> <p><strong>JavaScript (ES6)</strong></p> <pre class="lang-js prettyprint-override"><code>const adder = x =&gt; y =&gt; x + y; add5 = adder(5); add5(1) == 6 </code></pre> <p><strong>Scheme</strong></p> <pre class="lang-scheme prettyprint-override"><code>(define adder (lambda (x) (lambda (y) (+ x y)))) (define add5 (adder 5)) (add5 1) 6 </code></pre> <p><strong><a href="http://msdn.microsoft.com/en-us/library/0yw3tz5k%28v=vs.110%29.aspx" rel="noreferrer">C# 3.5 or higher</a></strong></p> <pre class="lang-cs prettyprint-override"><code>Func&lt;int, Func&lt;int, int&gt;&gt; adder = (int x) =&gt; (int y) =&gt; x + y; // `int` declarations optional Func&lt;int, int&gt; add5 = adder(5); var add6 = adder(6); // Using implicit typing Debug.Assert(add5(1) == 6); Debug.Assert(add6(-1) == 5); // Closure example int yEnclosed = 1; Func&lt;int, int&gt; addWithClosure = (x) =&gt; x + yEnclosed; Debug.Assert(addWithClosure(2) == 3); </code></pre> <p><strong>Swift</strong></p> <pre class="lang-swift prettyprint-override"><code>func adder(x: Int) -&gt; (Int) -&gt; Int{ return { y in x + y } } let add5 = adder(5) add5(1) 6 </code></pre> <p><strong>PHP</strong></p> <pre class="lang-php prettyprint-override"><code>$a = 1; $b = 2; $lambda = fn () =&gt; $a + $b; echo $lambda(); </code></pre> <p><strong>Haskell</strong></p> <pre><code>(\x y -&gt; x + y) </code></pre> <p><strong>Java</strong> see <a href="https://stackoverflow.com/questions/36233477/lambda-expression-in-java-1-8/36233545#36233545">this post</a></p> <pre class="lang-java prettyprint-override"><code>// The following is an example of Predicate : // a functional interface that takes an argument // and returns a boolean primitive type. Predicate&lt;Integer&gt; pred = x -&gt; x % 2 == 0; // Tests if the parameter is even. boolean result = pred.test(4); // true </code></pre> <p><strong>Lua</strong></p> <pre class="lang-lua prettyprint-override"><code>adder = function(x) return function(y) return x + y end end add5 = adder(5) add5(1) == 6 -- true </code></pre> <p><strong>Kotlin</strong></p> <pre class="lang-kotlin prettyprint-override"><code>val pred = { x: Int -&gt; x % 2 == 0 } val result = pred(4) // true </code></pre> <p><strong>Ruby</strong></p> <p>Ruby is slightly different in that you cannot call a lambda using the exact same syntax as calling a function, but it still has lambdas.</p> <pre class="lang-ruby prettyprint-override"><code>def adder(x) lambda { |y| x + y } end add5 = adder(5) add5[1] == 6 </code></pre> <p>Ruby being Ruby, there is a shorthand for lambdas, so you can define <code>adder</code> this way:</p> <pre><code>def adder(x) -&gt; y { x + y } end </code></pre> <p><strong>R</strong></p> <pre class="lang-r prettyprint-override"><code>adder &lt;- function(x) { function(y) x + y } add5 &lt;- adder(5) add5(1) #&gt; [1] 6 </code></pre>
{ "question_id": 16501, "question_date": "2008-08-19T16:20:37.650Z", "question_score": 825, "tags": "lambda|language-agnostic|computer-science|terminology|theory", "answer_id": 16509, "answer_date": "2008-08-19T16:27:22.643Z", "answer_score": 1180 }
Please answer the following Stack Overflow question: Title: Direct casting vs 'as' operator? <p>Consider the following code:</p> <pre><code>void Handler(object o, EventArgs e) { // I swear o is a string string s = (string)o; // 1 //-OR- string s = o as string; // 2 // -OR- string s = o.ToString(); // 3 } </code></pre> <p>What is the difference between the three types of casting (okay, the 3rd one is not a casting, but you get the intent). Which one should be preferred?</p>
<pre><code>string s = (string)o; // 1 </code></pre> <p>Throws <a href="https://msdn.microsoft.com/en-us/library/system.invalidcastexception" rel="noreferrer">InvalidCastException</a> if <code>o</code> is not a <code>string</code>. Otherwise, assigns <code>o</code> to <code>s</code>, even if <code>o</code> is <code>null</code>.</p> <pre><code>string s = o as string; // 2 </code></pre> <p>Assigns <code>null</code> to <code>s</code> if <code>o</code> is not a <code>string</code> or if <code>o</code> is <code>null</code>. For this reason, you cannot use it with value types (the operator could never return <code>null</code> in that case). Otherwise, assigns <code>o</code> to <code>s</code>.</p> <pre><code>string s = o.ToString(); // 3 </code></pre> <p>Causes a <a href="https://msdn.microsoft.com/en-us/library/system.nullreferenceexception" rel="noreferrer">NullReferenceException</a> if <code>o</code> is <code>null</code>. Assigns whatever <code>o.ToString()</code> returns to <code>s</code>, no matter what type <code>o</code> is.</p> <hr> <p>Use 1 for most conversions - it's simple and straightforward. I tend to almost never use 2 since if something is not the right type, I usually expect an exception to occur. I have only seen a need for this return-null type of functionality with badly designed libraries which use error codes (e.g. return null = error, instead of using exceptions).</p> <p>3 is not a cast and is just a method invocation. Use it for when you need the string representation of a non-string object.</p>
{ "question_id": 132445, "question_date": "2008-09-25T10:09:18.537Z", "question_score": 825, "tags": "c#|casting", "answer_id": 132467, "answer_date": "2008-09-25T10:16:26.240Z", "answer_score": 959 }
Please answer the following Stack Overflow question: Title: How do I add a library project to Android Studio? <p>How do I add a library project (such as Sherlock ABS) to <a href="https://en.wikipedia.org/wiki/Android_Studio">Android Studio</a>? </p> <p>(Not to the old ADT Eclipse-based bundle, but to the new <a href="https://en.wikipedia.org/wiki/Android_Studio">Android Studio</a>.)</p>
<p><strong>Update for Android Studio 1.0</strong></p> <p>Since Android Studio 1.0 was released (and a lot of versions between v1.0 and one of the firsts from the time of my previous answer) some things has changed.</p> <p>My description is focused on adding external library project by hand via Gradle files (for better understanding the process). If you want to add a library via Android Studio creator just check <a href="https://stackoverflow.com/a/16634680/2021293">the answer</a> below with visual guide (there are some differences between Android Studio 1.0 and those from screenshots, but the process is very similar).</p> <p>Before you start adding a library to your project by hand, consider adding the external dependency. It won’t mess in your project structure. Almost every well-known Android library is available in a <a href="http://en.wikipedia.org/wiki/Apache_Maven" rel="noreferrer">Maven</a> repository and its installation takes only one line of code in the <code>app/build.gradle</code> file:</p> <pre><code>dependencies { compile 'com.jakewharton:butterknife:6.0.0' } </code></pre> <p><strong>Adding the library</strong></p> <p>Here is the full process of adding external Android library to our project:</p> <ol> <li>Create a new project via Android Studio creator. I named it <em>HelloWorld</em>.</li> <li>Here is the original project structure created by Android Studio:</li> </ol> <blockquote> <pre><code>HelloWorld/ app/ - build.gradle // local Gradle configuration (for app only) ... - build.gradle // Global Gradle configuration (for whole project) - settings.gradle - gradle.properties ... </code></pre> </blockquote> <ol start="3"> <li>In the root directory (<code>HelloWorld/</code>), create new folder: <code>/libs</code> in which we’ll place our external libraries (this step is not required - only for keeping a cleaner project structure).</li> <li>Paste your library in the newly created <code>/libs</code> folder. In this example I used <a href="https://github.com/astuetz/PagerSlidingTabStrip" rel="noreferrer">PagerSlidingTabStrip library</a> (just download ZIP from GitHub, rename library directory to „PagerSlidingTabStrip" and copy it). Here is the new structure of our project:</li> </ol> <blockquote> <pre><code>HelloWorld/ app/ - build.gradle // Local Gradle configuration (for app only) ... libs/ PagerSlidingTabStrip/ - build.gradle // Local Gradle configuration (for library only) - build.gradle // Global Gradle configuration (for whole project) - settings.gradle - gradle.properties ... </code></pre> </blockquote> <ol start="5"> <li><p>Edit settings.gradle by adding your library to <code>include</code>. If you use a custom path like I did, you have also to define the project directory for our library. A whole settings.gradle should look like below:</p> <pre><code>include ':app', ':PagerSlidingTabStrip' project(':PagerSlidingTabStrip').projectDir = new File('libs/PagerSlidingTabStrip') </code></pre></li> </ol> <p>5.1 If you face "Default Configuration" error, then try this instead of step 5,</p> <pre><code> include ':app' include ':libs:PagerSlidingTabStrip' </code></pre> <ol start="6"> <li><p>In <code>app/build.gradle</code> add our library project as an dependency:</p> <pre><code>dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:21.0.3' compile project(":PagerSlidingTabStrip") } </code></pre></li> </ol> <p>6.1. If you followed step 5.1, then follow this instead of 6,</p> <pre><code> dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:21.0.3' compile project(":libs:PagerSlidingTabStrip") } </code></pre> <ol start="7"> <li><p>If your library project doesn’t have <code>build.gradle</code> file you have to create it manually. Here is example of that file:</p> <pre><code> apply plugin: 'com.android.library' dependencies { compile 'com.android.support:support-v4:21.0.3' } android { compileSdkVersion 21 buildToolsVersion "21.1.2" defaultConfig { minSdkVersion 14 targetSdkVersion 21 } sourceSets { main { manifest.srcFile 'AndroidManifest.xml' java.srcDirs = ['src'] res.srcDirs = ['res'] } } } </code></pre></li> <li><p>Additionally you can create a global configuration for your project which will contain SDK versions and build tools version for every module to keep consistency. Just edit <code>gradle.properties</code> file and add lines:</p> <pre><code>ANDROID_BUILD_MIN_SDK_VERSION=14 ANDROID_BUILD_TARGET_SDK_VERSION=21 ANDROID_BUILD_TOOLS_VERSION=21.1.3 ANDROID_BUILD_SDK_VERSION=21 </code></pre> <p>Now you can use it in your <code>build.gradle</code> files (in app and libraries modules) like below:</p> <pre><code>//... android { compileSdkVersion Integer.parseInt(project.ANDROID_BUILD_SDK_VERSION) buildToolsVersion project.ANDROID_BUILD_TOOLS_VERSION defaultConfig { minSdkVersion Integer.parseInt(project.ANDROID_BUILD_MIN_SDK_VERSION) targetSdkVersion Integer.parseInt(project.ANDROID_BUILD_TARGET_SDK_VERSION) } } //... </code></pre></li> <li><p>That’s all. Just click‚ synchronise the project with the Gradle’ icon <img src="https://i.stack.imgur.com/QH01w.png" alt="synchronise with Gradle">. Your library should be available in your project.</p></li> </ol> <p><em><a href="http://www.youtube.com/watch?v=LCJAgPkpmR0" rel="noreferrer">Google I/O 2013 - The New Android SDK Build System </a></em> is a great presentation about building Android apps with Gradle Build System: As Xavier Ducrohet said:</p> <blockquote> <p>Android Studio is all about editing, and debugging and profiling. It's not about building any more.</p> </blockquote> <p>At the beginning it may be little bit confusing (especially for those, who works with <a href="http://en.wikipedia.org/wiki/Eclipse_%28software%29" rel="noreferrer">Eclipse</a> and have never seen the ant - like me ;) ), but at the end Gradle gives us some great opportunities and it worth to learn this build system.</p>
{ "question_id": 16588064, "question_date": "2013-05-16T12:55:25.277Z", "question_score": 824, "tags": "android|android-studio|android-library", "answer_id": 16639227, "answer_date": "2013-05-19T20:35:15.657Z", "answer_score": 729 }
Please answer the following Stack Overflow question: Title: How to get the last day of the month? <p>Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?</p> <p>If the standard library doesn't support that, does the dateutil package support this?</p>
<p><a href="https://docs.python.org/library/calendar.html#calendar.monthrange" rel="noreferrer"><code>calendar.monthrange</code></a> provides this information:</p> <blockquote> <p>calendar.<b>monthrange</b>(year, month)<br>     Returns weekday of first day of the month and number of days in month, for the specified <em>year</em> and <em>month</em>.</p> </blockquote> <pre><code>&gt;&gt;&gt; import calendar &gt;&gt;&gt; calendar.monthrange(2002, 1) (1, 31) &gt;&gt;&gt; calendar.monthrange(2008, 2) # leap years are handled correctly (4, 29) &gt;&gt;&gt; calendar.monthrange(2100, 2) # years divisible by 100 but not 400 aren't leap years (0, 28) </code></pre> <p>so:</p> <pre><code>calendar.monthrange(year, month)[1] </code></pre> <p>seems like the simplest way to go.</p>
{ "question_id": 42950, "question_date": "2008-09-04T00:54:44.533Z", "question_score": 824, "tags": "python|date", "answer_id": 43663, "answer_date": "2008-09-04T12:44:12.970Z", "answer_score": 1386 }
Please answer the following Stack Overflow question: Title: How can I pull/push from multiple remote locations? <p><strong>The short:</strong> is there a way to have a git repo push to and pull from a list of remote repos (rather than a single "origin")?</p> <p><strong>The long:</strong> I often have a situation when I'm developing an app in multiple computers, with different connectivity – say a laptop while on transit, a computer "A" while I'm in a certain location, and another computer "B" while on another. Also, the laptop might have connectivity with only either "A" or "B", and sometimes both.</p> <p>What I would like to is for git to always "pull" from and "push" to all the computers it can currently connect to, so it's easier to jump from one machine to the other and continue working seamlessly.</p>
<p>You can configure multiple remote repositories with the <code>git remote</code> command:</p> <pre><code>git remote add alt alt-machine:/path/to/repo </code></pre> <p>To fetch from all the configured remotes and update tracking branches, but not merge into <code>HEAD</code>, do:</p> <pre><code>git remote update </code></pre> <p>If it's not currently connected to one of the remotes, it will take time out or throw an error, and go on to the next. You'll have to manually merge from the fetched repositories, or <code>cherry-pick</code>, depending on how you want to organize collecting changes.</p> <p>To fetch the master branch from alt and pull it into your current head, do:</p> <pre><code>git pull alt master </code></pre> <p>So in fact <code>git pull</code> is almost shorthand for <code>git pull origin HEAD</code> (actually it looks in the config file to determine this, but you get the idea).</p> <p>For pushing updates, you have to do that to each repo manually.<br> A push was, I think, designed with the central-repository workflow in mind.</p>
{ "question_id": 849308, "question_date": "2009-05-11T18:07:37.580Z", "question_score": 824, "tags": "git", "answer_id": 849960, "answer_date": "2009-05-11T20:34:26.233Z", "answer_score": 559 }
Please answer the following Stack Overflow question: Title: How to change the font size on a matplotlib plot <p>How does one change the font size for all elements (ticks, labels, title) on a matplotlib plot?</p> <p>I know how to change the tick label sizes, this is done with:</p> <pre><code>import matplotlib matplotlib.rc('xtick', labelsize=20) matplotlib.rc('ytick', labelsize=20) </code></pre> <p>But how does one change the rest?</p>
<p>From the <a href="http://matplotlib.sourceforge.net/api/matplotlib_configuration_api.html#matplotlib.rc" rel="noreferrer">matplotlib documentation</a>,</p> <pre><code>font = {'family' : 'normal', 'weight' : 'bold', 'size' : 22} matplotlib.rc('font', **font) </code></pre> <p>This sets the font of all items to the font specified by the kwargs object, <code>font</code>.</p> <p>Alternatively, you could also use the <code>rcParams</code> <code>update</code> method as suggested in <a href="https://stackoverflow.com/a/6441839/605121">this answer</a>:</p> <pre><code>matplotlib.rcParams.update({'font.size': 22}) </code></pre> <p>or</p> <pre><code>import matplotlib.pyplot as plt plt.rcParams.update({'font.size': 22}) </code></pre> <p>You can find a full list of available properties on the <a href="https://matplotlib.org/stable/tutorials/introductory/customizing.html" rel="noreferrer">Customizing matplotlib page</a>.</p>
{ "question_id": 3899980, "question_date": "2010-10-10T10:43:27.170Z", "question_score": 823, "tags": "python|matplotlib|font-size", "answer_id": 3900167, "answer_date": "2010-10-10T11:49:11.063Z", "answer_score": 1010 }
Please answer the following Stack Overflow question: Title: How to subtract days from a plain Date? <p>Is there an easy way of taking a olain JavaScript <code>Date</code> (e.g. today) and going back X days?</p> <p>So, for example, if I want to calculate the date 5 days before today.</p>
<p>Try something like this:</p> <pre><code> var d = new Date(); d.setDate(d.getDate()-5); </code></pre> <p>Note that this modifies the date object and returns the time value of the updated date.</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>var d = new Date(); document.write('Today is: ' + d.toLocaleString()); d.setDate(d.getDate() - 5); document.write('&lt;br&gt;5 days ago was: ' + d.toLocaleString());</code></pre> </div> </div> </p>
{ "question_id": 1296358, "question_date": "2009-08-18T20:37:56.273Z", "question_score": 823, "tags": "javascript|date", "answer_id": 1296374, "answer_date": "2009-08-18T20:41:06.987Z", "answer_score": 1303 }