input_text
stringlengths
115
13.8k
output_text
stringlengths
24
15k
metadata
dict
Please answer the following Stack Overflow question: Title: .Net Data structures: ArrayList, List, HashTable, Dictionary, SortedList, SortedDictionary -- Speed, memory, and when to use each? <p>.NET has a lot of complex data structures. Unfortunately, some of them are quite similar and I'm not always sure when to use one and when to use another. Most of my C# and VB books talk about them to a certain extent, but they never really go into any real detail.</p> <p>What's the difference between Array, ArrayList, List, Hashtable, Dictionary, SortedList, and SortedDictionary?</p> <p>Which ones are enumerable (IList -- can do 'foreach' loops)? Which ones use key/value pairs (IDict)?</p> <p>What about memory footprint? Insertion speed? Retrieval speed?</p> <p>Are there any other data structures worth mentioning?</p> <p>I'm still searching for more details on memory usage and speed (Big-O notation)</p>
<p>Off the top of my head:</p> <ul> <li><p><code>Array</code>* - represents an old-school memory array - kind of like a alias for a normal <code>type[]</code> array. Can enumerate. Can't grow automatically. I would assume very fast insert and retrival speed.</p></li> <li><p><code>ArrayList</code> - automatically growing array. Adds more overhead. Can enum., probably slower than a normal array but still pretty fast. These are used a lot in .NET</p></li> <li><p><code>List</code> - one of my favs - can be used with generics, so you can have a strongly typed array, e.g. <code>List&lt;string&gt;</code>. Other than that, acts very much like <code>ArrayList</code></p></li> <li><p><code>Hashtable</code> - plain old hashtable. O(1) to O(n) worst case. Can enumerate the value and keys properties, and do key/val pairs</p></li> <li><p><code>Dictionary</code> - same as above only strongly typed via generics, such as <code>Dictionary&lt;string, string&gt;</code></p></li> <li><p><code>SortedList</code> - a sorted generic list. Slowed on insertion since it has to figure out where to put things. Can enum., probably the same on retrieval since it doesn't have to resort, but deletion will be slower than a plain old list.</p></li> </ul> <p>I tend to use <code>List</code> and <code>Dictionary</code> all the time - once you start using them strongly typed with generics, its really hard to go back to the standard non-generic ones.</p> <p>There are lots of other data structures too - there's <code>KeyValuePair</code> which you can use to do some interesting things, there's a <code>SortedDictionary</code> which can be useful as well.</p>
{ "question_id": 128636, "question_date": "2008-09-24T17:47:27.897Z", "question_score": 222, "tags": "c#|.net|vb.net|arrays|data-structures", "answer_id": 128754, "answer_date": "2008-09-24T18:00:25.870Z", "answer_score": 166 }
Please answer the following Stack Overflow question: Title: How to retrieve inserted id after inserting row in SQLite using Python? <p>How to retrieve inserted id after inserting row in SQLite using Python? I have table like this:</p> <pre><code>id INT AUTOINCREMENT PRIMARY KEY, username VARCHAR(50), password VARCHAR(50) </code></pre> <p>I insert a new row with example data <code>username="test"</code> and <code>password="test"</code>. How do I retrieve the generated id in a transaction safe way? This is for a website solution, where two people may be inserting data at the same time. I know I can get the last read row, but I don't think that is transaction safe. Can somebody give me some advice?</p>
<p>You could use <a href="http://www.python.org/dev/peps/pep-0249/" rel="noreferrer">cursor.lastrowid</a> (see &quot;Optional DB API Extensions&quot;):</p> <pre class="lang-py prettyprint-override"><code>connection=sqlite3.connect(':memory:') cursor=connection.cursor() cursor.execute('''CREATE TABLE foo (id integer primary key autoincrement , username varchar(50), password varchar(50))''') cursor.execute('INSERT INTO foo (username,password) VALUES (?,?)', ('test','test')) print(cursor.lastrowid) # 1 </code></pre> <p>If two people are inserting at the same time, as long as they are using different <code>cursor</code>s, <code>cursor.lastrowid</code> will return the <code>id</code> for the last row that <code>cursor</code> inserted:</p> <pre class="lang-py prettyprint-override"><code>cursor.execute('INSERT INTO foo (username,password) VALUES (?,?)', ('blah','blah')) cursor2=connection.cursor() cursor2.execute('INSERT INTO foo (username,password) VALUES (?,?)', ('blah','blah')) print(cursor2.lastrowid) # 3 print(cursor.lastrowid) # 2 cursor.execute('INSERT INTO foo (id,username,password) VALUES (?,?,?)', (100,'blah','blah')) print(cursor.lastrowid) # 100 </code></pre> <p>Note that <code>lastrowid</code> returns <code>None</code> when you insert more than one row at a time with <code>executemany</code>:</p> <pre class="lang-py prettyprint-override"><code>cursor.executemany('INSERT INTO foo (username,password) VALUES (?,?)', (('baz','bar'),('bing','bop'))) print(cursor.lastrowid) # None </code></pre>
{ "question_id": 6242756, "question_date": "2011-06-05T11:59:13.783Z", "question_score": 222, "tags": "python|sqlite", "answer_id": 6242813, "answer_date": "2011-06-05T12:09:47.520Z", "answer_score": 324 }
Please answer the following Stack Overflow question: Title: .NET Core DI, ways of passing parameters to constructor <p>Having the following service constructor</p> <pre><code>public class Service : IService { public Service(IOtherService service1, IAnotherOne service2, string arg) { } } </code></pre> <p>What are the choices of passing the parameters using .NET Core IOC mechanism</p> <pre><code>services.AddSingleton&lt;IOtherService , OtherService&gt;(); services.AddSingleton&lt;IAnotherOne , AnotherOne&gt;(); services.AddSingleton&lt;IService&gt;(x =&gt; new Service( services.BuildServiceProvider().GetService&lt;IOtherService&gt;(), services.BuildServiceProvider().GetService&lt;IAnotherOne &gt;(), &quot;&quot;)); </code></pre> <p>Is there any other way ?</p>
<p>The expression parameter (<em>x</em> in this case) of the factory delegate is an <code>IServiceProvider</code>.</p> <p>Use that to resolve the dependencies:</p> <pre><code>_serviceCollection.AddSingleton&lt;IService&gt;(x =&gt; new Service(x.GetRequiredService&lt;IOtherService&gt;(), x.GetRequiredService&lt;IAnotherOne&gt;(), &quot;&quot;)); </code></pre> <p>The factory delegate is a delayed invocation. Whenever the type is to be resolved, it will pass the completed provider as the delegate parameter.</p>
{ "question_id": 53884417, "question_date": "2018-12-21T11:57:06.187Z", "question_score": 222, "tags": "c#|asp.net-core|dependency-injection|.net-core|ioc-container", "answer_id": 53884452, "answer_date": "2018-12-21T11:59:29.653Z", "answer_score": 265 }
Please answer the following Stack Overflow question: Title: How to specify more spaces for the delimiter using cut? <p>Is there any way to specify a field delimiter for more spaces with the cut command? (like " "+) ? For example: In the following string, I like to reach value '3744', what field delimiter I should say?</p> <pre><code>$ps axu | grep jboss jboss 2574 0.0 0.0 3744 1092 ? S Aug17 0:00 /bin/sh /usr/java/jboss/bin/run.sh -c example.com -b 0.0.0.0 </code></pre> <p><code>cut -d' '</code> is not what I want, for it's only for one single space. <code>awk</code> is not what I am looking for either, but how to do with 'cut'?</p> <p>thanks. </p>
<p>Actually <code>awk</code> is <em>exactly</em> the tool you should be looking into:</p> <pre><code>ps axu | grep '[j]boss' | awk '{print $5}' </code></pre> <p>or you can ditch the <code>grep</code> altogether since <code>awk</code> knows about regular expressions:</p> <pre><code>ps axu | awk '/[j]boss/ {print $5}' </code></pre> <p>But if, for some bizarre reason, you really <em>can't</em> use <code>awk</code>, there are other simpler things you can do, like collapse all whitespace to a single space first:</p> <pre><code>ps axu | grep '[j]boss' | sed 's/\s\s*/ /g' | cut -d' ' -f5 </code></pre> <hr> <p>That <code>grep</code> trick, by the way, is a neat way to only get the <code>jboss</code> processes and not the <code>grep jboss</code> one (ditto for the <code>awk</code> variant as well).</p> <p>The <code>grep</code> process will have a literal <code>grep [j]boss</code> in its process command so will not be caught by the <code>grep</code> itself, which is looking for the character class <code>[j]</code> followed by <code>boss</code>.</p> <p>This is a nifty way to avoid the <code>| grep xyz | grep -v grep</code> paradigm that some people use.</p>
{ "question_id": 7142735, "question_date": "2011-08-22T02:52:03.540Z", "question_score": 222, "tags": "linux|delimiter|cut", "answer_id": 7142771, "answer_date": "2011-08-22T03:00:08.607Z", "answer_score": 354 }
Please answer the following Stack Overflow question: Title: Can I get the name of the currently running function in JavaScript? <p>Is it possible to do this:</p> <pre><code>myfile.js: function foo() { alert(&lt;my-function-name&gt;); // pops-up "foo" // or even better: "myfile.js : foo" } </code></pre> <p>I've got the Dojo and jQuery frameworks in my stack, so if either of those make it easier, they're available.</p>
<p>In ES5 and above, there is no access to that information.</p> <p>In older versions of JS you can get it by using <code>arguments.callee</code>.</p> <p>You may have to parse out the name though, as it will probably include some extra junk. Though, in some implementations you can simply get the name using <code>arguments.callee.name</code>.</p> <p>Parsing:</p> <pre><code>function DisplayMyName() { var myName = arguments.callee.toString(); myName = myName.substr('function '.length); myName = myName.substr(0, myName.indexOf('(')); alert(myName); } </code></pre> <blockquote> <p>Source: <a href="http://www.tek-tips.com/viewthread.cfm?qid=1209619" rel="noreferrer">Javascript - get current function name</a>.</p> </blockquote>
{ "question_id": 1013239, "question_date": "2009-06-18T15:10:34.043Z", "question_score": 222, "tags": "javascript|jquery|dojo-1.6", "answer_id": 1013279, "answer_date": "2009-06-18T15:15:52.350Z", "answer_score": 221 }
Please answer the following Stack Overflow question: Title: How to install package from github repo in Yarn <p>When I use <code>npm install fancyapps/fancybox#v2.6.1 --save</code>, so fancybox package at v2.6.1 tag will be installed. This behavior is described in <a href="https://docs.npmjs.com/cli/install" rel="noreferrer">docs</a></p> <p>I want to ask, how to do this with <code>yarn</code>?</p> <p>Is this command the right alternative? In <a href="https://yarnpkg.com/lang/en/docs/cli/add/" rel="noreferrer">yarn docs</a> isn't anything about this format.</p> <pre><code>yarn add fancyapps/fancybox#v2.6.1 </code></pre>
<p>You can add any Git repository (or tarball) as a dependency to <code>yarn</code> by specifying the remote URL (either HTTPS or SSH):</p> <pre><code>yarn add &lt;git remote url&gt; installs a package from a remote git repository. yarn add &lt;git remote url&gt;#&lt;branch/commit/tag&gt; installs a package from a remote git repository at specific git branch, git commit or git tag. yarn add https://my-project.org/package.tgz installs a package from a remote gzipped tarball. </code></pre> <p>Here are some examples:</p> <pre><code>yarn add https://github.com/fancyapps/fancybox [remote url] yarn add ssh://github.com/fancyapps/fancybox#3.0 [branch] yarn add https://github.com/fancyapps/fancybox#5cda5b529ce3fb6c167a55d42ee5a316e921d95f [commit] </code></pre> <p><em>(Note: Fancybox v2.6.1 isn't available in the Git version.)</em></p> <p>To support both npm and yarn, you can use the git+url syntax:</p> <pre class="lang-sh prettyprint-override"><code>git+https://github.com/owner/package.git#commithashortagorbranch git+ssh://github.com/owner/package.git#commithashortagorbranch </code></pre>
{ "question_id": 43411864, "question_date": "2017-04-14T12:49:57Z", "question_score": 222, "tags": "node.js|yarnpkg", "answer_id": 43636577, "answer_date": "2017-04-26T14:07:55.783Z", "answer_score": 318 }
Please answer the following Stack Overflow question: Title: Simple and fast method to compare images for similarity <p>I need a simple and fast way to compare two images for similarity. I.e. I want to get a high value if they contain exactly the same thing but may have some slightly different background and may be moved / resized by a few pixel.</p> <p>(More concrete, if that matters: The one picture is an icon and the other picture is a subarea of a screenshot and I want to know if that subarea is exactly the icon or not.)</p> <p>I have <strong>OpenCV</strong> at hand but I am still not that used to it.</p> <p>One possibility I thought about so far: Divide both pictures into 10x10 cells and for each of those 100 cells, compare the color histogram. Then I can set some made up threshold value and if the value I get is above that threshold, I assume that they are similar.</p> <p>I haven't tried it yet how well that works but I guess it would be good enough. The images are already pretty much similar (in my use case), so I can use a pretty high threshold value.</p> <p>I guess there are dozens of other possible solutions for this which would work more or less (as the task itself is quite simple as I only want to detect similarity if they are really very similar). What would you suggest?</p> <hr> <p>There are a few very related / similar questions about obtaining a signature/fingerprint/hash from an image:</p> <ul> <li><a href="https://stackoverflow.com/questions/2146542/opencv-surf-how-to-generate-a-image-hash-fingerprint-signature-out-of-the">OpenCV / SURF How to generate a image hash / fingerprint / signature out of the descriptors?</a></li> <li><a href="https://stackoverflow.com/questions/596262/image-fingerprint-to-compare-similarity-of-many-images">Image fingerprint to compare similarity of many images</a></li> <li><a href="https://stackoverflow.com/questions/1034900/near-duplicate-image-detection/">Near-Duplicate Image Detection</a></li> <li><a href="https://stackoverflow.com/questions/7205489/opencv-fingerprint-image-and-compare-against-database">OpenCV: Fingerprint Image and Compare Against Database</a>.</li> <li><a href="https://stackoverflow.com/questions/843972/image-comparison-fast-algorithm">more</a>, <a href="https://stackoverflow.com/questions/23931/algorithm-to-compare-two-images">more</a>, <a href="https://stackoverflow.com/questions/189943/how-can-i-quantify-difference-between-two-images">more</a>, <a href="https://stackoverflow.com/questions/25977/how-can-i-measure-the-similarity-between-two-images">more</a>, <a href="https://stackoverflow.com/questions/75891/algorithm-for-finding-similar-images">more</a>, <a href="https://stackoverflow.com/questions/5730631/image-similarity-comparison">more</a>, <a href="https://stackoverflow.com/questions/25105599/algorithm-for-finding-similar-images-using-an-index">more</a></li> </ul> <p>Also, I stumbled upon these implementations which have such functions to obtain a fingerprint:</p> <ul> <li><a href="http://phash.org/" rel="noreferrer">pHash</a></li> <li><a href="http://www.imgseek.net/" rel="noreferrer">imgSeek</a> (<a href="https://github.com/ricardocabral/iskdaemon" rel="noreferrer">GitHub repo</a>) (GPL) based on the paper <a href="http://grail.cs.washington.edu/projects/query/" rel="noreferrer">Fast Multiresolution Image Querying</a></li> <li><a href="https://github.com/ascribe/image-match" rel="noreferrer">image-match</a>. Very similar to what I was searching for. Similar to pHash, based on <a href="http://www.cs.cmu.edu/~hcwong/Pdfs/icip02.ps" rel="noreferrer">An image signature for any kind of image, Goldberg et al</a>. Uses Python and Elasticsearch.</li> <li><a href="http://iqdb.org/code/" rel="noreferrer">iqdb</a></li> <li><a href="https://github.com/JohannesBuchner/imagehash" rel="noreferrer">ImageHash</a>. supports pHash.</li> <li><a href="https://idealo.github.io/imagededup/" rel="noreferrer">Image Deduplicator (imagededup)</a>. Supports CNN, PHash, DHash, WHash, AHash.</li> </ul> <p>Some discussions about perceptual image hashes: <a href="https://news.ycombinator.com/item?id=2614797" rel="noreferrer">here</a></p> <hr> <p>A bit offtopic: There exists many methods to create audio fingerprints. <a href="http://musicbrainz.org" rel="noreferrer">MusicBrainz</a>, a web-service which provides fingerprint-based lookup for songs, has a <a href="http://wiki.musicbrainz.org/Fingerprinting" rel="noreferrer">good overview in their wiki</a>. They are using <a href="http://acoustid.org/" rel="noreferrer">AcoustID</a> now. This is for finding exact (or mostly exact) matches. For finding similar matches (or if you only have some snippets or high noise), take a look at <a href="http://echoprint.me/" rel="noreferrer">Echoprint</a>. A related SO question is <a href="https://stackoverflow.com/questions/2068286/music-recognition-and-signal-processing">here</a>. So it seems like this is solved for audio. All these solutions work quite good.</p> <p>A somewhat more generic question about fuzzy search in general is <a href="https://stackoverflow.com/questions/13514575/how-to-do-fuzzy-search-in-big-data">here</a>. E.g. there is <a href="http://en.wikipedia.org/wiki/Locality-sensitive_hashing" rel="noreferrer">locality-sensitive hashing</a> and <a href="http://en.wikipedia.org/wiki/Nearest_neighbor_search" rel="noreferrer">nearest neighbor search</a>.</p>
<p>Can the screenshot or icon be transformed (scaled, rotated, skewed ...)? There are quite a few methods on top of my head that could possibly help you:</p> <ul> <li><strong>Simple euclidean distance</strong> as mentioned by @carlosdc (doesn't work with transformed images and you need a threshold).</li> <li><strong><a href="http://en.wikipedia.org/wiki/Cross-correlation" rel="noreferrer">(Normalized) Cross Correlation</a></strong> - a simple metrics which you can use for comparison of image areas. It's more robust than the simple euclidean distance but doesn't work on transformed images and you will again need a threshold.</li> <li><strong>Histogram comparison</strong> - if you use normalized histograms, this method works well and is not affected by affine transforms. The problem is determining the correct threshold. It is also very sensitive to color changes (brightness, contrast etc.). You can combine it with the previous two.</li> <li><strong>Detectors of salient points/areas</strong> - such as <a href="http://en.wikipedia.org/wiki/Maximally_stable_extremal_regions" rel="noreferrer">MSER (Maximally Stable Extremal Regions)</a>, <a href="http://en.wikipedia.org/wiki/SURF" rel="noreferrer">SURF</a> or <a href="http://en.wikipedia.org/wiki/Scale-invariant_feature_transform" rel="noreferrer">SIFT</a>. These are very robust algorithms and they might be too complicated for your simple task. Good thing is that you do not have to have an exact area with only one icon, these detectors are powerful enough to find the right match. A nice evaluation of these methods is in this paper: <a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.157.4126&rep=rep1&type=pdf" rel="noreferrer">Local invariant feature detectors: a survey</a>.</li> </ul> <p>Most of these are already implemented in OpenCV - see for example the cvMatchTemplate method (uses histogram matching): <a href="http://dasl.mem.drexel.edu/~noahKuntz/openCVTut6.html" rel="noreferrer">http://dasl.mem.drexel.edu/~noahKuntz/openCVTut6.html</a>. The salient point/area detectors are also available - see <a href="http://opencv.willowgarage.com/documentation/cpp/feature_detection.html" rel="noreferrer">OpenCV Feature Detection</a>.</p>
{ "question_id": 4196453, "question_date": "2010-11-16T16:31:37.567Z", "question_score": 222, "tags": "image-processing|opencv|computer-vision", "answer_id": 4203269, "answer_date": "2010-11-17T09:59:36.623Z", "answer_score": 123 }
Please answer the following Stack Overflow question: Title: How to animate the change of image in an UIImageView? <p>I have an <code>UIImageView</code> with an image. Now I have a completely new image (graphic file), and want to display that in this <code>UIImageView</code>. If I just set </p> <pre><code>myImageView.image = newImage; </code></pre> <p>the new image is visible immediately. Not animatable. </p> <p>I want it to nicely fade into the new image. I thought maybe there's a better solution than just creating a new <code>UIImageView</code> on top of that and blending with animation?</p>
<p>I am not sure if you can animate UIViews with fade effect as it seems all supported view transitions are defined in <code>UIViewAnimationTransition</code> enumeration. Fading effect can be achieved using CoreAnimation. Sample example for this approach:</p> <pre><code>#import &lt;QuartzCore/QuartzCore.h&gt; ... imageView.image = [UIImage imageNamed:(i % 2) ? @"3.jpg" : @"4.jpg"]; CATransition *transition = [CATransition animation]; transition.duration = 1.0f; transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; transition.type = kCATransitionFade; [imageView.layer addAnimation:transition forKey:nil]; </code></pre>
{ "question_id": 2834573, "question_date": "2010-05-14T13:45:03.623Z", "question_score": 222, "tags": "ios|iphone|animation|uiimageview|uiimage", "answer_id": 2834693, "answer_date": "2010-05-14T14:02:40.237Z", "answer_score": 262 }
Please answer the following Stack Overflow question: Title: Convert camelCaseText to Title Case Text <p>How can I convert a string either like 'helloThere' or 'HelloThere' to 'Hello There' in JavaScript?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const text = 'helloThereMister'; const result = text.replace(/([A-Z])/g, " $1"); const finalResult = result.charAt(0).toUpperCase() + result.slice(1); console.log(finalResult);</code></pre> </div> </div> </p> <p>capitalize the first letter - as an example. Note the space in <code>&quot; $1&quot;</code>.</p> <hr /> <p>Of course, in case the first letter is already capital - you would have a spare space to remove.</p>
{ "question_id": 7225407, "question_date": "2011-08-29T02:03:25.983Z", "question_score": 222, "tags": "javascript|regex|string", "answer_id": 7225450, "answer_date": "2011-08-29T02:11:46.067Z", "answer_score": 303 }
Please answer the following Stack Overflow question: Title: Is it possible to implement a Python for range loop without an iterator variable? <p>Is it possible to do following without the <code>i</code>?</p> <pre><code>for i in range(some_number): # do something </code></pre> <p>If you just want to do something N amount of times and don't need the iterator.</p>
<p>Off the top of my head, no.</p> <p>I think the best you could do is something like this:</p> <pre><code>def loop(f,n): for i in xrange(n): f() loop(lambda: &lt;insert expression here&gt;, 5) </code></pre> <p>But I think you can just live with the extra <code>i</code> variable.</p> <p>Here is the option to use the <code>_</code> variable, which in reality, is just another variable.</p> <pre><code>for _ in range(n): do_something() </code></pre> <p>Note that <code>_</code> is assigned the last result that returned in an interactive python session:</p> <pre><code>&gt;&gt;&gt; 1+2 3 &gt;&gt;&gt; _ 3 </code></pre> <p>For this reason, I would not use it in this manner. I am unaware of any idiom as mentioned by Ryan. It can mess up your interpreter.</p> <pre><code>&gt;&gt;&gt; for _ in xrange(10): pass ... &gt;&gt;&gt; _ 9 &gt;&gt;&gt; 1+2 3 &gt;&gt;&gt; _ 9 </code></pre> <p>And according to <a href="https://docs.python.org/2/reference/lexical_analysis.html#identifiers" rel="noreferrer">Python grammar</a>, it is an acceptable variable name:</p> <pre><code>identifier ::= (letter|"_") (letter | digit | "_")* </code></pre>
{ "question_id": 818828, "question_date": "2009-05-04T05:06:46.340Z", "question_score": 222, "tags": "python|loops|for-loop|range", "answer_id": 818836, "answer_date": "2009-05-04T05:14:35.387Z", "answer_score": 135 }
Please answer the following Stack Overflow question: Title: Do Git tags only apply to the current branch? <p>I'm currently working with a repository that has multiple branches.</p> <p>When I create a tag, does that tag refer to the then-current branch?</p> <p>In other words: Whenever I create a tag, do I need to switch to the desired branch and tag inside that branch so that the tag refers to that branch at that point in time?</p>
<p>If you create a tag by e.g.</p> <pre><code>git tag v1.0 </code></pre> <p>the tag will refer to the most recent commit of the branch you are currently on. You can change branch and create a tag there.</p> <p>You can also just refer to the other branch while tagging,</p> <pre><code>git tag v1.0 name_of_other_branch </code></pre> <p>which will create the tag to the most recent commit of the other branch.</p> <p>Or you can just put the tag anywhere, no matter which branch, by directly referencing to the SHA1 of some commit</p> <pre><code>git tag v1.0 &lt;sha1&gt; </code></pre>
{ "question_id": 14613540, "question_date": "2013-01-30T20:52:00.537Z", "question_score": 222, "tags": "git|git-tag", "answer_id": 14613683, "answer_date": "2013-01-30T21:00:49.147Z", "answer_score": 202 }
Please answer the following Stack Overflow question: Title: Git copy file preserving history <p>I have a somewhat confusing question in Git. Lets say, I have a file <code>dir1/A.txt</code> committed and git preserves a history of commits</p> <p>Now I need to copy the file into <code>dir2/A.txt</code> (not move, but copy). I know that there is a <code>git mv</code> command but I need <code>dir2/A.txt</code> to have the same history of commits as <code>dir1/A.txt</code>, and <code>dir1/A.txt</code> to still remain there.</p> <p>I'm not planning to update <code>A.txt</code> once the copy is created and all the future work will be done on <code>dir2/A.txt</code></p> <p>I know it sounds confusing, I'll add that this situation is on java based module (mavenized project) and we need to create a new version of code so that our customers will have the ability to have 2 different versions in runtime, the first version will be removed eventually when the alignment will be done. We can use maven versioning of course, I'm just newbie to Git and curious about what Git can provide here.</p>
<p>Unlike subversion, git does not have a per-file history. If you look at the commit data structure, it only points to the previous commits and the new tree object for this commit. No explicit information is stored in the commit object which files are changed by the commit; nor the nature of these changes.</p> <p>The tools to inspect changes can detect renames based on heuristics. E.g. <code>git diff</code> has the option <code>-M</code> that turns on rename detection. So in case of a rename, <code>git diff</code> might show you that one file has been deleted and another one created, while <code>git diff -M</code> will actually detect the move and display the change accordingly (see <code>man git diff</code> for details).</p> <p>So in git this is not a matter of how you commit your changes but how you look at the committed changes later.</p>
{ "question_id": 16937359, "question_date": "2013-06-05T10:20:00.923Z", "question_score": 222, "tags": "git|file|copy|filenames", "answer_id": 16937834, "answer_date": "2013-06-05T10:43:11.433Z", "answer_score": 89 }
Please answer the following Stack Overflow question: Title: Which HTTP methods match up to which CRUD methods? <p>In RESTful style programming, we should use HTTP methods as our building blocks. I'm a little confused though which methods match up to the classic CRUD methods. GET/Read and DELETE/Delete are obvious enough.</p> <p>However, what is the difference between PUT/POST? Do they match one to one with Create and Update?</p>
<pre><code>Create = PUT with a new URI POST to a base URI returning a newly created URI Read = GET Update = PUT with an existing URI Delete = DELETE </code></pre> <p>PUT can map to both Create and Update depending on the existence of the URI used with the PUT.</p> <p>POST maps to Create.</p> <p>Correction: POST can also map to Update although it's typically used for Create. POST can also be a partial update so we don't need the proposed PATCH method.</p>
{ "question_id": 6203231, "question_date": "2011-06-01T14:57:08.997Z", "question_score": 222, "tags": "http|rest|crud|http-method", "answer_id": 6210103, "answer_date": "2011-06-02T03:38:42.187Z", "answer_score": 310 }
Please answer the following Stack Overflow question: Title: How can I find the number of arguments of a Python function? <p>How can I find the number of arguments of a Python function? I need to know how many normal arguments it has and how many named arguments.</p> <p>Example:</p> <pre><code>def someMethod(self, arg1, kwarg1=None): pass </code></pre> <p>This method has 2 arguments and 1 named argument.</p>
<p>The previously accepted answer has been <a href="https://docs.python.org/3/library/inspect.html#inspect.getargspec" rel="noreferrer"><em>deprecated</em></a> as of <code>Python 3.0</code>. Instead of using <code>inspect.getargspec</code> you should now opt for the <code>Signature</code> class which superseded it. </p> <p>Creating a Signature for the function is easy via the <a href="https://docs.python.org/3/library/inspect.html#inspect.signature" rel="noreferrer"><code>signature</code> function</a>:</p> <pre><code>from inspect import signature def someMethod(self, arg1, kwarg1=None): pass sig = signature(someMethod) </code></pre> <p>Now, you can either view its parameters quickly by <code>str</code>ing it:</p> <pre><code>str(sig) # returns: '(self, arg1, kwarg1=None)' </code></pre> <p>or you can also get a mapping of attribute names to parameter objects via <code>sig.parameters</code>. </p> <pre><code>params = sig.parameters print(params['kwarg1']) # prints: kwarg1=20 </code></pre> <p>Additionally, you can call <code>len</code> on <code>sig.parameters</code> to also see the number of arguments this function requires:</p> <pre><code>print(len(params)) # 3 </code></pre> <p>Each entry in the <code>params</code> mapping is actually a <a href="https://docs.python.org/3/library/inspect.html#inspect.Parameter" rel="noreferrer"><code>Parameter</code> object</a> that has further attributes making your life easier. For example, grabbing a parameter and viewing its default value is now easily performed with:</p> <pre><code>kwarg1 = params['kwarg1'] kwarg1.default # returns: None </code></pre> <p>similarly for the rest of the objects contained in <code>parameters</code>.</p> <hr> <p>As for Python <code>2.x</code> users, while <code>inspect.getargspec</code> <em>isn't</em> deprecated, the language will soon be :-). The <code>Signature</code> class isn't available in the <code>2.x</code> series and won't be. So you still need to work with <a href="https://docs.python.org/3/library/inspect.html#inspect.getargspec" rel="noreferrer"><code>inspect.getargspec</code></a>.</p> <p>As for transitioning between Python 2 and 3, if you have code that relies on the interface of <code>getargspec</code> in Python 2 and switching to <code>signature</code> in <code>3</code> is too difficult, <em>you do have the valuable option</em> of using <a href="https://docs.python.org/3/library/inspect.html#inspect.getfullargspec" rel="noreferrer"><code>inspect.getfullargspec</code></a>. It offers a similar interface to <code>getargspec</code> (a single callable argument) in order to grab the arguments of a function while also handling some additional cases that <code>getargspec</code> doesn't:</p> <pre><code>from inspect import getfullargspec def someMethod(self, arg1, kwarg1=None): pass args = getfullargspec(someMethod) </code></pre> <p>As with <code>getargspec</code>, <code>getfullargspec</code> returns a <code>NamedTuple</code> which contains the arguments.</p> <pre><code>print(args) FullArgSpec(args=['self', 'arg1', 'kwarg1'], varargs=None, varkw=None, defaults=(None,), kwonlyargs=[], kwonlydefaults=None, annotations={}) </code></pre>
{ "question_id": 847936, "question_date": "2009-05-11T12:45:16.090Z", "question_score": 222, "tags": "python|function", "answer_id": 41188411, "answer_date": "2016-12-16T16:15:31.770Z", "answer_score": 199 }
Please answer the following Stack Overflow question: Title: How can you tell when a layout has been drawn? <p>I have a custom view that draws a scrollable bitmap to the screen. In order to initialize it, i need to pass in the size in pixels of the parent layout object. But during the onCreate and onResume functions, the Layout has not been drawn yet, and so layout.getMeasuredHeight() returns 0. </p> <p>As a workaround, i have added a handler to wait one second and then measure. This works, but its sloppy, and I have no idea how much i can trim the time before I end up before the layout gets drawn. </p> <p>What I want to know is, how can I detect when a layout gets drawn? Is there an event or callback?</p>
<p>You can add a tree observer to the layout. This should return the correct width and height. <code>onCreate()</code> is called before the layout of the child views are done. So the width and height is not calculated yet. To get the height and width, put this on the <code>onCreate()</code> method:</p> <pre><code> final LinearLayout layout = (LinearLayout) findViewById(R.id.YOUR_VIEW_ID); ViewTreeObserver vto = layout.getViewTreeObserver(); vto.addOnGlobalLayoutListener (new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.JELLY_BEAN) { layout.getViewTreeObserver() .removeOnGlobalLayoutListener(this); } else { layout.getViewTreeObserver() .removeGlobalOnLayoutListener(this); } int width = layout.getMeasuredWidth(); int height = layout.getMeasuredHeight(); } }); </code></pre>
{ "question_id": 7733813, "question_date": "2011-10-11T23:47:05.200Z", "question_score": 222, "tags": "android|android-layout", "answer_id": 7735122, "answer_date": "2011-10-12T04:01:31.897Z", "answer_score": 421 }
Please answer the following Stack Overflow question: Title: Why use 'git rm' to remove a file instead of 'rm'? <p>On SVN, removing something from the filesystem directly (rather than using svn) created a load of headaches.</p> <p>I haven't found this to be an issue when using <code>git</code>, but I notice that git has it's own <code>rm</code> implementation (<code>git rm</code>).</p> <p>What is the difference between <code>rm</code> and <code>git rm</code>?</p>
<p>If you just use <code>rm</code>, you will need to follow it up with <code>git add &lt;fileRemoved&gt;</code>. <code>git rm</code> does this in one step.</p> <p>You can also use <code>git rm --cached</code> which will remove the file from the index (staging it for deletion on the next commit), but keep your copy in the local file system.</p>
{ "question_id": 7434449, "question_date": "2011-09-15T16:43:02.987Z", "question_score": 222, "tags": "git", "answer_id": 7434558, "answer_date": "2011-09-15T16:51:30.957Z", "answer_score": 312 }
Please answer the following Stack Overflow question: Title: Accessing console and devtools of extension's background.js <p>I just started out with Google Chrome extensions and I can't seem to log to console from my background js. When an error occurs (because of a syntax error, for example), I can't find any error messages either.</p> <p>My manifest file:</p> <pre><code>{ "name": "My First Extension", "version": "1.0", "manifest_version": 2, "description": "The first extension that I made.", "browser_action": { "default_icon": "icon.png" }, "background": { "scripts": ["background.js"] }, "permissions": [ "pageCapture", "tabs" ] } </code></pre> <p>background.js:</p> <pre><code>alert("here"); console.log("Hello, world!") </code></pre> <p>When I load the extension, the alert comes up but I don't see anything being logged to console. What am I doing wrong?</p>
<p>You're looking at the wrong place. These console messages do not appear in the web page, but in the invisible background page (ManifestV2) or service worker (ManifestV3).</p> <p>To view the correct console open devtools for the background script's context:</p> <ol> <li>Visit <code>chrome://extensions/</code> or right-click the extension icon and select &quot;Manage extensions&quot;.</li> <li>Enable developer mode</li> <li>Click on the link named <code>background page</code> (ManifestV2) or <code>service worker</code> (ManifestV3).</li> </ol> <p>Screenshot for ManifestV2 extensions:</p> <p><a href="https://i.stack.imgur.com/90Bvq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/90Bvq.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/Oy4Sj.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Oy4Sj.png" alt="enter image description here" /></a></p> <p>Screenshot for ManifestV3 extensions:</p> <p><a href="https://i.stack.imgur.com/H2O2F.png" rel="noreferrer"><img src="https://i.stack.imgur.com/H2O2F.png" alt="enter image description here" /></a></p>
{ "question_id": 10257301, "question_date": "2012-04-21T07:59:40.530Z", "question_score": 222, "tags": "debugging|google-chrome-extension|console|google-chrome-devtools", "answer_id": 10258029, "answer_date": "2012-04-21T10:12:34.457Z", "answer_score": 417 }
Please answer the following Stack Overflow question: Title: Paste a multi-line Java String in Eclipse <p>Unfortunately, Java has no syntax for multi-line string literals. No problem if the IDE makes it easy to work with constructs like </p> <pre><code> String x = "CREATE TABLE TEST ( \n" + "A INTEGER NOT NULL PRIMARY KEY, \n" ... </code></pre> <p>What is the fastest way to paste a multi-line String from the clipboard into Java source using Eclipse (in a way that it automatically creates code like the above).</p>
<p>Okay, I just <a href="https://stackoverflow.com/questions/121199/surround-with-quotation-marks/121513#121513">found the answer</a> (on Stackoverflow, no less).</p> <p>Eclipse has an option so that copy-paste of multi-line text into String literals will result in quoted newlines: </p> <blockquote> <p>Preferences/Java/Editor/Typing/ "Escape text when pasting into a string literal"</p> </blockquote>
{ "question_id": 2159678, "question_date": "2010-01-29T03:18:16.720Z", "question_score": 222, "tags": "java|eclipse|multiline|multilinestring", "answer_id": 2159931, "answer_date": "2010-01-29T04:46:53.510Z", "answer_score": 423 }
Please answer the following Stack Overflow question: Title: Git bash Error: Could not fork child process: There are no available terminals (-1) <p>I have had up to 8 git bash terminals running at the same time before. </p> <p>Currently I have only 2 up.</p> <p>I have not seen this error before and I am not understanding what is causing it.</p> <p>Any help would be appreciated!</p> <p>Picture attached:</p> <p><a href="https://i.stack.imgur.com/Tps5X.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Tps5X.png" alt="enter image description here"></a></p>
<p>Found a similar issue and solution in <a href="https://groups.google.com/forum/#!topic/git-for-windows/EO27WWvHx64" rel="noreferrer">google groups</a></p> <blockquote> <p>I opened a windows command prompt and ran the command</p> <pre><code>$ tasklist </code></pre> <p>It looks as though the ssh connections I had made in my git bash shells weren't being closed when those windows were closed and were hanging the available git bash shell windows.</p> <p>This may be a dangerous solution but from the windows command prompt I ran</p> <pre><code>$ taskkill /F /IM ssh.exe </code></pre> <p>Everything appears to be working again after this. It may not have directly been an issue of orphan processes, but this worked for at least for me.</p> </blockquote> <p>Additional note: you can also kill other processes, for example like:</p> <pre><code>$ taskkill /F /IM vim.exe </code></pre>
{ "question_id": 45799650, "question_date": "2017-08-21T14:27:30.227Z", "question_score": 222, "tags": "git|terminal|git-bash", "answer_id": 45803951, "answer_date": "2017-08-21T18:59:58.343Z", "answer_score": 97 }
Please answer the following Stack Overflow question: Title: try/catch + using, right syntax <p>Which one:</p> <pre><code>using (var myObject = new MyClass()) { try { // something here... } catch(Exception ex) { // Handle exception } } </code></pre> <p>OR</p> <pre><code>try { using (var myObject = new MyClass()) { // something here... } } catch(Exception ex) { // Handle exception } </code></pre>
<p>I prefer the second one. May as well trap errors relating to the creation of the object as well.</p>
{ "question_id": 4590490, "question_date": "2011-01-04T03:53:54.370Z", "question_score": 222, "tags": "c#|try-catch|using-statement", "answer_id": 4590518, "answer_date": "2011-01-04T03:58:10.323Z", "answer_score": 116 }
Please answer the following Stack Overflow question: Title: Redis is single-threaded, then how does it do concurrent I/O? <p>Trying to grasp some basics of Redis I came across an interesting <a href="http://blog.kennejima.com/post/1226487020/thoughts-on-redis#" rel="noreferrer">blog post</a> .</p> <p>The author states:</p> <blockquote> <p>Redis is single-threaded with epoll/kqueue and scale indefinitely in terms of I/O concurrency. </p> </blockquote> <p>I surely misunderstand the whole threading thing, because I find this statement puzzling. If a program is single-threaded, how does it do anything concurrently? Why it is so great that Redis operations are atomic, if the server is single-threaded anyway?</p> <p>Could anybody please shed some light on the issue?</p>
<p>Well it depends on how you define concurrency.</p> <p>In server-side software, concurrency and parallelism are often considered as different concepts. In a server, supporting concurrent I/Os means the server is able to serve several clients by executing several flows corresponding to those clients with only one computation unit. In this context, parallelism would mean the server is able to perform several things at the same time (with multiple computation units), which is different.</p> <p>For instance a bartender is able to look after several customers while he can only prepare one beverage at a time. So he can provide concurrency without parallelism.</p> <p>This question has been debated here: <a href="https://stackoverflow.com/questions/1050222/concurrency-vs-parallelism-what-is-the-difference">What is the difference between concurrency and parallelism?</a></p> <p>See also <a href="https://talks.golang.org/2012/waza.slide#1" rel="noreferrer">this presentation</a> from Rob Pike.</p> <p>A single-threaded program can definitely provide concurrency at the I/O level by using an I/O (de)multiplexing mechanism and an event loop (which is what Redis does).</p> <p>Parallelism has a cost: with the multiple sockets/multiple cores you can find on modern hardware, synchronization between threads is extremely expensive. On the other hand, the bottleneck of an efficient storage engine like Redis is very often the network, well before the CPU. Isolated event loops (which require no synchronization) are therefore seen as a good design to build efficient, scalable, servers.</p> <p>The fact that Redis operations are atomic is simply a consequence of the single-threaded event loop. The interesting point is atomicity is provided at no extra cost (it does not require synchronization). It can be exploited by the user to implement optimistic locking and other patterns without paying for the synchronization overhead.</p>
{ "question_id": 10489298, "question_date": "2012-05-07T21:19:16.430Z", "question_score": 222, "tags": "multithreading|redis", "answer_id": 10495458, "answer_date": "2012-05-08T08:51:51.943Z", "answer_score": 428 }
Please answer the following Stack Overflow question: Title: How do I configure different environments in Angular.js? <p>How do you manage configuration variables/constants for different environments?</p> <p>This could be an example: </p> <p>My rest API is reachable on <code>localhost:7080/myapi/</code>, but my friend that works on the same code under Git version control has the API deployed on his Tomcat on <code>localhost:8099/hisapi/</code>.</p> <p>Supposing that we have something like this : </p> <pre><code>angular .module('app', ['ngResource']) .constant('API_END_POINT','&lt;local_end_point&gt;') .factory('User', function($resource, API_END_POINT) { return $resource(API_END_POINT + 'user'); }); </code></pre> <p>How do I dynamically inject the correct value of the API endpoint, depending on the environment?</p> <p>In PHP I usually do this kind of stuff with a <code>config.username.xml</code> file, merging the basic configuration file (config.xml) with the local environment configuration file recognised by the name of the user. But I don't know how to manage this kind of thing in JavaScript?</p>
<p>I'm a little late to the thread, but if you're using <a href="http://gruntjs.com/">Grunt</a> I've had great success with <a href="https://npmjs.org/package/grunt-ng-constant"><code>grunt-ng-constant</code></a>.</p> <p>The config section for <code>ngconstant</code> in my <code>Gruntfile.js</code> looks like</p> <pre><code>ngconstant: { options: { name: 'config', wrap: '"use strict";\n\n{%= __ngModule %}', space: ' ' }, development: { options: { dest: '&lt;%= yeoman.app %&gt;/scripts/config.js' }, constants: { ENV: 'development' } }, production: { options: { dest: '&lt;%= yeoman.dist %&gt;/scripts/config.js' }, constants: { ENV: 'production' } } } </code></pre> <p>The tasks that use <code>ngconstant</code> look like</p> <pre><code>grunt.registerTask('server', function (target) { if (target === 'dist') { return grunt.task.run([ 'build', 'open', 'connect:dist:keepalive' ]); } grunt.task.run([ 'clean:server', 'ngconstant:development', 'concurrent:server', 'connect:livereload', 'open', 'watch' ]); }); grunt.registerTask('build', [ 'clean:dist', 'ngconstant:production', 'useminPrepare', 'concurrent:dist', 'concat', 'copy', 'cdnify', 'ngmin', 'cssmin', 'uglify', 'rev', 'usemin' ]); </code></pre> <p>So running <code>grunt server</code> will generate a <code>config.js</code> file in <code>app/scripts/</code> that looks like</p> <pre><code>"use strict"; angular.module("config", []).constant("ENV", "development"); </code></pre> <p>Finally, I declare the dependency on whatever modules need it:</p> <pre><code>// the 'config' dependency is generated via grunt var app = angular.module('myApp', [ 'config' ]); </code></pre> <p>Now my constants can be dependency injected where needed. E.g.,</p> <pre><code>app.controller('MyController', ['ENV', function( ENV ) { if( ENV === 'production' ) { ... } }]); </code></pre>
{ "question_id": 16339595, "question_date": "2013-05-02T13:41:29.387Z", "question_score": 222, "tags": "javascript|angularjs|angularjs-service", "answer_id": 18343298, "answer_date": "2013-08-20T19:17:04.943Z", "answer_score": 208 }
Please answer the following Stack Overflow question: Title: Why use AJAX when WebSockets is available? <p>I've been using WebSockets for a while now, I have chosen to create an Agile project management tool for my final year project at University utilizing Node server and WebSockets. I found using WebSockets provided a 624% increase in the number of requests per second my application could process.</p> <p>However since starting the project I've read of security loopholes, and some browsers choosing to disable WebSockets by default..</p> <p><strong>This leads me to the question:</strong></p> <p>Why use AJAX when WebSockets seems to do such a great job of lowering latency and resource overhead, is there anything that AJAX does better than WebSockets?</p>
<p>WebSockets isn't intended to replace AJAX and is not strictly even a replacement for Comet/long-poll (although there are many cases where this makes sense).</p> <p>The purpose of WebSockets is to provide a low-latency, bi-directional, full-duplex and long-running connection between a browser and server. WebSockets opens up new application domains to browser applications that were not really possible using HTTP and AJAX (interactive games, dynamic media streams, bridging to existing network protocols, etc).</p> <p>However, there is certainly an overlap in purpose between WebSockets and AJAX/Comet. For example, when the browser wants to be notified of server events (i.e. push) then Comet techniques and WebSockets are certainly both viable options. If your application needs low-latency push events then this would be a factor in favor of WebSockets. On the other hand, if you need to co-exist with existing frameworks and deployed technologies (OAuth, RESTful APIs, proxies, load balancers) then this would be a factor in favor of Comet techniques (for now).</p> <p>If you don't need the specific benefits that WebSockets provides, then it's probably a better idea to stick with existing techniques like AJAX and Comet because this allows you to re-use and integrate with a huge existing ecosystem of tools, technologies, security mechanisms, knowledge bases (i.e. far more people on stackoverflow know HTTP/Ajax/Comet than WebSockets), etc.</p> <p>On the other hand, if you are creating a new application that just doesn't work well within the latency and connection constraints of HTTP/Ajax/Comet, then consider using WebSockets.</p> <p>Also, some answers indicate that one of the downsides of WebSockets is limited/mixed server and browser support. Let me just diffuse that a bit. While iOS (iPhone, iPad) still supports the older protocol (Hixie) most WebSockets servers support both Hixie and the HyBi/<a href="https://www.rfc-editor.org/rfc/rfc6455" rel="nofollow noreferrer">IETF 6455</a> version. Most other platforms (if they don't already have built-in support) can get WebSockets support via <a href="https://github.com/gimite/web-socket-js" rel="nofollow noreferrer">web-socket-js</a> (Flash based polyfill). This covers the vast majority of web users. Also, if you are using Node for the server backend, then consider using <a href="http://socket.io" rel="nofollow noreferrer">Socket.IO</a> which includes web-socket-js as a fallback and if even that is not available (or disabled) then it will fall back to using whatever Comet technique is available for the given browser.</p> <p><strong>Update</strong>: iOS 6 now supports the current HyBi/IETF 6455 standard.</p>
{ "question_id": 10377384, "question_date": "2012-04-30T01:02:25.270Z", "question_score": 222, "tags": "ajax|node.js|performance|websocket", "answer_id": 10388752, "answer_date": "2012-04-30T18:34:37.817Z", "answer_score": 221 }
Please answer the following Stack Overflow question: Title: How do I see a C/C++ source file after preprocessing in Visual Studio? <p>Let's say I have a source file with many preprocessor directives. Is it possible to see how it looks after the preprocessor is done with it?</p>
<p><code>cl.exe</code>, the command line interface to Microsoft Visual C++, has three different options for outputting the preprocessed file (hence the inconsistency in the previous responses about Visual C++):</p> <ul> <li><code>/E</code>: <a href="http://msdn.microsoft.com/en-us/library/3xkfswhy.aspx" rel="noreferrer">preprocess to stdout</a> (similar to GCC's -E option)</li> <li><code>/P</code>: <a href="http://msdn.microsoft.com/en-us/library/8z9z0bx6.aspx" rel="noreferrer">preprocess to file</a></li> <li><code>/EP</code>: <a href="http://msdn.microsoft.com/en-us/library/becb7sys.aspx" rel="noreferrer">preprocess to stdout without #line directives</a></li> </ul> <p>If you want to preprocess to a file without #line directives, combine the <code>/P</code> and <code>/EP</code> options.</p>
{ "question_id": 277258, "question_date": "2008-11-10T07:11:08.883Z", "question_score": 222, "tags": "c++|c|debugging|visual-studio-2005|c-preprocessor", "answer_id": 277362, "answer_date": "2008-11-10T08:33:17.533Z", "answer_score": 167 }
Please answer the following Stack Overflow question: Title: How to convert List to Map in Kotlin? <p>For example I have a list of strings like:</p> <pre><code>val list = listOf("a", "b", "c", "d") </code></pre> <p>and I want to convert it to a map, where the strings are the keys.</p> <p>I know I should use the <code>.toMap()</code> function, but I don't know how, and I haven't seen any examples of it.</p>
<p>You have two choices:</p> <p>The first and most performant is to use <code>associateBy</code> function that takes two lambdas for generating the key and value, and inlines the creation of the map:</p> <pre><code>val map = friends.associateBy({it.facebookId}, {it.points}) </code></pre> <p>The second, less performant, is to use the standard <code>map</code> function to create a list of <code>Pair</code> which can be used by <code>toMap</code> to generate the final map:</p> <pre><code>val map = friends.map { it.facebookId to it.points }.toMap() </code></pre>
{ "question_id": 32935470, "question_date": "2015-10-04T16:03:10.687Z", "question_score": 222, "tags": "dictionary|kotlin", "answer_id": 32938733, "answer_date": "2015-10-04T21:43:06.550Z", "answer_score": 416 }
Please answer the following Stack Overflow question: Title: Python void return type annotation <p>In python 3.x, it is common to use return type annotation of a function, such as:</p> <pre><code>def foo() -&gt; str: return &quot;bar&quot; </code></pre> <p>What is the correct annotation for the &quot;void&quot; type?</p> <p>I'm considering 3 options:</p> <ol> <li><code>def foo() -&gt; None:</code> <ul> <li>not logical IMO, because <code>None</code> is not a type,</li> </ul> </li> <li><code>def foo() -&gt; type(None):</code> <ul> <li>using the best syntax I know for obtaining <code>NoneType</code>,</li> </ul> </li> <li><code>def foo():</code> <ul> <li>omit explicit return type information.</li> </ul> </li> </ol> <p>Option 2. seems the most logical to me, but I've already seen some instances of 1.</p>
<p>This is straight from <a href="https://www.python.org/dev/peps/pep-0484/#using-none" rel="noreferrer">PEP 484 -- Type Hints</a> documentation:</p> <blockquote> <p>When used in a type hint, the expression <code>None</code> is considered equivalent to <code>type(None)</code>.</p> </blockquote> <p>And, as you can see most of the examples use <code>None</code> as return type.</p>
{ "question_id": 36797282, "question_date": "2016-04-22T15:02:45.860Z", "question_score": 222, "tags": "python|annotations|void|type-hinting|python-typing", "answer_id": 36797437, "answer_date": "2016-04-22T15:10:12.763Z", "answer_score": 243 }
Please answer the following Stack Overflow question: Title: How to do a safe join pathname in ruby? <p>My Rails development environment is Windows-based, and my production environment is Linux-based.</p> <p>It's possible that VirtualHost will be used. Assume that one filename needs to be referenced in the <code>/public</code> folder with <code>File.open('/tmp/abc.txt', 'r')</code>.</p> <p>—but in Windows it should be <code>C:\tmp\abc.txt</code>. How can I do a correct path join to handle the two different environments?</p> <pre><code>prefix_tmp_path = '/tmp/' filename = "/#{rand(10)}.txt" fullname = prefix_tmp_path + filename # /tmp//1.txt &lt;- but I don't want a double // </code></pre> <p>And when <code>prefix_tmp_path = "C:\tmp\"</code> I get <code>C:\tmp\/1.txt</code></p> <p>What is the correct way to handle both cases?</p>
<p>I recommend using File.join</p> <pre><code>&gt;&gt; File.join("path", "to", "join") =&gt; "path/to/join" </code></pre>
{ "question_id": 597488, "question_date": "2009-02-28T04:25:49.883Z", "question_score": 222, "tags": "ruby", "answer_id": 597496, "answer_date": "2009-02-28T04:33:38.773Z", "answer_score": 382 }
Please answer the following Stack Overflow question: Title: Difference between java.util.Random and java.security.SecureRandom <p>My team got handed over some server side code (in Java) that generates random tokens and I have a question regarding the same -</p> <p>The purpose of these tokens is fairly sensitive - used for session id, password reset links etc. So they do need to be cryptographically random to avoid somebody guessing them or brute force them feasibly. The token is a "long" so it is 64 bits long.</p> <p>The code currently uses the <code>java.util.Random</code> class to generate these tokens. The <a href="https://docs.oracle.com/javase/7/docs/api/java/util/Random.html" rel="noreferrer">documentation</a> for <code>java.util.Random</code> clearly states the following: </p> <blockquote> <p>Instances of java.util.Random are not cryptographically secure. Consider instead using SecureRandom to get a cryptographically secure pseudo-random number generator for use by security-sensitive applications.</p> </blockquote> <p>However, the way the code is currently using <code>java.util.Random</code> is this - It instantiates the <code>java.security.SecureRandom</code> class and then uses the <code>SecureRandom.nextLong()</code> method to obtain the seed that is used for instantiating the <code>java.util.Random</code>class. Then it uses <code>java.util.Random.nextLong()</code> method to generate the token.</p> <p>So my question now - Is it still insecure given that the <code>java.util.Random</code> is being seeded using <code>java.security.SecureRandom</code>? Do I need to modify the code so that it uses <code>java.security.SecureRandom</code> exclusively to generate the tokens?</p> <p>Currently the code seed's the <code>Random</code> once at startup</p>
<p>The standard Oracle JDK 7 implementation uses what's called a Linear Congruential Generator to produce random values in <code>java.util.Random</code>. </p> <p>Taken from <code>java.util.Random</code> source code (JDK 7u2), from a comment on the method <code>protected int next(int bits)</code>, which is the one that generates the random values:</p> <blockquote> <p>This is a linear congruential pseudorandom number generator, as defined by D. H. Lehmer and described by Donald E. Knuth in <i>The Art of Computer Programming,</i> Volume 3: <i>Seminumerical Algorithms</i>, section 3.2.1.</p> </blockquote> <h3>Predictability of Linear Congruential Generators</h3> <p>Hugo Krawczyk wrote a pretty good paper about how these LCGs can be predicted ("How to predict congruential generators"). If you're lucky and interested, you may still find a free, downloadable version of it on the web. And there's plenty more research that clearly shows that you should <strong>never</strong> use an LCG for security-critical purposes. This also means that your random numbers <em>are</em> predictable right now, something you don't want for session IDs and the like.</p> <h3>How to break a Linear Congruential Generator</h3> <p>The assumption that an attacker would have to wait for the LCG to repeat after a full cycle is wrong. Even with an optimal cycle (the modulus m in its recurrence relation) it is very easy to predict future values in much less time than a full cycle. After all, it's just a bunch of modular equations that need to be solved, which becomes easy as soon as you have observed enough output values of the LCG. </p> <p>The security doesn't improve with a "better" seed. It simply doesn't matter if you seed with a random value generated by <code>SecureRandom</code> or even produce the value by rolling a die several times. </p> <p>An attacker will simply compute the seed from the output values observed. This takes <em>significantly less</em> time than 2^48 in the case of <code>java.util.Random</code>. Disbelievers may try out this <a href="http://jazzy.id.au/default/2010/09/20/cracking_random_number_generators_part_1.html" rel="noreferrer">experiment</a>, where it is shown that you can predict future <code>Random</code> outputs observing only two(!) output values in time roughly 2^16. It takes not even a second on a modern computer to predict the output of your random numbers right now.</p> <h3>Conclusion</h3> <p>Replace your current code. Use <code>SecureRandom</code> exclusively. Then at least you will have a little guarantee that the result will be hard to predict. If you want the properties of a cryptographically secure PRNG (in your case, that's what you want), then you have to go with <code>SecureRandom</code> only. Being clever about changing the way it was supposed to be used will almost always result in something less secure...</p>
{ "question_id": 11051205, "question_date": "2012-06-15T13:04:41.600Z", "question_score": 222, "tags": "java|random|cryptography|security", "answer_id": 11052736, "answer_date": "2012-06-15T14:32:29.463Z", "answer_score": 250 }
Please answer the following Stack Overflow question: Title: How to branch with TortoiseHG <p>I downloaded TortoiseHg 1.0 for evaluation. For the life of me I can't figure out how to make a branch. It seems to understand branches (e.g. in its repository browser) but I just can't seem to find a way to make a branch. This seems like such a fundamental capability since out of the often touted benefits of DVC is the lightweight branching.</p> <p>I Googled around and couldn't find much discussion of this topic (at least for recent versions) so I have to assume I'm missing something, right?</p> <p><strong>Update:</strong> So I flagged Chad Birch's answer below to answer the "new branch" issue. As he correctly points out, you do a commit and then click on the branch button to bring up the branch maintenance dialog which is where you create new branches. I kind of wish they had given us a context menu option for this. Once you've branched, the next natural question is how to merge and this is also not obvious. It turns out that option is buried in the repository explorer. You need to select the head of another branch, right-click and then select "Merge with...".</p>
<p><a href="http://tortoisehg.readthedocs.io/en/latest/commit.html" rel="noreferrer">As shown in the docs</a>, all you should need to do is just click on the <kbd>branch: default</kbd> button near the top of the commit dialog, and change to a new branch name.</p>
{ "question_id": 2562899, "question_date": "2010-04-01T19:02:52.780Z", "question_score": 222, "tags": "mercurial|tortoisehg", "answer_id": 2562957, "answer_date": "2010-04-01T19:10:02.673Z", "answer_score": 216 }
Please answer the following Stack Overflow question: Title: Disable tooltip hint in Visual Studio Code <p>How can I disable the default tooltip hint message in VSCode? It's annoying sometimes.</p> <p><a href="https://i.stack.imgur.com/cd8gZ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/cd8gZ.png" alt="enter image description here"></a></p>
<blockquote> <p><code>editor.hover.enabled: false</code> in settings.json to Tooltip</p> </blockquote> <p>Click on Edit in settings.json</p> <p><em>There are two panes</em></p> <p><strong>Default User Settings</strong></p> <pre><code>"editor.quickSuggestions": { "other": false, "comments": false, "strings": false } </code></pre> <p><strong>User Settings</strong></p> <pre><code>"editor.parameterHints.enabled": false, "editor.suggest.snippetsPreventQuickSuggestions": false, "html.suggest.html5": false, "editor.snippetSuggestions": "none", </code></pre> <p>This also can be done UI.</p> <p><strong>Setting Snippet Suggestions : false</strong></p> <p>Update August 2018 (version 1.27)</p> <p>Goto <code>File=&gt;Preference=&gt;Settings</code></p> <p><code>Text Editor =&gt; Suggestions</code></p> <p>Click on Edit in settings.json</p> <pre><code>"editor.parameterHints.enabled": false, "editor.suggest.snippetsPreventQuickSuggestions": false, "html.suggest.html5": false, </code></pre> <p>Update your suggest options and save.</p> <p><a href="https://i.stack.imgur.com/dWK0p.png" rel="noreferrer"><img src="https://i.stack.imgur.com/dWK0p.png" alt="New update option"></a></p> <p><strong>Before August 2018</strong></p> <p>Goto <code>File=&gt;Preference=&gt;User Settings</code></p> <p>You will find <code>settings.json</code></p> <pre><code>// Configures if the built-in HTML language support suggests Angular tags and properties. "html.suggest.angular1": false, "html.suggest.ionic": false, "html.suggest.html5": false, </code></pre> <p>Just find your language and set <code>suggest = false</code></p> <p><strong>Update</strong></p> <blockquote> <p>Setting to turn off ALL popups</p> </blockquote> <pre><code>"editor.parameterHints": false </code></pre> <p><a href="https://i.stack.imgur.com/Yl9Zq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Yl9Zq.png" alt="See the settings.json"></a></p>
{ "question_id": 41115285, "question_date": "2016-12-13T07:01:31.197Z", "question_score": 222, "tags": "visual-studio-code|vscode-settings", "answer_id": 41115383, "answer_date": "2016-12-13T07:07:41.567Z", "answer_score": 189 }
Please answer the following Stack Overflow question: Title: What's the difference between IEquatable and just overriding Object.Equals()? <p>I want my <code>Food</code> class to be able to test whenever it is equal to another instance of <code>Food</code>. I will later use it against a List, and I want to use its <code>List.Contains()</code> method. Should I implement <code>IEquatable&lt;Food&gt;</code> or just override <code>Object.Equals()</code>? From MSDN:</p> <blockquote> <p>This method determines equality by using the default equality comparer, as defined by the object's implementation of the IEquatable.Equals method for T (the type of values in the list).</p> </blockquote> <p>So my next question is: which functions/classes of the .NET framework make use of <code>Object.Equals()</code>? Should I use it in the first place?</p>
<p>The main reason is performance. When generics were introduced in .NET 2.0 they were able to add a bunch of neat classes such as <code>List&lt;T&gt;</code>, <code>Dictionary&lt;K,V&gt;</code>, <code>HashSet&lt;T&gt;</code>, etc. These structures make heavy use of <code>GetHashCode</code> and <code>Equals</code>. But for value types this required boxing. <code>IEquatable&lt;T&gt;</code> lets a structure implement a strongly typed <code>Equals</code> method so no boxing is required. Thus much better performance when using value types with generic collections.</p> <p>Reference types don't benefit as much but the <code>IEquatable&lt;T&gt;</code> implementation does let you avoid a cast from <code>System.Object</code> which can make a difference if it's called frequently.</p> <p>As noted on <a href="https://blog.paranoidcoding.com/2009/01/15/if-you-implement-iequatable-t-you-still-must-override-object-s-equals-and-gethashcode.html" rel="noreferrer">Jared Parson's blog</a> though, you <strong>must</strong> still implement the standard <code>Object.Equals</code> and <code>Object.GetHashcode</code> overrides.</p>
{ "question_id": 2734914, "question_date": "2010-04-29T05:12:40.510Z", "question_score": 222, "tags": "c#|.net|equals|equality|iequatable", "answer_id": 2734941, "answer_date": "2010-04-29T05:20:43.583Z", "answer_score": 256 }
Please answer the following Stack Overflow question: Title: Good introduction to the .NET Reactive Framework <p>Aside from the Microsoft documentation, is there a good introduction and tutorial to the Microsoft Reactive (Rx) framework?</p> <p>Also, what is a good example (with code) that Reactive makes easier of a programming problem that is challenging to solve using conventional asynchronous coding techniques?</p>
<p>Here's a wiki site with lots of code examples demonstrating how to use different features of the .NET Rx framework: <a href="http://rxwiki.wikidot.com/101samples" rel="noreferrer">http://rxwiki.wikidot.com/101samples</a></p> <p>I found this to be the most comprehensive site out there, and the one that's quickest to get started with.</p>
{ "question_id": 1596158, "question_date": "2009-10-20T17:33:42.437Z", "question_score": 222, "tags": "c#|.net|asynchronous|system.reactive", "answer_id": 1950381, "answer_date": "2009-12-23T02:30:26.090Z", "answer_score": 85 }
Please answer the following Stack Overflow question: Title: Beginner's guide to ElasticSearch <p>There hasn't been any books about ElasticSearch (that I know of), and <a href="http://www.elasticsearch.org/guide/">http://www.elasticsearch.org/guide/</a> seems to contain only references.</p> <p>Any good beginner's guide or tutorials, perhaps by examples, to recommend, especially in terms of the different mapping and indexing strategies?</p>
<p><strong>Edit (April 2015):</strong></p> <p>As many have noticed, my old blog is now defunct. Most of my articles were transferred over to the Elastic blog, and can be found by filtering on my name: <a href="https://www.elastic.co/blog/author/zachary-tong" rel="noreferrer">https://www.elastic.co/blog/author/zachary-tong</a></p> <p>To be perfectly honest, the best source of beginner knowledge is now <a href="https://www.elastic.co/guide/en/elasticsearch/guide/master/index.html" rel="noreferrer">Elasticsearch - The Definitive Guide</a> written by myself and Clinton Gormley. </p> <p>It assumes zero search engine knowledge and explains information retrieval first principals in context of Elasticsearch. While the reference docs are all about finding the precise parameter you need, the Guide is a narrative that discusses problems in search and how to solve them.</p> <p>Best of all, the book is OSS and free (unless you want to buy a paper copy, in which case O'Reilly will happily sell you one :) )</p> <p><strong>Edit (August 2013):</strong> </p> <p>Many of my articles have been migrated over to the <a href="http://elasticsearch.org/blog/" rel="noreferrer">official Elasticsearch blog</a>, as well as new articles that have not been published on my personal site.</p> <p><strong>Original post:</strong></p> <p>I've also been frustrated with learning ElasticSearch, having no Lucene/Solr experience. I've been slowly documenting things I've learned at my blog, and have four tutorials written so far:</p> <p>So I don't have to keep editing, <a href="http://euphonious-intuition.com/category/elasticsearch/" rel="noreferrer">all future tutorials on my blog can be found under this category link.</a></p> <p>And these are some links that I have bookmarked, because they have been incredibly helpful in one way or another:</p> <ul> <li><a href="http://elasticsearch-users.115913.n3.nabble.com/I-am-tired-of-continuously-trying-to-override-the-default-analyzer-and-tokanizer-settings-tp3350150p3354293.html" rel="noreferrer">Thinking through and debugging problems with your query</a></li> <li><a href="http://elasticsearch-users.115913.n3.nabble.com/help-needed-with-the-query-tp3177477p3178856.html" rel="noreferrer">Another example of complicated mapping (ngram, synonyms, phonemes)</a></li> <li><a href="http://blog.avisi.nl/2012/02/22/searching-parts-of-words-with-elasticsearch/" rel="noreferrer">Searching parts of a word</a></li> <li><a href="http://www.spacevatican.org/2012/6/3/fun-with-elasticsearch-s-children-and-nested-documents/" rel="noreferrer">Fun with ElasticSearch's children and nested documents</a></li> </ul>
{ "question_id": 11593035, "question_date": "2012-07-21T14:34:52.993Z", "question_score": 222, "tags": "search|full-text-search|elasticsearch", "answer_id": 11767610, "answer_date": "2012-08-01T21:08:00.877Z", "answer_score": 283 }
Please answer the following Stack Overflow question: Title: Setting design time DataContext on a Window is giving a compiler error? <p>I have the following XAML below for the main window in my WPF application, I am trying to set the design time <code>d:DataContext</code> below, which I can successfully do for all my various UserControls, but it gives me this error when I try to do it on the window...</p> <p><code>Error 1 The property 'DataContext' must be in the default namespace or in the element namespace 'http://schemas.microsoft.com/winfx/2006/xaml/presentation'. Line 8 Position 9. C:\dev\bplus\PMT\src\UI\MainWindow.xaml 8 9 UI</code></p> <pre><code>&lt;Window x:Class="BenchmarkPlus.PMT.UI.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:UI="clr-namespace:BenchmarkPlus.PMT.UI" xmlns:Controls="clr-namespace:BenchmarkPlus.PMT.UI.Controls" d:DataContext="{d:DesignInstance Type=UI:MainViewModel, IsDesignTimeCreatable=True}" Title="MainWindow" Height="1000" Width="1600" Background="#FF7A7C82"&gt; &lt;Grid&gt; &lt;!-- Content Here --&gt; &lt;/grid&gt; &lt;/Window&gt; </code></pre>
<p>I needed to add the <code>mc:Ignorable="d"</code> attribute to the Window tag. Essentially I learned something new. The <code>d:</code> namespace prefix that Expression Blend/Visual Studio designer acknowledges is actually <em>ignored/"commented out"</em> by the real compiler/xaml parser!</p> <pre><code>&lt;Window ... xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" ... /&gt; </code></pre> <p>The following was taken from </p> <p><a href="http://amzn.com/0672331195" rel="noreferrer"><em>Nathan, Adam (2010-06-04). WPF 4 Unleashed (Kindle Locations 1799-1811). Sams. Kindle Edition.</em></a></p> <p><strong>Markup Compatibility</strong></p> <p>The markup compatibility XML namespace (<a href="http://schemas.openxmlformats.org/markup-compatibility/2006" rel="noreferrer">http://schemas.openxmlformats.org/markup-compatibility/2006</a>, typically used with an <code>mc</code> prefix) contains an Ignorable attribute that instructs XAML processors to ignore all elements/attributes in specified namespaces if they can’t be resolved to their .NET types/members. (The namespace also has a ProcessContent attribute that overrides Ignorable for specific types inside the ignored namespaces.)</p> <p>Expression Blend takes advantage of this feature to do things like add design-time properties to XAML content that can be ignored at runtime.</p> <p><code>mc:Ignorable</code> can be given a space-delimited list of namespaces, and mc:ProcessContent can be given a space-delimited list of elements. When XamlXmlReader encounters ignorable content that can’t be resolved, it doesn’t report any nodes for it. If the ignorable content can be resolved, it will be reported normally. So consumers don’t need to do anything special to handle markup compatibility correctly.</p>
{ "question_id": 8303803, "question_date": "2011-11-28T23:20:20.040Z", "question_score": 222, "tags": "wpf", "answer_id": 8303989, "answer_date": "2011-11-28T23:43:14.473Z", "answer_score": 303 }
Please answer the following Stack Overflow question: Title: How do I avoid capturing self in blocks when implementing an API? <p>I have a working app and I'm working on converting it to ARC in Xcode 4.2. One of the pre-check warnings involves capturing <code>self</code> strongly in a block leading to a retain cycle. I've made a simple code sample to illustrate the issue. I believe I understand what this means but I'm not sure the "correct" or recommended way to implement this type of scenario.</p> <ul> <li>self is an instance of class MyAPI</li> <li>the code below is simplified to show only the interactions with the objects and blocks relevant to my question</li> <li>assume that MyAPI gets data from a remote source and MyDataProcessor works on that data and produces an output</li> <li>the processor is configured with blocks to communicate progress &amp; state</li> </ul> <p>code sample:</p> <pre><code>// code sample self.delegate = aDelegate; self.dataProcessor = [[MyDataProcessor alloc] init]; self.dataProcessor.progress = ^(CGFloat percentComplete) { [self.delegate myAPI:self isProcessingWithProgress:percentComplete]; }; self.dataProcessor.completion = ^{ [self.delegate myAPIDidFinish:self]; self.dataProcessor = nil; }; // start the processor - processing happens asynchronously and the processor is released in the completion block [self.dataProcessor startProcessing]; </code></pre> <p>Question: what am I doing "wrong" and/or how should this be modified to conform to ARC conventions?</p>
<h2>Short answer</h2> <p>Instead of accessing <code>self</code> directly, you should access it indirectly, from a reference that will not be retained. <strong>If you're not using Automatic Reference Counting (ARC)</strong>, you can do this:</p> <pre><code>__block MyDataProcessor *dp = self; self.progressBlock = ^(CGFloat percentComplete) { [dp.delegate myAPI:dp isProcessingWithProgress:percentComplete]; } </code></pre> <p>The <code>__block</code> keyword marks variables that can be modified inside the block (we're not doing that) but also they are not automatically retained when the block is retained (unless you are using ARC). If you do this, you must be sure that nothing else is going to try to execute the block after the MyDataProcessor instance is released. (Given the structure of your code, that shouldn't be a problem.) <a href="https://stackoverflow.com/questions/7080927/what-does-the-block-keyword-mean">Read more about <code>__block</code></a>.</p> <p><strong>If you are using ARC</strong>, the semantics of <code>__block</code> changes and the reference will be retained, in which case you should declare it <code>__weak</code> instead.</p> <h2>Long answer</h2> <p>Let's say you had code like this:</p> <pre><code>self.progressBlock = ^(CGFloat percentComplete) { [self.delegate processingWithProgress:percentComplete]; } </code></pre> <p>The problem here is that self is retaining a reference to the block; meanwhile the block must retain a reference to self in order to fetch its delegate property and send the delegate a method. If everything else in your app releases its reference to this object, its retain count won't be zero (because the block is pointing to it) and the block isn't doing anything wrong (because the object is pointing to it) and so the pair of objects will leak into the heap, occupying memory but forever unreachable without a debugger. Tragic, really.</p> <p>That case could be easily fixed by doing this instead:</p> <pre><code>id progressDelegate = self.delegate; self.progressBlock = ^(CGFloat percentComplete) { [progressDelegate processingWithProgress:percentComplete]; } </code></pre> <p>In this code, self is retaining the block, the block is retaining the delegate, and there are no cycles (visible from here; the delegate may retain our object but that's out of our hands right now). This code won't risk a leak in the same way, because the value of the delegate property is captured when the block is created, instead of looked up when it executes. A side effect is that, if you change the delegate after this block is created, the block will still send update messages to the old delegate. Whether that is likely to happen or not depends on your application.</p> <p>Even if you were cool with that behavior, you still can't use that trick in your case:</p> <pre><code>self.dataProcessor.progress = ^(CGFloat percentComplete) { [self.delegate myAPI:self isProcessingWithProgress:percentComplete]; }; </code></pre> <p>Here you are passing <code>self</code> directly to the delegate in the method call, so you have to get it in there somewhere. If you have control over the definition of the block type, the best thing would be to pass the delegate into the block as a parameter:</p> <pre><code>self.dataProcessor.progress = ^(MyDataProcessor *dp, CGFloat percentComplete) { [dp.delegate myAPI:dp isProcessingWithProgress:percentComplete]; }; </code></pre> <p>This solution avoids the retain cycle <em>and</em> always calls the current delegate.</p> <p>If you can't change the block, you could <em>deal with it</em>. The reason a retain cycle is a warning, not an error, is that they don't necessarily spell doom for your application. If <code>MyDataProcessor</code> is able to release the blocks when the operation is complete, before its parent would try to release it, the cycle will be broken and everything will be cleaned up properly. If you could be sure of this, then the right thing to do would be to use a <code>#pragma</code> to suppress the warnings for that block of code. (Or use a per-file compiler flag. But don't disable the warning for the whole project.)</p> <p>You could also look into using a similar trick above, declaring a reference weak or unretained and using that in the block. For example:</p> <pre><code>__weak MyDataProcessor *dp = self; // OK for iOS 5 only __unsafe_unretained MyDataProcessor *dp = self; // OK for iOS 4.x and up __block MyDataProcessor *dp = self; // OK if you aren't using ARC self.progressBlock = ^(CGFloat percentComplete) { [dp.delegate myAPI:dp isProcessingWithProgress:percentComplete]; } </code></pre> <p>All three of the above will give you a reference without retaining the result, though they all behave a little bit differently: <code>__weak</code> will try to zero the reference when the object is released; <code>__unsafe_unretained</code> will leave you with an invalid pointer; <code>__block</code> will actually add another level of indirection and allow you to change the value of the reference from within the block (irrelevant in this case, since <code>dp</code> isn't used anywhere else).</p> <p>What's <em>best</em> will depend on what code you are able to change and what you cannot. But hopefully this has given you some ideas on how to proceed.</p>
{ "question_id": 7853915, "question_date": "2011-10-21T18:49:40.057Z", "question_score": 222, "tags": "objective-c|ios|objective-c-blocks|automatic-ref-counting", "answer_id": 7854315, "answer_date": "2011-10-21T19:25:07.197Z", "answer_score": 509 }
Please answer the following Stack Overflow question: Title: bash HISTSIZE vs. HISTFILESIZE? <p>What is the difference in <code>HISTSIZE</code> vs. <code>HISTFILESIZE</code>?</p> <p>They are used to extend bash history beyond the default 500 lines.</p> <p>There seems to be lack of clarity here and in other forums about why they are both needed. (<a href="http://www.unix.com/unix-dummies-questions-answers/191301-histsize-histfilesize.html" rel="noreferrer">Example 1</a>, <a href="https://stackoverflow.com/questions/10401898/linux-history-command/10401951#10401951">Example 2</a>, <a href="https://unix.stackexchange.com/a/17587">Example 3</a>).</p>
<h2>Short answer:</h2> <p><code>HISTSIZE</code> is the number of lines or commands that are stored in memory in a history list while your bash session is ongoing.</p> <p><code>HISTFILESIZE</code> is the number of lines or commands that (a) are allowed in the history file at startup time of a session, and (b) are stored in the history file at the end of your bash session for use in future sessions.</p> <p>Notice the distinction between <code>file</code>: on disk - and <code>list</code>: in memory.</p> <h2>Long answer:</h2> <p>All the info above + some examples:</p> <p><strong>Example 1</strong>: <code>HISTFILESIZE=10</code> and <code>HISTSIZE=10</code></p> <ol> <li>You start your session.</li> <li>Your HISTFILE (file that stores your bash command history), is truncated to contain HISTFILESIZE=10 lines.</li> <li>You write 50 lines.</li> <li>At the end of your 50 commands, only commands 41 to 50 are in your history list, whose size is determined by HISTSIZE=10.</li> <li>You end your session.</li> <li>Assuming <code>histappend</code> is not enabled, commands 41 to 50 are saved to your HISTFILE which now has the 10 commands it held at the beginning plus the 10 newly written commands.</li> <li>Your HISTFILE is truncated to contain HISTFILESIZE=10 lines.</li> <li>You now have 10 commands in your history - the last 10 that you just typed in the session you just finished.</li> <li>When you start a new session, you start over at 1 with a HISTFILE of HISTFILESIZE=10.</li> </ol> <p><strong>Example 2</strong>: <code>HISTFILESIZE=10</code> and <code>HISTSIZE=5</code></p> <ol> <li>You start your session.</li> <li>Your HISTFILE (file that stores your bash command history), is truncated to contain at most HISTFILESIZE=10 lines.</li> <li>You write 50 lines.</li> <li>At the end of your 50 commands, only commands 46 to 50 are in your history list, whose size is determined by HISTSIZE=5.</li> <li>You end your session.</li> <li>Assuming <code>histappend</code> is not enabled, commands 46 to 50 are saved to your HISTFILE which now has the 10 commands it held at the beginning plus the 5 newly written commands.</li> <li>Your HISTFILE is truncated to contain HISTFILESIZE=10 lines.</li> <li>You now have 10 commands in your history - 5 from a previous session and the last 5 that you just typed in the session you just finished.</li> <li>When you start a new session, you start over at 1 with a HISTFILE of HISTFILESIZE=10.</li> </ol> <p><strong>Example 3</strong>: <code>HISTFILESIZE=5</code> and <code>HISTSIZE=10</code></p> <ol> <li>You start your session.</li> <li>Your HISTFILE (file that stores your bash command history), is truncated to contain at most HISTFILESIZE=5 lines.</li> <li>You write 50 lines.</li> <li>At the end of your 50 commands, only commands 41 to 50 are in your history list, whose size is determined by HISTSIZE=10.</li> <li>You end your session.</li> <li>Assuming <code>histappend</code> is not enabled, commands 41 to 50 are saved to your HISTFILE which now has the 5 commands it held at the beginning plus the 10 newly written commands.</li> <li>Your HISTFILE is truncated to contain HISTFILESIZE=5 lines.</li> <li>You now have 5 commands in your history - the last 5 that you just typed in the session you just finished.</li> <li>When you start a new session, you start over at step 1 with a HISTFILE of HISTFILESIZE=5.</li> </ol> <p>Info from <a href="http://www.unix.com/unix-dummies-questions-answers/191301-histsize-histfilesize.html" rel="noreferrer">elixir_sinari</a>:</p> <blockquote> <p>The history &quot;file&quot; is not updated as you type the commands. The commands get stored in a &quot;list&quot; separately (accessed by the history command). The number of these stored commands is controlled by HISTSIZE value. When the shell (interactive) exits, the last $HISTSIZE lines are copied/appended to $HISTFILE from that &quot;list&quot;. If HISTFILESIZE is set, then after this operation, it is ensured that only $HISTFILESIZE lines (latest) exist in $HISTFILE . And when the shell starts, the &quot;list&quot; is initialized from $HISTFILE up to a maximum of $HISTSIZE commands.</p> </blockquote> <p>And from the <code>man bash</code> page:</p> <blockquote> <p>The value of the HISTSIZE variable is used as the number of commands to save in a history list. The text of the last HISTSIZE commands (default 500) is saved. (...)</p> <p>On startup, the history is initialized from the file named by the variable HISTFILE (default ~/.bash_history). The file named by the value of HISTFILE is truncated, if necessary, to contain no more than the number of lines specified by the value of HISTFILESIZE. (...) When an interactive shell exits, the last $HISTSIZE lines are copied from the history list to $HISTFILE. If the histappend shell option is enabled (see the description of shopt under SHELL BUILTIN COMMANDS below), the lines are appended to the history file, otherwise the history file is overwritten. If HISTFILE is unset, or if the history file is unwritable, the history is not saved. (...) After saving the history, the history file is truncated to contain no more than HISTFILESIZE lines. If HISTFILESIZE is not set, no truncation is performed.</p> </blockquote>
{ "question_id": 19454837, "question_date": "2013-10-18T16:43:37.317Z", "question_score": 222, "tags": "bash|unix", "answer_id": 19454838, "answer_date": "2013-10-18T16:43:37.317Z", "answer_score": 365 }
Please answer the following Stack Overflow question: Title: If I revoke an existing distribution certificate, will it mess up anything with existing apps? <p>I built an iOS app for an organization that has an app already on the store. After weeks of trying to get the guy who has the key to sign the app, they finally came back and said, "Just get it done!". So I am wondering how to proceed. If I go into the provisioning portal, and revoke the dist certificate, and then re-assign one, will I then be able to sign the app and upload it without problem?</p> <p>That is what I was going to do, but I don't know the ramifications for the existing app. Will it mess anything up with that? And then when the organization wants to continue updates on their apps, can't they just revoke, and then reassign the certificate to them again?</p> <p>This part of the process is a bit foggy to me, so a little clarification would be appreciated!!</p>
<p>There is no problem doing this unless you are on an enterprise account. Distribution certificates expire anyway, so eventually it will happen that you need a new one. Go ahead and delete away.</p> <p>You can also find this question asked, answered, and asked again many times over on the Apple Dev forums (e.g. <a href="https://discussions.apple.com/thread/2671101?threadID=2671101" rel="noreferrer">here's one</a>), so google around there if you're still hesitant.</p> <p><strong>About Enterprise Developer accounts:</strong> With thanks to Mike's comment</p> <p>An App store app gets resigned with an Apple certificate when it goes on the store. Revoking the cert in the provisioning portal therefore won't affect it. Enterprise apps use the original certificate, which means revoking it will cause the app to stop functioning on all devices it is installed on. If you revoke an enterprise account's certificate, all apps installed on all employee devices will stop working</p>
{ "question_id": 6320255, "question_date": "2011-06-12T05:07:08.837Z", "question_score": 222, "tags": "certificate|app-store|apple-developer|ios-app-signing", "answer_id": 6320268, "answer_date": "2011-06-12T05:11:00.160Z", "answer_score": 243 }
Please answer the following Stack Overflow question: Title: What is the inverse function of zip in python? <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/19339/a-transpose-unzip-function-in-python">A Transpose/Unzip Function in Python</a> </p> </blockquote> <p>I've used the zip() function from the numpy library to sort tuples and now I have a list containing all the tuples. I had since modified that list and now I would like to restore the tuples so I can use my data. How can I do this?</p>
<pre><code>lst1, lst2 = zip(*zipped_list) </code></pre> <p>should give you the unzipped list.</p> <p><code>*zipped_list</code> unpacks the zipped_list object. it then passes all the tuples from the zipped_list object to zip, which just packs them back up as they were when you passed them in.</p> <p>so if:</p> <pre><code>a = [1,2,3] b = [4,5,6] </code></pre> <p>then <code>zipped_list = zip(a,b)</code> gives you:</p> <pre><code>[(1,4), (2,5), (3,6)] </code></pre> <p>and <code>*zipped_list</code> gives you back</p> <pre><code>(1,4), (2,5), (3,6) </code></pre> <p>zipping that with <code>zip(*zipped_list)</code> gives you back the two collections:</p> <pre><code>[(1, 2, 3), (4, 5, 6)] </code></pre>
{ "question_id": 13635032, "question_date": "2012-11-29T21:26:25.347Z", "question_score": 222, "tags": "python|list|numpy|tuples", "answer_id": 13635074, "answer_date": "2012-11-29T21:28:51.800Z", "answer_score": 437 }
Please answer the following Stack Overflow question: Title: Spring @Autowired usage <p>What are the pros and cons of using <strong>@Autowired</strong> in a class that will be wired up by Spring? </p> <p>Just to clarify, I'm talking specifically about the <strong>@Autowired</strong> annotation, not auto-wiring in XML.</p> <p>I probably just don't understand it, but to me it almost seems like an anti-pattern - your classes start to become aware that they are tied to a DI framework, rather than just being POJOs. Maybe I'm a glutton for punishment, but I like having the external XML config for beans, and I like to have explicit wirings, so I know exactly what is wired where.</p>
<p>For a long time I believed that there was a value in having a "centralized, declarative, configuration" like the xml files we all used to use. Then I realized that most of the stuff in the files wasn't <em>configuration</em> - it was never changed anywhere after development, ever. Then I realized that "centralized" only has value in quite small systems - only in small systems will you ever be able to grok a configuration file <em>as a whole</em>. And what is really the value of understanding the wiring as a whole, when the same "wirings" are mostly duplicated by dependencies in the code? So the only thing I've kept is meta-data (annotations), which is still kind-of declarative. These <em>never</em> change at runtime and they're <em>never</em> "configuration" data that someone will change on the fly - so I think keeping it in the code is nice.</p> <p>I use full auto-wiring as much as I can. I love it. I won't go back to old-style spring unless threatened at gun-point. My reasons for preferring fully <code>@Autowired</code> have changed over time.</p> <p>Right now I think the most important reason for using autowiring is that there's one less abstraction in your system to keep track of. The "bean name" is effectively gone. It turns out the bean name only exists because of xml. So a full layer of abstract indirections (where you would wire bean-name "foo" into bean "bar") is gone. Now I wire the "Foo" interface into my bean directly, and implementation is chosen by run-time profile. This allows me to <em>work with code</em> when tracing dependencies and implementations. When I see an autowired dependency in my code I can just press the "go to implementation" key in my IDE and up comes the list of known implementations. In most cases there's just one implementation and I'm straight into the class. Can't be much simpler than that, and I always know <em>exactly</em> what implementation is being used (I claim that the opposite is closer to the truth with xml wiring - funny how your perspective changes!)</p> <p>Now you could say that it's just a very simple layer, but each layer of abstraction that we add to our systems <em>increase</em> complexity. I really don't think the xml ever added any real value to any system I've worked with. </p> <p>Most systems I've ever work with only have <em>one</em> configuration of the production runtime environment. There may be other configurations for test and so on.</p> <p>I'd say that full autowiring is the ruby-on-rails of spring: It embraces the notion that there's a normal and common usage pattern that most use cases follow. With XML configuration you <em>permit</em> a lot of consistent/inconsistent configuration usage that may/may not be intended. I've seen so much xml configuration go overboard with inconsistencies - does it get refactored together with the code ? Thought not. Are those variations there for a reason? Usually not.</p> <p>We hardly use qualifiers in our configuration, and found other ways to solve these situations. This is a clear "disadvantage" we encounter: We've slightly changed the way we code to make it interact smoother with autowiring: A customer repository no longer implements the generic <code>Repository&lt;Customer&gt;</code> interface but we make an interface <code>CustomerRepository</code> that extends <code>Repository&lt;Customer&gt;</code>. Sometimes there's also a trick or two when it comes to subclassing. But it usually just points us in the direction of stronger typing, which I find is almost always a better solution.</p> <p>But yes, you're tying to a particular style of DI that mostly spring does. We don't even make public setters for dependencies any more (So you could argue that we're +1 in the encapsulation/information hiding department) We still have some xml in our system, but the xml basically <em>only</em> contains the anomalies. Full autowiring integrates nicely with xml.</p> <p>The only thing we need now is for the <code>@Component</code>, <code>@Autowired</code> and the rest to be included in a JSR (like <a href="https://www.jcp.org/en/jsr/detail?id=250" rel="noreferrer">JSR-250</a>), so we don't have to tie in with spring. This is the way things have been happening in the past (the <code>java.util.concurrent</code> stuff springs to mind), so I wouldn't be entirely surprised if this happened again.</p>
{ "question_id": 633158, "question_date": "2009-03-11T02:44:24.170Z", "question_score": 222, "tags": "java|spring|autowired", "answer_id": 634754, "answer_date": "2009-03-11T14:30:36.980Z", "answer_score": 255 }
Please answer the following Stack Overflow question: Title: Why does the month argument range from 0 to 11 in JavaScript's Date constructor? <p>When initializing a new <code>Date</code> object in JavaScript using the below call, I found out that the month argument counts starting from zero.</p> <pre><code>new Date(2010, 3, 1); // that's the 1st April 2010! </code></pre> <p>Why does the month argument start from 0? On the other hand, the day of the month argument (last one) is a number from 1 to 31. Are there good reasons for this?</p>
<p>It's an old (probably unfortunate, probably dying) tradition in the programming world, see the old standard (POSIX) <em>localtime</em> C function <a href="http://linux.die.net/man/3/localtime" rel="noreferrer">http://linux.die.net/man/3/localtime</a></p>
{ "question_id": 2552483, "question_date": "2010-03-31T11:34:35.007Z", "question_score": 222, "tags": "javascript|datetime|date", "answer_id": 2552517, "answer_date": "2010-03-31T11:40:05.137Z", "answer_score": 84 }
Please answer the following Stack Overflow question: Title: Kotlin : Public get private set var <p>What is the correct way to define a var in kotlin that has a public getter and private (only internally modifiable) setter?</p>
<pre><code>var setterVisibility: String = "abc" // Initializer required, not a nullable type private set // the setter is private and has the default implementation </code></pre> <p>See: <a href="http://kotlinlang.org/docs/reference/properties.html#getters-and-setters">Properties Getter and Setter</a></p>
{ "question_id": 33428957, "question_date": "2015-10-30T04:58:55.057Z", "question_score": 222, "tags": "kotlin", "answer_id": 33430227, "answer_date": "2015-10-30T06:47:38.343Z", "answer_score": 361 }
Please answer the following Stack Overflow question: Title: returning in the middle of a using block <p>Something like:</p> <pre><code>using (IDisposable disposable = GetSomeDisposable()) { //..... //...... return Stg(); } </code></pre> <p>I believe it is not a proper place for a return statement, is it?</p>
<p>As several others have pointed out in general this is not a problem.</p> <p>The only case it will cause you issues is if you return in the middle of a using statement and additionally return the in using variable. But then again, this would also cause you issues even if you didn't return and simply kept a reference to a variable. </p> <pre><code>using ( var x = new Something() ) { // not a good idea return x; } </code></pre> <p>Just as bad</p> <pre><code>Something y; using ( var x = new Something() ) { y = x; } </code></pre>
{ "question_id": 662773, "question_date": "2009-03-19T15:53:39.960Z", "question_score": 222, "tags": "c#|dispose|idisposable|using-statement", "answer_id": 662816, "answer_date": "2009-03-19T16:02:18.627Z", "answer_score": 211 }
Please answer the following Stack Overflow question: Title: Git search for string in a single file's history <p>So if I have a file called <strong>foo.rb</strong> and it is giving me an error for a missing method called <strong>bar</strong>, so I want to search the history of <strong>foo.rb</strong> for the string <code>bar</code> to see if it was ever defined in the past.</p> <p>I found this <a href="https://stackoverflow.com/questions/4468361/search-all-of-git-history-for-string">Search all of Git history for a string?</a></p> <p>But this searches all files. I just want to search in one file.</p>
<p>For this purpose you can use the -S option to git log:</p> <pre><code>git log -S'bar' -- foo.rb </code></pre>
{ "question_id": 10215197, "question_date": "2012-04-18T18:00:25.873Z", "question_score": 222, "tags": "git", "answer_id": 10216050, "answer_date": "2012-04-18T18:55:53.163Z", "answer_score": 306 }
Please answer the following Stack Overflow question: Title: Xcode 4 says "finished running <my app>" on the targeted device -- Nothing happens <p>The app neither installs nor runs on my device. All provisioning profiles are up to date. I've already tried deleting and re-installing them.</p> <p>The status bar shows that Xcode is building my project, then it says running my project on , then it says "finished running ." Throughout this entire period, the iPod screen stays black. The iPod is being detected in the Organizer and I don't see anything wrong with its configuration. Everything was working perfectly just a couple days ago with Xcode 3.</p> <p>It doesn't work on the simulator, but it may be important to note that in the simulator it appears to get stuck on "Attaching to " and the simulator refuses to start.</p>
<p>For those reading this in regards to Xcode 4.2, and attempting to run on an earlier device (e.g. iPhone 3G, 2G, iPod 1st gen, etc) I have another solution. New projects created in Xcode 4.2 by default specify 'armv7' in the 'Required Device Capabilities'. You'll need to remove this if wanting to support devices that run armv6 (e.g. the iPhone 3G).</p> <p><img src="https://i.stack.imgur.com/AOGLP.png" alt="enter image description here"></p> <p>Delete armv7 from the 'Required device capabilities' in yourProjectName-Info.plist</p> <p>You may also need to change the build settings to compile with armv6 instead of armv7. </p> <p>This is the default:</p> <p><img src="https://i.stack.imgur.com/kCvA4.png" alt="enter image description here"></p> <p>Double click on 'Standard (armv7)' to add another, then click the '+' in the popup, and type in 'armv6':</p> <p><img src="https://i.stack.imgur.com/TjZJT.png" alt="enter image description here"></p> <p>Click done and it should look like this:</p> <p><img src="https://i.stack.imgur.com/Hi7qP.png" alt="enter image description here"></p>
{ "question_id": 5292286, "question_date": "2011-03-13T20:48:50.193Z", "question_score": 222, "tags": "iphone|ios|xcode|xcode4|ipod-touch", "answer_id": 7788578, "answer_date": "2011-10-17T01:21:36.480Z", "answer_score": 267 }
Please answer the following Stack Overflow question: Title: Visual Studio refuses to forget breakpoints? <p>Visual Studio remembers breakpoints from previous debugging sessions, which is awesome.</p> <p>However, when I'm debugging, and I clear one of these "old" breakpoints by clicking on it, it's only temporarily deleted. What I mean is the next time I debug, the breakpoint that I thought I removed is back. </p> <p>This is super annoying--is there a setting to make it not do this? </p>
<p>go to <code>Debug</code> menu then <code>Delete All Breakpoints</code> <code>Ctrl+Shift+F9</code></p>
{ "question_id": 5983918, "question_date": "2011-05-12T20:14:37.557Z", "question_score": 222, "tags": "visual-studio|debugging|breakpoints", "answer_id": 5983950, "answer_date": "2011-05-12T20:18:19.390Z", "answer_score": 138 }
Please answer the following Stack Overflow question: Title: Do I need to explicitly handle negative numbers or zero when summing squared digits? <p>I recently had a test in my class. One of the problems was the following:</p> <blockquote> <p>Given a number <strong>n</strong>, write a function in C/C++ that returns the sum of the digits of the number <em>squared</em>. (The following is important). The <em>range</em> of <strong>n</strong> is [ -(10^7), 10^7 ]. Example: If <strong>n</strong> = 123, your function should return 14 (1^2 + 2^2 + 3^2 = 14).</p> </blockquote> <p>This is the function that I wrote:</p> <pre><code>int sum_of_digits_squared(int n) { int s = 0, c; while (n) { c = n % 10; s += (c * c); n /= 10; } return s; } </code></pre> <p>Looked right to me. So now the test came back and I found that the teacher didn't give me all the points for a reason that I do not understand. According to him, for my function to be complete, I should've have added the following detail:</p> <pre><code>int sum_of_digits_squared(int n) { int s = 0, c; if (n == 0) { // return 0; // } // // THIS APPARENTLY SHOULD'VE if (n &lt; 0) { // BEEN IN THE FUNCTION FOR IT n = n * (-1); // TO BE CORRECT } // while (n) { c = n % 10; s += (c * c); n /= 10; } return s; } </code></pre> <p>The argument for this is that the number <strong>n</strong> is in the range [-(10^7), 10^7], so it can be a negative number. But I don't see where my own version of the function fails. If I understand correctly, the meaning of <code>while(n)</code> is <code>while(n != 0)</code>, <strong>not</strong> <code>while (n &gt; 0)</code>, so in my version of the function the number <strong>n</strong> wouldn't fail to enter the loop. It would work just the same. </p> <p>Then, I tried both versions of the function on my computer at home and I got exactly the same answers for all the examples that I tried. So, <code>sum_of_digits_squared(-123)</code> is equal to <code>sum_of_digits_squared(123)</code> (which again, is equal to <code>14</code>) (even without the detail that I apparently should've added). Indeed, if I try to print on the screen the digits of the number (from least to greatest in importance), in the <code>123</code> case I get <code>3 2 1</code> and in the <code>-123</code> case I get <code>-3 -2 -1</code> (which is actually kind of interesting). But in this problem it wouldn't matter since we square the digits. </p> <p>So, who's wrong?</p> <p><strong>EDIT</strong>: My bad, I forgot to specify and didn't know it was important. The version of C used in our class and tests has to be C99 or <strong>newer</strong>. So I guess (by reading the comments) that my version would get the correct answer in any way.</p>
<p>Summarizing a discussion that's been percolating in the comments:</p> <ul> <li>There is no good reason to test in advance for <code>n == 0</code>. The <code>while(n)</code> test will handle that case perfectly.</li> <li>It's likely your teacher is still used to earlier times, when the result of <code>%</code> with negative operands was differently defined. On some old systems (including, notably, early Unix on a PDP-11, where Dennis Ritchie originally developed C), the result of <code>a % b</code> was <em>always</em> in the range <code>[0 .. b-1]</code>, meaning that -123 % 10 was 7. On such a system, the test in advance for <code>n &lt; 0</code> would be necessary.</li> </ul> <p>But the second bullet applies only to earlier times. In the current versions of both the C and C++ standards, integer division is defined to truncate towards 0, so it turns out that <code>n % 10</code> is guaranteed to give you the (possibly negative) last digit of <code>n</code> even when <code>n</code> is negative.</p> <p>So the answer to the question <em>"What is the meaning of <code>while(n)</code>?"</em> is <em>"Exactly the same as <code>while(n != 0)</code>"</em>, and the answer to <em>"Will this code work properly for negative as well as positive <code>n</code>?"</em> is <em>"Yes, under any modern, Standards-conforming compiler."</em> The answer to the question <em>"Then why did the instructor mark it down?"</em> is probably that they're not aware of a significant language redefinition that happened to C in 1999 and to C++ in 2010 or so.</p>
{ "question_id": 58224638, "question_date": "2019-10-03T18:06:42.300Z", "question_score": 222, "tags": "c", "answer_id": 58225192, "answer_date": "2019-10-03T18:46:58.580Z", "answer_score": 253 }
Please answer the following Stack Overflow question: Title: What do the parentheses around a function name mean? <p>In one of my project source files, I found this C function definition:</p> <pre><code>int (foo) (int *bar) { return foo (bar); } </code></pre> <p>Note: there is no asterisk next to <code>foo</code>, so it's not a function pointer. Or is it? What is going on here with the recursive call?</p>
<p>In the absence of any preprocessor stuff going on, <code>foo</code>'s signature is equivalent to</p> <pre><code>int foo (int *bar) </code></pre> <p>The only context in which I've seen people putting seemingly unnecessary parentheses around function names is when there are both a function and a function-like macro with the same name, and the programmer wants to prevent macro expansion.</p> <p>This practice may seem a little odd at first, but the C library sets a precedent by <a href="https://softwareengineering.stackexchange.com/questions/159846/why-does-the-c-library-use-macros-and-functions-with-same-name">providing some macros and functions with identical names</a>.</p> <p>One such function/macro pair is <code>isdigit()</code>. The library might define it as follows:</p> <pre><code>/* the macro */ #define isdigit(c) ... /* the function */ int (isdigit)(int c) /* avoid the macro through the use of parentheses */ { return isdigit(c); /* use the macro */ } </code></pre> <p>Your function looks almost identical to the above, so I suspect this is what's going on in your code too.</p>
{ "question_id": 13600790, "question_date": "2012-11-28T08:27:44.917Z", "question_score": 222, "tags": "c|function|parentheses", "answer_id": 13600837, "answer_date": "2012-11-28T08:30:46.817Z", "answer_score": 339 }
Please answer the following Stack Overflow question: Title: How do I do multiple CASE WHEN conditions using SQL Server 2008? <p>What I'm trying to do is use more than one CASE WHEN condition for the same column.</p> <p>Here is my code for the query:</p> <pre><code> SELECT Url='', p.ArtNo, p.[Description], p.Specification, CASE WHEN 1 = 1 or 1 = 1 THEN 1 ELSE 0 END as Qty, p.NetPrice, [Status] = 0 FROM Product p (NOLOCK) </code></pre> <p>However, what I want to do is use more then one WHEN for the same column "qty".</p> <p>As in the following code:</p> <pre><code>IF // CODE ELSE IF // CODE ELSE IF // CODE ELSE // CODE </code></pre>
<p>There are <a href="https://docs.microsoft.com/en-in/sql/t-sql/language-elements/case-transact-sql" rel="noreferrer">three formats of case expression</a>. You can do <code>CASE</code> with many <code>WHEN</code> as;</p> <pre><code>CASE WHEN Col1 = 1 OR Col3 = 1 THEN 1 WHEN Col1 = 2 THEN 2 ... ELSE 0 END as Qty </code></pre> <p><em>Or</em> a Simple <code>CASE</code> expression</p> <pre><code>CASE Col1 WHEN 1 THEN 11 WHEN 2 THEN 21 ELSE 13 END </code></pre> <p><em>Or</em> <code>CASE</code> <em>within</em> <code>CASE</code> as;</p> <pre><code>CASE WHEN Col1 &lt; 2 THEN CASE Col2 WHEN 'X' THEN 10 ELSE 11 END WHEN Col1 = 2 THEN 2 ... ELSE 0 END as Qty </code></pre>
{ "question_id": 14630984, "question_date": "2013-01-31T16:51:44.313Z", "question_score": 221, "tags": "sql|sql-server-2008", "answer_id": 14631123, "answer_date": "2013-01-31T16:58:32.533Z", "answer_score": 511 }
Please answer the following Stack Overflow question: Title: how to change directory using Windows command line <p>I'm using <code>cmd.exe</code> (C:\WINDOWS\System32\cmd.exe) and I have to change my current directory to "D:\temp" i.e. temp folder in the D drive.</p> <p>When I try to <code>cd</code> nothing happens.</p> <pre><code>C:\&gt; cd D:\temp C:\&gt; </code></pre> <p>I don't know what else to do here. Even pressing <code>tab</code> key does not give any hints. I have never got the reason to use cmd.exe until now when I have to. I mostly use Linux for development.</p> <p>If this helps: I'm on a remote login to another computer and <code>D:\temp</code> in on the remote machine, but so is <code>C:\</code> where I have opened the terminal (cmd.exe).</p>
<p>The "cd" command changes the directory, but not what drive you are working with. So when you go "cd d:\temp", you are changing the D drive's directory to temp, but staying in the C drive.</p> <p>Execute these two commands:</p> <pre><code>D: cd temp </code></pre> <p>That will get you the results you want.</p>
{ "question_id": 17753986, "question_date": "2013-07-19T19:25:52.150Z", "question_score": 221, "tags": "windows|command-line|cmd|command-prompt", "answer_id": 17754011, "answer_date": "2013-07-19T19:27:37.983Z", "answer_score": 405 }
Please answer the following Stack Overflow question: Title: How to list files in windows using command prompt (cmd). I've tried using ' ls ' as in Linux but it shows an error? <p>When I tried to use list <code>ls</code> on a Windows command prompt, the system doesn't recognize it. I already added <code>C:\Windows\System32</code> in the path.</p>
<p>Use the command <code>dir</code> to list all the directories and files in a directory; <code>ls</code> is a unix command.</p>
{ "question_id": 42727245, "question_date": "2017-03-10T20:33:39.663Z", "question_score": 221, "tags": "windows|cmd|ls", "answer_id": 42727272, "answer_date": "2017-03-10T20:35:22.807Z", "answer_score": 383 }
Please answer the following Stack Overflow question: Title: Calling a JavaScript function in another js file <p>I wanted to call a function defined in a <em>first.js</em> file in <em>second.js</em> file. Both files are defined in an HTML file like:</p> <pre><code>&lt;script type=&quot;text/javascript&quot; src=&quot;first.js&quot;&gt;&lt;/script&gt; &lt;script type=&quot;text/javascript&quot; src=&quot;second.js&quot;&gt;&lt;/script&gt; </code></pre> <p>I want to call <code>fn1()</code> defined in <code>first.js</code> in <code>second.js</code>. From my searches answers were if <code>first.js</code> is defined first it is possible, but from my tests I haven't found any way to do that.</p> <p>Here is my code:</p> <p><code>second.js</code></p> <pre><code>document.getElementById(&quot;btn&quot;).onclick = function() { fn1(); } </code></pre> <p><code>first.js</code></p> <pre><code>function fn1() { alert(&quot;external fn clicked&quot;); } </code></pre>
<p>A function cannot be called unless it was defined in the same file or one loaded before the attempt to call it.</p> <p>A function cannot be called unless it is in the same or greater scope then the one trying to call it.</p> <p>You declare function <code>fn1</code> in first.js, and then in second you can just have <code>fn1();</code></p> <p><strong>1.js:</strong> </p> <pre><code>function fn1 () { alert(); } </code></pre> <p><strong>2.js:</strong> </p> <pre><code>fn1(); </code></pre> <p>index.html : </p> <pre><code>&lt;script type="text/javascript" src="1.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="2.js"&gt;&lt;/script&gt; </code></pre>
{ "question_id": 25962958, "question_date": "2014-09-21T19:19:56.570Z", "question_score": 221, "tags": "javascript|html", "answer_id": 25963012, "answer_date": "2014-09-21T19:26:43.297Z", "answer_score": 224 }
Please answer the following Stack Overflow question: Title: An existing connection was forcibly closed by the remote host <p>I am working with a commercial application which is throwing a SocketException with the message,</p> <blockquote> <p>An existing connection was forcibly closed by the remote host</p> </blockquote> <p>This happens with a socket connection between client and server. The connection is alive and well, and heaps of data is being transferred, but it then becomes disconnected out of nowhere.</p> <p>Has anybody seen this before? What could the causes be? I can kind of guess a few causes, but also is there any way to add more into this code to work out what the cause could be?</p> <p>Any comments / ideas are welcome.</p> <p>... The latest ...</p> <p>I have some logging from some .NET tracing,</p> <pre><code>System.Net.Sockets Verbose: 0 : [8188] Socket#30180123::Send() DateTime=2010-04-07T20:49:48.6317500Z System.Net.Sockets Error: 0 : [8188] Exception in the Socket#30180123::Send - An existing connection was forcibly closed by the remote host DateTime=2010-04-07T20:49:48.6317500Z System.Net.Sockets Verbose: 0 : [8188] Exiting Socket#30180123::Send() -&gt; 0#0 </code></pre> <p>Based on other parts of the logging I have seen the fact that it says <code>0#0</code> means a packet of 0 bytes length is being sent. But what does that really mean?</p> <p>One of two possibilities is occurring, and I am not sure which,</p> <ol> <li><p>The connection is being closed, but data is then being written to the socket, thus creating the exception above. The <code>0#0</code> simply means that nothing was sent because the socket was already closed.</p> </li> <li><p>The connection is still open, and a packet of zero bytes is being sent (i.e. the code has a bug) and the <code>0#0</code> means that a packet of zero bytes is trying to be sent.</p> </li> </ol> <p>What do you reckon? It might be inconclusive I guess, but perhaps someone else has seen this kind of thing?</p>
<p>This generally means that the remote side closed the connection (usually by sending a TCP/IP <code>RST</code> packet). If you're working with a third-party application, the likely causes are:</p> <ul> <li>You are sending malformed data to the application (which could include sending an HTTPS request to an HTTP server)</li> <li>The network link between the client and server is going down for some reason</li> <li>You have triggered a bug in the third-party application that caused it to crash</li> <li>The third-party application has exhausted system resources</li> </ul> <p>It's likely that the first case is what's happening.</p> <p>You can fire up <a href="http://www.wireshark.org/" rel="noreferrer">Wireshark</a> to see exactly what is happening on the wire to narrow down the problem.</p> <p>Without more specific information, it's unlikely that anyone here can really help you much.</p>
{ "question_id": 2582036, "question_date": "2010-04-06T00:54:22.460Z", "question_score": 221, "tags": "c#|.net|networking|sockets", "answer_id": 2582070, "answer_date": "2010-04-06T01:07:05.583Z", "answer_score": 138 }
Please answer the following Stack Overflow question: Title: Creating a copy of an object in C# <p>Please have a look at the code below (excerpt from a C# book):</p> <pre><code>public class MyClass { public int val; } public struct myStruct { public int val; } public class Program { private static void Main(string[] args) { MyClass objectA = new MyClass(); MyClass objectB = objectA; objectA.val = 10; objectB.val = 20; myStruct structA = new myStruct(); myStruct structB = structA; structA.val = 30; structB.val = 40; Console.WriteLine(&quot;objectA.val = {0}&quot;, objectA.val); Console.WriteLine(&quot;objectB.val = {0}&quot;, objectB.val); Console.WriteLine(&quot;structA.val = {0}&quot;, structA.val); Console.WriteLine(&quot;structB.val = {0}&quot;, structB.val); Console.ReadKey(); } } </code></pre> <p>I understands it produces the output below:</p> <pre><code>objectA.val = 20 objectB.val = 20 structA.val = 30 structB.val = 40 </code></pre> <p>The last two lines of the output I have no problem with, but the first two tell me that <code>objectA</code> and <code>objectB</code> are pointing to the same memory block (since in C#, objects are reference types).</p> <p>The question is how do make <code>objectB</code>, a copy of <code>objectA</code> so that it points to a different area in memory. I understand that trying to assign their members may not work since those members may be references, too. So how do I go about making <code>objectB</code> a completely different entity from <code>objectA</code>?</p>
<p>There is no built-in way. You can have MyClass implement the <code>IClonable</code> interface (but it is sort of deprecated) or just write your own Copy/Clone method. In either case you will have to write some code. </p> <p>For big objects you could consider Serialization + Deserialization (through a MemoryStream), just to reuse existing code. </p> <p>Whatever the method, think carefully about what "a copy" means exactly. How deep should it go, are there Id fields to be excepted etc. </p>
{ "question_id": 6569486, "question_date": "2011-07-04T09:21:23.857Z", "question_score": 221, "tags": "c#|object|reference|cloning", "answer_id": 6569524, "answer_date": "2011-07-04T09:25:07.290Z", "answer_score": 141 }
Please answer the following Stack Overflow question: Title: Adding one day to a date <p>My code to add one day to a date returns a date before day adding: <code>2009-09-30 20:24:00</code> date after adding one day SHOULD be rolled over to the next month: <code>1970-01-01 17:33:29</code></p> <pre><code>&lt;?php //add day to date test for month roll over $stop_date = date('Y-m-d H:i:s', strtotime("2009-09-30 20:24:00")); echo 'date before day adding: '.$stop_date; $stop_date = date('Y-m-d H:i:s', strtotime('+1 day', $stop_date)); echo ' date after adding one day. SHOULD be rolled over to the next month: '.$stop_date; ?&gt; </code></pre> <p>I have used pretty similar code before, what am I doing wrong here?</p>
<pre><code>&lt;?php $stop_date = '2009-09-30 20:24:00'; echo 'date before day adding: ' . $stop_date; $stop_date = date('Y-m-d H:i:s', strtotime($stop_date . ' +1 day')); echo 'date after adding 1 day: ' . $stop_date; ?&gt; </code></pre> <p>For PHP 5.2.0+, you may also do as follows:</p> <pre><code>$stop_date = new DateTime('2009-09-30 20:24:00'); echo 'date before day adding: ' . $stop_date-&gt;format('Y-m-d H:i:s'); $stop_date-&gt;modify('+1 day'); echo 'date after adding 1 day: ' . $stop_date-&gt;format('Y-m-d H:i:s'); </code></pre>
{ "question_id": 1394791, "question_date": "2009-09-08T15:55:34.057Z", "question_score": 221, "tags": "php|date|datetime", "answer_id": 1394811, "answer_date": "2009-09-08T16:00:21.970Z", "answer_score": 405 }
Please answer the following Stack Overflow question: Title: Plotting a 2D heatmap with Matplotlib <p>Using Matplotlib, I want to plot a 2D heat map. My data is an n-by-n Numpy array, each with a value between 0 and 1. So for the (i, j) element of this array, I want to plot a square at the (i, j) coordinate in my heat map, whose color is proportional to the element's value in the array.</p> <p>How can I do this?</p>
<p>The <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.imshow.html" rel="noreferrer"><code>imshow()</code></a> function with parameters <code>interpolation='nearest'</code> and <code>cmap='hot'</code> should do what you want.</p> <pre><code>import matplotlib.pyplot as plt import numpy as np a = np.random.random((16, 16)) plt.imshow(a, cmap='hot', interpolation='nearest') plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/O8e3x.png" rel="noreferrer"><img src="https://i.stack.imgur.com/O8e3x.png" alt="A sample color map produced by the example code" /></a></p>
{ "question_id": 33282368, "question_date": "2015-10-22T13:37:08.587Z", "question_score": 221, "tags": "python|numpy|matplotlib", "answer_id": 33282548, "answer_date": "2015-10-22T13:44:57.357Z", "answer_score": 285 }
Please answer the following Stack Overflow question: Title: How do I clear all options in a dropdown box? <p>My code works in IE but breaks in Safari, Firefox, and Opera. (big surprise)</p> <pre><code>document.getElementById("DropList").options.length=0; </code></pre> <p>After searching, I've learned that it's the <code>length=0</code> that it doesn't like.<br> I've tried <code>...options=null</code> and <code>var clear=0; ...length=clear</code> with the same result.</p> <p>I am doing this to multiple objects at a time, so I am looking for some lightweight JS code.</p>
<p>You can use the following to clear all the elements.</p> <pre><code>var select = document.getElementById("DropList"); var length = select.options.length; for (i = length-1; i &gt;= 0; i--) { select.options[i] = null; } </code></pre>
{ "question_id": 3364493, "question_date": "2010-07-29T15:57:47.007Z", "question_score": 221, "tags": "javascript|html-select", "answer_id": 3364526, "answer_date": "2010-07-29T16:01:01.507Z", "answer_score": 50 }
Please answer the following Stack Overflow question: Title: jQuery Scroll To bottom of the page <p>After my page is done loading. I want jQUery to nicely scroll to the bottom of the page, animating quickly, not a snap/jolt.</p> <p>Do iI need a plugin like <code>ScrollTo</code> for that? or is that built into jQuery some how?</p>
<p>You can just animate to scroll down the page by animating the <code>scrollTop</code> property, no plugin required, like this:</p> <pre><code>$(window).load(function() { $("html, body").animate({ scrollTop: $(document).height() }, 1000); }); </code></pre> <p>Note the use of <code>window.onload</code> (when images are loaded...which occupy height) rather than <code>document.ready</code>.</p> <p>To be technically correct, you need to subtract the window's height, but the above works:</p> <pre><code>$("html, body").animate({ scrollTop: $(document).height()-$(window).height() }); </code></pre> <hr> <p>To scroll to a particular ID, use its <a href="http://api.jquery.com/scrollTop/" rel="noreferrer"><code>.scrollTop()</code></a>, like this:</p> <pre><code>$("html, body").animate({ scrollTop: $("#myID").scrollTop() }, 1000); </code></pre>
{ "question_id": 4249353, "question_date": "2010-11-22T19:23:23.583Z", "question_score": 221, "tags": "jquery|jquery-plugins", "answer_id": 4249365, "answer_date": "2010-11-22T19:25:00.380Z", "answer_score": 466 }
Please answer the following Stack Overflow question: Title: Get list of pandas dataframe columns based on data type <p>If I have a dataframe with the following columns:</p> <pre><code>1. NAME object 2. On_Time object 3. On_Budget object 4. %actual_hr float64 5. Baseline Start Date datetime64[ns] 6. Forecast Start Date datetime64[ns] </code></pre> <p>I would like to be able to say: for this dataframe, <strong>give me a list of the columns which are of type 'object' or of type 'datetime'</strong>?</p> <p>I have a function which converts numbers ('float64') to two decimal places, and I would like to use this list of dataframe columns, of a particular type, and run it through this function to convert them all to 2dp.</p> <p>Maybe something like:</p> <pre><code>For c in col_list: if c.dtype = &quot;Something&quot; list[] List.append(c)? </code></pre>
<p>If you want a list of columns of a certain type, you can use <code>groupby</code>:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame([[1, 2.3456, 'c', 'd', 78]], columns=list("ABCDE")) &gt;&gt;&gt; df A B C D E 0 1 2.3456 c d 78 [1 rows x 5 columns] &gt;&gt;&gt; df.dtypes A int64 B float64 C object D object E int64 dtype: object &gt;&gt;&gt; g = df.columns.to_series().groupby(df.dtypes).groups &gt;&gt;&gt; g {dtype('int64'): ['A', 'E'], dtype('float64'): ['B'], dtype('O'): ['C', 'D']} &gt;&gt;&gt; {k.name: v for k, v in g.items()} {'object': ['C', 'D'], 'int64': ['A', 'E'], 'float64': ['B']} </code></pre>
{ "question_id": 22470690, "question_date": "2014-03-18T04:54:22.053Z", "question_score": 221, "tags": "python|pandas|dtype", "answer_id": 22475141, "answer_date": "2014-03-18T09:29:34.047Z", "answer_score": 345 }
Please answer the following Stack Overflow question: Title: Row count with PDO <p>There are many conflicting statements around. What is the best way to get the row count using PDO in PHP? Before using PDO, I just simply used <code>mysql_num_rows</code>.</p> <p><code>fetchAll</code> is something I won't want because I may sometimes be dealing with large datasets, so not good for my use.</p> <p>Do you have any suggestions?</p>
<pre><code>$sql = "SELECT count(*) FROM `table` WHERE foo = ?"; $result = $con-&gt;prepare($sql); $result-&gt;execute([$bar]); $number_of_rows = $result-&gt;fetchColumn(); </code></pre> <p>Not the most elegant way to do it, plus it involves an extra query.</p> <p>PDO has <code>PDOStatement::rowCount()</code>, which apparently does <strong>not</strong> work in MySql. What a pain.</p> <p>From the PDO Doc:</p> <blockquote> <p>For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned. Your application can then perform the correct action.</p> </blockquote> <p>EDIT: The above code example uses a prepared statement, which is in many cases is probably unnecessary for the purpose of counting rows, so:</p> <pre><code>$nRows = $pdo-&gt;query('select count(*) from blah')-&gt;fetchColumn(); echo $nRows; </code></pre>
{ "question_id": 883365, "question_date": "2009-05-19T15:12:30.717Z", "question_score": 221, "tags": "php|mysql|pdo", "answer_id": 883382, "answer_date": "2009-05-19T15:16:13.767Z", "answer_score": 301 }
Please answer the following Stack Overflow question: Title: How to erase the file contents of text file in Python? <p>I have text file which I want to erase in Python. How do I do that?</p>
<p>In python:</p> <pre><code>open('file.txt', 'w').close() </code></pre> <p>Or alternatively, if you have already an opened file:</p> <pre><code>f = open('file.txt', 'r+') f.truncate(0) # need '0' when using r+ </code></pre>
{ "question_id": 2769061, "question_date": "2010-05-04T21:21:06.037Z", "question_score": 221, "tags": "python", "answer_id": 2769090, "answer_date": "2010-05-04T21:27:03.940Z", "answer_score": 423 }
Please answer the following Stack Overflow question: Title: How to gzip all files in all sub-directories into one compressed file in bash <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/3341131/gzipping-up-a-set-of-directories-and-creating-a-tar-compressed-file">gzipping up a set of directories and creating a tar compressed file</a> </p> </blockquote> <p><a href="https://stackoverflow.com/questions/10363921/how-to-gzip-all-files-in-all-sub-directories-in-bash">This post</a> describes how to gzip each file individually within a directory structure. However, I need to do something slightly different. I need to produce one big gzip file for all files under a certain directory. I also need to be able to specify the output filename for the compressed file (e.g., files.gz) and overwrite the old compressed file file if one already exists.</p>
<pre><code>tar -zcvf compressFileName.tar.gz folderToCompress </code></pre> <p>everything in folderToCompress will go to compressFileName</p> <p>Edit: After review and comments I realized that people may get confused with compressFileName without an extension. If you want you can use .tar.gz extension(as suggested) with the compressFileName</p>
{ "question_id": 12331633, "question_date": "2012-09-08T14:32:35.440Z", "question_score": 221, "tags": "linux|bash|shell|gzip", "answer_id": 12331698, "answer_date": "2012-09-08T14:40:20.523Z", "answer_score": 424 }
Please answer the following Stack Overflow question: Title: Is there a WinSCP equivalent for Linux? <p>I love <a href="https://en.wikipedia.org/wiki/WinSCP" rel="noreferrer">WinSCP</a> for Windows. What is the best equivalent software for Linux?</p> <p>I tried to use sshfs to mount the remote file system on my local machine, but it is not as user friendly as simply launching a GUI, plus it seems to require root access on the client machine, which is not very convenient.</p> <p>Of course command-line tools such as scp are possible, but I am looking for a simple GUI.</p>
<p>If you're using <a href="https://en.wikipedia.org/wiki/GNOME" rel="noreferrer">GNOME</a>, you can go to: <em>Places</em> → <em>Connect to Server</em> in <a href="https://en.wikipedia.org/wiki/GNOME_Files" rel="noreferrer">Nautilus</a> and choose SSH. If you have an SSH agent running and configured, no password will be asked! (This is the same as sftp://root@servername/directory in Nautilus)</p> <p>In <a href="https://en.wikipedia.org/wiki/Konqueror" rel="noreferrer">Konqueror</a>, you can simply type: fish://servername.</p> <p>Per Mike R: In <a href="https://en.wikipedia.org/wiki/Ubuntu_version_history#Ubuntu_14.04_LTS_.28Trusty_Tahr.29" rel="noreferrer">Ubuntu 14.04</a> (with <a href="https://en.wikipedia.org/wiki/Unity_(user_interface)" rel="noreferrer">Unity</a>) it’s under <em>Files</em> → <em>Connect to Server</em> in the menu or <em>Network</em> → <em>Connect to Server</em> in the sidebar.</p>
{ "question_id": 299412, "question_date": "2008-11-18T17:10:24.780Z", "question_score": 221, "tags": "linux|scp|winscp", "answer_id": 299714, "answer_date": "2008-11-18T18:44:04.483Z", "answer_score": 232 }
Please answer the following Stack Overflow question: Title: Import / Export database with SQL Server Server Management Studio <p><em>I thought this would be trivial, but it isn't... I'm sure there is a simple way to do it but I can't manage to find it. Shame on me.</em></p> <p>I want to import/export the database itself, the tables, the constraints (foreign keys and so on). I'd rather not get the data with it, but I can get rid of it after if there's no other way.</p> <p>So... how do you export a database using MS SQL Server Management Studio ? How do you import it?</p> <p>The only solution I found was right click on the tables and "script to Create", but I have something like 100 tables, so I'd rather avoid this.</p> <p>Thanks!</p>
<p>Right click the database itself, Tasks -> Generate Scripts...</p> <p>Then follow the wizard.</p> <p>For SSMS2008+, if you want to also export the data, on the "Set Scripting Options" step, select the "Advanced" button and change "Types of data to script" from "Schema Only" to "Data Only" or "Schema and Data".</p>
{ "question_id": 1126571, "question_date": "2009-07-14T16:32:11.827Z", "question_score": 221, "tags": "sql-server|import|export|ssms", "answer_id": 1126590, "answer_date": "2009-07-14T16:36:45.340Z", "answer_score": 353 }
Please answer the following Stack Overflow question: Title: How to keep a Python script output window open? <p>I have just started with Python. When I execute a python script file on Windows, the output window appears but instantaneously goes away. I need it to stay there so I can analyze my output. How can I keep it open?</p>
<p>You have a few options:</p> <ol> <li><p>Run the program from an already-open terminal. Open a command prompt and type:</p> <pre><code>python myscript.py </code></pre> <p>For that to work you need the python executable in your path. Just check on <a href="https://superuser.com/questions/284342/what-are-path-and-other-environment-variables-and-how-can-i-set-or-use-them">how to edit environment variables</a> on Windows, and add <code>C:\PYTHON26</code> (or whatever directory you installed python to).</p> <p>When the program ends, it'll drop you back to the <strong>cmd</strong> prompt instead of closing the window.</p></li> <li><p>Add code to wait at the end of your script. For Python2, adding ...</p> <pre><code>raw_input() </code></pre> <p>... at the end of the script makes it wait for the <kbd>Enter</kbd> key. That method is annoying because you have to modify the script, and have to remember removing it when you're done. Specially annoying when testing other people's scripts. For Python3, use <code>input()</code>.</p></li> <li><p>Use an editor that pauses for you. Some editors prepared for python will automatically pause for you after execution. Other editors allow you to configure the command line it uses to run your program. I find it particularly useful to configure it as "<code>python -i myscript.py</code>" when running. That drops you to a python shell after the end of the program, with the program environment loaded, so you may further play with the variables and call functions and methods.</p></li> </ol>
{ "question_id": 1000900, "question_date": "2009-06-16T11:31:16.737Z", "question_score": 221, "tags": "python|windows", "answer_id": 1000968, "answer_date": "2009-06-16T11:43:55.933Z", "answer_score": 182 }
Please answer the following Stack Overflow question: Title: Angular 2 - How do I navigate to another route using this.router.parent.navigate('/about')? <p>Angular 2 - How do I navigate to another route using <code>this.router.parent.navigate('/about')</code>?</p> <p>It doesn't seem to work. I tried <code>location.go(&quot;/about&quot;);</code> as that didn't work.</p> <p>Basically, once a user has logged in I want to redirect them to another page.</p> <p>Here is my code below:</p> <pre><code> import {Component} from 'angular2/angular2'; import {CORE_DIRECTIVES, FORM_DIRECTIVES} from 'angular2/angular2'; import {Router} from 'angular2/router'; import {AuthService} from '../../authService'; //Model class User { constructor(public email: string, public password: string) {} } @Component({ templateUrl:'src/app/components/todo/todo.html', directives: [CORE_DIRECTIVES, FORM_DIRECTIVES] }) export class Todo { model = new User('[email protected]', 'Password'); authService:AuthService; router: Router; constructor(_router: Router, _authService: AuthService){ this.authService = _authService; this.router = _router; } onLogin = () =&gt; { this.authService.logUserIn(this.model).then((success) =&gt; { //This is where its broke - below: this.router.parent.navigate('/about'); }); } } </code></pre>
<p><strong>Absolute path routing</strong></p> <p>There are 2 methods for navigation, <code>.navigate()</code> and <code>.navigateByUrl()</code></p> <p>You can use the method <code>.navigateByUrl()</code> for absolute path routing:</p> <pre><code>import {Router} from '@angular/router'; constructor(private router: Router) {} navigateToLogin() { this.router.navigateByUrl('/login'); } </code></pre> <p>You put the absolute path to the URL of the component you want to navigate to. </p> <p>Note: Always specify the complete absolute path when calling router's <code>navigateByUrl</code> method. Absolute paths must start with a leading <code>/</code></p> <pre><code>// Absolute route - Goes up to root level this.router.navigate(['/root/child/child']); // Absolute route - Goes up to root level with route params this.router.navigate(['/root/child', crisis.id]); </code></pre> <p><strong>Relative path routing</strong></p> <p>If you want to use relative path routing, use the <code>.navigate()</code> method. </p> <p>NOTE: It's a little unintuitive how the routing works, particularly parent, sibling, and child routes:</p> <pre><code>// Parent route - Goes up one level // (notice the how it seems like you're going up 2 levels) this.router.navigate(['../../parent'], { relativeTo: this.route }); // Sibling route - Stays at the current level and moves laterally, // (looks like up to parent then down to sibling) this.router.navigate(['../sibling'], { relativeTo: this.route }); // Child route - Moves down one level this.router.navigate(['./child'], { relativeTo: this.route }); // Moves laterally, and also add route parameters // if you are at the root and crisis.id = 15, will result in '/sibling/15' this.router.navigate(['../sibling', crisis.id], { relativeTo: this.route }); // Moves laterally, and also add multiple route parameters // will result in '/sibling;id=15;foo=foo'. // Note: this does not produce query string URL notation with ? and &amp; ... instead it // produces a matrix URL notation, an alternative way to pass parameters in a URL. this.router.navigate(['../sibling', { id: crisis.id, foo: 'foo' }], { relativeTo: this.route }); </code></pre> <p>Or if you just need to navigate within the current route path, but to a different route parameter: </p> <pre><code>// If crisis.id has a value of '15' // This will take you from `/hero` to `/hero/15` this.router.navigate([crisis.id], { relativeTo: this.route }); </code></pre> <p><strong>Link parameters array</strong></p> <p>A link parameters array holds the following ingredients for router navigation:</p> <ul> <li>The path of the route to the destination component. <code>['/hero']</code></li> <li>Required and optional route parameters that go into the route URL. <code>['/hero', hero.id]</code> or <code>['/hero', { id: hero.id, foo: baa }]</code></li> </ul> <p><strong>Directory-like syntax</strong></p> <p>The router supports directory-like syntax in a link parameters list to help guide route name lookup:</p> <p><code>./</code> or no leading slash is relative to the current level.</p> <p><code>../</code> to go up one level in the route path.</p> <p>You can combine relative navigation syntax with an ancestor path. If you must navigate to a sibling route, you could use the <code>../&lt;sibling&gt;</code> convention to go up one level, then over and down the sibling route path.</p> <p><strong>Important notes about relative nagivation</strong></p> <p>To navigate a relative path with the <code>Router.navigate</code> method, you must supply the <code>ActivatedRoute</code> to give the router knowledge of where you are in the current route tree.</p> <p>After the link parameters array, add an object with a <code>relativeTo</code> property set to the <code>ActivatedRoute</code>. The router then calculates the target URL based on the active route's location.</p> <p>From official <a href="https://angular.io/docs/ts/latest/guide/router.html" rel="noreferrer">Angular Router Documentation</a></p>
{ "question_id": 33571605, "question_date": "2015-11-06T16:45:20.040Z", "question_score": 221, "tags": "angular|typescript|angular2-routing", "answer_id": 37622179, "answer_date": "2016-06-03T19:38:19.453Z", "answer_score": 397 }
Please answer the following Stack Overflow question: Title: Using os.walk() to recursively traverse directories in Python <p>I want to navigate from the root directory to all other directories within and print the same.</p> <p>Here's my code:</p> <pre><code>#!/usr/bin/python import os import fnmatch for root, dir, files in os.walk("."): print root print "" for items in fnmatch.filter(files, "*"): print "..." + items print "" </code></pre> <p>And here's my O/P:</p> <pre><code>. ...Python_Notes ...pypy.py ...pypy.py.save ...classdemo.py ....goutputstream-J9ZUXW ...latest.py ...pack.py ...classdemo.pyc ...Python_Notes~ ...module-demo.py ...filetype.py ./packagedemo ...classdemo.py ...__init__.pyc ...__init__.py ...classdemo.pyc </code></pre> <p>Above, <code>.</code> and <code>./packagedemo</code> are directories.</p> <p>However, I need to print the O/P in the following manner: </p> <pre><code>A ---a.txt ---b.txt ---B ------c.out </code></pre> <p>Above, <code>A</code> and <code>B</code> are directories and the rest are files.</p>
<p>This will give you the desired result</p> <pre><code>#!/usr/bin/python import os # traverse root directory, and list directories as dirs and files as files for root, dirs, files in os.walk("."): path = root.split(os.sep) print((len(path) - 1) * '---', os.path.basename(root)) for file in files: print(len(path) * '---', file) </code></pre>
{ "question_id": 16953842, "question_date": "2013-06-06T04:47:00.707Z", "question_score": 221, "tags": "python|os.walk", "answer_id": 16974952, "answer_date": "2013-06-07T01:37:08.267Z", "answer_score": 308 }
Please answer the following Stack Overflow question: Title: @RequestParam in Spring MVC handling optional parameters <p>Is it possible for a Spring controller to handle both kind of requests? </p> <p>1) <code>http://localhost:8080/submit/id/ID123432?logout=true</code></p> <p>2) <code>http://localhost:8080/submit/id/ID123432?name=sam&amp;password=543432</code></p> <p>If I define a single controller of the kind:</p> <pre><code> @RequestMapping (value = "/submit/id/{id}", method = RequestMethod.GET, produces="text/xml") public String showLoginWindow(@PathVariable("id") String id, @RequestParam(value = "logout", required = false) String logout, @RequestParam("name") String username, @RequestParam("password") String password, @ModelAttribute("submitModel") SubmitModel model, BindingResult errors) throws LoginException {...} </code></pre> <p>the HTTP request with "logout" is not accepted.</p> <p>If I define two controllers to handle each request separately, Spring complains with the exception "There is already 'Controller' bean method ... mapped".</p>
<p><strong>Before Java 8 and Spring 5 (but works with Java 8+ and Spring 5+ too)</strong></p> <p>You need to give <code>required = false</code> for <code>name</code> and <code>password</code> request parameters as well. That's because, when you provide just the <code>logout</code> parameter, it actually expects for <code>name</code> and <code>password</code> because they are still &quot;implicitly&quot; mandatory.</p> <p>It worked when you just gave <code>name</code> and <code>password</code> because <code>logout</code> wasn't a mandatory parameter thanks to <code>required = false</code> already given for <code>logout</code>.</p> <p><strong>Update for Java 8 and Spring 5 (and above)</strong></p> <p>You can now use the <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html" rel="noreferrer">Optional</a> class from Java 8 onwards to make the parameters optional.</p> <pre><code>@RequestMapping (value = &quot;/path&quot;, method = RequestMethod.GET) public String handleRequest(@RequestParam(&quot;paramName&quot;) Optional&lt;String&gt; variableName) { String paramValue = variableName.orElse(&quot;&quot;); // use the paramValue } </code></pre>
{ "question_id": 22373696, "question_date": "2014-03-13T09:05:34.163Z", "question_score": 221, "tags": "java|spring|spring-mvc", "answer_id": 22374803, "answer_date": "2014-03-13T09:53:38.147Z", "answer_score": 268 }
Please answer the following Stack Overflow question: Title: How can I check if a URL exists via PHP? <p>How do I check if a URL exists (not 404) in PHP?</p>
<p>Here:</p> <pre><code>$file = 'http://www.example.com/somefile.jpg'; $file_headers = @get_headers($file); if(!$file_headers || $file_headers[0] == 'HTTP/1.1 404 Not Found') { $exists = false; } else { $exists = true; } </code></pre> <p>From <a href="http://www.php.net/manual/en/function.file-exists.php#75064" rel="noreferrer">here</a> and <a href="http://www.php.net/manual/en/function.file-exists.php#74469" rel="noreferrer">right below</a> the above post, there's a <a href="http://php.net/manual/en/book.curl.php" rel="noreferrer">curl</a> solution:</p> <pre><code>function url_exists($url) { return curl_init($url) !== false; } </code></pre>
{ "question_id": 2280394, "question_date": "2010-02-17T12:06:26.240Z", "question_score": 221, "tags": "php|url", "answer_id": 2280413, "answer_date": "2010-02-17T12:10:32.473Z", "answer_score": 337 }
Please answer the following Stack Overflow question: Title: AttributeError: 'datetime' module has no attribute 'strptime' <p>Here is my <code>Transaction</code> class:</p> <pre><code>class Transaction(object): def __init__(self, company, num, price, date, is_buy): self.company = company self.num = num self.price = price self.date = datetime.strptime(date, "%Y-%m-%d") self.is_buy = is_buy </code></pre> <p>And when I'm trying to run the <code>date</code> function:</p> <pre><code>tr = Transaction('AAPL', 600, '2013-10-25') print tr.date </code></pre> <p>I'm getting the following error:</p> <pre><code> self.date = datetime.strptime(self.d, "%Y-%m-%d") AttributeError: 'module' object has no attribute 'strptime' </code></pre> <p>How can I fix that?</p>
<p>If I had to guess, you did this:</p> <pre><code>import datetime </code></pre> <p>at the top of your code. This means that you have to do this:</p> <pre><code>datetime.datetime.strptime(date, "%Y-%m-%d") </code></pre> <p>to access the <code>strptime</code> method. Or, you could change the import statement to this:</p> <pre><code>from datetime import datetime </code></pre> <p>and access it as you are.</p> <p>The people who made the <a href="https://docs.python.org/3/library/datetime.html" rel="noreferrer"><code>datetime</code> module</a> also named their <a href="https://docs.python.org/3/library/datetime.html#available-types" rel="noreferrer">class <code>datetime</code></a>:</p> <pre><code>#module class method datetime.datetime.strptime(date, "%Y-%m-%d") </code></pre>
{ "question_id": 19480028, "question_date": "2013-10-20T16:45:24.537Z", "question_score": 221, "tags": "python|class|python-2.7", "answer_id": 19480045, "answer_date": "2013-10-20T16:46:37.710Z", "answer_score": 537 }
Please answer the following Stack Overflow question: Title: Create array of all integers between two numbers, inclusive, in Javascript/jQuery <p>Say I have the following checkbox:</p> <pre><code>&lt;input type="checkbox" value="1-25" /&gt; </code></pre> <p>To get the two numbers that define the boundaries of range I'm looking for, I use the following jQuery:</p> <pre><code>var value = $(this).val(); var lowEnd = Number(value.split('-')[0]); var highEnd = Number(value.split('-')[1]); </code></pre> <p>How do I then create an array that contains all integers between <code>lowEnd</code> and <code>highEnd</code>, including <code>lowEnd</code> and <code>highEnd</code> themselves? For this specific example, obviously, the resulting array would be:</p> <pre><code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25] </code></pre>
<pre><code>var list = []; for (var i = lowEnd; i &lt;= highEnd; i++) { list.push(i); } </code></pre>
{ "question_id": 8069315, "question_date": "2011-11-09T17:52:33.937Z", "question_score": 221, "tags": "javascript|jquery|arrays", "answer_id": 8069367, "answer_date": "2011-11-09T17:56:44.297Z", "answer_score": 230 }
Please answer the following Stack Overflow question: Title: Get second child using jQuery <pre><code>$(t).html() </code></pre> <p>returns </p> <pre><code>&lt;td&gt;test1&lt;/td&gt;&lt;td&gt;test2&lt;/td&gt; </code></pre> <p>I want to retrieve the second <code>td</code> from the <code>$(t)</code> object. I searched for a solution but nothing worked for me. Any idea how to get the second element?</p>
<p>grab the second child:</p> <pre><code>$(t).children().eq(1); </code></pre> <p>or, grab the second child <code>&lt;td&gt;</code>:</p> <pre><code>$(t).children('td').eq(1); </code></pre> <p>See documentation for <a href="https://api.jquery.com/children/" rel="noreferrer"><code>children</code></a> and <a href="https://api.jquery.com/eq/" rel="noreferrer"><code>eq</code></a>.</p>
{ "question_id": 4727263, "question_date": "2011-01-18T17:48:28.477Z", "question_score": 221, "tags": "jquery|jquery-selectors", "answer_id": 4727293, "answer_date": "2011-01-18T17:51:27.633Z", "answer_score": 401 }
Please answer the following Stack Overflow question: Title: How to skip iterations in a loop? <p>I have a loop going, but there is the possibility for exceptions to be raised inside the loop. This of course would stop my program all together. To prevent that I catch the exceptions and handle them. But then the rest of the iteration runs even though an exception occurred. Is there a keyword to use in my <code>except:</code> clause to just skip the rest of the current iteration?</p>
<p>You are looking for <a href="https://docs.python.org/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops" rel="noreferrer"><code>continue</code></a>.</p>
{ "question_id": 549674, "question_date": "2009-02-14T19:48:04.270Z", "question_score": 221, "tags": "python", "answer_id": 549682, "answer_date": "2009-02-14T19:50:46.353Z", "answer_score": 481 }
Please answer the following Stack Overflow question: Title: How do you truncate all tables in a database using TSQL? <p>I have a test environment for a database that I want to reload with new data at the start of a testing cycle. I am not interested in rebuilding the entire database- just simply "re-setting" the data. </p> <p>What is the best way to remove all the data from all the tables using TSQL? Are there system stored procedures, views, etc. that can be used? I do not want to manually create and maintain truncate table statements for each table- I would prefer it to be dynamic.</p>
<p>For SQL 2005, </p> <pre><code>EXEC sp_MSForEachTable 'TRUNCATE TABLE ?' </code></pre> <p>Couple more links for <a href="http://www.databasejournal.com/scripts/article.php/2226781" rel="noreferrer">2000</a> and <a href="http://www.keithrull.com/2007/09/07/HowToTruncateMultipleTablesInSQLServerAndTheMagicOfSpMSforeachtable.aspx" rel="noreferrer">2005/2008</a>..</p>
{ "question_id": 155246, "question_date": "2008-09-30T21:49:17.663Z", "question_score": 221, "tags": "sql-server|tsql", "answer_id": 155275, "answer_date": "2008-09-30T21:56:32.310Z", "answer_score": 201 }
Please answer the following Stack Overflow question: Title: How to enable production mode? <p>I was reading related questions and I found <a href="https://stackoverflow.com/questions/35710895/angular2-method-binding-error-value-has-changed-after-it-was-checked">this one</a>, but my question is how can I switch from development to production mode. There are some differences between the modes which are pointed out <a href="https://stackoverflow.com/questions/34868810/what-is-diff-between-production-and-development-mode-in-angular2">here</a>.</p> <p>In the console I can see <code>....Call enableProdMode() to enable the production mode.</code> However, I'm not sure instance of which type should I call that method on.</p> <p>Can somebody answer this question?</p>
<p>You enable it by importing and executing the function (before calling bootstrap):</p> <pre><code>import {enableProdMode} from '@angular/core'; enableProdMode(); bootstrap(....); </code></pre> <p>But this error is indicator that something is wrong with your bindings, so you shouldn't just dismiss it, but try to figure out why it's happening.</p>
{ "question_id": 35721206, "question_date": "2016-03-01T11:04:46.750Z", "question_score": 221, "tags": "angular", "answer_id": 35721252, "answer_date": "2016-03-01T11:06:54.767Z", "answer_score": 235 }
Please answer the following Stack Overflow question: Title: Prevent HTML5 video from being downloaded (right-click saved)? <p>How can I disable "Save Video As..." from a browser's right-click menu to prevent clients from downloading a video?</p> <p>Are there more complete solutions that prevent the client from accessing a file path directly?</p>
<hr /> <h2>You can't.</h2> <p>That's because that's what browsers were designed to do: <em>Serve content</em>. But you can <em>make it harder to download</em>.</p> <hr /> <h2>Convenient &quot;Solution&quot;</h2> <p>I'd just upload my video to a third-party video site, like YouTube or Vimeo. They have good video management tools, optimizes playback to the device, and they make efforts in preventing their videos from being ripped with zero effort on your end.</p> <hr /> <h2>Workaround 1, Disabling &quot;The Right Click&quot;</h2> <p>You <em>could</em> disable the <a href="https://developer.mozilla.org/en-US/docs/Web/Events/contextmenu" rel="noreferrer"><code>contextmenu</code> event</a>, aka &quot;the right click&quot;. That would prevent your regular skiddie from blatantly ripping your video by right clicking and Save As. But then they could just disable JS and get around this or find the video source via the browser's debugger. Plus this is bad UX. There are lots of legitimate things in a context menu than just Save As.</p> <hr /> <h2>Workaround 2, Video Player Libraries</h2> <p>Use custom video player libraries. Most of them implement video players that customize the context menu to your liking. So you don't get the default browser context menu. And if ever they do serve a menu item similar to Save As, you can disable it. But again, this is a JS workaround. Weaknesses are similar to Workaround 1.</p> <hr /> <h2>Workaround 3, HTTP Live Streaming</h2> <p>Another way to do it is to serve the video using <a href="https://en.wikipedia.org/wiki/HTTP_Live_Streaming" rel="noreferrer">HTTP Live Streaming</a>. What it essentially does is chop up the video into chunks and serve it one after the other. This is how most streaming sites serve video. So even if you manage to Save As, you only save a chunk, not the whole video. It would take a bit more effort to gather all the chunks and stitch them using some dedicated software.</p> <hr /> <h2>Workaround 4, Painting on Canvas</h2> <p>Another technique is to <a href="http://html5doctor.com/video-canvas-magic/" rel="noreferrer">paint <code>&lt;video&gt;</code> on <code>&lt;canvas&gt;</code></a>. In this technique, with a bit of JavaScript, what you see on the page is a <code>&lt;canvas&gt;</code> element rendering frames from a hidden <code>&lt;video&gt;</code>. And because it's a <code>&lt;canvas&gt;</code>, the context menu will use an <code>&lt;img&gt;</code>'s menu, not a <code>&lt;video&gt;</code>'s. You'll get a Save Image As instead of a Save Video As.</p> <hr /> <h2>Workaround 5, CSRF Tokens</h2> <p>You could also use <a href="http://en.wikipedia.org/wiki/Cross-site_request_forgery#Prevention" rel="noreferrer">CSRF tokens</a> to your advantage. You'd have your sever send down a token on the page. You then use that token to fetch your video. Your server checks to see if it's a valid token before it serves the video, or get an <a href="http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_Client_Error" rel="noreferrer">HTTP 401</a>. The idea is that you can only ever get a video by having a token which you can only ever get if you came from the page, not directly visiting the video url.</p> <hr />
{ "question_id": 9756837, "question_date": "2012-03-18T07:53:17.473Z", "question_score": 221, "tags": "javascript|html|html5-video", "answer_id": 9756909, "answer_date": "2012-03-18T08:05:06.420Z", "answer_score": 309 }
Please answer the following Stack Overflow question: Title: How to find entry by object property from an array of objects? <p>The array looks like:</p> <pre><code>[0] =&gt; stdClass Object ( [ID] =&gt; 420 [name] =&gt; Mary ) [1] =&gt; stdClass Object ( [ID] =&gt; 10957 [name] =&gt; Blah ) ... </code></pre> <p>And I have an integer variable called <code>$v</code>.</p> <p>How could I select an array entry that has an object where the <code>ID</code> property has the <code>$v</code> value?</p>
<p>You either iterate the array, searching for the particular record (ok in a one time only search) or build a hashmap using another associative array.</p> <p>For the former, something like this</p> <pre><code>$item = null; foreach($array as $struct) { if ($v == $struct-&gt;ID) { $item = $struct; break; } } </code></pre> <p>See this question and subsequent answers for more information on the latter - <a href="https://stackoverflow.com/questions/4405281/reference-php-array-by-multiple-indexes">Reference PHP array by multiple indexes</a></p>
{ "question_id": 4742903, "question_date": "2011-01-20T02:24:39.047Z", "question_score": 221, "tags": "php|arrays|object", "answer_id": 4742925, "answer_date": "2011-01-20T02:27:59.097Z", "answer_score": 211 }
Please answer the following Stack Overflow question: Title: Get value of c# dynamic property via string <p>I'd like to access the value of a <code>dynamic</code> c# property with a string:</p> <p><code>dynamic d = new { value1 = "some", value2 = "random", value3 = "value" };</code></p> <p>How can I get the value of d.value2 ("random") if I only have "value2" as a string? In javascript, I could do d["value2"] to access the value ("random"), but I'm not sure how to do this with c# and reflection. The closest I've come is this:</p> <p><code>d.GetType().GetProperty("value2")</code> ... but I don't know how to get the actual value from that.</p> <p>As always, thanks for your help!</p>
<p>Once you have your <code>PropertyInfo</code> (from <code>GetProperty</code>), you need to call <code>GetValue</code> and pass in the instance that you want to get the value from. In your case:</p> <pre><code>d.GetType().GetProperty("value2").GetValue(d, null); </code></pre>
{ "question_id": 4939508, "question_date": "2011-02-08T22:59:33.163Z", "question_score": 221, "tags": "c#|dynamic", "answer_id": 4939524, "answer_date": "2011-02-08T23:01:34.183Z", "answer_score": 274 }
Please answer the following Stack Overflow question: Title: Extract a part of the filepath (a directory) in Python <p>I need to extract the name of the parent directory of a certain path. This is what it looks like:</p> <pre><code>C:\stuff\directory_i_need\subdir\file.jpg </code></pre> <p>I would like to extract <code>directory_i_need</code>.</p>
<pre><code>import os ## first file in current dir (with full path) file = os.path.join(os.getcwd(), os.listdir(os.getcwd())[0]) file os.path.dirname(file) ## directory of file os.path.dirname(os.path.dirname(file)) ## directory of directory of file ... </code></pre> <p>And you can continue doing this as many times as necessary...</p> <p><strong>Edit:</strong> from <a href="http://docs.python.org/library/os.path.html" rel="noreferrer">os.path</a>, you can use either os.path.split or os.path.basename:</p> <pre><code>dir = os.path.dirname(os.path.dirname(file)) ## dir of dir of file ## once you're at the directory level you want, with the desired directory as the final path node: dirname1 = os.path.basename(dir) dirname2 = os.path.split(dir)[1] ## if you look at the documentation, this is exactly what os.path.basename does. </code></pre>
{ "question_id": 10149263, "question_date": "2012-04-13T22:48:00.680Z", "question_score": 221, "tags": "python|directory|filepath", "answer_id": 10149358, "answer_date": "2012-04-13T23:01:11.660Z", "answer_score": 297 }
Please answer the following Stack Overflow question: Title: How can I break up this long line in Python? <p>How would you go about formatting a long line such as this? I'd like to get it to no more than 80 characters wide:</p> <pre><code>logger.info("Skipping {0} because its thumbnail was already in our system as {1}.".format(line[indexes['url']], video.title)) </code></pre> <p>Is this my best option?</p> <pre><code>url = "Skipping {0} because its thumbnail was already in our system as {1}." logger.info(url.format(line[indexes['url']], video.title)) </code></pre>
<p>That's a start. It's not a bad practice to define your longer strings outside of the code that uses them. It's a way to separate data and behavior. Your first option is to join string literals together implicitly by making them adjacent to one another:</p> <pre><code>(&quot;This is the first line of my text, &quot; &quot;which will be joined to a second.&quot;) </code></pre> <p>Or with line ending continuations, which is a little more fragile, as this works:</p> <pre><code>&quot;This is the first line of my text, &quot; \ &quot;which will be joined to a second.&quot; </code></pre> <p>But this doesn't:</p> <pre><code>&quot;This is the first line of my text, &quot; \ &quot;which will be joined to a second.&quot; </code></pre> <p>See the difference? No? Well you won't when it's your code either.</p> <p><em>(There's a space after <code>\</code> in the second example.)</em></p> <p>The downside to implicit joining is that it only works with string literals, not with strings taken from variables, so things can get a little more hairy when you refactor. Also, you can only interpolate formatting on the combined string as a whole.</p> <p>Alternatively, you can join explicitly using the concatenation operator (<code>+</code>):</p> <pre><code>(&quot;This is the first line of my text, &quot; + &quot;which will be joined to a second.&quot;) </code></pre> <p>Explicit is better than implicit, as the zen of python says, but this creates three strings instead of one, and uses twice as much memory: there are the two you have written, plus one which is the two of them joined together, so you have to know when to ignore the zen. The upside is you can apply formatting to any of the substrings separately on each line, or to the whole lot from outside the parentheses.</p> <p>Finally, you can use triple-quoted strings:</p> <pre><code>&quot;&quot;&quot;This is the first line of my text which will be joined to a second.&quot;&quot;&quot; </code></pre> <p>This is often my favorite, though its behavior is slightly different as the newline and any leading whitespace on subsequent lines will show up in your final string. You can eliminate the newline with an escaping backslash.</p> <pre><code>&quot;&quot;&quot;This is the first line of my text \ which will be joined to a second.&quot;&quot;&quot; </code></pre> <p>This has the same problem as the same technique above, in that correct code only differs from incorrect code by invisible whitespace.</p> <p>Which one is &quot;best&quot; depends on your particular situation, but the answer is not simply aesthetic, but one of subtly different behaviors.</p>
{ "question_id": 2058925, "question_date": "2010-01-13T17:41:07.703Z", "question_score": 221, "tags": "python|formatting|code-formatting", "answer_id": 2059025, "answer_date": "2010-01-13T17:59:25.197Z", "answer_score": 409 }
Please answer the following Stack Overflow question: Title: How to Apply Gradient to background view of iOS Swift App <p>I'm trying to apply a gradient as the background color of a View (main view of a storyboard). The code runs, but nothing changes. I'm using xCode Beta 2 and Swift.</p> <p>Here's the code:</p> <pre><code>class Colors { let colorTop = UIColor(red: 192.0/255.0, green: 38.0/255.0, blue: 42.0/255.0, alpha: 1.0) let colorBottom = UIColor(red: 35.0/255.0, green: 2.0/255.0, blue: 2.0/255.0, alpha: 1.0) let gl: CAGradientLayer init() { gl = CAGradientLayer() gl.colors = [ colorTop, colorBottom] gl.locations = [ 0.0, 1.0] } } </code></pre> <p>then in the view controller:</p> <pre><code> let colors = Colors() func refresh() { view.backgroundColor = UIColor.clearColor() var backgroundLayer = colors.gl backgroundLayer.frame = view.frame view.layer.insertSublayer(backgroundLayer, atIndex: 0) } } } </code></pre>
<p>The Colors you're providing to gradient must be of type <code>CGColor</code>. So set your array of <code>CGColor</code> to <code>gl.colors</code>.</p> <p>The correct code is :</p> <pre><code>class Colors { var gl:CAGradientLayer! init() { let colorTop = UIColor(red: 192.0 / 255.0, green: 38.0 / 255.0, blue: 42.0 / 255.0, alpha: 1.0).cgColor let colorBottom = UIColor(red: 35.0 / 255.0, green: 2.0 / 255.0, blue: 2.0 / 255.0, alpha: 1.0).cgColor self.gl = CAGradientLayer() self.gl.colors = [colorTop, colorBottom] self.gl.locations = [0.0, 1.0] } } </code></pre>
{ "question_id": 24380535, "question_date": "2014-06-24T07:13:36.747Z", "question_score": 221, "tags": "ios|ios7|swift|cagradientlayer", "answer_id": 24380968, "answer_date": "2014-06-24T07:39:05.433Z", "answer_score": 173 }
Please answer the following Stack Overflow question: Title: Remove substring from the string <p>I am just wondering if there is any method to remove string from another string? Something like this:</p> <pre><code>class String def remove(s) self[s.length, self.length - s.length] end end </code></pre>
<p>You can use the slice method:</p> <pre><code>a = "foobar" a.slice! "foo" =&gt; "foo" a =&gt; "bar" </code></pre> <p>there is a non '!' version as well. More info can be seen in the documentation about other versions as well: <a href="http://www.ruby-doc.org/core/classes/String.html#method-i-slice-21" rel="noreferrer">http://www.ruby-doc.org/core/classes/String.html#method-i-slice-21</a></p>
{ "question_id": 5367164, "question_date": "2011-03-20T06:49:27.227Z", "question_score": 221, "tags": "ruby|string", "answer_id": 5367171, "answer_date": "2011-03-20T06:52:33.620Z", "answer_score": 282 }
Please answer the following Stack Overflow question: Title: MySQL Workbench: How to keep the connection alive <p><strong>Error Code: 2013. Lost connection to MySQL server during query</strong></p> <p>I am using MySQL Workbench. Also, I am running a batch of inserts, about 1000 lines total (Ex. <code>INSERT INTO mytable SELECT * FROM mysource1; INSERT INTO mytable SELECT * FROM mysource2;...mysource3...mysource4</code> multiplied 1000 times) Each batch takes a considerable amount of time, some of them, more than 600 seconds.</p> <p><strong>How can I configure workbench, to continue working overnight, without stopping and without losing the connection?</strong></p>
<p>From the now <a href="https://web.archive.org/web/20130322031356/http://www.hassmann-software.de/mysql-workbench-lost-connection-to-mysql-server-after-600-seconds" rel="noreferrer">unavailable</a> internet archive:</p> <blockquote> <p>Go to Edit -> Preferences -> SQL Editor and set to a higher value this parameter: DBMS connection read time out (in seconds). For instance: 86400.</p> <p>Close and reopen MySQL Workbench. Kill your previously query that probably is running and run the query again.</p> </blockquote>
{ "question_id": 15712512, "question_date": "2013-03-29T22:40:25.383Z", "question_score": 221, "tags": "mysql|sql|mysql-workbench|connection-timeout", "answer_id": 15712616, "answer_date": "2013-03-29T22:49:55.073Z", "answer_score": 457 }
Please answer the following Stack Overflow question: Title: jQuery If DIV Doesn't Have Class "x" <p>In jQuery I need to do an if statement to see if $this doesn't contain the class '.selected'.</p> <pre><code>$(".thumbs").hover(function(){ $(this).stop().fadeTo("normal", 1.0); },function(){ $(this).stop().fadeTo("slow", 0.3); }); </code></pre> <p>Basically when this function is run (on hover) I don't want to perform the fades if the class '.selected' has been appended to the div, this will mean that the image will be at full opacity to signify that it's selected. Searched on Google to no luck even though it's a simple question of how to use an IF statement...</p>
<p>Use the <a href="http://docs.jquery.com/Selectors/not#selector" rel="noreferrer">"not</a>" selector.</p> <p>For example, instead of:</p> <p><code>$(".thumbs").hover()</code></p> <p>try:</p> <p><code>$(".thumbs:not(.selected)").hover()</code></p>
{ "question_id": 520250, "question_date": "2009-02-06T13:17:38.670Z", "question_score": 221, "tags": "jquery", "answer_id": 520271, "answer_date": "2009-02-06T13:24:13.370Z", "answer_score": 379 }
Please answer the following Stack Overflow question: Title: drag drop files into standard html file input <p>These days we can drag &amp; drop files into a special container and upload them with XHR 2. Many at a time. With live progress bars etc. Very cool stuff. <a href="http://hotblocks.nl/tests/ajax/file-drag-drop.html" rel="noreferrer">Example here.</a></p> <p>But sometimes we don't want that much coolness. What I'd like is to drag &amp; drop files -- many at a time -- <strong>into a standard HTML file input</strong>: <code>&lt;input type=file multiple&gt;</code>.</p> <p>Is that possible? Is there some way to 'fill' the file input with the right filenames (?) from the file drop? (Full filepaths aren't available for file system security reasons.)</p> <p><strong>Why?</strong> Because I'd like to submit a normal form. For all browsers and all devices. The drag &amp; drop is just progressive enhancement to enhance &amp; simplify UX. The standard form with standard file input (+ <code>multiple</code> attribute) will be there. I'd like to add the HTML5 enhancement.</p> <p><strong>edit</strong><br> I know in <strong>some</strong> browsers you can <strong>sometimes</strong> (almost always) drop files into the file input itself. I know Chrome usually does this, but sometimes it fails and then loads the file in the current page (a big fail if you're filling out a form). I want to fool- &amp; browserproof it.</p>
<p>The following works in Chrome and FF, but i've yet to find a solution that covers IE10+ as well:</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>// dragover and dragenter events need to have 'preventDefault' called // in order for the 'drop' event to register. // See: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Drag_operations#droptargets dropContainer.ondragover = dropContainer.ondragenter = function(evt) { evt.preventDefault(); }; dropContainer.ondrop = function(evt) { // pretty simple -- but not for IE :( fileInput.files = evt.dataTransfer.files; // If you want to use some of the dropped files const dT = new DataTransfer(); dT.items.add(evt.dataTransfer.files[0]); dT.items.add(evt.dataTransfer.files[3]); fileInput.files = dT.files; evt.preventDefault(); };</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;body&gt; &lt;div id="dropContainer" style="border:1px solid black;height:100px;"&gt; Drop Here &lt;/div&gt; Should update here: &lt;input type="file" id="fileInput" /&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>You'll probably want to use <code>addEventListener</code> or jQuery (etc.) to register your evt handlers - this is just for brevity's sake.</p>
{ "question_id": 8006715, "question_date": "2011-11-04T08:42:13.697Z", "question_score": 221, "tags": "javascript|html|file-upload|drag-and-drop", "answer_id": 38968948, "answer_date": "2016-08-16T07:29:11.357Z", "answer_score": 143 }
Please answer the following Stack Overflow question: Title: AngularJS toggle class using ng-class <p>I am trying to toggle the class of an element using <code>ng-class</code></p> <pre><code>&lt;button class="btn"&gt; &lt;i ng-class="{(isAutoScroll()) ? 'icon-autoscroll' : 'icon-autoscroll-disabled'}"&gt;&lt;/i&gt; &lt;/button&gt; </code></pre> <p>isAutoScroll():</p> <pre><code>$scope.isAutoScroll = function() { $scope.autoScroll = ($scope.autoScroll) ? false : true; return $scope.autoScroll; } </code></pre> <p>Basically, if <code>$scope.autoScroll</code> is true, I want ng-class to be <code>icon-autoscroll</code> and if its false, I want it to be <code>icon-autoscroll-disabled</code></p> <p>What I have now isn't working and is producing this error in the console</p> <p><code>Error: Lexer Error: Unexpected next character at columns 18-18 [?] in expression [{(isAutoScroll()) ? 'icon-autoscroll' : 'icon-autoscroll-disabled'}].</code></p> <p>How do I correctly do this?</p> <p><strong>EDIT</strong></p> <p>solution 1: (outdated)</p> <pre><code>&lt;button class="btn" ng-click="autoScroll = !autoScroll"&gt; &lt;i ng-class="{'icon-autoscroll': autoScroll, 'icon-autoscroll-disabled': !autoScroll}"&gt;&lt;/i&gt; &lt;/button&gt; </code></pre> <p><strong>EDIT 2</strong></p> <p>solution 2:</p> <p>I wanted to update the solution as <code>Solution 3</code>, provided by Stewie, should be the one used. It is the most standard when it comes to ternary operator (and to me easiest to read). The solution would be</p> <pre><code>&lt;button class="btn" ng-click="autoScroll = !autoScroll"&gt; &lt;i ng-class="autoScroll ? 'icon-autoscroll' : 'icon-autoscroll-disabled'"&gt;&lt;/i&gt; &lt;/button&gt; </code></pre> <p>translates to:</p> <p><code>if (autoScroll == true) ?</code> //use class <code>'icon-autoscroll' :</code> //else use <code>'icon-autoscroll-disabled'</code></p>
<p>How to use conditional in ng-class: </p> <p>Solution 1:</p> <pre><code>&lt;i ng-class="{'icon-autoscroll': autoScroll, 'icon-autoscroll-disabled': !autoScroll}"&gt;&lt;/i&gt; </code></pre> <p>Solution 2:</p> <pre><code>&lt;i ng-class="{true: 'icon-autoscroll', false: 'icon-autoscroll-disabled'}[autoScroll]"&gt;&lt;/i&gt; </code></pre> <p>Solution 3 (angular v.1.1.4+ introduced support for ternary operator):</p> <pre><code>&lt;i ng-class="autoScroll ? 'icon-autoscroll' : 'icon-autoscroll-disabled'"&gt;&lt;/i&gt; </code></pre> <p><a href="http://plnkr.co/edit/EdiNmaQYbVSftTuvNVpG" rel="noreferrer">Plunker</a></p>
{ "question_id": 15397252, "question_date": "2013-03-13T21:54:39.280Z", "question_score": 221, "tags": "javascript|angularjs", "answer_id": 15397408, "answer_date": "2013-03-13T22:05:47.503Z", "answer_score": 440 }
Please answer the following Stack Overflow question: Title: How to convert milliseconds to "hh:mm:ss" format? <p>I'm confused. After stumbling upon <a href="https://stackoverflow.com/questions/625433/how-to-convert-milliseconds-to-x-mins-x-seconds-in-java">this</a> thread, I tried to figure out how to format a countdown timer that had the format <code>hh:mm:ss</code>.</p> <p>Here's my attempt - </p> <pre><code>//hh:mm:ss String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis), TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.MINUTES.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))); </code></pre> <p>So, when I try a value like <code>3600000ms</code>, I get <code>01:59:00</code>, which is wrong since it should be <code>01:00:00</code>. Obviously there's something wrong with my logic, but at the moment, I cannot see what it is!</p> <p>Can anyone help?</p> <p><strong>Edit -</strong></p> <p>Fixed it. Here's the right way to format milliseconds to <code>hh:mm:ss</code> format -</p> <pre><code>//hh:mm:ss String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis), TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)))); </code></pre> <p>The problem was this <code>TimeUnit.MINUTES.toMinutes(TimeUnit.MILLISECONDS.toHours(millis))</code>. It should have been this <code>TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis))</code> instead.</p>
<p>You were <em>really</em> close:</p> <pre><code>String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis), TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), // The change is in this line TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))); </code></pre> <p>You were converting hours to millisseconds using <em>minutes</em> instead of <em>hours</em>.</p> <p>BTW, I like your use of the <code>TimeUnit</code> API :)</p> <p>Here's some test code:</p> <pre><code>public static void main(String[] args) throws ParseException { long millis = 3600000; String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis), TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))); System.out.println(hms); } </code></pre> <p>Output:</p> <pre><code>01:00:00 </code></pre> <hr> <p>I realised that my code above can be greatly simplified by using a modulus division instead of subtraction:</p> <pre><code>String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis), TimeUnit.MILLISECONDS.toMinutes(millis) % TimeUnit.HOURS.toMinutes(1), TimeUnit.MILLISECONDS.toSeconds(millis) % TimeUnit.MINUTES.toSeconds(1)); </code></pre> <p>Still using the <code>TimeUnit</code> API for all magic values, and gives exactly the same output.</p>
{ "question_id": 9027317, "question_date": "2012-01-27T00:01:58.660Z", "question_score": 221, "tags": "java|time-format|countdowntimer", "answer_id": 9027379, "answer_date": "2012-01-27T00:11:22.500Z", "answer_score": 410 }
Please answer the following Stack Overflow question: Title: How can I run MongoDB as a Windows service? <p>How can I set up MongoDB so it can run as a Windows service?</p>
<p>I think if you run it with the <code>--install</code> command line switch, it installs it as a Windows Service.</p> <pre><code>mongod --install </code></pre> <p>It might be worth reading <a href="http://groups.google.com/group/mongodb-user/browse_thread/thread/fde13e7ceb64ac44/a39a7e1b711a6b00" rel="noreferrer">this thread</a> first though. There seems to be some problems with relative/absolute paths when the relevant registry key gets written.</p>
{ "question_id": 2438055, "question_date": "2010-03-13T10:49:05.893Z", "question_score": 221, "tags": "mongodb|windows-services|nosql", "answer_id": 2438758, "answer_date": "2010-03-13T14:58:00.303Z", "answer_score": 123 }
Please answer the following Stack Overflow question: Title: Request Monitoring in Chrome <p>In Firefox, I use Firebug which allows me to view every http request my ajax calls are making. I've switched over my development to Chrome and am liking it so far. My only complaint, however, is that the developer tools don't seem to allow you to view each ajax request. I've had it happen once where the Resources panel showed multiple requests to the same resource, but it's only done it once and never again.</p> <p>Is there a way to reliably see every http request that a page is making through javascript from within Chrome?</p> <p>[Edit:11/30/09 11:55]</p> <p>Currently, to get around this, I'm running Fiddler next to Chrome to view my requests, but if there's a way to do it from within the browser, I'd prefer that.</p>
<p>I know this is an old thread but I thought I would chime in. </p> <p>Chrome currently has a solution built in. </p> <ol> <li>Use <code>CTRL+SHIFT+I</code> (or navigate to <code>Current Page Control &gt; Developer &gt; Developer Tools</code>. In the newer versions of Chrome, click the Wrench icon > Tools > Developer Tools.) to enable the Developer Tools. </li> <li>From within the developer tools click on the <code>Network</code> button. If it isn't already, enable it for the session or always. </li> <li>Click the <code>"XHR"</code> sub-button.</li> <li>Initiate an <code>AJAX call</code>. </li> <li>You will see items begin to show up in the left column under <code>"Resources"</code>. </li> <li>Click the resource and there are 2 tabs showing the headers and return content.</li> </ol>
{ "question_id": 1820927, "question_date": "2009-11-30T16:41:57.573Z", "question_score": 221, "tags": "ajax|google-chrome|httprequest", "answer_id": 3019085, "answer_date": "2010-06-10T22:46:06.947Z", "answer_score": 379 }
Please answer the following Stack Overflow question: Title: CSS content generation before or after 'input' elements <p>In Firefox 3 and Google Chrome 8.0 the following works as expected:</p> <pre><code>&lt;style type="text/css"&gt; span:before { content: 'span: '; } &lt;/style&gt; &lt;span&gt;Test&lt;/span&gt; &lt;!-- produces: "span: Test" --&gt; </code></pre> <p>But it doesn't when the element is <code>&lt;input&gt;</code>:</p> <pre><code>&lt;style type="text/css"&gt; input:before { content: 'input: '; } &lt;/style&gt; &lt;input type="text"&gt;&lt;/input&gt; &lt;!-- produces only the textbox; the generated content is nowhere to be seen in both FF3 and Chrome 8 --&gt; </code></pre> <p>Why is it not working like I expected?</p>
<p>With <code>:before</code> and <code>:after</code> you specify which content should be inserted before (or after) <strong>the content</strong> inside of that element. <code>input</code> elements have no content.</p> <p>E.g. if you write <code>&lt;input type="text"&gt;Test&lt;/input&gt;</code> (which is wrong) the browser will correct this and put the text <em>after</em> the input element.</p> <p>The only thing you could do is to wrap every input element in a span or div and apply the CSS on these.</p> <p>See the examples in the <a href="http://www.w3.org/TR/CSS2/generate.html#before-after-content" rel="noreferrer">specification</a>:</p> <blockquote> <p>For example, the following document fragment and style sheet:</p> <pre><code>&lt;h2&gt; Header &lt;/h2&gt; h2 { display: run-in; } &lt;p&gt; Text &lt;/p&gt; p:before { display: block; content: 'Some'; } </code></pre> <p>...would render in exactly the same way as the following document fragment and style sheet:</p> <pre><code>&lt;h2&gt; Header &lt;/h2&gt; h2 { display: run-in; } &lt;p&gt;&lt;span&gt;Some&lt;/span&gt; Text &lt;/p&gt; span { display: block } </code></pre> </blockquote> <p>This is the same reason why it does not work for <code>&lt;br&gt;</code>, <code>&lt;img&gt;</code>, etc. (<code>&lt;textarea&gt;</code> seems to be special).</p>
{ "question_id": 4574912, "question_date": "2011-01-01T17:29:18.617Z", "question_score": 221, "tags": "html|css", "answer_id": 4574946, "answer_date": "2011-01-01T17:37:05.917Z", "answer_score": 330 }
Please answer the following Stack Overflow question: Title: The specified child already has a parent. You must call removeView() on the child's parent first (Android) <p>I have to switch between two layouts frequently. The error is happening in the layout posted below.</p> <p>When my layout is called the first time, there doesn't occur any error and everything's fine. When I then call a different layout (a blank one) and afterwards call my layout a second time, it throws the following error:</p> <pre><code>&gt; FATAL EXCEPTION: main &gt; java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. </code></pre> <p>My layout-code looks like this:</p> <pre><code> tv = new TextView(getApplicationContext()); // are initialized somewhere else et = new EditText(getApplicationContext()); // in the code private void ConsoleWindow(){ runOnUiThread(new Runnable(){ @Override public void run(){ // MY LAYOUT: setContentView(R.layout.activity_console); // LINEAR LAYOUT LinearLayout layout=new LinearLayout(getApplicationContext()); layout.setOrientation(LinearLayout.VERTICAL); setContentView(layout); // TEXTVIEW layout.addView(tv); // &lt;========== ERROR IN THIS LINE DURING 2ND RUN // EDITTEXT et.setHint("Enter Command"); layout.addView(et); } } } </code></pre> <p>I know this question has been asked before, but it didn't help in my case.</p>
<p>The error message says what You should do.</p> <pre><code>// TEXTVIEW if(tv.getParent() != null) { ((ViewGroup)tv.getParent()).removeView(tv); // &lt;- fix } layout.addView(tv); // &lt;========== ERROR IN THIS LINE DURING 2ND RUN // EDITTEXT </code></pre>
{ "question_id": 28071349, "question_date": "2015-01-21T15:50:27.850Z", "question_score": 221, "tags": "java|android|android-edittext|textview|parent-child", "answer_id": 28071422, "answer_date": "2015-01-21T15:53:42.303Z", "answer_score": 427 }
Please answer the following Stack Overflow question: Title: TypeError: a bytes-like object is required, not 'str' in python and CSV <blockquote> <p>TypeError: a bytes-like object is required, not 'str'</p> </blockquote> <p>Getting the above error while executing below python code to save the HTML table data in CSV file. Don't know how to get rideup. Pls help me.</p> <pre><code>import csv import requests from bs4 import BeautifulSoup url='http://www.mapsofindia.com/districts-india/' response=requests.get(url) html=response.content soup=BeautifulSoup(html,'html.parser') table=soup.find('table', attrs={'class':'tableizer-table'}) list_of_rows=[] for row in table.findAll('tr')[1:]: list_of_cells=[] for cell in row.findAll('td'): list_of_cells.append(cell.text) list_of_rows.append(list_of_cells) outfile=open('./immates.csv','wb') writer=csv.writer(outfile) writer.writerow([&quot;SNo&quot;, &quot;States&quot;, &quot;Dist&quot;, &quot;Population&quot;]) writer.writerows(list_of_rows) </code></pre> <p>on above the last line.</p>
<p>You are using Python 2 methodology instead of Python 3.</p> <p>Change:</p> <pre><code>outfile=open('./immates.csv','wb') </code></pre> <p>To:</p> <pre><code>outfile=open('./immates.csv','w') </code></pre> <p>and you will get a file with the following output:</p> <pre><code>SNo,States,Dist,Population 1,Andhra Pradesh,13,49378776 2,Arunachal Pradesh,16,1382611 3,Assam,27,31169272 4,Bihar,38,103804637 5,Chhattisgarh,19,25540196 6,Goa,2,1457723 7,Gujarat,26,60383628 ..... </code></pre> <p>In Python 3 csv takes the input in text mode, whereas in Python 2 it took it in binary mode.</p> <p><strong>Edited to Add</strong></p> <p>Here is the code I ran:</p> <pre><code>url='http://www.mapsofindia.com/districts-india/' html = urllib.request.urlopen(url).read() soup = BeautifulSoup(html) table=soup.find('table', attrs={'class':'tableizer-table'}) list_of_rows=[] for row in table.findAll('tr')[1:]: list_of_cells=[] for cell in row.findAll('td'): list_of_cells.append(cell.text) list_of_rows.append(list_of_cells) outfile = open('./immates.csv','w') writer=csv.writer(outfile) writer.writerow(['SNo', 'States', 'Dist', 'Population']) writer.writerows(list_of_rows) </code></pre>
{ "question_id": 34283178, "question_date": "2015-12-15T07:20:35.487Z", "question_score": 221, "tags": "python|beautifulsoup|html-table", "answer_id": 34283957, "answer_date": "2015-12-15T08:12:08.663Z", "answer_score": 425 }
Please answer the following Stack Overflow question: Title: How can I replace (or strip) an extension from a filename in Python? <p>Is there a built-in function in Python that would replace (or remove, whatever) the extension of a filename (if it has one)?</p> <p>Example:</p> <pre><code>print replace_extension('/home/user/somefile.txt', '.jpg') </code></pre> <p>In my example: <code>/home/user/somefile.txt</code> would become <code>/home/user/somefile.jpg</code></p> <p>I don't know if it matters, but I need this for a SCons module I'm writing. (So perhaps there is some SCons specific function I can use ?)</p> <p>I'd like something <strong>clean</strong>. Doing a simple string replacement of all occurrences of <code>.txt</code> within the string is obviously not clean. (This would fail if my filename is <code>somefile.txt.txt.txt</code>)</p>
<p>Try <a href="http://docs.python.org/library/os.path.html#os.path.splitext" rel="noreferrer">os.path.splitext</a> it should do what you want.</p> <pre><code>import os print os.path.splitext('/home/user/somefile.txt')[0]+'.jpg' # /home/user/somefile.jpg </code></pre> <pre><code>os.path.splitext('/home/user/somefile.txt') # returns ('/home/user/somefile', '.txt') </code></pre>
{ "question_id": 3548673, "question_date": "2010-08-23T14:49:25.530Z", "question_score": 221, "tags": "python|filenames|scons|strip", "answer_id": 3548689, "answer_date": "2010-08-23T14:51:09.613Z", "answer_score": 258 }
Please answer the following Stack Overflow question: Title: Usage of sys.stdout.flush() method <p>What does <code>sys.stdout.flush()</code> do?</p>
<p>Python's standard out is buffered (meaning that it collects some of the data "written" to standard out before it writes it to the terminal). Calling <code>sys.stdout.flush()</code> forces it to "flush" the buffer, meaning that it will write everything in the buffer to the terminal, even if normally it would wait before doing so. </p> <p>Here's some good information about (un)buffered I/O and why it's useful:<br> <a href="http://en.wikipedia.org/wiki/Data_buffer" rel="noreferrer">http://en.wikipedia.org/wiki/Data_buffer</a><br> <a href="https://stackoverflow.com/questions/1450551/buffered-i-o-vs-unbuffered-io">Buffered vs unbuffered IO</a></p>
{ "question_id": 10019456, "question_date": "2012-04-04T21:22:57.353Z", "question_score": 221, "tags": "python|sys", "answer_id": 10019605, "answer_date": "2012-04-04T21:35:18.087Z", "answer_score": 219 }
Please answer the following Stack Overflow question: Title: Java 8: How do I work with exception throwing methods in streams? <p>Suppose I have a class and a method</p> <pre><code>class A { void foo() throws Exception() { ... } } </code></pre> <p>Now I would like to call foo for each instance of <code>A</code> delivered by a stream like:</p> <pre><code>void bar() throws Exception { Stream&lt;A&gt; as = ... as.forEach(a -&gt; a.foo()); } </code></pre> <p>Question: How do I properly handle the exception? The code does not compile on my machine because I do not handle the possible exceptions that can be thrown by foo(). The <code>throws Exception</code> of <code>bar</code> seems to be useless here. Why is that?</p>
<p>You need to wrap your method call into another one, where you do not throw <em>checked exceptions</em>. You can still throw anything that is a subclass of <code>RuntimeException</code>.</p> <p>A normal wrapping idiom is something like:</p> <pre><code>private void safeFoo(final A a) { try { a.foo(); } catch (Exception ex) { throw new RuntimeException(ex); } } </code></pre> <p>(Supertype exception <code>Exception</code> is <em>only</em> used as example, never try to catch it yourself)</p> <p>Then you can call it with: <code>as.forEach(this::safeFoo)</code>.</p>
{ "question_id": 23548589, "question_date": "2014-05-08T17:24:59.783Z", "question_score": 221, "tags": "java|java-8|unhandled-exception|java-stream", "answer_id": 23548793, "answer_date": "2014-05-08T17:35:43.200Z", "answer_score": 176 }
Please answer the following Stack Overflow question: Title: Best way to detect when a user leaves a web page? <p>What is the best way to detect if a user leaves a web page?</p> <p>The <code>onunload</code> JavaScript event doesn't work every time (the HTTP request takes longer than the time required to terminate the browser).</p> <p>Creating one will probably be blocked by current browsers.</p>
<p>Try the <code>onbeforeunload</code> event: It is fired just before the page is unloaded. It also allows you to ask back if the user really wants to leave. See the demo <em><a href="https://web.archive.org/web/20211028110528/http://www.4guysfromrolla.com/demos/OnBeforeUnloadDemo1.htm" rel="noreferrer">onbeforeunload Demo</a></em>.</p> <p>Alternatively, you can send out an <a href="http://en.wikipedia.org/wiki/Ajax_%28programming%29" rel="noreferrer">Ajax</a> request when he leaves.</p>
{ "question_id": 147636, "question_date": "2008-09-29T05:30:46.383Z", "question_score": 221, "tags": "javascript", "answer_id": 147765, "answer_date": "2008-09-29T07:02:06.493Z", "answer_score": 236 }
Please answer the following Stack Overflow question: Title: Resize a large bitmap file to scaled output file on Android <p>I have a large bitmap (say 3888x2592) in a file. Now, I want to resize that bitmap to 800x533 and save it to another file. I normally would scale the bitmap by calling <code>Bitmap.createBitmap</code> method but it needs a source bitmap as the first argument, which I can't provide because loading the original image into a Bitmap object would of course exceed the memory (see <a href="https://stackoverflow.com/questions/477572/android-strange-out-of-memory-issue">here</a>, for example).</p> <p>I also can't read the bitmap with, for example, <code>BitmapFactory.decodeFile(file, options)</code>, providing a <code>BitmapFactory.Options.inSampleSize</code>, because I want to resize it to an exact width and height. Using <code>inSampleSize</code> would resize the bitmap to 972x648 (if I use <code>inSampleSize=4</code>) or to 778x518 (if I use <code>inSampleSize=5</code>, which isn't even a power of 2).</p> <p>I would also like to avoid reading the image using inSampleSize with, for example, 972x648 in a first step and then resizing it to exactly 800x533 in a second step, because the quality would be poor compared to a direct resizing of the original image.</p> <p>To sum up my question: Is there a way to read a large image file with 10MP or more and save it to a new image file, resized to a specific new width and height, without getting an OutOfMemory exception?</p> <p>I also tried <code>BitmapFactory.decodeFile(file, options)</code> and setting the Options.outHeight and Options.outWidth values manually to 800 and 533, but it doesn't work that way.</p>
<p><strong>No.</strong> I'd love for someone to correct me, but I accepted the load/resize approach you tried as a compromise.</p> <p>Here are the steps for anyone browsing:</p> <ol> <li>Calculate the maximum possible <code>inSampleSize</code> that still yields an image larger than your target.</li> <li>Load the image using <code>BitmapFactory.decodeFile(file, options)</code>, passing inSampleSize as an option.</li> <li>Resize to the desired dimensions using <code>Bitmap.createScaledBitmap()</code>.</li> </ol>
{ "question_id": 3331527, "question_date": "2010-07-26T00:06:25.020Z", "question_score": 221, "tags": "android|image|resize|bitmap", "answer_id": 3331673, "answer_date": "2010-07-26T00:56:22.343Z", "answer_score": 148 }
Please answer the following Stack Overflow question: Title: how to get request path with express req object <p>I'm using express + node.js and I have a req object, the request in the browser is /account but when I log req.path I get '/' --- not '/account'.</p> <pre><code> //auth required or redirect app.use('/account', function(req, res, next) { console.log(req.path); if ( !req.session.user ) { res.redirect('/login?ref='+req.path); } else { next(); } }); </code></pre> <p>req.path is / when it should be /account ??</p>
<p><strong>UPDATE 8 YEARS LATER:</strong></p> <p><code>req.path</code> was <a href="https://github.com/expressjs/express/blob/b400814d000613745673e39a6e1cd294a69a2677/lib/request.js#L416" rel="noreferrer">already doing exactly same thing</a> that I mentioned here. I don't remember how this answer solved issue and accepted as a correct answer but currently <strong>it's not a valid answer</strong>. Please ignore this answer. Thanks @mhodges for mentioning this.</p> <p><strong>Original answer:</strong></p> <p>If you want to really get only &quot;path&quot; without querystring, you can use <code>url</code> library to parse and get only path part of url.</p> <pre><code>var url = require('url'); //auth required or redirect app.use('/account', function(req, res, next) { var path = url.parse(req.url).pathname; if ( !req.session.user ) { res.redirect('/login?ref='+path); } else { next(); } }); </code></pre>
{ "question_id": 12525928, "question_date": "2012-09-21T07:21:52.120Z", "question_score": 221, "tags": "javascript|node.js|express", "answer_id": 17186033, "answer_date": "2013-06-19T08:08:26.527Z", "answer_score": 15 }
Please answer the following Stack Overflow question: Title: How to get the command line args passed to a running process on unix/linux systems? <p>On SunOS there is <code>pargs</code> command that prints the command line arguments passed to the running process. </p> <p>Is there is any similar command on other Unix environments?</p>
<p>There are several options:</p> <pre><code>ps -fp &lt;pid&gt; cat /proc/&lt;pid&gt;/cmdline | sed -e "s/\x00/ /g"; echo </code></pre> <p>There is more info in <code>/proc/&lt;pid&gt;</code> on Linux, just have a look.</p> <p>On other Unixes things might be different. The <code>ps</code> command will work everywhere, the <code>/proc</code> stuff is OS specific. For example on AIX there is no <code>cmdline</code> in <code>/proc</code>.</p>
{ "question_id": 821837, "question_date": "2009-05-04T20:18:13.187Z", "question_score": 221, "tags": "linux|unix|aix|hp-ux|sunos", "answer_id": 821889, "answer_date": "2009-05-04T20:26:54.397Z", "answer_score": 338 }
Please answer the following Stack Overflow question: Title: Create a list with initial capacity in Python <p>Code like this often happens:</p> <pre><code>l = [] while foo: # baz l.append(bar) # qux </code></pre> <p>This is really slow if you're about to append thousands of elements to your list, as the list will have to be constantly resized to fit the new elements.</p> <p>In Java, you can create an ArrayList with an initial capacity. If you have some idea how big your list will be, this will be a lot more efficient.</p> <p>I understand that code like this can often be refactored into a list comprehension. If the <em>for</em>/<em>while</em> loop is very complicated, though, this is unfeasible. Is there an equivalent for us Python programmers?</p>
<h2>Warning: This answer is contested. See comments.</h2> <pre><code>def doAppend( size=10000 ): result = [] for i in range(size): message= &quot;some unique object %d&quot; % ( i, ) result.append(message) return result def doAllocate( size=10000 ): result=size*[None] for i in range(size): message= &quot;some unique object %d&quot; % ( i, ) result[i]= message return result </code></pre> <p><strong>Results</strong>. (evaluate each function 144 times and average the duration)</p> <pre><code>simple append 0.0102 pre-allocate 0.0098 </code></pre> <p><strong>Conclusion</strong>. It barely matters.</p> <p>Premature optimization is the root of all evil.</p>
{ "question_id": 311775, "question_date": "2008-11-22T20:56:41.313Z", "question_score": 221, "tags": "python|list|dictionary|initialization", "answer_id": 311833, "answer_date": "2008-11-22T22:02:34.847Z", "answer_score": 123 }
Please answer the following Stack Overflow question: Title: What data type to use for money in Java? <p>What data type should you use for money in Java?</p>
<p>Java has <a href="http://download.oracle.com/javase/6/docs/api/java/util/Currency.html" rel="noreferrer"><code>Currency</code></a> class that represents the ISO 4217 currency codes. <code>BigDecimal</code> is the best type for representing currency decimal values. </p> <p><a href="http://www.joda.org/joda-money/" rel="noreferrer">Joda Money</a> has provided a library to represent money.</p>
{ "question_id": 8148684, "question_date": "2011-11-16T08:29:51.437Z", "question_score": 221, "tags": "java|types|currency", "answer_id": 8148773, "answer_date": "2011-11-16T08:37:23.413Z", "answer_score": 167 }