input_text
stringlengths
115
13.8k
output_text
stringlengths
24
15k
metadata
dict
Please answer the following Stack Overflow question: Title: What is the difference between Non-Repeatable Read and Phantom Read? <p>What is the difference between <strong>non-repeatable read</strong> and <strong>phantom read</strong>?</p> <p>I have read the <a href="http://en.wikipedia.org/wiki/Isolation_(database_systems)" rel="nofollow noreferrer">Isolation (database systems) article from Wikipedia</a>, but I have a few doubts. In the below example, what will happen: the <strong>non-repeatable read</strong> and <strong>phantom read</strong>?</p> <p>####<strong>Transaction A</strong></p> <pre><code>SELECT ID, USERNAME, accountno, amount FROM USERS WHERE ID=1 </code></pre> <p>####<strong>OUTPUT:</strong></p> <pre><code>1----MIKE------29019892---------5000 </code></pre> <p>####<strong>Transaction B</strong></p> <pre><code>UPDATE USERS SET amount=amount+5000 where ID=1 AND accountno=29019892; COMMIT; </code></pre> <p>####<strong>Transaction A</strong></p> <pre><code>SELECT ID, USERNAME, accountno, amount FROM USERS WHERE ID=1 </code></pre> <p>Another doubt is, in the above example, which isolation level should be used? And why?</p>
<p><a href="http://en.wikipedia.org/wiki/Isolation_%28database_systems%29#Non-repeatable_reads" rel="noreferrer">From Wikipedia</a> (which has great and detailed examples for this):</p> <blockquote> <p>A non-repeatable read occurs, when during the course of a transaction, a row is retrieved twice and the values within the row differ between reads.</p> </blockquote> <p>and</p> <blockquote> <p>A phantom read occurs when, in the course of a transaction, two identical queries are executed, and the collection of rows returned by the second query is different from the first.</p> </blockquote> <p>Simple examples:</p> <ul> <li>User A runs the same query twice. </li> <li>In between, User B runs a transaction and commits.</li> <li>Non-repeatable read: The A row that user A has queried has a different value the second time.</li> <li>Phantom read: All the rows in the query have the same value before and after, <em>but different rows are being selected</em> (because B has deleted or inserted some). Example: <code>select sum(x) from table;</code> will return a different result even if none of the affected rows themselves have been updated, if rows have been added or deleted.</li> </ul> <blockquote> <p>In the above example,which isolation level to be used?</p> </blockquote> <p>What isolation level you need depends on your application. There is a high cost to a "better" isolation level (such as reduced concurrency).</p> <p>In your example, you won't have a phantom read, because you select only from a single row (identified by primary key). You can have non-repeatable reads, so if that is a problem, you may want to have an isolation level that prevents that. In Oracle, transaction A could also issue a SELECT FOR UPDATE, then transaction B cannot change the row until A is done.</p>
{ "question_id": 11043712, "question_date": "2012-06-15T01:54:03.760Z", "question_score": 226, "tags": "database|oracle|transactions|isolation-level|transaction-isolation", "answer_id": 11044968, "answer_date": "2012-06-15T05:17:37.187Z", "answer_score": 229 }
Please answer the following Stack Overflow question: Title: Can JSON start with "["? <p>From what I can read on <a href="http://json.org/" rel="noreferrer">json.org</a>, all JSON strings should start with <code>{</code> (curly brace), and <code>[</code> characters (square brackets) represent an array element in JSON.</p> <p>I use the <code>json4j</code> library, and I got an input that starts with <code>[</code>, so I didn't think this was valid JSON. I looked briefly at the JSON schema, but I couldn't really find it stated that a JSON file cannot start with <code>[</code>, or that it can only start with <code>{</code>.</p>
<p>JSON can be either an array or an object. Specifically off of json.org:</p> <blockquote> <p>JSON is built on two structures:</p> <ul> <li>A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.</li> <li>An ordered list of values. In most languages, this is realized as an<br> array, vector, list, or sequence.</li> </ul> </blockquote> <p>It then goes on to describe the two structures as: <img src="https://i.stack.imgur.com/wAM3m.gif" alt="A JSON object"> <img src="https://i.stack.imgur.com/rdLQh.gif" alt="A JSON array"></p> <p>Note that the starting and ending characters are curly brackets and square brackets respectively.</p> <p><strong>Edit</strong><br> And from here: <a href="http://www.ietf.org/rfc/rfc4627.txt" rel="noreferrer">http://www.ietf.org/rfc/rfc4627.txt</a></p> <blockquote> <p>A JSON text is a sequence of tokens. The set of tokens includes six structural characters, strings, numbers, and three literal names.</p> <p>A JSON text is a serialized object or array.</p> </blockquote> <h2>Update (2014)</h2> <p>As of March 2014, there is a new JSON RFC (<a href="http://www.rfc-editor.org/rfc/rfc7159.txt" rel="noreferrer">7159</a>) that modifies the definition slightly (see pages 4/5).</p> <p>The definition per RFC 4627 was: <code>JSON-text = object / array</code></p> <p>This has been changed in RFC 7159 to: <code>JSON-text = ws value ws</code></p> <p>Where <code>ws</code> represents whitespace and <code>value</code> is defined as follows:</p> <blockquote> <p>A JSON value MUST be an object, array, number, or string, or one of the following three literal names:</p> <pre><code>false null true </code></pre> </blockquote> <p>So, the answer to the question is still yes, JSON text can start with a square bracket (i.e. an array). But in addition to objects and arrays, it can now also be a number, string or the values <code>false</code>, <code>null</code> or <code>true</code>.</p> <p>Also, this has changed from my previous RFC 4627 quote (emphasis added):</p> <blockquote> <p>A JSON text is a sequence of tokens. The set of tokens includes six structural characters, strings, numbers, and three literal names.</p> <p>A JSON text is a serialized <strong>value</strong>. Note that certain previous specifications of JSON constrained a JSON text to be an object or an array. Implementations that generate only objects or arrays where a JSON text is called for will be interoperable in the sense that all implementations will accept these as conforming JSON texts.</p> </blockquote>
{ "question_id": 5034444, "question_date": "2011-02-17T20:46:42.477Z", "question_score": 226, "tags": "json", "answer_id": 5034547, "answer_date": "2011-02-17T20:56:09.777Z", "answer_score": 269 }
Please answer the following Stack Overflow question: Title: How to check if an object is nullable? <p>How do I check if a given object is nullable in other words how to implement the following method...</p> <pre><code>bool IsNullableValueType(object o) { ... } </code></pre> <p>I am looking for nullable <em>value types.</em> I didn't have reference types in mind.</p> <pre><code>//Note: This is just a sample. The code has been simplified //to fit in a post. public class BoolContainer { bool? myBool = true; } var bc = new BoolContainer(); const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ; object obj; object o = (object)bc; foreach (var fieldInfo in o.GetType().GetFields(bindingFlags)) { obj = (object)fieldInfo.GetValue(o); } </code></pre> <p><code>obj</code> now refers to an object of type <code>bool</code> (<code>System.Boolean</code>) with value equal to <code>true</code>. What I really wanted was an object of type <code>Nullable&lt;bool&gt;</code></p> <p>So now as a work around I decided to check if o is nullable and create a nullable wrapper around obj.</p>
<p>There are two types of nullable - <code>Nullable&lt;T&gt;</code> and reference-type.</p> <p>Jon has corrected me that it is hard to get type if boxed, but you can with generics: - so how about below. This is actually testing type <code>T</code>, but using the <code>obj</code> parameter purely for generic type inference (to make it easy to call) - it would work almost identically without the <code>obj</code> param, though.</p> <pre><code>static bool IsNullable&lt;T&gt;(T obj) { if (obj == null) return true; // obvious Type type = typeof(T); if (!type.IsValueType) return true; // ref-type if (Nullable.GetUnderlyingType(type) != null) return true; // Nullable&lt;T&gt; return false; // value-type } </code></pre> <p>But this won't work so well if you have already boxed the value to an object variable.</p> <p>Microsoft documentation: <a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/nullable-types/how-to-identify-a-nullable-type" rel="noreferrer">https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/nullable-types/how-to-identify-a-nullable-type</a></p>
{ "question_id": 374651, "question_date": "2008-12-17T14:17:16.010Z", "question_score": 226, "tags": "c#|.net|nullable", "answer_id": 374663, "answer_date": "2008-12-17T14:20:52.930Z", "answer_score": 301 }
Please answer the following Stack Overflow question: Title: What is the purpose of std::make_pair vs the constructor of std::pair? <p>What is the purpose of <code>std::make_pair</code>?</p> <p>Why not just do <code>std::pair&lt;int, char&gt;(0, 'a')</code>?</p> <p>Is there any difference between the two methods?</p>
<p>The difference is that with <code>std::pair</code> you need to specify the types of both elements, whereas <code>std::make_pair</code> will create a pair with the type of the elements that are passed to it, without you needing to tell it. That's what I could gather from various docs anyways.</p> <p>See this example from <a href="http://www.cplusplus.com/reference/std/utility/make_pair/" rel="noreferrer">http://www.cplusplus.com/reference/std/utility/make_pair/</a></p> <pre><code>pair &lt;int,int&gt; one; pair &lt;int,int&gt; two; one = make_pair (10,20); two = make_pair (10.5,'A'); // ok: implicit conversion from pair&lt;double,char&gt; </code></pre> <p>Aside from the implicit conversion bonus of it, if you didn't use make_pair you'd have to do</p> <pre><code>one = pair&lt;int,int&gt;(10,20) </code></pre> <p>every time you assigned to one, which would be annoying over time...</p>
{ "question_id": 9270563, "question_date": "2012-02-14T01:37:10.673Z", "question_score": 226, "tags": "c++|stl|std-pair", "answer_id": 9270585, "answer_date": "2012-02-14T01:39:57.687Z", "answer_score": 207 }
Please answer the following Stack Overflow question: Title: Is it possible to define more than one function per file in MATLAB, and access them from outside that file? <p>When I was studying for my undergraduate degree in EE, MATLAB required each function to be defined in its own file, even if it was a one-liner.</p> <p>I'm studying for a graduate degree now, and I have to write a project in MATLAB. Is this still a requirement for newer versions of MATLAB?</p> <p>If it is possible to put more than one function in a file, are there any restrictions to this? For instance, can all the functions in the file be accessed from outside the file, or only the function that has the same name as the file?</p> <p>Note: I am using MATLAB release R2007b.</p>
<p>The first function in an m-file (i.e. the <a href="http://www.mathworks.com/help/matlab/ref/function.html" rel="noreferrer">main function</a>), is invoked when that m-file is called. It is not <em>required</em> that the main function have the same name as the m-file, but for clarity it <em>should</em>. When the function and file name differ, the <em>file name</em> must be used to call the main function.</p> <p>All subsequent functions in the m-file, called <a href="http://www.mathworks.com/help/matlab/matlab_prog/local-functions.html" rel="noreferrer">local functions</a> (or "subfunctions" in the older terminology), can only be called by the main function and other local functions in that m-file. Functions in other m-files can not call them. Starting in R2016b, you can <a href="https://www.mathworks.com/help/matlab/matlab_prog/local-functions-in-scripts.html" rel="noreferrer">add local functions to scripts</a> as well, although the scoping behavior is still the same (i.e. they can only be called from within the script).</p> <p>In addition, you can also declare functions <em>within</em> other functions. These are called <a href="http://www.mathworks.com/help/matlab/matlab_prog/nested-functions.html" rel="noreferrer">nested functions</a>, and these can only be called from within the function they are nested. They can also have access to variables in functions in which they are nested, which makes them quite useful albeit slightly tricky to work with.</p> <p><strong>More food for thought...</strong></p> <p>There are some ways around the normal function scoping behavior outlined above, such as passing <a href="http://www.mathworks.com/help/techdoc/ref/function_handle.html" rel="noreferrer">function handles</a> as output arguments as mentioned in the answers from <a href="https://stackoverflow.com/a/3571423/52738">SCFrench</a> and <a href="https://stackoverflow.com/questions/3569933/is-it-possible-to-define-more-than-one-function-per-file-in-matlab/3570017#3570017">Jonas</a> (which, starting in R2013b, is facilitated by the <a href="https://www.mathworks.com/help/matlab/ref/localfunctions.html" rel="noreferrer"><code>localfunctions</code></a> function). However, I wouldn't suggest making it a habit of resorting to such tricks, as there are likely much better options for organizing your functions and files.</p> <p>For example, let's say you have a main function <code>A</code> in an m-file <code>A.m</code>, along with local functions <code>D</code>, <code>E</code>, and <code>F</code>. Now let's say you have two other related functions <code>B</code> and <code>C</code> in m-files <code>B.m</code> and <code>C.m</code>, respectively, that you also want to be able to call <code>D</code>, <code>E</code>, and <code>F</code>. Here are some options you have:</p> <ul> <li><p>Put <code>D</code>, <code>E</code>, and <code>F</code> each in their own separate m-files, allowing any other function to call them. The downside is that the scope of these functions is large and isn't restricted to just <code>A</code>, <code>B</code>, and <code>C</code>, but the upside is that this is quite simple.</p></li> <li><p>Create a <code>defineMyFunctions</code> m-file (like in Jonas' example) with <code>D</code>, <code>E</code>, and <code>F</code> as local functions and a main function that simply returns function handles to them. This allows you to keep <code>D</code>, <code>E</code>, and <code>F</code> in the same file, but it doesn't do anything regarding the scope of these functions since any function that can call <code>defineMyFunctions</code> can invoke them. You also then have to worry about passing the function handles around as arguments to make sure you have them where you need them.</p></li> <li><p>Copy <code>D</code>, <code>E</code> and <code>F</code> into <code>B.m</code> and <code>C.m</code> as local functions. This limits the scope of their usage to just <code>A</code>, <code>B</code>, and <code>C</code>, but makes updating and maintenance of your code a nightmare because you have three copies of the same code in different places.</p></li> <li><p><strong>Use <a href="http://www.mathworks.com/help/matlab/matlab_prog/private-functions.html" rel="noreferrer">private functions</a>!</strong> If you have <code>A</code>, <code>B</code>, and <code>C</code> in the same directory, you can create a subdirectory called <code>private</code> and place <code>D</code>, <code>E</code>, and <code>F</code> in there, each as a separate m-file. This limits their scope so they can only be called by functions in the directory immediately above (i.e. <code>A</code>, <code>B</code>, and <code>C</code>) and keeps them together in the same place (but still different m-files):</p> <pre><code>myDirectory/ A.m B.m C.m private/ D.m E.m F.m </code></pre></li> </ul> <p>All this goes somewhat outside the scope of your question, and is probably more detail than you need, but I thought it might be good to touch upon the more general concern of organizing all of your m-files. ;)</p>
{ "question_id": 3569933, "question_date": "2010-08-25T20:26:40.817Z", "question_score": 226, "tags": "matlab|function|file|scope|function-declaration", "answer_id": 3569946, "answer_date": "2010-08-25T20:28:24.767Z", "answer_score": 279 }
Please answer the following Stack Overflow question: Title: Visual Studio Code — Insert Newline at the End of Files <p>When saving a file using Visual Studio Code, a newline is not automatically added to the end of the file, causing all sorts of <a href="https://stackoverflow.com/questions/729692/why-should-text-files-end-with-a-newline">potential issues</a>.</p> <p>How can I append a newline automatically in Visual Studio Code?</p>
<p>There are two easy methods to make Visual Studio Code insert a new line at the end of files:</p> <h2>Method I</h2> <ol> <li><p>Open Visual Studio Code and go to <strong>File (Code if using a Mac) -> Preferences -> Settings</strong>; you should now be viewing a settings page</p></li> <li><p>Enter '<strong>insert final newline</strong>' in to the search bar</p></li> <li><p>Select the checkbox under the heading '<strong>Files: Insert Final Newline</strong>' in the '<strong>Workspace Settings</strong>' and/or '<strong>User Settings</strong>' tab(s) as required</p></li> </ol> <p><a href="https://i.stack.imgur.com/bWSmc.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bWSmc.png" alt="Settings Page with &#39;Files: Insert Final Newline&#39; checkbox selected"></a></p> <h2>Method II</h2> <ol> <li><p>Open Visual Studio Code and go to <strong>File (Code if using a Mac) -> Preferences -> Settings</strong>; you should now be viewing a settings page</p></li> <li><p>Open the JSON settings page by clicking the <strong>{}</strong> icon at the top right of the page</p></li> <li><p>Enter '<strong>files.insertFinalNewline</strong>' in to the search bar of the JSON settings page</p></li> <li><p>Either</p> <ul> <li>Click on the white 'edit pen' on the left hand side of the line containing the <code>files.insertFinalNewline</code> JSON key and select <code>True</code></li> </ul> <p><em>or</em></p> <ul> <li>Copy the line containing the <code>files.insertFinalNewline</code> JSON key, paste it into the right hand side JSON file under the <strong>'User Settings'</strong> and/or <strong>'Workspace Settings'</strong> tab(s) as required, and set its value to <code>true</code></li> </ul></li> </ol> <p><a href="https://i.stack.imgur.com/1kLMH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1kLMH.png" alt="User Settings JSON with &lt;code&gt;files.insertFinalNewline&lt;/code&gt; set to &lt;code&gt;true&lt;/code&gt;"></a></p> <h2>Final Result</h2> <p>In either your <strong>User Settings</strong> or <strong>Workspace Settings</strong> JSON file, you should have a line reading <code>"files.insertFinalNewline": true</code>, within the provided curly braces ({ }). Additionally, in the <strong>Settings</strong> page, the checkbox under the heading '<strong>Files: Insert Final Newline</strong>' will be selected.</p> <p>Visual Studio Code will now add an empty line to the end of files when being saved, if there isn't already one.</p>
{ "question_id": 44704968, "question_date": "2017-06-22T16:33:11.013Z", "question_score": 226, "tags": "visual-studio-code|newline", "answer_id": 44704969, "answer_date": "2017-06-22T16:33:11.013Z", "answer_score": 353 }
Please answer the following Stack Overflow question: Title: onRequestPermissionsResult not being called in fragment if defined in both fragment and activity <p>I have a fragment in which I have recyclerview and setting data in this recyclerview using recyclerview adapter.</p> <p>Now, I am having a button in the adapter's list item clicking on which I need to check the READ_EXTERNAL_STORAGE permission in android for new permission model in android. </p> <p>I have created a new function in this adapter's fragment to check if permission is granted or not and request for permission if not granted already.</p> <p>I have passed MyFragment.this as a parameter in the adapter and calling the fragment's method on the button click in the adapter.</p> <p>I have used the below code to call requestPermission in fragment.</p> <pre><code>if(ContextCompat.checkSelfPermission(mContext, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){ requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, ConstantVariables.READ_EXTERNAL_STORAGE); } </code></pre> <p>I have overridden the <code>onRequestPermissionsResult</code> method in fragment by using the below code:</p> <pre><code>@Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case ConstantVariables.READ_EXTERNAL_STORAGE: // If request is cancelled, the result arrays are empty. if (grantResults.length &gt; 0 &amp;&amp; grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission was granted, proceed to the normal flow. startImageUploading(); } else {} </code></pre> <p>But it is not getting called, instead of this Activity's onRequestPermissionsResult method is getting called. </p> <p>I have defined the same onRequestPermissionsResult method in fragment's parent activity also and it is getting called.</p> <p>I can not remove the activity's onRequestPermissionsResult method but want to call fragment's onRequestPermissionsResult method when I request permission from fragment. How can I do this? Am I doing something wrong here, please help me if anyone have idea here.</p>
<p>Edited answer to cover broader issues</p> <p>I think you are confusing the method for fragment and activity. Had a similar issue my project last month. Please check if you have finally the following:</p> <ol> <li>In AppCompatActivity use the method <strong>ActivityCompat.requestpermissions</strong></li> <li>In v4 support fragment you should use <strong>requestpermissions</strong></li> <li>Catch is if you call AppcompatActivity.requestpermissions in your fragment then callback will come to activity and not fragment </li> <li>Make sure to call <code>super.onRequestPermissionsResult</code> from the activity's <code>onRequestPermissionsResult</code>.</li> </ol> <p>See if it helps . </p>
{ "question_id": 35989288, "question_date": "2016-03-14T13:47:29.590Z", "question_score": 226, "tags": "android|android-6.0-marshmallow", "answer_id": 35996955, "answer_date": "2016-03-14T20:01:22.737Z", "answer_score": 454 }
Please answer the following Stack Overflow question: Title: How do I call ::std::make_shared on a class with only protected or private constructors? <p>I have this code that doesn't work, but I think the intent is clear:</p> <p><em>testmakeshared.cpp</em></p> <pre><code>#include &lt;memory&gt; class A { public: static ::std::shared_ptr&lt;A&gt; create() { return ::std::make_shared&lt;A&gt;(); } protected: A() {} A(const A &amp;) = delete; const A &amp;operator =(const A &amp;) = delete; }; ::std::shared_ptr&lt;A&gt; foo() { return A::create(); } </code></pre> <p>But I get this error when I compile it:</p> <pre><code>g++ -std=c++0x -march=native -mtune=native -O3 -Wall testmakeshared.cpp In file included from /usr/lib/gcc/x86_64-redhat-linux/4.6.1/../../../../include/c++/4.6.1/bits/shared_ptr.h:52:0, from /usr/lib/gcc/x86_64-redhat-linux/4.6.1/../../../../include/c++/4.6.1/memory:86, from testmakeshared.cpp:1: testmakeshared.cpp: In constructor ‘std::_Sp_counted_ptr_inplace&lt;_Tp, _Alloc, _Lp&gt;::_Sp_counted_ptr_inplace(_Alloc) [with _Tp = A, _Alloc = std::allocator&lt;A&gt;, __gnu_cxx::_Lock_policy _Lp = (__gnu_cxx::_Lock_policy)2u]’: /usr/lib/gcc/x86_64-redhat-linux/4.6.1/../../../../include/c++/4.6.1/bits/shared_ptr_base.h:518:8: instantiated from ‘std::__shared_count&lt;_Lp&gt;::__shared_count(std::_Sp_make_shared_tag, _Tp*, const _Alloc&amp;, _Args&amp;&amp; ...) [with _Tp = A, _Alloc = std::allocator&lt;A&gt;, _Args = {}, __gnu_cxx::_Lock_policy _Lp = (__gnu_cxx::_Lock_policy)2u]’ /usr/lib/gcc/x86_64-redhat-linux/4.6.1/../../../../include/c++/4.6.1/bits/shared_ptr_base.h:986:35: instantiated from ‘std::__shared_ptr&lt;_Tp, _Lp&gt;::__shared_ptr(std::_Sp_make_shared_tag, const _Alloc&amp;, _Args&amp;&amp; ...) [with _Alloc = std::allocator&lt;A&gt;, _Args = {}, _Tp = A, __gnu_cxx::_Lock_policy _Lp = (__gnu_cxx::_Lock_policy)2u]’ /usr/lib/gcc/x86_64-redhat-linux/4.6.1/../../../../include/c++/4.6.1/bits/shared_ptr.h:313:64: instantiated from ‘std::shared_ptr&lt;_Tp&gt;::shared_ptr(std::_Sp_make_shared_tag, const _Alloc&amp;, _Args&amp;&amp; ...) [with _Alloc = std::allocator&lt;A&gt;, _Args = {}, _Tp = A]’ /usr/lib/gcc/x86_64-redhat-linux/4.6.1/../../../../include/c++/4.6.1/bits/shared_ptr.h:531:39: instantiated from ‘std::shared_ptr&lt;_Tp&gt; std::allocate_shared(const _Alloc&amp;, _Args&amp;&amp; ...) [with _Tp = A, _Alloc = std::allocator&lt;A&gt;, _Args = {}]’ /usr/lib/gcc/x86_64-redhat-linux/4.6.1/../../../../include/c++/4.6.1/bits/shared_ptr.h:547:42: instantiated from ‘std::shared_ptr&lt;_Tp1&gt; std::make_shared(_Args&amp;&amp; ...) [with _Tp = A, _Args = {}]’ testmakeshared.cpp:6:40: instantiated from here testmakeshared.cpp:10:8: error: ‘A::A()’ is protected /usr/lib/gcc/x86_64-redhat-linux/4.6.1/../../../../include/c++/4.6.1/bits/shared_ptr_base.h:400:2: error: within this context Compilation exited abnormally with code 1 at Tue Nov 15 07:32:58 </code></pre> <p>This message is basically saying that some random method way down in the template instantiation stack from <code>::std::make_shared</code> can't access the constructor because it's protected.</p> <p>But I really want to use both <code>::std::make_shared</code> and prevent anybody from making an object of this class that isn't pointed at by a <code>::std::shared_ptr</code>. Is there any way to accomplish this?</p>
<p><a href="https://stackoverflow.com/questions/8147027/how-do-i-call-stdmake-shared-on-a-class-with-only-protected-or-private-const/8147213#8147213">This answer</a> is probably better, and the one I'll likely accept. But I also came up with a method that's uglier, but does still let everything still be inline and doesn't require a derived class:</p> <pre><code>#include &lt;memory&gt; #include &lt;string&gt; class A { protected: struct this_is_private; public: explicit A(const this_is_private &amp;) {} A(const this_is_private &amp;, ::std::string, int) {} template &lt;typename... T&gt; static ::std::shared_ptr&lt;A&gt; create(T &amp;&amp;...args) { return ::std::make_shared&lt;A&gt;(this_is_private{0}, ::std::forward&lt;T&gt;(args)...); } protected: struct this_is_private { explicit this_is_private(int) {} }; A(const A &amp;) = delete; const A &amp;operator =(const A &amp;) = delete; }; ::std::shared_ptr&lt;A&gt; foo() { return A::create(); } ::std::shared_ptr&lt;A&gt; bar() { return A::create("George", 5); } ::std::shared_ptr&lt;A&gt; errors() { ::std::shared_ptr&lt;A&gt; retval; // Each of these assignments to retval properly generates errors. retval = A::create("George"); retval = new A(A::this_is_private{0}); return ::std::move(retval); } </code></pre> <p><strong>Edit 2017-01-06:</strong> I changed this to make it clear that this idea is clearly and simply extensible to constructors that take arguments because other people were providing answers along those lines and seemed confused about this.</p>
{ "question_id": 8147027, "question_date": "2011-11-16T05:11:36.480Z", "question_score": 226, "tags": "c++|c++11|shared-ptr", "answer_id": 8147326, "answer_date": "2011-11-16T05:53:25.057Z", "answer_score": 126 }
Please answer the following Stack Overflow question: Title: Why generate long serialVersionUID instead of a simple 1L? <p>When class implements Serializable in Eclipse, I have two options: add default <code>serialVersionUID(1L)</code> or generated <code>serialVersionUID(3567653491060394677L)</code>. I think that first one is cooler, but many times I saw people using the second option. Is there any reason to generate <code>long serialVersionUID</code>?</p>
<p>As far as I can tell, that would be only for compatibility with previous releases. This would only be useful if you neglected to use a serialVersionUID before, and then made a change that you know should be <a href="http://java.sun.com/javase/6/docs/platform/serialization/spec/version.html#6678" rel="noreferrer">compatible</a> but which causes serialization to break.</p> <p>See the <a href="http://java.sun.com/javase/6/docs/platform/serialization/spec/version.html" rel="noreferrer">Java Serialization Spec</a> for more details.</p>
{ "question_id": 888335, "question_date": "2009-05-20T14:37:43.963Z", "question_score": 226, "tags": "java|serialization|code-generation|serialversionuid", "answer_id": 888370, "answer_date": "2009-05-20T14:44:50.483Z", "answer_score": 95 }
Please answer the following Stack Overflow question: Title: Maven surefire could not find ForkedBooter class <p>Recently coming to a new project, I'm trying to compile our source code. Everything worked fine yesterday, but today is another story.</p> <p>Every time I'm running <code>mvn clean install</code> on a module, once reaching the tests, it crashes into an error:</p> <pre><code>[INFO] --- maven-surefire-plugin:2.18.1:test (default-test) @ recorder --- [INFO] Surefire report directory: /lhome/code/recorder/target/surefire-reports [INFO] Using configured provider org.apache.maven.surefire.junitcore.JUnitCoreProvider [INFO] parallel='none', perCoreThreadCount=true, threadCount=0, useUnlimitedThreads=false, threadCountSuites=0, threadCountClasses=0, threadCountMethods=0, parallelOptimized=true ------------------------------------------------------- T E S T S ------------------------------------------------------- Error: Could not find or load main class org.apache.maven.surefire.booter.ForkedBooter Results : Tests run: 0, Failures: 0, Errors: 0, Skipped: 0 </code></pre> <p>and later on:</p> <pre><code>[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.18.1:test (default-test) on project recorder: Execution default-test of goal org.apache.maven.plugins:maven-surefire-plugin:2.18.1:test failed: The forked VM terminated without properly saying goodbye. VM crash or System.exit called? </code></pre> <p>I'm running on <a href="https://en.wikipedia.org/wiki/Debian_version_history#Debian_9_(Stretch)" rel="noreferrer">Debian&nbsp;9</a> (Stretch) 64-bits with OpenJDK 1.8.0_181, <a href="http://en.wikipedia.org/wiki/Apache_Maven" rel="noreferrer">Maven</a> 3.5.4, working behind my company proxy which I configured in my <code>~/.m2/settings.xml</code>.</p> <p>A strange thing it that the latest Surefire version is 2.22.1 if I remember correctly. I tried to specify the plugin version, but it does not get updated, otherwise there's no plugin version specification in any <a href="https://en.wikipedia.org/wiki/Apache_Maven#Project_Object_Model" rel="noreferrer">POM</a> (parent, grand-parent or this one).</p> <p>I managed to force Maven to change the Surefire version to the latest, but now it's even worse:</p> <pre><code>[INFO] ------------------------------------------------------- [INFO] T E S T S [INFO] ------------------------------------------------------- [INFO] [INFO] Results: [INFO] [INFO] Tests run: 0, Failures: 0, Errors: 0, Skipped: 0 [...] [ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.22.1:test (default-test) on project recorder: There are test failures. [ERROR] [ERROR] Please refer to /lhome/code/recorder/target/surefire-reports for the individual test results. [ERROR] Please refer to dump files (if any exist) [date].dump, [date]-jvmRun[N].dump and [date].dumpstream. [ERROR] The forked VM terminated without properly saying goodbye. VM crash or System.exit called? [ERROR] Command was /bin/sh -c cd /lhome/code/recorder/ &amp;&amp; /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java '-javaagent:/lhome1/johndoe/.m2/repository/org/jacoco/org.jacoco.agent/0.7.4.201502262128/org.jacoco.agent-0.7.4.201502262128-runt ime.jar=destfile=/lhome/code/recorder/target/jacoco.exec,append=true,includes=esa/*,excludes=**/api/**/*.class' -jar /lhome/code/recorder/target/surefire/surefirebooter7426165516226884923.jar /lhome/code/recorder/target/surefire 2018-10-26T16-16-12_829-jvmRun1 surefire1721866559613511529tmp surefire_023400764142672144tmp [ERROR] Error occurred in starting fork, check output in log [ERROR] Process Exit Code: 1 [ERROR] org.apache.maven.surefire.booter.SurefireBooterForkException: The forked VM terminated without properly saying goodbye. VM crash or System.exit called? [ERROR] Command was /bin/sh -c cd /lhome/code/recorder/ &amp;&amp; /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java '-javaagent:/lhome1/johndoe/.m2/repository/org/jacoco/org.jacoco.agent/0.7.4.201502262128/org.jacoco.agent-0.7.4.201502262128-runt ime.jar=destfile=/lhome/code/recorder/target/jacoco.exec,append=true,includes=esa/*,excludes=**/api/**/*.class' -jar /lhome/code/recorder/target/surefire/surefirebooter7426165516226884923.jar /lhome/code/recorder/target/surefire 2018-10-26T16-16-12_829-jvmRun1 surefire1721866559613511529tmp surefire_023400764142672144tmp [ERROR] Error occurred in starting fork, check output in log [ERROR] Process Exit Code: 1 [ERROR] at org.apache.maven.plugin.surefire.booterclient.ForkStarter.fork(ForkStarter.java:669) [ERROR] at org.apache.maven.plugin.surefire.booterclient.ForkStarter.run(ForkStarter.java:282) [ERROR] at org.apache.maven.plugin.surefire.booterclient.ForkStarter.run(ForkStarter.java:245) [ERROR] at org.apache.maven.plugin.surefire.AbstractSurefireMojo.executeProvider(AbstractSurefireMojo.java:1183) [ERROR] at org.apache.maven.plugin.surefire.AbstractSurefireMojo.executeAfterPreconditionsChecked(AbstractSurefireMojo.java:1011) [ERROR] at org.apache.maven.plugin.surefire.AbstractSurefireMojo.execute(AbstractSurefireMojo.java:857) [ERROR] at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:137) [ERROR] at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208) [ERROR] at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:154) [ERROR] at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:146) [ERROR] at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:117) [ERROR] at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:81) [ERROR] at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:56) [ERROR] at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128) [ERROR] at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:305) [ERROR] at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:192) [ERROR] at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:105) [ERROR] at org.apache.maven.cli.MavenCli.execute(MavenCli.java:954) [ERROR] at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:288) [ERROR] at org.apache.maven.cli.MavenCli.main(MavenCli.java:192) [ERROR] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [ERROR] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) [ERROR] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [ERROR] at java.lang.reflect.Method.invoke(Method.java:498) [ERROR] at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289) [ERROR] at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229) [ERROR] at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415) [ERROR] at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356) </code></pre>
<p><strong>To fix it (in 2018), update your openjdk to the latest version, at least 8u191-b12.</strong> In case this issue reappears in 2020, it is likely that the default behavior of openjdk was changed, and you will then need to update the maven surefire plugin.</p> <p>This was a <strong>now fixed</strong> <strong><a href="http://bugs.debian.org/911925" rel="noreferrer">bug in the openjdk-8 package</a></strong> (behaviour deviates from upstream significantly without need; missing the upstream patch to revert back to disabling a security check) that you just upgraded to. But it is also <a href="https://issues.apache.org/jira/browse/SUREFIRE-1588" rel="noreferrer">a <strong>bug in the surefire plugin, SUREFIRE-1588</strong>, supposedly fixed in surefire 3.0.0-M1</a>: it apparently is using absolute paths in a place where Java will in the future only allow relative path names (and Debian activated the future behavior already).</p> <p>The package version 8u181-b13-2 states:</p> <ul> <li>Apply patches from 8u191-b12 security update.</li> </ul> <p>Note that 191-b12 != 181-b13. The 191-b12 security patches were just out a few days ago, and apparently the maintainers wanted to get them to you fast. Updating completely to 191-b12 will likely need additional testing (well, so should have this upload, apparently).</p> <p>There had been several workaounds:</p> <ol> <li>You can install the <a href="http://snapshot.debian.org/package/openjdk-8/8u181-b13-1/" rel="noreferrer"><strong>previous package</strong> from snapshots.d.o</a> instead. After downgrading, you can forbid the broken version (if you are using aptitude and not <code>apt</code>) using <code>sudo aptitude forbid-version openjdk-8-jre-headless</code>. For regular "apt" I didn't see a similar forbid mechanism, so you would likely need to use apt pinning to prevent this upgrade from being reinstalled (or you just keep on downgrading again, I hope this will be resolved soon).</li> <li>According to bug tracking, setting the property <code>-Djdk.net.URLClassPath.disableClassPathURLCheck=true</code> with any of the usual methods (e.g., <code>JAVA_FLAGS</code>) should also help. But I have not verified this myself. You can apparently even <a href="https://issues.apache.org/jira/browse/SUREFIRE-1588?focusedCommentId=16671777&amp;page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-16671777" rel="noreferrer"><strong>add the workaround to <code>~/.m2/settings.xml</code></strong></a> to get it enabled for all your Maven builds easily.</li> </ol> <p>As you can see, <strong>bug tracking works</strong>, the issue was narrowed down, and a fixed package is available and a new version of the surefire plugin will come soon!</p>
{ "question_id": 53010200, "question_date": "2018-10-26T13:47:31.300Z", "question_score": 226, "tags": "java|maven|maven-surefire-plugin", "answer_id": 53016532, "answer_date": "2018-10-26T21:30:51.800Z", "answer_score": 259 }
Please answer the following Stack Overflow question: Title: git command to show all (lightweight) tags creation dates <p>Is there a one liner that shows me the dates where all git lightweight tags where created ?</p> <p>Something like: <code>git show tags --format=date</code> ?</p>
<p>I found in this <a href="http://osdir.com/ml/git/2009-05/msg01404.html" rel="noreferrer">link</a> a solution that fits my needs:</p> <pre><code>git log --tags --simplify-by-decoration --pretty="format:%ai %d" </code></pre> <p>I've put that command in an alias in my <code>~/.alias</code>, so now everytime I run <code>gitshowtagbydate</code> I get what I needed.</p>
{ "question_id": 6900328, "question_date": "2011-08-01T14:58:52.363Z", "question_score": 226, "tags": "git|date|tags", "answer_id": 6900369, "answer_date": "2011-08-01T15:01:32.457Z", "answer_score": 360 }
Please answer the following Stack Overflow question: Title: What is string_view? <p><code>string_view</code> was a proposed feature within the C++ Library Fundamentals TS(<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3921.html" rel="noreferrer">N3921</a>) added to C++17</p> <p>As far as i understand it is a type that represent some kind of string "concept" that is a view of any type of container that could store something viewable as a string.</p> <ul> <li>Is this right ? </li> <li>Should the canonical <code>const std::string&amp;</code> parameter type become <code>string_view</code> ?</li> <li>Is there another important point about <code>string_view</code> to take into consideration ?</li> </ul>
<p>The purpose of any and all kinds of "string reference" and "array reference" proposals is to avoid copying data which is already owned somewhere else and of which only a non-mutating view is required. The <code>string_view</code> in question is one such proposal; there were earlier ones called <code>string_ref</code> and <code>array_ref</code>, too.</p> <p>The idea is always to store a pair of pointer-to-first-element and size of some <em>existing</em> data array or string.</p> <p>Such a view-handle class could be passed around cheaply by value and would offer cheap substringing operations (which can be implemented as simple pointer increments and size adjustments).</p> <p>Many uses of strings don't require actual owning of the strings, and the string in question will often already be owned by someone else. So there is a genuine potential for increasing the efficiency by avoiding unneeded copies (think of all the allocations and exceptions you can save).</p> <p>The original C strings were suffering from the problem that the null terminator was part of the string APIs, and so you couldn't easily create substrings without mutating the underlying string (a la <code>strtok</code>). In C++, this is easily solved by storing the length separately and wrapping the pointer and the size into one class.</p> <p>The one major obstacle and divergence from the C++ standard library philosophy that I can think of is that such "referential view" classes have completely different ownership semantics from the rest of the standard library. Basically, everything else in the standard library is unconditionally safe and correct (if it compiles, it's correct). With reference classes like this, that's no longer true. The correctness of your program depends on the ambient code that uses these classes. So that's harder to check and to teach.</p>
{ "question_id": 20803826, "question_date": "2013-12-27T16:10:11.483Z", "question_score": 226, "tags": "c++|c++17|string-view|fundamentals-ts", "answer_id": 20803969, "answer_date": "2013-12-27T16:18:27.230Z", "answer_score": 232 }
Please answer the following Stack Overflow question: Title: What's the difference between HTTP 301 and 308 status codes? <p>What's the difference between HTTP <code>301</code> and <code>308</code> status codes?</p> <ul> <li><p><code>301</code> (Moved Permanently): This and all future requests should be directed to the given URI.</p></li> <li><p><code>308</code> (Permanent Redirect): The request and all future requests should be repeated using another URI. </p></li> </ul> <p>They seem to be similar.</p>
<h2>An overview of <code>301</code>, <code>302</code> and <code>307</code></h2> <p>The <a href="https://www.rfc-editor.org/rfc/rfc7231" rel="noreferrer">RFC 7231</a>, the current reference for semantics and content of the HTTP/1.1 protocol, defines the <a href="https://www.rfc-editor.org/rfc/rfc7231#section-6.4.2" rel="noreferrer"><code>301</code></a> (Moved Permanently) and <a href="https://www.rfc-editor.org/rfc/rfc7231#section-6.4.3" rel="noreferrer"><code>302</code></a> (Found) status code, that allows the request method to be changed from <code>POST</code> to <code>GET</code>. This specification also defines the <a href="https://www.rfc-editor.org/rfc/rfc7231#section-6.4.7" rel="noreferrer"><code>307</code></a> (Temporary Redirect) status code that doesn't allow the request method to be changed from <code>POST</code> to <code>GET</code>.</p> <p>See more details below:</p> <blockquote> <p><a href="https://www.rfc-editor.org/rfc/rfc7231#section-6.4.2" rel="noreferrer"><strong>6.4.2. 301 Moved Permanently</strong></a></p> <p>The <code>301</code> (Moved Permanently) status code indicates that the target resource has been assigned a new permanent URI and any future references to this resource ought to use one of the enclosed URIs. [...]</p> <p><strong>Note:</strong> For historical reasons, a user agent MAY change the request method from <code>POST</code> to <code>GET</code> for the subsequent request. If this behavior is undesired, the <code>307</code> (Temporary Redirect) status code can be used instead.</p> </blockquote> <blockquote> <p><a href="https://www.rfc-editor.org/rfc/rfc7231#section-6.4.3" rel="noreferrer"><strong>6.4.3. 302 Found</strong></a></p> <p>The <code>302</code> (Found) status code indicates that the target resource resides temporarily under a different URI. Since the redirection might be altered on occasion, the client ought to continue to use the effective request URI for future requests. [...]</p> <p><strong>Note:</strong> For historical reasons, a user agent MAY change the request method from <code>POST</code> to <code>GET</code> for the subsequent request. If this behavior is undesired, the <code>307</code> (Temporary Redirect) status code can be used instead.</p> </blockquote> <blockquote> <p><a href="https://www.rfc-editor.org/rfc/rfc7231#section-6.4.7" rel="noreferrer"><strong>6.4.7. 307 Temporary Redirect</strong></a></p> <p>The <code>307</code> (Temporary Redirect) status code indicates that the target resource resides temporarily under a different URI and the user agent MUST NOT change the request method if it performs an automatic redirection to that URI. Since the redirection can change over time, the client ought to continue using the original effective request URI for future requests. [...]</p> <p><strong>Note:</strong> This status code is similar to <code>302</code> (Found), except that it does not allow changing the request method from <code>POST</code> to <code>GET</code>. This specification defines no equivalent counterpart for <code>301</code> (Moved Permanently) (<a href="https://www.rfc-editor.org/rfc/rfc7238" rel="noreferrer">RFC 7238</a>, however, defines the status code <code>308</code> (Permanent Redirect) for this purpose).</p> </blockquote> <h2>The need for <code>308</code></h2> <p>The <a href="https://www.rfc-editor.org/rfc/rfc7238" rel="noreferrer">RFC 7238</a> has been created to define the <a href="https://www.rfc-editor.org/rfc/rfc7538" rel="noreferrer"><code>308</code></a> (Permanent Redirect) status code, that is similar to <a href="https://www.rfc-editor.org/rfc/rfc7231#section-6.4.2" rel="noreferrer"><code>301</code></a> (Moved Permanently) but does not allows the request method to be changed from <code>POST</code> to <code>GET</code>.</p> <p>The <a href="https://www.rfc-editor.org/rfc/rfc7538" rel="noreferrer"><code>308</code></a> status code is now defined by the <a href="https://www.rfc-editor.org/rfc/rfc7538" rel="noreferrer">RFC 7538</a> (that obsoleted the <a href="https://www.rfc-editor.org/rfc/rfc7238" rel="noreferrer">RFC 7238</a>).</p> <blockquote> <p><a href="https://www.rfc-editor.org/rfc/rfc7538" rel="noreferrer"><strong>3. 308 Permanent Redirect</strong></a></p> <p>The <code>308</code> (Permanent Redirect) status code indicates that the target resource has been assigned a new permanent URI and any future references to this resource ought to use one of the enclosed URIs. Clients with link editing capabilities ought to automatically re-link references to the effective request URI to one or more of the new references sent by the server, where possible. [...]</p> <p><strong>Note:</strong> This status code is similar to <code>301</code> (Moved Permanently), except that it does not allow changing the request method from <code>POST</code> to <code>GET</code>.</p> </blockquote> <p>Se we have the following:</p> <pre class="lang-none prettyprint-override"><code> +-----------+-----------+ | Permanent | Temporary | +------------------------------------------------------------+-----------+-----------+ | Allows changing the request method from POST to GET | 301 | 302 | +------------------------------------------------------------+-----------+-----------+ | Doesn't allow changing the request method from POST to GET | 308 | 307 | +------------------------------------------------------------+-----------+-----------+ </code></pre> <h2>Choosing the most suitable status code</h2> <p><a href="https://stackoverflow.com/u/27581">Michael Kropat</a> put together a <a href="https://www.codetinkerer.com/2015/12/04/choosing-an-http-status-code.html" rel="noreferrer">set of decision charts</a> that helps to determine the best status code for each situation. See the following for <code>2xx</code> and <code>3xx</code> status codes:</p> <p><a href="http://racksburg.com/choosing-an-http-status-code/" rel="noreferrer"><img src="https://i.stack.imgur.com/fyqUl.png" alt="Picking a 2xx or 3xx status code" /></a></p>
{ "question_id": 42136829, "question_date": "2017-02-09T12:32:21.450Z", "question_score": 226, "tags": "http|http-status-code-301|http-status-codes|http-status-code-308", "answer_id": 42138726, "answer_date": "2017-02-09T14:02:33.870Z", "answer_score": 403 }
Please answer the following Stack Overflow question: Title: What should Xcode 6 gitignore file include? <p>What should the typical <code>.gitignore</code> include for Xcode 6?</p> <p>Also for information regarding the <code>xccheckout</code> introduced in Xcode 5 see <a href="https://stackoverflow.com/q/18340453/2158465">here</a></p>
<p>1)</p> <p>The easiest answer is that mine looks like this:</p> <pre><code># Xcode .DS_Store build/ *.pbxuser !default.pbxuser *.mode1v3 !default.mode1v3 *.mode2v3 !default.mode2v3 *.perspectivev3 !default.perspectivev3 *.xcworkspace !default.xcworkspace xcuserdata profile *.moved-aside DerivedData .idea/ # Pods - for those of you who use CocoaPods Pods </code></pre> <p>which I believe is the same .gitignore that GitHub sets up with all their repositories by default.</p> <p>2)</p> <p>Another answer is that there's a <a href="http://www.gitignore.io">website called "gitignore.io"</a> , which generates the files based on the .gitignore templates from <a href="https://github.com/github/gitignore">https://github.com/github/gitignore</a>.</p>
{ "question_id": 18939421, "question_date": "2013-09-22T01:27:28.377Z", "question_score": 226, "tags": "ios|iphone|xcode|git", "answer_id": 18939465, "answer_date": "2013-09-22T01:40:04.610Z", "answer_score": 278 }
Please answer the following Stack Overflow question: Title: Android Google maps java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/http/ProtocolVersion <p>I am using Google maps Android SDK 11.6.2(Also tried 15.0.1),but I get following crash before map shows. Already checked API key in manifest,it is available, but still this issue occurs. I am having targetSDk version as 28.Is it causes this issue.</p> <pre><code>java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/http/ProtocolVersion; at el.b(:com.google.android.gms.dynamite_mapsdynamite@[email protected] (100408-196123505):3) at ek.a(:com.google.android.gms.dynamite_mapsdynamite@[email protected] (100408-196123505):4) at em.a(:com.google.android.gms.dynamite_mapsdynamite@[email protected] (100408-196123505):51) at com.google.maps.api.android.lib6.drd.ap.a(:com.google.android.gms.dynamite_mapsdynamite@[email protected] (100408-196123505):11) at dw.a(:com.google.android.gms.dynamite_mapsdynamite@[email protected] (100408-196123505):16) at dw.run(:com.google.android.gms.dynamite_mapsdynamite@[email protected] (100408-196123505):61) Caused by: java.lang.ClassNotFoundException: Didn't find class "org.apache.http.ProtocolVersion" on path: DexPathList[[zip file "/system/priv-app/PrebuiltGmsCorePi/app_chimera/m/MapsDynamite.apk"],nativeLibraryDirectories=[/data/user_de/0/com.google.android.gms/app_chimera/m/00000036/MapsDynamite.apk!/lib/armeabi-v7a, /data/user_de/0/com.google.android.gms/app_chimera/m/00000036/MapsDynamite.apk!/lib/armeabi, /system/lib]] at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:126) at java.lang.ClassLoader.loadClass(ClassLoader.java:379) at ad.loadClass(:com.google.android.gms.dynamite_dynamiteloader@[email protected] (100408-196123505):25) at java.lang.ClassLoader.loadClass(ClassLoader.java:312) at el.b(:com.google.android.gms.dynamite_mapsdynamite@[email protected] (100408-196123505):3)  at ek.a(:com.google.android.gms.dynamite_mapsdynamite@[email protected] (100408-196123505):4)  at em.a(:com.google.android.gms.dynamite_mapsdynamite@[email protected] (100408-196123505):51)  at com.google.maps.api.android.lib6.drd.ap.a(:com.google.android.gms.dynamite_mapsdynamite@[email protected] (100408-196123505):11)  at dw.a(:com.google.android.gms.dynamite_mapsdynamite@[email protected] (100408-196123505):16)  at dw.run(:com.google.android.gms.dynamite_mapsdynamite@[email protected] (100408-196123505):61)  </code></pre>
<p>Put this in the Manifest <code>&lt;application&gt;</code> tag:</p> <pre><code>&lt;uses-library android:name="org.apache.http.legacy" android:required="false"/&gt; </code></pre> <p>More info: <a href="https://issuetracker.google.com/issues/79478779" rel="noreferrer">https://issuetracker.google.com/issues/79478779</a></p>
{ "question_id": 50782806, "question_date": "2018-06-10T10:35:21.900Z", "question_score": 226, "tags": "android|google-maps|google-play-services", "answer_id": 50794266, "answer_date": "2018-06-11T09:18:24.140Z", "answer_score": 546 }
Please answer the following Stack Overflow question: Title: How to exclude file extensions and languages from "format on save" in VSCode? <p>Currently in VSCode settings you can configure format on save as following: </p> <pre class="lang-json prettyprint-override"><code>"editor.formatOnSave": true </code></pre> <p>I want to exclude some file extensions, for example only format JavaScript but not HTML files.</p>
<p>You can use <a href="https://code.visualstudio.com/docs/getstarted/settings#_language-specific-editor-settings" rel="noreferrer">language specific settings</a> to <em>enable</em> it for a specific language only, e.g. JavaScript:</p> <pre class="lang-json prettyprint-override"><code>"[javascript]": { "editor.formatOnSave": true } </code></pre> <p>To <em>disable</em> it for a specific language, you could switch the global default to <code>true</code> and combine it with a language-specific <code>false</code>:</p> <pre class="lang-json prettyprint-override"><code>"editor.formatOnSave": true "[javascript]": { "editor.formatOnSave": false } </code></pre> <p>Note that language specific settings are based on <a href="https://code.visualstudio.com/docs/languages/identifiers" rel="noreferrer">language identifiers</a> rather than directly on file extensions. There's an open feature request to allow for <a href="https://github.com/Microsoft/vscode/issues/35350" rel="noreferrer">file extension specific settings</a> as well.</p> <p>In cases where the language ID isn't specific enough, <code>"files.associations"</code> could be used to remap files with a specific extension and/or in a specific directory to another ID, but this will affect syntax highlighting, code completion, etc. as well. For instance, this would work to disable formatting for JavaScript files in <code>out</code> directories, but they will be treated as plaintext:</p> <pre class="lang-json prettyprint-override"><code>"[javascript]": { "editor.formatOnSave": true }, "files.associations": { "**/out/**/*.js": "plaintext" } </code></pre>
{ "question_id": 44831313, "question_date": "2017-06-29T17:14:41.637Z", "question_score": 226, "tags": "visual-studio-code|vscode-settings", "answer_id": 44831631, "answer_date": "2017-06-29T17:34:58.470Z", "answer_score": 346 }
Please answer the following Stack Overflow question: Title: Accessing Kotlin extension functions from Java <p>Is it possible to access extension functions from Java code?</p> <p>I defined the extension function in a Kotlin file.</p> <pre><code>package com.test.extensions import com.test.model.MyModel /** * */ public fun MyModel.bar(): Int { return this.name.length() } </code></pre> <p>Where <code>MyModel</code> is a (generated) java class. Now, I wanted to access it in my normal java code:</p> <pre><code>MyModel model = new MyModel(); model.bar(); </code></pre> <p>However, that doesn't work. <strong>The IDE won't recognize the <code>bar()</code> method and compilation fails.</strong> </p> <p>What does work is using with a static function from kotlin:</p> <pre><code>public fun bar(): Int { return 2*2 } </code></pre> <p>by using <code>import com.test.extensions.ExtensionsPackage</code> so my IDE seems to be configured correctly.</p> <p>I searched through the whole Java-interop file from the kotlin docs and also googled a lot, but I couldn't find it.</p> <p>What am I doing wrong? Is this even possible?</p>
<p>All Kotlin functions declared in a file will be compiled by default to static methods in a class within the same package and with a name derived from the Kotlin source file (First letter capitalized and <em>".kt"</em> extension replaced with the <em>"Kt"</em> suffix). Methods generated for extension functions will have an additional first parameter with the extension function receiver type.</p> <p>Applying it to the original question, Java compiler will see Kotlin source file with the name <em>example.kt</em></p> <pre><code>package com.test.extensions public fun MyModel.bar(): Int { /* actual code */ } </code></pre> <p>as if the following Java class was declared</p> <pre><code>package com.test.extensions class ExampleKt { public static int bar(MyModel receiver) { /* actual code */ } } </code></pre> <p>As nothing happens with the extended class from the Java point of view, you can't just use dot-syntax to access such methods. But they are still callable as normal Java static methods:</p> <pre><code>import com.test.extensions.ExampleKt; MyModel model = new MyModel(); ExampleKt.bar(model); </code></pre> <p>Static import can be used for ExampleKt class:</p> <pre><code>import static com.test.extensions.ExampleKt.*; MyModel model = new MyModel(); bar(model); </code></pre>
{ "question_id": 28294509, "question_date": "2015-02-03T08:37:56.023Z", "question_score": 226, "tags": "java|kotlin|extension-function", "answer_id": 28364983, "answer_date": "2015-02-06T11:39:59.240Z", "answer_score": 313 }
Please answer the following Stack Overflow question: Title: When is "i += x" different from "i = i + x" in Python? <p>I was told that <code>+=</code> can have different effects than the standard notation of <code>i = i +</code>. Is there a case in which <code>i += 1</code> would be different from <code>i = i + 1</code>?</p>
<p>This depends entirely on the object <code>i</code>.</p> <p><code>+=</code> calls the <a href="http://docs.python.org/2/reference/datamodel.html#object.__iadd__" rel="nofollow noreferrer"><code>__iadd__</code> method</a> (if it exists -- falling back on <code>__add__</code> if it doesn't exist) whereas <code>+</code> calls the <a href="http://docs.python.org/2/reference/datamodel.html#object.__add__" rel="nofollow noreferrer"><code>__add__</code> method</a><sup>1</sup> or the <a href="http://docs.python.org/2/reference/datamodel.html#object.__radd__" rel="nofollow noreferrer"><code>__radd__</code> method in a few cases</a><sup>2</sup>.</p> <p>From an API perspective, <code>__iadd__</code> is supposed to be used for modifying mutable objects <em>in place</em> (returning the object which was mutated) whereas <code>__add__</code> should return a <em>new instance</em> of something. For <em>immutable</em> objects, both methods return a new instance, but <code>__iadd__</code> will put the new instance in the current namespace with the same name that the old instance had. This is why</p> <pre><code>i = 1 i += 1 </code></pre> <p>seems to increment <code>i</code>. In reality, you get a new integer and assign it &quot;on top of&quot; <code>i</code> -- losing one reference to the old integer. In this case, <code>i += 1</code> is exactly the same as <code>i = i + 1</code>. But, with most mutable objects, it's a different story:</p> <p>As a concrete example:</p> <pre><code>a = [1, 2, 3] b = a b += [1, 2, 3] print(a) # [1, 2, 3, 1, 2, 3] print(b) # [1, 2, 3, 1, 2, 3] </code></pre> <p>compared to:</p> <pre><code>a = [1, 2, 3] b = a b = b + [1, 2, 3] print(a) # [1, 2, 3] print(b) # [1, 2, 3, 1, 2, 3] </code></pre> <p>notice how in the first example, since <code>b</code> and <code>a</code> reference the same object, when I use <code>+=</code> on <code>b</code>, it actually changes <code>b</code> (and <code>a</code> sees that change too -- After all, it's referencing the same list). In the second case however, when I do <code>b = b + [1, 2, 3]</code>, this takes the list that <code>b</code> is referencing and concatenates it with a new list <code>[1, 2, 3]</code>. It then stores the concatenated list in the current namespace as <code>b</code> -- With no regard for what <code>b</code> was the line before.</p> <hr /> <p><sup><sup>1</sup>In the expression <code>x + y</code>, if <code>x.__add__</code> isn't implemented or if <code>x.__add__(y)</code> returns <code>NotImplemented</code> <strong>and</strong> <em><code>x</code> and <code>y</code> have different types</em>, then <code>x + y</code> tries to call <a href="http://docs.python.org/2/reference/datamodel.html#object.__radd__" rel="nofollow noreferrer"><code>y.__radd__(x)</code></a>. So, in the case where you have </sup></p> <p><sup><code>foo_instance += bar_instance</code></sup></p> <p><sup>if <code>Foo</code> doesn't implement <code>__add__</code> or <code>__iadd__</code> then the result here is the same as </sup></p> <p><sup><code>foo_instance = bar_instance.__radd__(bar_instance, foo_instance)</code></sup></p> <p><sup><sup>2</sup>In the expression <code>foo_instance + bar_instance</code>, <code>bar_instance.__radd__</code> will be tried before <code>foo_instance.__add__</code> <em>if</em> the type of <code>bar_instance</code> is a subclass of the type of <code>foo_instance</code> (e.g. <code>issubclass(Bar, Foo)</code>). The rationale for this is that <code>Bar</code> is in some sense a &quot;higher-level&quot; object than <code>Foo</code> so <code>Bar</code> should get the option of overriding <code>Foo</code>'s behavior.</sup></p>
{ "question_id": 15376509, "question_date": "2013-03-13T03:24:44.210Z", "question_score": 226, "tags": "python|operators", "answer_id": 15376520, "answer_date": "2013-03-13T03:25:31.807Z", "answer_score": 343 }
Please answer the following Stack Overflow question: Title: A clean, lightweight alternative to Python's twisted? <p>A (long) while ago I wrote a web-spider that I multithreaded to enable concurrent requests to occur at the same time. That was in my Python youth, in the days before I knew about the <a href="http://www.dabeaz.com/python/GIL.pdf" rel="noreferrer">GIL</a> and the associated woes it creates for multithreaded code (IE, most of the time stuff just ends up serialized!)...</p> <p>I'd like to rework this code to make it more robust and perform better. There are basically two ways I could do this: I could use the new <a href="http://docs.python.org/library/multiprocessing.html" rel="noreferrer">multiprocessing module</a> in 2.6+ or I could go for a reactor / event-based model of some sort. I would rather do the later since it's far simpler and less error-prone.</p> <p>So the question relates to what framework would be best suited to my needs. The following is a list of the options I know about so far:</p> <ul> <li><a href="http://twistedmatrix.com/trac/" rel="noreferrer">Twisted</a>: The granddaddy of Python reactor frameworks: seems complex and a bit bloated however. Steep learning curve for a small task.</li> <li><a href="http://eventlet.net/" rel="noreferrer">Eventlet</a>: From the guys at <a href="http://lindenlab.com/" rel="noreferrer">lindenlab</a>. Greenlet based framework that's geared towards these kinds of tasks. I had a look at the code though and it's not too pretty: non-pep8 compliant, scattered with prints (why do people do this in a framework!?), API seems a little inconsistent.</li> <li><a href="http://code.google.com/p/pyev/" rel="noreferrer">PyEv</a>: Immature, doesn't seem to be anyone using it right now though it is based on libevent so it's got a solid backend.</li> <li><a href="http://docs.python.org/library/asyncore.html" rel="noreferrer">asyncore</a>: From the stdlib: über low-level, seems like a lot of legwork involved just to get something off the ground.</li> <li><a href="http://www.tornadoweb.org/" rel="noreferrer">tornado</a>: Though this is a server oriented product designed to server dynamic websites it does feature an <a href="http://github.com/facebook/tornado/blob/master/tornado/httpclient.py" rel="noreferrer">async HTTP client</a> and a simple <a href="http://github.com/facebook/tornado/blob/master/tornado/ioloop.py" rel="noreferrer">ioloop</a>. Looks like it could get the job done but not what it was intended for. [edit: doesn't run on Windows unfortunately, which counts it out for me - its a requirement for me to support this lame platform]</li> </ul> <p>Is there anything I have missed at all? Surely there must be a library out there that fits the sweet-spot of a simplified async networking library!</p> <p>[edit: big thanks to <a href="https://stackoverflow.com/users/177663/intgr">intgr</a> for his pointer to <a href="http://code.google.com/p/cogen/" rel="noreferrer">this page</a>. If you scroll to the bottom you will see there is a really nice list of projects that aim to tackle this task in one way or another. It seems actually that things have indeed moved on since the inception of Twisted: people now seem to favour a <a href="http://en.wikipedia.org/wiki/Coroutine" rel="noreferrer">co-routine</a> based solution rather than a traditional reactor / callback oriented one. The benefits of this approach are clearer more direct code: I've certainly found in the past, especially when working with <a href="http://www.boost.org/doc/libs/1_41_0/doc/html/boost_asio.html" rel="noreferrer">boost.asio</a> in C++ that callback based code can lead to designs that can be hard-to-follow and are relatively obscure to the untrained eye. Using co-routines allows you to write code that looks a little more synchronous at least. I guess now my task is to work out which one of these many libraries I like the look of and give it a go! Glad I asked now...]</p> <p>[edit: perhaps of interest to anyone who followed or stumbled on this this question or cares about this topic in any sense: I found a really great writeup of the current state of <a href="http://nichol.as/asynchronous-servers-in-python" rel="noreferrer">the available tools</a> for this job]</p>
<p>I liked the <a href="http://opensource.hyves.org/concurrence/" rel="noreferrer">concurrence</a> Python module which relies on either Stackless Python microthreads or Greenlets for light-weight threading. All blocking network I/O is transparently made asynchronous through a single <code>libevent</code> loop, so it should be nearly as efficient as an real asynchronous server.</p> <p>I suppose it's similar to Eventlet in this way.</p> <p>The downside is that its API is quite different from Python's <code>sockets</code>/<code>threading</code> modules; you need to rewrite a fair bit of your application (or write a compatibility shim layer)</p> <p><strong>Edit:</strong> It seems that there's also <a href="http://code.google.com/p/cogen/" rel="noreferrer">cogen</a>, which is similar, but uses Python 2.5's <em>enhanced generators</em> for its coroutines, instead of Greenlets. This makes it more portable than concurrence and other alternatives. Network I/O is done directly with epoll/kqueue/iocp.</p>
{ "question_id": 1824418, "question_date": "2009-12-01T06:49:32.460Z", "question_score": 226, "tags": "python|networking|twisted|asynchronous", "answer_id": 1824705, "answer_date": "2009-12-01T08:12:18.687Z", "answer_score": 29 }
Please answer the following Stack Overflow question: Title: Difference between . and : in Lua <p>I am confused about the difference between function calls via <code>.</code> and via <code>:</code></p> <pre><code>&gt; x = {foo = function(a,b) return a end, bar = function(a,b) return b end, } &gt; return x.foo(3,4) 3 &gt; return x.bar(3,4) 4 &gt; return x:foo(3,4) table: 0x10a120 &gt; return x:bar(3,4) 3 </code></pre> <p>What is the <code>:</code> doing ?</p>
<p>The colon is for implementing methods that pass <code>self</code> as the first parameter. So <code>x:bar(3,4)</code>should be the same as <code>x.bar(x,3,4)</code>.</p>
{ "question_id": 4911186, "question_date": "2011-02-06T02:43:54.897Z", "question_score": 226, "tags": "function|lua", "answer_id": 4911217, "answer_date": "2011-02-06T02:55:12.390Z", "answer_score": 315 }
Please answer the following Stack Overflow question: Title: Naming of enums in Java: Singular or Plural? <p>Is there an "official" recommendation of how to name Java enums?</p> <pre><code>enum Protocol { HTTP, HTTPS, FTP } </code></pre> <p>or</p> <pre><code>enum Protocols { HTTP, HTTPS, FTP } </code></pre> <p>I know in the .Net world the recommendation is to use singular except for enums that represent bit flags. Just curious if there is something similar in Java.</p> <p>A related question that seems to be .Net specific: <a href="https://stackoverflow.com/questions/1335959/singular-or-plural-for-enumerations">Singular or plural for enumerations?</a></p>
<p>Enums in Java (and probably enums in general) should be singular. The thinking is that you're not selecting multiple Protocols, but rather one Protocol of the possible choices in the list of values. </p> <p>Note the absence of plurals: <a href="http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html" rel="noreferrer">http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html</a></p>
{ "question_id": 15755955, "question_date": "2013-04-02T04:14:49.913Z", "question_score": 226, "tags": "java|enums|naming-conventions", "answer_id": 15756009, "answer_date": "2013-04-02T04:20:14.440Z", "answer_score": 274 }
Please answer the following Stack Overflow question: Title: What is the difference / relationship between GitHub Projects and Milestones? <p>The recent update to GitHub added something called <strong><em>Projects</em></strong> into the GitHub workflow, and because I don't have any particular experience with <em>project tracking tools</em> such as Jira or Trello <em>(hey, at least I noticed the similarity)</em>, could anyone, please, <strong>elaborate on the (key) differences</strong> between GitHub's <strong><em>Milestones</em></strong> and the new <strong><em>Projects</em></strong>?</p> <p>If I understand correctly, <strong><em>Milestones</em></strong> are a way of organizing issues into smaller "sub-projects" - smaller than the whole "project" (which, in my world view, is represented by <strong><em>the repository</em></strong>). When all issues are done/closed, the milestone can be regarded as <em>complete</em>.</p> <p>The newly introduced <strong><em>Projects</em></strong> are also, as I see it, a way of organizing issues into <em>smaller-than-the-repository</em> "sub-projects" (albeit called <em>Projects</em>). I understand the workflow is supposed to be slightly different and more fine-grained than with "mere" <strong><em>Milestones</em></strong>.</p> <p>So, are <em>Projects</em> something that supplements <em>Milestones</em> (or rather <em>Milestones</em> supplement <em>Projects</em> now?) or should I rather view <em>Projects</em> as a <strong><em>replacement</em></strong> of <em>Milestones</em>?</p> <p>Where exactly do the <strong><em>Projects</em></strong> actually fall into the <code>repository[-milestone]-issue</code> hierarchy?</p> <p>Sadly, GitHub's blog entry about the introduction of the <strong><em>Projects</em></strong> doesn't mention any relationship (<a href="https://github.com/blog/2256-a-whole-new-github-universe-announcing-new-tools-forums-and-features" rel="noreferrer">https://github.com/blog/2256-a-whole-new-github-universe-announcing-new-tools-forums-and-features</a>).</p> <p><em>I somehow feel there is one, but I can't put a finger on it.</em></p>
<p>I'm wondering the exact same thing. Here is what I came up with.</p> <p>First, let's review the main similarities and differences:</p> <ul> <li>An issue can belong to multiple Projects, but only one Milestone.</li> <li><del>Projects are never <em>complete</em>. There is no progress bar, or deadline.</del> Projects <del>have no progress bar or deadline</del> (they do now, though it is hidden inside the project's menu as a &quot;Track project progress&quot; checkmark, and there's no percentage calculation of progress), but can now be closed (as pointed out by @Sheen)</li> <li>Milestones on the other hand have all that, but lack any form of organization. An issue is either in a milestone, or isn't. (They can be ordered as pointed out by @Nick McCurdy)</li> <li><del>Issues can be filtered by Milestone, but not by Project.</del> As pointed out by @cmonkey, issues can now be filtered by Project as well as Milestone.</li> <li>Projects can contain <em>Notes</em> (which can be converted as issues) so it doesn't pollute the issue tracker with vague ideas</li> <li>A Project can span over multiple Milestones, and a Milestone can contains parts of different Projects.</li> <li>An Organization can have Projects as well. These projects can include tickets from any repository in the organization, which makes it quite useful.</li> </ul> <p>So the way I see it, is that <strong>Projects</strong> are a completely separate way to visualize and organize your work on an higher level (think &quot;project management&quot;, multiple teams, multiple repository, etc.), while <strong>Milestones</strong> are a way to organize your deadlines and releases on a more basic level (think &quot;release management&quot;, &quot;versions&quot;, etc.). With this in mind, it makes sense that an issue only belongs to one Milestone (it's only released or pushed to production once) but can be part of different Projects.</p> <p>I'm sure they are other ways to look at it though, and I'm interested to hear other opinions.</p> <h2>Edit December 2017</h2> <p>Some time ago, after working with Milestones and Projects for over a year, I realized there is another important aspect I had completely overlooked.</p> <ul> <li><strong>Milestones</strong> is a tool for <strong>Scrum</strong> methodology. Milestones are good for timeboxed iterations and working in sprints with batches of issues.</li> <li><strong>Projects</strong> is a tool for <strong>Kanban</strong> methodology. Projects are good for continuous delivery and steady flow of work.</li> </ul>
{ "question_id": 39591795, "question_date": "2016-09-20T10:29:44.060Z", "question_score": 226, "tags": "github|project", "answer_id": 39701381, "answer_date": "2016-09-26T11:16:21.463Z", "answer_score": 201 }
Please answer the following Stack Overflow question: Title: SQL query for finding records where count > 1 <p>I have a table named <code>PAYMENT</code>. Within this table I have a user ID, an account number, a ZIP code and a date. I would like to find all records for all users that have more than one payment per day with the same account number. </p> <p><strong>UPDATE:</strong> Additionally, there should be a filter than only counts the records whose ZIP code is different.</p> <p>This is how the table looks like:</p> <pre>| user_id | account_no | zip | date | | 1 | 123 | 55555 | 12-DEC-09 | | 1 | 123 | 66666 | 12-DEC-09 | | 1 | 123 | 55555 | 13-DEC-09 | | 2 | 456 | 77777 | 14-DEC-09 | | 2 | 456 | 77777 | 14-DEC-09 | | 2 | 789 | 77777 | 14-DEC-09 | | 2 | 789 | 77777 | 14-DEC-09 | </pre> <p>The result should look similar to this:</p> <pre>| user_id | count | | 1 | 2 | </pre> <p>How would you express this in a SQL query? I was thinking self join but for some reason my count is wrong.</p>
<p>Use the <a href="http://www.w3schools.com/sql/sql_having.asp" rel="noreferrer">HAVING</a> clause and GROUP By the fields that make the row unique</p> <p>The below will find</p> <blockquote> <p>all users that have more than one payment per day with the same account number</p> </blockquote> <pre><code>SELECT user_id , COUNT(*) count FROM PAYMENT GROUP BY account, user_id , date HAVING COUNT(*) &gt; 1 </code></pre> <p><strong>Update</strong> If you want to only include those that have a distinct ZIP you can get a distinct set first and then perform you HAVING/GROUP BY</p> <pre><code> SELECT user_id, account_no , date, COUNT(*) FROM (SELECT DISTINCT user_id, account_no , zip, date FROM payment ) payment GROUP BY user_id, account_no , date HAVING COUNT(*) &gt; 1 </code></pre>
{ "question_id": 7151401, "question_date": "2011-08-22T17:49:43.963Z", "question_score": 225, "tags": "sql|count|group-by|having", "answer_id": 7151428, "answer_date": "2011-08-22T17:51:25.653Z", "answer_score": 426 }
Please answer the following Stack Overflow question: Title: Javascript - Track mouse position <p>I am hoping to track the position of the mouse cursor, periodically every t mseconds. So essentially, when a page loads - this tracker should start and for (say) every 100 ms, I should get the new value of posX and posY and print it out in the form. </p> <p>I tried the following code - but the values do not get refreshed - only the initial values of posX and posY show up in the form boxes. Any ideas on how I can get this up and running ? </p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt; Track Mouse &lt;/title&gt; &lt;script type="text/javascript"&gt; function mouse_position() { var e = window.event; var posX = e.clientX; var posY = e.clientY; document.Form1.posx.value = posX; document.Form1.posy.value = posY; var t = setTimeout(mouse_position,100); } &lt;/script&gt; &lt;/head&gt; &lt;body onload="mouse_position()"&gt; &lt;form name="Form1"&gt; POSX: &lt;input type="text" name="posx"&gt;&lt;br&gt; POSY: &lt;input type="text" name="posy"&gt;&lt;br&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
<p>The mouse's position is reported on the <code>event</code> object received by a handler for the <code>mousemove</code> event, which you can attach to the window (the event bubbles):</p> <pre><code>(function() { document.onmousemove = handleMouseMove; function handleMouseMove(event) { var eventDoc, doc, body; event = event || window.event; // IE-ism // If pageX/Y aren't available and clientX/Y are, // calculate pageX/Y - logic taken from jQuery. // (This is to support old IE) if (event.pageX == null &amp;&amp; event.clientX != null) { eventDoc = (event.target &amp;&amp; event.target.ownerDocument) || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = event.clientX + (doc &amp;&amp; doc.scrollLeft || body &amp;&amp; body.scrollLeft || 0) - (doc &amp;&amp; doc.clientLeft || body &amp;&amp; body.clientLeft || 0); event.pageY = event.clientY + (doc &amp;&amp; doc.scrollTop || body &amp;&amp; body.scrollTop || 0) - (doc &amp;&amp; doc.clientTop || body &amp;&amp; body.clientTop || 0 ); } // Use event.pageX / event.pageY here } })(); </code></pre> <p>(Note that the body of that <code>if</code> will only run on old IE.)</p> <p><a href="http://jsbin.com/gejuz/1" rel="noreferrer">Example of the above in action</a> - it draws dots as you drag your mouse over the page. (Tested on IE8, IE11, Firefox 30, Chrome 38.)</p> <p>If you really need a timer-based solution, you combine this with some state variables:</p> <pre><code>(function() { var mousePos; document.onmousemove = handleMouseMove; setInterval(getMousePosition, 100); // setInterval repeats every X ms function handleMouseMove(event) { var dot, eventDoc, doc, body, pageX, pageY; event = event || window.event; // IE-ism // If pageX/Y aren't available and clientX/Y are, // calculate pageX/Y - logic taken from jQuery. // (This is to support old IE) if (event.pageX == null &amp;&amp; event.clientX != null) { eventDoc = (event.target &amp;&amp; event.target.ownerDocument) || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = event.clientX + (doc &amp;&amp; doc.scrollLeft || body &amp;&amp; body.scrollLeft || 0) - (doc &amp;&amp; doc.clientLeft || body &amp;&amp; body.clientLeft || 0); event.pageY = event.clientY + (doc &amp;&amp; doc.scrollTop || body &amp;&amp; body.scrollTop || 0) - (doc &amp;&amp; doc.clientTop || body &amp;&amp; body.clientTop || 0 ); } mousePos = { x: event.pageX, y: event.pageY }; } function getMousePosition() { var pos = mousePos; if (!pos) { // We haven't seen any movement yet } else { // Use pos.x and pos.y } } })(); </code></pre> <p>As far as I'm aware, you can't get the mouse position without having seen an event, something which <a href="https://stackoverflow.com/questions/1133807/mouse-position-using-jquery-outside-of-events">this answer to another Stack Overflow question</a> seems to confirm.</p> <p><strong>Side note</strong>: If you're going to do something every 100ms (10 times/second), try to keep the actual processing you do in that function <em>very, very limited</em>. That's a lot of work for the browser, particularly older Microsoft ones. Yes, on modern computers it doesn't seem like much, but there is a lot going on in browsers... So for example, you might keep track of the last position you processed and bail from the handler immediately if the position hasn't changed.</p>
{ "question_id": 7790725, "question_date": "2011-10-17T07:44:25.080Z", "question_score": 225, "tags": "javascript", "answer_id": 7790764, "answer_date": "2011-10-17T07:49:15.503Z", "answer_score": 236 }
Please answer the following Stack Overflow question: Title: How to sort an ArrayList in Java <p>I have a class named Fruit. I am creating a list of this class and adding each fruit in the list. I want to sort this list based on the order of fruit name.</p> <pre><code>public class Fruit{ private String fruitName; private String fruitDesc; private int quantity; public String getFruitName() { return fruitName; } public void setFruitName(String fruitName) { this.fruitName = fruitName; } public String getFruitDesc() { return fruitDesc; } public void setFruitDesc(String fruitDesc) { this.fruitDesc = fruitDesc; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } } </code></pre> <p>and I am creating its list using for loop</p> <pre><code>List&lt;Fruit&gt; fruits= new ArrayList&lt;Fruit&gt;(); Fruit fruit; for(int i=0;i&lt;100;i++) { fruit = new fruit(); fruit.setname(...); fruits.add(fruit); } </code></pre> <p>and I need to sort this arrayList using the fruit name of each object in the list</p> <p>how??</p>
<p>Use a <code>Comparator</code> like this:</p> <pre><code>List&lt;Fruit&gt; fruits= new ArrayList&lt;Fruit&gt;(); Fruit fruit; for(int i = 0; i &lt; 100; i++) { fruit = new Fruit(); fruit.setname(...); fruits.add(fruit); } // Sorting Collections.sort(fruits, new Comparator&lt;Fruit&gt;() { @Override public int compare(Fruit fruit2, Fruit fruit1) { return fruit1.fruitName.compareTo(fruit2.fruitName); } }); </code></pre> <p>Now your fruits list is sorted based on <code>fruitName</code>.</p>
{ "question_id": 18441846, "question_date": "2013-08-26T10:20:05.337Z", "question_score": 225, "tags": "java|sorting|collections|arraylist", "answer_id": 18441978, "answer_date": "2013-08-26T10:27:58.190Z", "answer_score": 426 }
Please answer the following Stack Overflow question: Title: jQuery on window resize <p>I have the following JQuery code:</p> <pre><code>$(document).ready(function () { var $containerHeight = $(window).height(); if ($containerHeight &lt;= 818) { $('.footer').css({ position: 'static', bottom: 'auto', left: 'auto' }); } if ($containerHeight &gt; 819) { $('.footer').css({ position: 'absolute', bottom: '3px', left: '0px' }); } }); </code></pre> <p>The only problem is that this only works when the browser first loads, I want <code>containerHeight</code> to also be checked when they are resizing the window?</p> <p>Any ideas?</p>
<p><strong>Here's an example using jQuery, javascript and css to handle resize events.</strong> <br />(css if your best bet if you're just stylizing things on resize (media queries))<br /> <a href="http://jsfiddle.net/CoryDanielson/LAF4G/" rel="noreferrer">http://jsfiddle.net/CoryDanielson/LAF4G/</a></p> <h2>css</h2> <pre><code>.footer { /* default styles applied first */ } @media screen and (min-height: 820px) /* height &gt;= 820 px */ { .footer { position: absolute; bottom: 3px; left: 0px; /* more styles */ } } </code></pre> <h2>javascript</h2> <pre><code>window.onresize = function() { if (window.innerHeight &gt;= 820) { /* ... */ } if (window.innerWidth &lt;= 1280) { /* ... */ } } </code></pre> <h2>jQuery</h2> <pre><code>$(window).on('resize', function(){ var win = $(this); //this = window if (win.height() &gt;= 820) { /* ... */ } if (win.width() &gt;= 1280) { /* ... */ } }); </code></pre> <h2>How do I stop my resize code from executing so often!?</h2> <p>This is the first problem you'll notice when binding to resize. The resize code gets called a LOT when the user is resizing the browser manually, and can feel pretty janky.</p> <p>To limit how often your resize code is called, you can use the <a href="http://underscorejs.org/#debounce" rel="noreferrer">debounce</a> or <a href="http://underscorejs.org/#throttle" rel="noreferrer">throttle</a> methods from the <a href="http://underscorejs.org/" rel="noreferrer">underscore</a> &amp; <a href="http://lodash.com/" rel="noreferrer">lodash</a> libraries.</p> <ul> <li><code>debounce</code> will only execute your resize code X number of milliseconds after the LAST resize event. This is ideal when you only want to call your resize code once, after the user is done resizing the browser. It's good for updating graphs, charts and layouts that may be expensive to update every single resize event.</li> <li><code>throttle</code> will only execute your resize code every X number of milliseconds. It &quot;throttles&quot; how often the code is called. This isn't used as often with resize events, but it's worth being aware of.</li> </ul> <p>If you don't have underscore or lodash, you can implement a similar solution yourself: <a href="https://stackoverflow.com/questions/2854407/javascript-jquery-window-resize-how-to-fire-after-the-resize-is-completed">JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?</a></p>
{ "question_id": 9828831, "question_date": "2012-03-22T19:04:37.363Z", "question_score": 225, "tags": "jquery|html|css", "answer_id": 9828919, "answer_date": "2012-03-22T19:11:28.223Z", "answer_score": 429 }
Please answer the following Stack Overflow question: Title: Invalid hook call. Hooks can only be called inside of the body of a function component <p>I want to show some records in a table using React but I got this error:</p> <blockquote> <p>Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:</p> <ol> <li>You might have mismatching versions of React and the renderer (such as React DOM)</li> <li>You might be breaking the Rules of Hooks</li> <li>You might have more than one copy of React in the same app See for tips about how to debug and fix this problem.</li> </ol> </blockquote> <pre class="lang-js prettyprint-override"><code>import React, { Component } from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import TableHead from '@material-ui/core/TableHead'; import TableRow from '@material-ui/core/TableRow'; import Paper from '@material-ui/core/Paper'; const useStyles = makeStyles(theme =&gt; ({ root: { width: '100%', marginTop: theme.spacing(3), overflowX: 'auto', }, table: { minWidth: 650, }, })); class allowance extends Component { constructor() { super(); this.state = { allowances: [], }; } componentWillMount() { fetch('http://127.0.0.1:8000/allowances') .then(data =&gt; { return data.json(); }).then(data =&gt; { this.setState({ allowances: data }); console.log(&quot;allowance state&quot;, this.state.allowances); }) } render() { const classes = useStyles(); return ( &lt; Paper className = { classes.root } &gt; &lt; Table className = { classes.table } &gt; &lt; TableHead &gt; &lt; TableRow &gt; &lt; TableCell &gt; Allow ID &lt; /TableCell&gt; &lt; TableCell align = &quot;right&quot; &gt; Description &lt; /TableCell&gt; &lt; TableCell align = &quot;right&quot; &gt; Allow Amount &lt; /TableCell&gt; &lt; TableCell align = &quot;right&quot; &gt; AllowType &lt; /TableCell&gt; &lt; /TableRow&gt; &lt; /TableHead&gt; &lt; TableBody &gt; { this.state.allowances.map(row =&gt; ( &lt; TableRow key = { row.id } &gt; &lt; TableCell component = &quot;th&quot; scope = &quot;row&quot; &gt; { row.AllowID } &lt; /TableCell&gt; &lt; TableCell align = &quot;right&quot; &gt; { row.AllowDesc } &lt; /TableCell&gt; &lt; TableCell align = &quot;right&quot; &gt; { row.AllowAmt } &lt; /TableCell&gt; &lt; TableCell align = &quot;right&quot; &gt; { row.AllowType } &lt; /TableCell&gt; &lt; /TableRow&gt; )) } &lt; /TableBody&gt; &lt; /Table&gt; &lt; /Paper&gt; ); } } export default allowance; </code></pre>
<p>You can only call hooks from React functions. Read more <a href="https://reactjs.org/docs/hooks-rules.html#only-call-hooks-from-react-functions" rel="noreferrer">here</a>.</p> <p>Just convert the <code>Allowance</code> class component to a functional component.</p> <p><a href="https://codesandbox.io/s/amazing-poitras-k2fuf" rel="noreferrer">Working CodeSandbox demo</a>.</p> <pre class="lang-js prettyprint-override"><code>const Allowance = () =&gt; { const [allowances, setAllowances] = useState([]); useEffect(() =&gt; { fetch(&quot;http://127.0.0.1:8000/allowances&quot;) .then(data =&gt; { return data.json(); }) .then(data =&gt; { setAllowances(data); }) .catch(err =&gt; { console.log(123123); }); }, []); const classes = useStyles(); return ( &lt; Paper className = { classes.root } &gt; &lt; Table className = { classes.table } &gt; &lt; TableHead &gt; &lt; TableRow &gt; &lt; TableCell &gt; Allow ID &lt; /TableCell&gt; &lt; TableCell align = &quot;right&quot; &gt; Description &lt; /TableCell&gt; &lt; TableCell align = &quot;right&quot; &gt; Allow Amount &lt; /TableCell&gt; &lt; TableCell align = &quot;right&quot; &gt; AllowType &lt; /TableCell&gt; &lt; /TableRow&gt; &lt; /TableHead&gt; &lt; TableBody &gt; { allowances.map(row =&gt; ( &lt; TableRow key = { row.id } &gt; &lt; TableCell component = &quot;th&quot; scope = &quot;row&quot; &gt; { row.AllowID } &lt; /TableCell&gt; &lt; TableCell align = &quot;right&quot; &gt; { row.AllowDesc } &lt; /TableCell&gt; &lt; TableCell align = &quot;right&quot; &gt; { row.AllowAmt } &lt; /TableCell&gt; &lt; TableCell align = &quot;right&quot; &gt; { row.AllowType } &lt; /TableCell&gt; &lt; /TableRow&gt; )) } &lt; /TableBody&gt; &lt; /Table&gt; &lt; /Paper&gt; ); }; export default Allowance; </code></pre>
{ "question_id": 56663785, "question_date": "2019-06-19T08:57:15.553Z", "question_score": 225, "tags": "javascript|reactjs|react-hooks|material-ui", "answer_id": 56664084, "answer_date": "2019-06-19T09:13:05.097Z", "answer_score": 88 }
Please answer the following Stack Overflow question: Title: Converting a UNIX Timestamp to Formatted Date String <p>Using PHP, I want to convert UNIX timestamps to date strings similar to this: <code>2008-07-17T09:24:17Z</code></p> <p>How do I convert a timestamp such as <code>1333699439</code> to <code>2008-07-17T09:24:17Z</code>?</p>
<p>Try <a href="http://php.net/manual/en/function.gmdate.php" rel="noreferrer"><code>gmdate</code></a> like this:</p> <pre><code>&lt;?php $timestamp=1333699439; echo gmdate("Y-m-d\TH:i:s\Z", $timestamp); ?&gt; </code></pre>
{ "question_id": 10040291, "question_date": "2012-04-06T07:08:25.593Z", "question_score": 225, "tags": "php|unix-timestamp", "answer_id": 10040407, "answer_date": "2012-04-06T07:20:10.060Z", "answer_score": 381 }
Please answer the following Stack Overflow question: Title: Showing Difference between two datetime values in hours <p>I am retrieving two date time values from the database. Once the value is retrieved, I need the difference between the two values. For that, I create a timespan variable to store the difference of the 2 date values.</p> <pre><code>TimeSpan? variable = datevalue1 - datevalue2; </code></pre> <p>Now i need to show the difference which is stored in the Timespan variable in terms of number of hours. I referred to <a href="http://msdn.microsoft.com/en-us/library/system.timespan.totalhours.aspx">TimeSpan.TotalHours</a> but couldn't apply the same for some reason. How do I do that? I am using C# on a MVC project. I simple need to show the difference value in hours?</p> <p><strong>EDIT: Since timespan was nullable, i couldn't use the total hours property. Now I can use it by doing TimeSpanVal.Value.TotalHours</strong>;</p>
<p>I think you're confused because you haven't declared a <code>TimeSpan</code> you've declared a <code>TimeSpan?</code> which is a <a href="http://msdn.microsoft.com/en-us/library/1t3y8s4s(v=vs.80).aspx" rel="noreferrer">nullable</a> <code>TimeSpan</code>. Either remove the question mark if you don't need it to be nullable or use <code>variable.Value.TotalHours</code>.</p>
{ "question_id": 4946316, "question_date": "2011-02-09T14:39:44.733Z", "question_score": 225, "tags": "c#|asp.net-mvc-2|datetime|timespan", "answer_id": 4946390, "answer_date": "2011-02-09T14:44:25.707Z", "answer_score": 133 }
Please answer the following Stack Overflow question: Title: Python Request Post with param data <p>This is the raw request for an API call:</p> <pre><code>POST http://192.168.3.45:8080/api/v2/event/log?sessionKey=b299d17b896417a7b18f46544d40adb734240cc2&amp;format=json HTTP/1.1 Accept-Encoding: gzip,deflate Content-Type: application/json Content-Length: 86 Host: 192.168.3.45:8080 Connection: Keep-Alive User-Agent: Apache-HttpClient/4.1.1 (java 1.5) {"eventType":"AAS_PORTAL_START","data":{"uid":"hfe3hf45huf33545","aid":"1","vid":"1"}}""" </code></pre> <p>This request returns a success (2xx) response.</p> <p>Now I am trying to post this request using <code>requests</code>:</p> <pre><code>&gt;&gt;&gt; import requests &gt;&gt;&gt; headers = {'content-type' : 'application/json'} &gt;&gt;&gt; data ={"eventType":"AAS_PORTAL_START","data{"uid":"hfe3hf45huf33545","aid":"1","vid":"1"}} &gt;&gt;&gt; url = "http://192.168.3.45:8080/api/v2/event/log?sessionKey=9ebbd0b25760557393a43064a92bae539d962103&amp;format=xml&amp;platformId=1" &gt;&gt;&gt; requests.post(url,params=data,headers=headers) &lt;Response [400]&gt; </code></pre> <p>Everything looks fine to me and I am not quite sure what I posting wrong to get a 400 response.</p>
<p><code>params</code> is for GET-style URL parameters, <code>data</code> is for POST-style body information. It is perfectly legal to provide <em>both</em> types of information in a request, and your request does so too, but you encoded the URL parameters into the URL already.</p> <p>Your raw post contains <em>JSON</em> data though. <code>requests</code> can handle JSON encoding for you, and it'll set the correct <code>Content-Type</code> header too; all you need to do is pass in the Python object to be encoded as JSON into the <code>json</code> keyword argument.</p> <p>You could split out the URL parameters as well:</p> <pre><code>params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1} </code></pre> <p>then post your data with:</p> <pre><code>import requests url = 'http://192.168.3.45:8080/api/v2/event/log' data = {&quot;eventType&quot;: &quot;AAS_PORTAL_START&quot;, &quot;data&quot;: {&quot;uid&quot;: &quot;hfe3hf45huf33545&quot;, &quot;aid&quot;: &quot;1&quot;, &quot;vid&quot;: &quot;1&quot;}} params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1} requests.post(url, params=params, json=data) </code></pre> <p>The <code>json</code> keyword is new in <code>requests</code> version 2.4.2; if you still have to use an older version, encode the JSON manually using the <code>json</code> module and post the encoded result as the <code>data</code> key; you will have to explicitly set the Content-Type header in that case:</p> <pre><code>import requests import json headers = {'content-type': 'application/json'} url = 'http://192.168.3.45:8080/api/v2/event/log' data = {&quot;eventType&quot;: &quot;AAS_PORTAL_START&quot;, &quot;data&quot;: {&quot;uid&quot;: &quot;hfe3hf45huf33545&quot;, &quot;aid&quot;: &quot;1&quot;, &quot;vid&quot;: &quot;1&quot;}} params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1} requests.post(url, params=params, data=json.dumps(data), headers=headers) </code></pre>
{ "question_id": 15900338, "question_date": "2013-04-09T11:12:56.547Z", "question_score": 225, "tags": "python|httprequest|python-requests|http-status-codes", "answer_id": 15900453, "answer_date": "2013-04-09T11:19:20.547Z", "answer_score": 381 }
Please answer the following Stack Overflow question: Title: Checking version of angular-cli that's installed? <p>Is there a way to check the specific version of <code>angular-cli</code> that's installed globally on my machine? I'm in a Windows environment. <code>*npm -v* and *node -v*</code> only gives me the version of npm and node respectively, and I can't seem to find any commands with <em>ng</em>.</p> <p>I'm trying to run a project that I'm working on, and it ran on an older version of angular-cli using npm. However, after installing other demo projects, my main project doesn't work anymore without uninstalling and reinstalling <code>angular-cli</code> at the specific version.</p>
<p>angular cli can report its version when you run it with the version flag</p> <pre><code>ng --version </code></pre>
{ "question_id": 41026895, "question_date": "2016-12-07T20:36:00.457Z", "question_score": 225, "tags": "node.js|angular|npm|angular-cli", "answer_id": 41027175, "answer_date": "2016-12-07T20:53:53.520Z", "answer_score": 438 }
Please answer the following Stack Overflow question: Title: get an element's id <p>Is there another way to get an DOM element's ID?</p> <pre><code>element.getAttribute('id') </code></pre>
<p>Yes you can just use the <a href="https://developer.mozilla.org/en/DOM/element.id" rel="noreferrer"><code>.id</code> property</a> of the <a href="https://developer.mozilla.org/en/DOM/element" rel="noreferrer">dom element</a>, for example:</p> <pre><code>myDOMElement.id </code></pre> <p>Or, something like this:</p> <pre><code>var inputs = document.getElementsByTagName("input"); for (var i = 0; i &lt; inputs.length; i++) { alert(inputs[i].id); } </code></pre>
{ "question_id": 3623110, "question_date": "2010-09-02T00:52:12.363Z", "question_score": 225, "tags": "javascript|html", "answer_id": 3623125, "answer_date": "2010-09-02T00:55:10.687Z", "answer_score": 335 }
Please answer the following Stack Overflow question: Title: Label axes on Seaborn Barplot <p>I'm trying to use my own labels for a Seaborn barplot with the following code:</p> <pre><code>import pandas as pd import seaborn as sns fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]}) fig = sns.barplot(x = 'val', y = 'cat', data = fake, color = 'black') fig.set_axis_labels('Colors', 'Values') </code></pre> <p><a href="https://i.stack.imgur.com/kZFNu.png" rel="noreferrer"><img src="https://i.stack.imgur.com/kZFNu.png" alt="enter image description here"></a></p> <p>However, I get an error that:</p> <pre><code>AttributeError: 'AxesSubplot' object has no attribute 'set_axis_labels' </code></pre> <p>What gives?</p>
<p>Seaborn's barplot returns an axis-object (not a figure). This means you can do the following:</p> <pre><code>import pandas as pd import seaborn as sns import matplotlib.pyplot as plt fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]}) ax = sns.barplot(x = 'val', y = 'cat', data = fake, color = 'black') ax.set(xlabel='common xlabel', ylabel='common ylabel') plt.show() </code></pre>
{ "question_id": 31632637, "question_date": "2015-07-26T01:08:48.417Z", "question_score": 225, "tags": "python|matplotlib|seaborn|bar-chart", "answer_id": 31632745, "answer_date": "2015-07-26T01:28:00.767Z", "answer_score": 363 }
Please answer the following Stack Overflow question: Title: Can I use a binary literal in C or C++? <p>I need to work with a binary number.</p> <p>I tried writing:</p> <pre><code>const char x = 00010000; </code></pre> <p>But it didn't work.</p> <p>I know that I can use a hexadecimal number that has the same value as <code>00010000</code>, but I want to know if there is a type in C++ for binary numbers, and if there isn't, is there another solution for my problem?</p>
<p>You can <a href="http://www.boost.org/doc/libs/1_42_0/libs/utility/utility.htm#BOOST_BINARY" rel="nofollow noreferrer">use <strong><code>BOOST_BINARY</code></strong></a> while waiting for C++0x. :) <code>BOOST_BINARY</code> arguably has an advantage over template implementation insofar as it <strong>can be used in C programs as well</strong> (it is 100% preprocessor-driven.)</p> <p>To do the converse (i.e. print out a number in binary form), you can use the non-portable <a href="http://www.cplusplus.com/reference/clibrary/cstdlib/itoa/" rel="nofollow noreferrer"><code>itoa</code> function</a>, or <a href="http://www.jb.man.ac.uk/~slowe/cpp/itoa.html" rel="nofollow noreferrer">implement your own</a>.</p> <p>Unfortunately you cannot do base 2 formatting with STL streams (since <a href="http://en.cppreference.com/w/cpp/io/manip/setbase" rel="nofollow noreferrer"><code>setbase</code></a> will only honour bases 8, 10 and 16), but you <em>can</em> use either a <code>std::string</code> version of <code>itoa</code>, or (the more concise, yet marginally less efficient) <code>std::bitset</code>.</p> <pre><code>#include &lt;boost/utility/binary.hpp&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;bitset&gt; #include &lt;iostream&gt; #include &lt;iomanip&gt; using namespace std; int main() { unsigned short b = BOOST_BINARY( 10010 ); char buf[sizeof(b)*8+1]; printf("hex: %04x, dec: %u, oct: %06o, bin: %16s\n", b, b, b, itoa(b, buf, 2)); cout &lt;&lt; setfill('0') &lt;&lt; "hex: " &lt;&lt; hex &lt;&lt; setw(4) &lt;&lt; b &lt;&lt; ", " &lt;&lt; "dec: " &lt;&lt; dec &lt;&lt; b &lt;&lt; ", " &lt;&lt; "oct: " &lt;&lt; oct &lt;&lt; setw(6) &lt;&lt; b &lt;&lt; ", " &lt;&lt; "bin: " &lt;&lt; bitset&lt; 16 &gt;(b) &lt;&lt; endl; return 0; } </code></pre> <p>produces:</p> <pre><code>hex: 0012, dec: 18, oct: 000022, bin: 10010 hex: 0012, dec: 18, oct: 000022, bin: 0000000000010010 </code></pre> <p>Also read Herb Sutter's <em><a href="http://www.gotw.ca/publications/mill19.htm" rel="nofollow noreferrer">The String Formatters of Manor Farm</a></em> for an interesting discussion.</p>
{ "question_id": 2611764, "question_date": "2010-04-10T00:35:10.700Z", "question_score": 225, "tags": "c++|c|binary", "answer_id": 2611883, "answer_date": "2010-04-10T01:25:32.983Z", "answer_score": 71 }
Please answer the following Stack Overflow question: Title: Django TemplateDoesNotExist? <p>My local machine is running Python 2.5 and Nginx on Ubuntu 8.10, with Django builded from latest development trunk.</p> <p>For every URL I request, it throws:</p> <blockquote> <p>TemplateDoesNotExist at /appname/path appname/template_name.html</p> <p>Django tried loading these templates, in this order: * Using loader django.template.loaders.filesystem.function: * Using loader django.template.loaders.app_directories.function: </p> <p>TEMPLATE_DIRS ('/usr/lib/python2.5/site-packages/projectname/templates',)</p> </blockquote> <p>Is it looking for <strong>/usr/lib/python2.5/site-packages/projectname/templates/appname/template_name.html</strong> in this case? The weird thing is this file does existed on disk. Why can't Django locate it?</p> <p>I run the same application on a remote server with Python 2.6 on Ubuntu 9.04 without such problem. Other settings are the same.</p> <p>Is there anything misconfigured on my local machine, or what could possibly have caused such errors that I should look into?</p> <p>In my <strong>settings.py</strong>, I have specified:</p> <pre><code>SETTINGS_PATH = os.path.normpath(os.path.dirname(__file__)) # Find templates in the same folder as settings.py. TEMPLATE_DIRS = ( os.path.join(SETTINGS_PATH, 'templates'), ) </code></pre> <p>It should be looking for the following files:</p> <ul> <li>/usr/lib/python2.5/site-packages/projectname/templates/appname1/template1.html</li> <li>/usr/lib/python2.5/site-packages/projectname/templates/appname1/template2.html</li> <li>/usr/lib/python2.5/site-packages/projectname/templates/appname2/template3.html</li> <li>...</li> </ul> <p>All the above files exist on disk.</p> <p><strong>Solved</strong></p> <p>It works now after I tried:</p> <pre><code>chown -R www-data:www-data /usr/lib/python2.5/site-packages/projectname/* </code></pre> <p>It's strange. I don't need to do this on the remote server to make it work.</p>
<p><strong>First solution</strong>:</p> <p>These settings</p> <pre><code>TEMPLATE_DIRS = ( os.path.join(SETTINGS_PATH, 'templates'), ) </code></pre> <p>mean that Django will look at the templates from <code>templates/</code> directory under your project.</p> <p>Assuming your Django project is located at <code>/usr/lib/python2.5/site-packages/projectname/</code> then with your settings django will look for the templates under <code>/usr/lib/python2.5/site-packages/projectname/templates/</code></p> <p>So in that case we want to move our templates to be structured like this:</p> <pre><code>/usr/lib/python2.5/site-packages/projectname/templates/template1.html /usr/lib/python2.5/site-packages/projectname/templates/template2.html /usr/lib/python2.5/site-packages/projectname/templates/template3.html </code></pre> <p><strong>Second solution</strong>:</p> <p>If that still doesn't work and assuming that you have the apps configured in settings.py like this:</p> <pre><code>INSTALLED_APPS = ( 'appname1', 'appname2', 'appname3', ) </code></pre> <p>By default Django will load the templates under <code>templates/</code> directory under every installed apps. So with your directory structure, we want to move our templates to be like this:</p> <pre><code>/usr/lib/python2.5/site-packages/projectname/appname1/templates/template1.html /usr/lib/python2.5/site-packages/projectname/appname2/templates/template2.html /usr/lib/python2.5/site-packages/projectname/appname3/templates/template3.html </code></pre> <p><code>SETTINGS_PATH</code> may not be defined by default. In which case, you will want to define it (in settings.py):</p> <pre><code>import os SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__)) </code></pre>
{ "question_id": 1926049, "question_date": "2009-12-18T03:12:10.843Z", "question_score": 225, "tags": "python|python-3.x|django|django-templates|python-2.x", "answer_id": 1926354, "answer_date": "2009-12-18T04:54:05.017Z", "answer_score": 259 }
Please answer the following Stack Overflow question: Title: Label points in geom_point <p>The data I'm playing with comes from the internet source listed below</p> <pre><code>nba &lt;- read.csv("http://datasets.flowingdata.com/ppg2008.csv", sep=",") </code></pre> <p>What I want to do, is create a 2D points graph comparing two metrics from this table, with each player representing a dot on the graph. I have the following code: </p> <pre><code>nbaplot &lt;- ggplot(nba, aes(x= MIN, y= PTS, colour="green", label=Name)) + geom_point() </code></pre> <p>This gives me the following: </p> <p><img src="https://i.stack.imgur.com/RVZz8.png" alt="NBA Plot"></p> <p>What I want is a label of player's name right next to the dots. I thought the label function in ggplot's aesthetics would do this for me, but it didn't. </p> <p>I also tried <code>text()</code> function and the <code>textxy()</code> function from <code>library(calibrate)</code>, neither of which appears to work with ggplot. </p> <p>How can I add name labels to these points? </p>
<p>Use <code>geom_text</code> , with <code>aes</code> label. You can play with <code>hjust, vjust</code> to adjust text position.</p> <pre><code>ggplot(nba, aes(x= MIN, y= PTS, colour=&quot;green&quot;, label=Name))+ geom_point() +geom_text(hjust=0, vjust=0) </code></pre> <p><img src="https://i.stack.imgur.com/EGOIn.png" alt="enter image description here" /></p> <h2>EDIT: Label only values above a certain threshold:</h2> <pre><code> ggplot(nba, aes(x= MIN, y= PTS, colour=&quot;green&quot;, label=Name))+ geom_point() + geom_text(aes(label=ifelse(PTS&gt;24,as.character(Name),'')),hjust=0,vjust=0) </code></pre> <p><img src="https://i.stack.imgur.com/qxK00.png" alt="chart with conditional labels" /></p>
{ "question_id": 15624656, "question_date": "2013-03-25T21:00:05.290Z", "question_score": 225, "tags": "r|plot|ggplot2|labeling|ggrepel", "answer_id": 15625149, "answer_date": "2013-03-25T21:30:45.823Z", "answer_score": 343 }
Please answer the following Stack Overflow question: Title: Difference between except: and except Exception as e: <p>Both the following snippets of code do the same thing. They catch every exception and execute the code in the <code>except:</code> block</p> <p>Snippet 1 - </p> <pre><code>try: #some code that may throw an exception except: #exception handling code </code></pre> <p>Snippet 2 - </p> <pre><code>try: #some code that may throw an exception except Exception as e: #exception handling code </code></pre> <p>What is exactly the difference in both the constructs?</p>
<p>In the second you can access the attributes of the exception object:</p> <pre><code>&gt;&gt;&gt; def catch(): ... try: ... asd() ... except Exception as e: ... print e.message, e.args ... &gt;&gt;&gt; catch() global name 'asd' is not defined ("global name 'asd' is not defined",) </code></pre> <p>But it doesn't catch <code>BaseException</code> or the system-exiting exceptions <code>SystemExit</code>, <code>KeyboardInterrupt</code> and <code>GeneratorExit</code>:</p> <pre><code>&gt;&gt;&gt; def catch(): ... try: ... raise BaseException() ... except Exception as e: ... print e.message, e.args ... &gt;&gt;&gt; catch() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 3, in catch BaseException </code></pre> <p>Which a bare except does:</p> <pre><code>&gt;&gt;&gt; def catch(): ... try: ... raise BaseException() ... except: ... pass ... &gt;&gt;&gt; catch() &gt;&gt;&gt; </code></pre> <p>See the <a href="http://docs.python.org/2/library/exceptions.html" rel="noreferrer">Built-in Exceptions</a> section of the docs and the <a href="http://docs.python.org/2/tutorial/errors.html" rel="noreferrer">Errors and Exceptions</a> section of the tutorial for more info.</p>
{ "question_id": 18982610, "question_date": "2013-09-24T13:11:41.800Z", "question_score": 225, "tags": "python|python-3.x", "answer_id": 18982726, "answer_date": "2013-09-24T13:16:29.843Z", "answer_score": 244 }
Please answer the following Stack Overflow question: Title: Create a CSV File for a user in PHP <p>I have data in a MySQL database. I am sending the user a URL to get their data out as a CSV file.</p> <p>I have the e-mailing of the link, MySQL query, etc. covered.</p> <p>How can I, when they click the link, have a pop-up to download a CVS with the record from MySQL? </p> <p>I have all the information to get the record already. I just don't see how to have PHP create the CSV file and let them download a file with a .csv extension.</p>
<p>Try:</p> <pre><code>header("Content-type: text/csv"); header("Content-Disposition: attachment; filename=file.csv"); header("Pragma: no-cache"); header("Expires: 0"); echo "record1,record2,record3\n"; die; </code></pre> <p>etc</p> <p>Edit: Here's a snippet of code I use to optionally encode CSV fields:</p> <pre><code>function maybeEncodeCSVField($string) { if(strpos($string, ',') !== false || strpos($string, '"') !== false || strpos($string, "\n") !== false) { $string = '"' . str_replace('"', '""', $string) . '"'; } return $string; } </code></pre>
{ "question_id": 217424, "question_date": "2008-10-20T03:11:46.533Z", "question_score": 225, "tags": "php|csv|download|http-headers", "answer_id": 217434, "answer_date": "2008-10-20T03:15:36.633Z", "answer_score": 293 }
Please answer the following Stack Overflow question: Title: How to return a file (FileContentResult) in ASP.NET WebAPI <p>In a regular MVC controller, we can output pdf with a <code>FileContentResult</code>.</p> <pre><code>public FileContentResult Test(TestViewModel vm) { var stream = new MemoryStream(); //... add content to the stream. return File(stream.GetBuffer(), "application/pdf", "test.pdf"); } </code></pre> <p>But how can we change it into an <code>ApiController</code>?</p> <pre><code>[HttpPost] public IHttpActionResult Test(TestViewModel vm) { //... return Ok(pdfOutput); } </code></pre> <hr> <p>Here is what I've tried but it doesn't seem to work. </p> <pre><code>[HttpGet] public IHttpActionResult Test() { var stream = new MemoryStream(); //... var content = new StreamContent(stream); content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf"); content.Headers.ContentLength = stream.GetBuffer().Length; return Ok(content); } </code></pre> <p>The returned result displayed in the browser is:</p> <pre><code>{"Headers":[{"Key":"Content-Type","Value":["application/pdf"]},{"Key":"Content-Length","Value":["152844"]}]} </code></pre> <p>And there is a similar post on SO: <a href="https://stackoverflow.com/questions/9541351/returning-binary-file-from-controller-in-asp-net-web-api?rq=1">Returning binary file from controller in ASP.NET Web API </a>. It talks about output an existing file. But I could not make it work with a stream.</p> <p>Any suggestions?</p>
<p>Instead of returning <code>StreamContent</code> as the <code>Content</code>, I can make it work with <code>ByteArrayContent</code>.</p> <pre><code>[HttpGet] public HttpResponseMessage Generate() { var stream = new MemoryStream(); // processing the stream. var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(stream.ToArray()) }; result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = "CertificationCard.pdf" }; result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); return result; } </code></pre>
{ "question_id": 26038856, "question_date": "2014-09-25T12:37:01.170Z", "question_score": 225, "tags": "c#|asp.net|asp.net-mvc|asp.net-web-api", "answer_id": 26041298, "answer_date": "2014-09-25T14:34:45.787Z", "answer_score": 238 }
Please answer the following Stack Overflow question: Title: PHP server on local machine? <p>I'm trying to build a PHP site and I'm wanting to test my PHP files without uploading them to my host. Basically testing them on my own machine before I upload them. How do I do that?</p>
<p>Install and run XAMPP: <a href="http://www.apachefriends.org/en/xampp.html" rel="noreferrer">http://www.apachefriends.org/en/xampp.html</a></p>
{ "question_id": 1678010, "question_date": "2009-11-05T02:48:54.983Z", "question_score": 225, "tags": "php|server|local", "answer_id": 1678024, "answer_date": "2009-11-05T02:52:41.123Z", "answer_score": 67 }
Please answer the following Stack Overflow question: Title: Where is body in a nodejs http.get response? <p>I'm reading the docs at <a href="http://nodejs.org/docs/v0.4.0/api/http.html#http.request" rel="noreferrer">http://nodejs.org/docs/v0.4.0/api/http.html#http.request</a>, but for some reason, I can't seem to to actually find the body/data attribute on the returned, finished response object. </p> <pre><code>&gt; var res = http.get({host:'www.somesite.com', path:'/'}) &gt; res.finished true &gt; res._hasBody true </code></pre> <p>It's finished (http.get does that for you), so it should have some kind of content. But there's no body, no data, and I can't read from it. Where is the body hiding?</p>
<h3>Edit: replying to self 6 years later</h3> <p>The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await" rel="nofollow noreferrer"><em>await</em> keyword</a> is the best way to get a response from an HTTP request, avoiding callbacks and <code>.then()</code></p> <p><strong>You'll also need to use an HTTP client that returns Promises.</strong> <code>http.get()</code> still returns a Request object, so that won't work.</p> <ul> <li><code>fetch</code> is a low level client, that is both available from npm and nodeJS 17 onwards.</li> <li><code>superagent</code> is a mature HTTP clients that features more reasonable defaults including simpler query string encoding, properly using mime types, JSON by default, and other common HTTP client features.</li> <li><code>axios</code> is also quite popular and has similar advantages to <code>superagent</code></li> </ul> <p><code>await</code> will wait until the Promise has a value - in this case, an HTTP response!</p> <pre><code>const superagent = require('superagent'); (async function(){ const response = await superagent.get('https://www.google.com') console.log(response.text) })(); </code></pre> <p>Using await, control <strong>simply passes onto the next line</strong> once the promise returned by <code>superagent.get()</code> has a value.</p>
{ "question_id": 6968448, "question_date": "2011-08-06T17:30:21.477Z", "question_score": 225, "tags": "node.js|http", "answer_id": 6968657, "answer_date": "2011-08-06T18:05:55.293Z", "answer_score": 61 }
Please answer the following Stack Overflow question: Title: How to view the contents of a .pem certificate? <p>I am using Java <code>keytool</code>. I have exported a self-signed <code>.pem</code> certificate from my keystore. Is there a command to view the certificate details directly from the <code>.pem</code> file (not of the certificate in the keystore)?</p>
<p>Use the <a href="https://docs.oracle.com/javase/8/docs/technotes/tools/unix/keytool.html#keytool_option_printcert" rel="noreferrer"><code>-printcert</code></a> command like this:</p> <pre><code>keytool -printcert -file certificate.pem </code></pre>
{ "question_id": 9758238, "question_date": "2012-03-18T12:19:58.837Z", "question_score": 225, "tags": "keytool", "answer_id": 9758496, "answer_date": "2012-03-18T13:00:04.013Z", "answer_score": 218 }
Please answer the following Stack Overflow question: Title: See line breaks and carriage returns in editor <p>Is there a text editor on Linux that allows me to see line breaks and carriage returns? Does Vim support this feature?</p>
<p><em>Assuming your vim settings for <code>:set listchars=...</code> is set to visualize the characters you are attempting to <em>see</em>, in this case the carriage return characters (typed with CTL + V, CTRM + M) —— otherwise, as reported in many of the comments on this answer, the ^M character will not show on <code>:set list</code></em></p> <p><code>:set list</code> in Vim will show whitespace. End of lines show as '<code>$</code>' and carriage returns usually show as '<code>^M</code>'.</p>
{ "question_id": 3860519, "question_date": "2010-10-05T02:42:18.210Z", "question_score": 225, "tags": "vim|newline|text-editor|line-breaks|carriage-return", "answer_id": 3860537, "answer_date": "2010-10-05T02:50:55.307Z", "answer_score": 153 }
Please answer the following Stack Overflow question: Title: Correctly determine if date string is a valid date in that format <p>I'm receiving a date string from an API, and it is formatted as <code>yyyy-mm-dd</code>.</p> <p>I am currently using a regex to validate the string format, which works ok, but I can see some cases where it could be a correct format according to the string but actually an invalid date. i.e. <code>2013-13-01</code>, for example.</p> <p>Is there a better way in PHP to take a string such as <code>2013-13-01</code> and tell if it is a valid date or not for the format <code>yyyy-mm-dd</code>?</p>
<p>You can use <a href="https://www.php.net/manual/en/datetime.createfromformat.php" rel="noreferrer"><code>DateTime::createFromFormat()</code></a> for this purpose:</p> <pre class="lang-php prettyprint-override"><code>function validateDate($date, $format = 'Y-m-d') { $d = DateTime::createFromFormat($format, $date); // The Y ( 4 digits year ) returns TRUE for any integer with any number of digits so changing the comparison from == to === fixes the issue. return $d &amp;&amp; $d-&gt;format($format) === $date; } </code></pre> <p><sup>[<em>Function taken from <a href="https://stackoverflow.com/a/12323025/67332">this answer</a>. Also on <a href="http://www.php.net/manual/en/function.checkdate.php#113205" rel="noreferrer">php.net</a>. Originally written by <a href="https://stackoverflow.com/users/67332">Glavić</a>.</em>]</sup></p> <hr /> <p>Test cases:</p> <pre><code>var_dump(validateDate('2013-13-01')); // false var_dump(validateDate('20132-13-01')); // false var_dump(validateDate('2013-11-32')); // false var_dump(validateDate('2012-2-25')); // false var_dump(validateDate('2013-12-01')); // true var_dump(validateDate('1970-12-01')); // true var_dump(validateDate('2012-02-29')); // true var_dump(validateDate('2012', 'Y')); // true var_dump(validateDate('12012', 'Y')); // false </code></pre> <p><a href="https://eval.in/53309" rel="noreferrer"><strong>Demo!</strong></a></p>
{ "question_id": 19271381, "question_date": "2013-10-09T11:58:03.960Z", "question_score": 225, "tags": "php|date|datetime", "answer_id": 19271434, "answer_date": "2013-10-09T11:59:54.410Z", "answer_score": 558 }
Please answer the following Stack Overflow question: Title: How to send Basic Auth with axios <p>I'm trying to implement the following code, but something is not working. Here is the code:</p> <pre class="lang-js prettyprint-override"><code> var session_url = 'http://api_address/api/session_endpoint'; var username = 'user'; var password = 'password'; var credentials = btoa(username + ':' + password); var basicAuth = 'Basic ' + credentials; axios.post(session_url, { headers: { 'Authorization': + basicAuth } }).then(function(response) { console.log('Authenticated'); }).catch(function(error) { console.log('Error on Authentication'); }); </code></pre> <p>It's returning a 401 error. When I do it with Postman there is an option to set Basic Auth; if I don't fill those fields it also returns 401, but if I do, the request is successful.</p> <p>Any ideas what I'm doing wrong?</p> <p>Here is part of the docs of the API of how to implement this:</p> <blockquote> <p>This service uses Basic Authentication information in the header to establish a user session. Credentials are validated against the Server. Using this web-service will create a session with the user credentials passed and return a JSESSIONID. This JSESSIONID can be used in the subsequent requests to make web-service calls.*</p> </blockquote>
<p>There is an "auth" parameter for Basic Auth:</p> <pre><code>auth: { username: 'janedoe', password: 's00pers3cret' } </code></pre> <p>Source/Docs: <a href="https://github.com/mzabriskie/axios" rel="noreferrer">https://github.com/mzabriskie/axios</a></p> <p>Example:</p> <pre><code>await axios.post(session_url, {}, { auth: { username: uname, password: pass } }); </code></pre>
{ "question_id": 44072750, "question_date": "2017-05-19T14:33:46.023Z", "question_score": 225, "tags": "request|postman|axios", "answer_id": 44239543, "answer_date": "2017-05-29T09:54:26.363Z", "answer_score": 335 }
Please answer the following Stack Overflow question: Title: Compare two DataFrames and output their differences side-by-side <p>I am trying to highlight exactly what changed between two dataframes.</p> <p>Suppose I have two Python Pandas dataframes:</p> <pre><code>"StudentRoster Jan-1": id Name score isEnrolled Comment 111 Jack 2.17 True He was late to class 112 Nick 1.11 False Graduated 113 Zoe 4.12 True "StudentRoster Jan-2": id Name score isEnrolled Comment 111 Jack 2.17 True He was late to class 112 Nick 1.21 False Graduated 113 Zoe 4.12 False On vacation </code></pre> <p>My goal is to output an HTML table that:</p> <ol> <li>Identifies rows that have changed (could be int, float, boolean, string)</li> <li><p>Outputs rows with same, OLD and NEW values (ideally into an HTML table) so the consumer can clearly see what changed between two dataframes: </p> <pre><code>"StudentRoster Difference Jan-1 - Jan-2": id Name score isEnrolled Comment 112 Nick was 1.11| now 1.21 False Graduated 113 Zoe 4.12 was True | now False was "" | now "On vacation" </code></pre></li> </ol> <p>I suppose I could do a row by row and column by column comparison, but is there an easier way?</p>
<p>The first part is similar to Constantine, you can get the boolean of which rows are empty*:</p> <pre><code>In [21]: ne = (df1 != df2).any(1) In [22]: ne Out[22]: 0 False 1 True 2 True dtype: bool </code></pre> <p>Then we can see which entries have changed:</p> <pre><code>In [23]: ne_stacked = (df1 != df2).stack() In [24]: changed = ne_stacked[ne_stacked] In [25]: changed.index.names = ['id', 'col'] In [26]: changed Out[26]: id col 1 score True 2 isEnrolled True Comment True dtype: bool </code></pre> <p><em>Here the first entry is the index and the second the columns which has been changed.</em></p> <pre><code>In [27]: difference_locations = np.where(df1 != df2) In [28]: changed_from = df1.values[difference_locations] In [29]: changed_to = df2.values[difference_locations] In [30]: pd.DataFrame({'from': changed_from, 'to': changed_to}, index=changed.index) Out[30]: from to id col 1 score 1.11 1.21 2 isEnrolled True False Comment None On vacation </code></pre> <p>* Note: it's important that <code>df1</code> and <code>df2</code> share the same index here. To overcome this ambiguity, you can ensure you only look at the shared labels using <code>df1.index &amp; df2.index</code>, but I think I'll leave that as an exercise.</p>
{ "question_id": 17095101, "question_date": "2013-06-13T19:08:16.757Z", "question_score": 225, "tags": "python|pandas|dataframe", "answer_id": 17095620, "answer_date": "2013-06-13T19:39:44.703Z", "answer_score": 174 }
Please answer the following Stack Overflow question: Title: HTTP Request in Swift with POST method <p>I'm trying to run a HTTP Request in Swift, to POST 2 parameters to a URL.</p> <p>Example:</p> <p>Link: <code>www.thisismylink.com/postName.php</code></p> <p>Params:</p> <pre><code>id = 13 name = Jack </code></pre> <p>What is the simplest way to do that?</p> <p>I don't even want to read the response. I just want to send that to perform changes on my database through a PHP file.</p>
<p>The key is that you want to:</p> <ul> <li>set the <code>httpMethod</code> to <code>POST</code>;</li> <li>optionally, set the <code>Content-Type</code> header, to specify how the request body was encoded, in case server might accept different types of requests;</li> <li>optionally, set the <code>Accept</code> header, to request how the response body should be encoded, in case the server might generate different types of responses; and</li> <li>set the <code>httpBody</code> to be properly encoded for the specific <code>Content-Type</code>; e.g. if <code>application/x-www-form-urlencoded</code> request, we need to percent-encode the body of the request.</li> </ul> <p>E.g., in Swift 3 and later you can:</p> <pre class="lang-swift prettyprint-override"><code>let url = URL(string: &quot;https://httpbin.org/post&quot;)! var request = URLRequest(url: url) request.setValue(&quot;application/x-www-form-urlencoded&quot;, forHTTPHeaderField: &quot;Content-Type&quot;) request.setValue(&quot;application/json&quot;, forHTTPHeaderField: &quot;Accept&quot;) request.httpMethod = &quot;POST&quot; let parameters: [String: Any] = [ &quot;id&quot;: 13, &quot;name&quot;: &quot;Jack &amp; Jill&quot; ] request.httpBody = parameters.percentEncoded() let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, let response = response as? HTTPURLResponse, error == nil else { // check for fundamental networking error print(&quot;error&quot;, error ?? URLError(.badServerResponse)) return } guard (200 ... 299) ~= response.statusCode else { // check for http errors print(&quot;statusCode should be 2xx, but is \(response.statusCode)&quot;) print(&quot;response = \(response)&quot;) return } // do whatever you want with the `data`, e.g.: do { let responseObject = try JSONDecoder().decode(ResponseObject&lt;Foo&gt;.self, from: data) print(responseObject) } catch { print(error) // parsing error if let responseString = String(data: data, encoding: .utf8) { print(&quot;responseString = \(responseString)&quot;) } else { print(&quot;unable to parse response as string&quot;) } } } task.resume() </code></pre> <p>Where the following extensions facilitate the percent-encoding request body, converting a Swift <code>Dictionary</code> to a <code>application/x-www-form-urlencoded</code> formatted <code>Data</code>:</p> <pre class="lang-swift prettyprint-override"><code>extension Dictionary { func percentEncoded() -&gt; Data? { map { key, value in let escapedKey = &quot;\(key)&quot;.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? &quot;&quot; let escapedValue = &quot;\(value)&quot;.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? &quot;&quot; return escapedKey + &quot;=&quot; + escapedValue } .joined(separator: &quot;&amp;&quot;) .data(using: .utf8) } } extension CharacterSet { static let urlQueryValueAllowed: CharacterSet = { let generalDelimitersToEncode = &quot;:#[]@&quot; // does not include &quot;?&quot; or &quot;/&quot; due to RFC 3986 - Section 3.4 let subDelimitersToEncode = &quot;!$&amp;'()*+,;=&quot; var allowed: CharacterSet = .urlQueryAllowed allowed.remove(charactersIn: &quot;\(generalDelimitersToEncode)\(subDelimitersToEncode)&quot;) return allowed }() } </code></pre> <p>And the following <code>Decodable</code> model objects facilitate the parsing of the <code>application/json</code> response using <code>JSONDecoder</code>:</p> <pre class="lang-swift prettyprint-override"><code>// sample Decodable objects for https://httpbin.org struct ResponseObject&lt;T: Decodable&gt;: Decodable { let form: T // often the top level key is `data`, but in the case of https://httpbin.org, it echos the submission under the key `form` } struct Foo: Decodable { let id: String let name: String } </code></pre> <p>This checks for both fundamental networking errors as well as high-level HTTP errors. This also properly percent escapes the parameters of the query.</p> <p>Note, I used a <code>name</code> of <code>Jack &amp; Jill</code>, to illustrate the proper <code>x-www-form-urlencoded</code> result of <code>name=Jack%20%26%20Jill</code>, which is “percent encoded” (i.e. the space is replaced with <code>%20</code> and the <code>&amp;</code> in the value is replaced with <code>%26</code>).</p> <hr /> <p>See <a href="https://stackoverflow.com/revisions/26365148/5">previous revision of this answer</a> for Swift 2 rendition.</p>
{ "question_id": 26364914, "question_date": "2014-10-14T15:47:14.153Z", "question_score": 225, "tags": "post|swift|parameters|http-post|httprequest", "answer_id": 26365148, "answer_date": "2014-10-14T15:59:30.643Z", "answer_score": 468 }
Please answer the following Stack Overflow question: Title: How to "crop" a rectangular image into a square with CSS? <p>I know that it is impossible to actually modify an image with CSS, which is why I put crop in quotes. </p> <p>What I'd like to do is take rectangular images and use CSS to make them appear square without distorting the image at all.</p> <p>I'd basically like to turn this:</p> <p><img src="https://i.stack.imgur.com/GA6bB.png" alt="enter image description here"></p> <p>Into this:</p> <p><img src="https://i.stack.imgur.com/ZPSrK.png" alt="enter image description here"></p>
<p>Assuming they do not have to be in IMG tags...</p> <p><strong>HTML:</strong></p> <pre class="lang-html prettyprint-override"><code>&lt;div class=&quot;thumb1&quot;&gt; &lt;/div&gt; </code></pre> <p><strong>CSS:</strong></p> <pre class="lang-css prettyprint-override"><code>.thumb1 { background: url(blah.jpg) 50% 50% no-repeat; /* 50% 50% centers image in div */ width: 250px; height: 250px; } .thumb1:hover { YOUR HOVER STYLES HERE } </code></pre> <p>EDIT: If the div needs to link somewhere just adjust HTML and Styles like so:</p> <p><strong>HTML:</strong></p> <pre class="lang-html prettyprint-override"><code>&lt;div class=&quot;thumb1&quot;&gt; &lt;a href=&quot;#&quot;&gt;Link&lt;/a&gt; &lt;/div&gt; </code></pre> <p><strong>CSS:</strong></p> <pre class="lang-css prettyprint-override"><code>.thumb1 { background: url(blah.jpg) 50% 50% no-repeat; /* 50% 50% centers image in div */ width: 250px; height: 250px; } .thumb1 a { display: block; width: 250px; height: 250px; } .thumb1 a:hover { YOUR HOVER STYLES HERE } </code></pre> <p>Note this could also be modified to be responsive, for example % widths and heights etc.</p>
{ "question_id": 15167545, "question_date": "2013-03-01T21:58:58.137Z", "question_score": 225, "tags": "html|css|image|crop", "answer_id": 15167623, "answer_date": "2013-03-01T22:04:21.237Z", "answer_score": 88 }
Please answer the following Stack Overflow question: Title: How can I use Guzzle to send a POST request in JSON? <p>Does anybody know the correct way to <code>post</code> JSON using <code>Guzzle</code>?</p> <pre><code>$request = $this-&gt;client-&gt;post(self::URL_REGISTER,array( 'content-type' =&gt; 'application/json' ),array(json_encode($_POST))); </code></pre> <p>I get an <code>internal server error</code> response from the server. It works using Chrome <code>Postman</code>.</p>
<p>For <strong>Guzzle &lt;= 4</strong>:</p> <p>It's a raw post request so putting the JSON in the body solved the problem</p> <pre><code>$request = $this-&gt;client-&gt;post( $url, [ 'content-type' =&gt; 'application/json' ], ); $request-&gt;setBody($data); #set body! $response = $request-&gt;send(); </code></pre>
{ "question_id": 22244738, "question_date": "2014-03-07T08:06:37.220Z", "question_score": 225, "tags": "php|postman|guzzle", "answer_id": 22245541, "answer_date": "2014-03-07T08:56:21.987Z", "answer_score": 53 }
Please answer the following Stack Overflow question: Title: What's the easiest way to install a missing Perl module? <p>I get this error:</p> <p><code>Can't locate Foo.pm in @INC</code></p> <p>Is there an easier way to install it than downloading, untarring, making, etc?</p>
<p><strong>On Unix</strong>:</p> <p>usually you start <em>cpan</em> in your shell:</p> <p><code>$ cpan</code></p> <p>and type</p> <p><code>install Chocolate::Belgian</code></p> <p>or in short form:</p> <p><code>cpan Chocolate::Belgian</code></p> <p><strong>On Windows</strong>:</p> <blockquote> <p>If you're using ActivePerl on Windows, the <a href="http://docs.activestate.com/activeperl/5.10/faq/ActivePerl-faq2.html#pkg_operations" rel="noreferrer">PPM (Perl Package Manager)</a> has much of the same functionality as CPAN.pm.</p> </blockquote> <p>Example:</p> <p><code>$ ppm</code><br/> <code>ppm&gt; search net-smtp</code><br/> <code>ppm&gt; install Net-SMTP-Multipart</code></p> <p><strong>see <a href="http://www.cpan.org/misc/cpan-faq.html#How_install_Perl_modules" rel="noreferrer">How do I install Perl modules?</a> in the CPAN FAQ</strong></p> <p>Many distributions ship a lot of perl modules as packages.</p> <ul> <li>Debian/Ubuntu: <code>apt-cache search 'perl$'</code></li> <li>Arch Linux: <code>pacman -Ss '^perl-'</code></li> <li>Gentoo: category <code>dev-perl</code></li> </ul> <p>You should <em>always</em> prefer them as you benefit from automatic (security) <strong>updates</strong> and the ease of <strong>removal</strong>. This can be pretty tricky with the <em>cpan</em> tool itself.</p> <p>For Gentoo there's a nice tool called <strong><a href="https://wiki.gentoo.org/wiki/Project:Perl/g-cpan" rel="noreferrer">g-cpan</a></strong> which builds/installs the module from CPAN and creates a Gentoo package (<a href="http://en.wikipedia.org/wiki/Ebuild" rel="noreferrer">ebuild</a>) for you.</p>
{ "question_id": 65865, "question_date": "2008-09-15T19:16:07.910Z", "question_score": 225, "tags": "perl|module|cpan", "answer_id": 65883, "answer_date": "2008-09-15T19:17:52.553Z", "answer_score": 260 }
Please answer the following Stack Overflow question: Title: How to print register values in GDB? <p>How do I print the value of <code>%eax</code> and <code>%ebp</code>?</p> <pre><code>(gdb) p $eax $1 = void </code></pre>
<p><code>info registers</code> shows all the registers; <code>info registers eax</code> shows just the register <code>eax</code>. The command can be abbreviated as <code>i r</code></p>
{ "question_id": 5429137, "question_date": "2011-03-25T06:07:58.113Z", "question_score": 225, "tags": "gdb|cpu-registers", "answer_id": 5429148, "answer_date": "2011-03-25T06:09:27.943Z", "answer_score": 289 }
Please answer the following Stack Overflow question: Title: Getting HTTP code in PHP using curl <p>I'm using CURL to get the status of a site, if it's up/down or redirecting to another site. I want to get it as streamlined as possible, but it's not working well.</p> <pre><code>&lt;?php $ch = curl_init($url); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch,CURLOPT_TIMEOUT,10); $output = curl_exec($ch); $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); return $httpcode; ?&gt; </code></pre> <p>I have this wrapped in a function. It works fine but performance is not the best because it downloads the whole page, thing in if I remove <code>$output = curl_exec($ch);</code> it returns <code>0</code> all the time.</p> <p>Does anyone know how to make the performance better?</p>
<p>First make sure if the URL is actually valid (a string, not empty, good syntax), this is quick to check server side. For example, doing this first could save a lot of time:</p> <pre><code>if(!$url || !is_string($url) || ! preg_match('/^http(s)?:\/\/[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(\/.*)?$/i', $url)){ return false; } </code></pre> <p>Make sure you only fetch the headers, not the body content:</p> <pre><code>@curl_setopt($ch, CURLOPT_HEADER , true); // we want headers @curl_setopt($ch, CURLOPT_NOBODY , true); // we don't need body </code></pre> <p>For more details on getting the URL status http code I refer to another post I made (it also helps with following redirects):</p> <ul> <li><a href="https://stackoverflow.com/questions/2280394/check-if-an-url-exists-in-php/12628971#12628971">How can I check if a URL exists via PHP?</a></li> </ul> <hr> <p>As a whole:</p> <pre><code>$url = 'http://www.example.com'; $ch = curl_init($url); curl_setopt($ch, CURLOPT_HEADER, true); // we want headers curl_setopt($ch, CURLOPT_NOBODY, true); // we don't need body curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_TIMEOUT,10); $output = curl_exec($ch); $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); echo 'HTTP code: ' . $httpcode; </code></pre>
{ "question_id": 11797680, "question_date": "2012-08-03T14:27:34Z", "question_score": 225, "tags": "php|performance|curl|http-headers", "answer_id": 12629254, "answer_date": "2012-09-27T20:07:42.323Z", "answer_score": 334 }
Please answer the following Stack Overflow question: Title: What is the syntax to insert one list into another list in python? <p>Given two lists:</p> <pre><code>x = [1,2,3] y = [4,5,6] </code></pre> <p>What is the syntax to:</p> <ol> <li>Insert <code>x</code> into <code>y</code> such that <code>y</code> now looks like <code>[1, 2, 3, [4, 5, 6]]</code>?</li> <li>Insert all the items of <code>x</code> into <code>y</code> such that <code>y</code> now looks like <code>[1, 2, 3, 4, 5, 6]</code>?</li> </ol>
<p>Do you mean <code>append</code>?</p> <pre><code>&gt;&gt;&gt; x = [1,2,3] &gt;&gt;&gt; y = [4,5,6] &gt;&gt;&gt; x.append(y) &gt;&gt;&gt; x [1, 2, 3, [4, 5, 6]] </code></pre> <p>Or merge?</p> <pre><code>&gt;&gt;&gt; x = [1,2,3] &gt;&gt;&gt; y = [4,5,6] &gt;&gt;&gt; x + y [1, 2, 3, 4, 5, 6] &gt;&gt;&gt; x.extend(y) &gt;&gt;&gt; x [1, 2, 3, 4, 5, 6] </code></pre>
{ "question_id": 3748063, "question_date": "2010-09-20T00:41:13.507Z", "question_score": 225, "tags": "python|list|append|extend", "answer_id": 3748071, "answer_date": "2010-09-20T00:46:01.840Z", "answer_score": 404 }
Please answer the following Stack Overflow question: Title: Android splash screen image sizes to fit all devices <p>I have a full screen PNG I want to display on splash. Only one error there, and I have no idea what size to put in every drawable folder (<code>ldpi</code>, <code>mdpi</code>, <code>hdpi</code>, and <code>xhdpi</code>). My application is supposed to run good and beautiful on all phones and tablets. What sizes (in pixels) should I create so the splash displays nice on all screens?</p>
<h1>Disclaimer</h1> <p>This answer is from 2013 and is seriously outdated. As of Android 3.2 there are now 6 groups of screen density. This answer will be updated as soon as I am able, but with no ETA. Refer to the <a href="http://developer.android.com/guide/practices/screens_support.html" rel="noreferrer">official documentation</a> for all the densities at the moment (although information on specific pixel sizes is as always hard to find). </p> <h1>Here's the tl/dr version</h1> <ul> <li><p>Create 4 images, one for each screen density: </p> <ul> <li>xlarge (xhdpi): 640x960</li> <li>large (hdpi): 480x800</li> <li>medium (mdpi): 320x480</li> <li>small (ldpi): 240x320</li> </ul></li> <li><p>Read <a href="http://developer.android.com/training/multiscreen/screensizes.html#TaskUse9Patch" rel="noreferrer">9-patch image introduction</a> in Android Developer Guide</p></li> <li>Design images that have areas that can be safely stretched without compromising the end result</li> </ul> <p>With this, Android will select the appropriate file for the device's image density, then it will stretch the image according to the 9-patch standard.</p> <h1>end of tl;dr. Full post ahead</h1> <p>I am answering in respect to the design-related aspect of the question. I am not a developer, so I won't be able to provide code for implementing many of the solutions provided. Alas, my intent is to help designers who are as lost as I was when I helped develop my first Android App.</p> <h2>Fitting all sizes</h2> <p>With Android, companies can develop their mobile phones and tables of almost any size, with almost any resolution they want. Because of that, there is no "right image size" for a splash screen, as there are no fixed screen resolutions. That poses a problem for people that want to implement a splash screen.</p> <h3>Do your users really want to see a splash screen?</h3> <p>(On a side note, splash screens are somewhat discouraged among the usability guys. It is argued that the user already knows what app he tapped on, and branding your image with a splash screen is not necessary, as it only interrupts the user experience with an "ad". It should be used, however, in applications that require some considerable loading when initialized (5s+), including games and such, so that the user is not stuck wondering if the app crashed or not)</p> <h2>Screen density; 4 classes</h2> <p>So, given so many different screen resolutions in the phones on the market, Google implemented some alternatives and nifty solutions that can help. The first thing you have to know is that Android separates <em>ALL</em> screens into 4 distinct screen densities:</p> <ol> <li>Low Density (ldpi ~ 120dpi)</li> <li>Medium Density (mdpi ~ 160dpi)</li> <li>High Density (hdpi ~ 240dpi)</li> <li>Extra-High Density (xhdpi ~ 320dpi) (These dpi values are approximations, since custom built devices will have varying dpi values)</li> </ol> <p>What you (if you're a designer) need to know from this is that Android basically chooses from 4 images to display, depending on the device. So you basically have to design 4 different images (although more can be developed for different formats such as widescreen, portrait/landscape mode, etc).</p> <p>With that in mind know this: unless you design a screen for every single resolution that is used in Android, your image will stretch to fit screen size. And unless your image is basically a gradient or blur, you'll get some undesired distortion with the stretching. So you have basically two options: create an image for each screen size/density combination, or create four 9-patch images.</p> <p>The hardest solution is to design a different splash screen for every single resolution. You can start by following the resolutions in the table at the end of <a href="http://developer.android.com/guide/practices/screens_support.html#testing" rel="noreferrer">this page</a> (there are more. Example: 960 x 720 is not listed there). And assuming you have some small detail in the image, such as small text, you have to design more than one screen for each resolution. For example, a 480x800 image being displayed in a medium screen might look ok, but on a smaller screen (with higher density/dpi) the logo might become too small, or some text might become unreadable.</p> <h2>9-patch image</h2> <p>The other solution is to <a href="http://developer.android.com/tools/help/draw9patch.html" rel="noreferrer">create a 9-patch image</a>. It is basically a 1-pixel-transparent-border around your image, and by drawing black pixels in the top and left area of this border you can define which portions of your image will be allowed to stretch. I won't go into the details of how 9-patch images work but, in short, the pixels that align to the markings in the top and left area are the pixels that will be repeated to stretch the image. </p> <h3>A few ground rules</h3> <ol> <li>You can make these images in photoshop (or any image editing software that can accurately create transparent pngs).</li> <li>The 1-pixel border has to be FULL TRANSPARENT.</li> <li>The 1-pixel transparent border has to be all around your image, not just top and left.</li> <li>you can only draw black (#000000) pixels in this area.</li> <li>The top and left borders (which define the image stretching) can only have one dot (1px x 1px), two dots (both 1px x 1px) or ONE continuous line (width x 1px or 1px x height).</li> <li>If you choose to use 2 dots, the image will be expanded proportionally (so each dot will take turns expanding until the final width/height is achieved)</li> <li>The 1px border has to be in addition to the intended base file dimensions. So a 100x100 9-patch image has to actually have 102x102 (100x100 +1px on top, bottom, left and right)</li> <li>9-patch images have to end with *.9.png</li> </ol> <p>So you can place 1 dot on either side of your logo (in the top border), and 1 dot above and below it (on the left border), and these marked rows and columns will be the only pixels to stretch.</p> <h2>Example</h2> <p>Here's a 9-patch image, 102x102px (100x100 final size, for app purposes):</p> <p><img src="https://i.stack.imgur.com/AZv2V.png" alt="9-patch image, 102x102px"></p> <p>Here's a 200% zoom of the same image:</p> <p><img src="https://i.stack.imgur.com/KD99c.png" alt="the same image, magnified 2x for clarity"></p> <p>Notice the 1px marks on top and left saying which rows/columns will expand.</p> <p>Here's what this image would look like in 100x100 inside the app:</p> <p><img src="https://i.stack.imgur.com/2cH0F.png" alt="rendered into 100x100"></p> <p>And here's what it would like if expanded to 460x140:</p> <p><img src="https://i.stack.imgur.com/9Ol8e.png" alt="rendered into 460x140"></p> <p>One last thing to consider. These images might look fine on your monitor screen and on most mobiles, but if the device has a very high image density (dpi), the image would look too small. Probably still legible, but on a tablet with 1920x1200 resolution, the image would appear as a very small square in the middle. So what's the solution? Design 4 different 9-patch launcher images, each for a different density set. To ensure that no shrinking will occur, you should design in the lowest common resolution for each density category. Shrinking is undesirable here because 9-patch only accounts for stretching, so in a shrinking process small text and other elements might lose legibility.</p> <p>Here's a list of the smallest, most common resolutions for each density category:</p> <ul> <li>xlarge (xhdpi): 640x960</li> <li>large (hdpi): 480x800</li> <li>medium (mdpi): 320x480</li> <li>small (ldpi): 240x320</li> </ul> <p>So design four splash screens in the above resolutions, expand the images, putting a 1px transparent border around the canvas, and mark which rows/columns will be stretchable. Keep in mind these images will be used for <em>ANY</em> device in the density category, so your ldpi image (240 x 320) might be stretched to 1024x600 on an extra large tablet with small image density (~120 dpi). So 9-patch is the best solution for the stretching, as long as you don't want a photo or complicated graphics for a splash screen (keep in mind these limitations as you create the design).</p> <p>Again, the only way for this stretching not to happen is to design one screen each resolution (or one for each resolution-density combination, if you want to avoid images becoming too small/big on high/low density devices), or to tell the image not to stretch and have a background color appear wherever stretching would occur (also remember that a specific color rendered by the Android engine will probably look different from the same specific color rendered by photoshop, because of color profiles).</p> <p>I hope this made any sense. Good luck!</p>
{ "question_id": 10574363, "question_date": "2012-05-13T18:55:50.463Z", "question_score": 225, "tags": "android|png|screen|drawable|splash-screen", "answer_id": 15744389, "answer_date": "2013-04-01T13:27:39.093Z", "answer_score": 407 }
Please answer the following Stack Overflow question: Title: "Register" an .exe so you can run it from any command line in Windows <p>How can you make a .exe file accessible from any location in the Windows command window? Is there some registry entry that has to be entered?</p>
<p>You need to make sure that the exe is in a folder that's on the <code>PATH</code> environment variable.</p> <p>You can do this by either installing it into a folder that's already on the <code>PATH</code> or by adding your folder to the <code>PATH</code>.</p> <p>You can have your installer do this - but you may need to restart the machine to make sure it gets picked up.</p>
{ "question_id": 4822400, "question_date": "2011-01-27T21:59:22.730Z", "question_score": 225, "tags": "windows", "answer_id": 4822427, "answer_date": "2011-01-27T22:02:55.750Z", "answer_score": 145 }
Please answer the following Stack Overflow question: Title: Font-awesome, input type 'submit' <p>There seems to be no class for input type 'submit' in font-awesome. Is it possible to use some class from font-awesome for button input? I've added icons to all buttons (which actually links with class 'btn' from twitter-bootstrap) in my applications, but can't add icons on 'input type submit'. </p> <p>Or, how to use this code:</p> <pre><code>input#image-button{ background: #ccc url('icon.png') no-repeat top left; padding-left: 16px; height: 16px; } </code></pre> <p>html:</p> <pre><code>&lt;input type="submit" id="image-button"&gt;Text&lt;/input&gt; </code></pre> <p>(which I took from <a href="https://stackoverflow.com/questions/1621891/html-how-to-make-a-submit-button-with-text-image-in-it">HTML: How to make a submit button with text + image in it?</a>) with font-awesome?</p>
<p>use button type="submit" instead of input</p> <pre><code>&lt;button type="submit" class="btn btn-success"&gt; &lt;i class="fa fa-arrow-circle-right fa-lg"&gt;&lt;/i&gt; Next &lt;/button&gt; </code></pre> <p>for Font Awesome 3.2.0 use</p> <pre><code>&lt;button type="submit" class="btn btn-success"&gt; &lt;i class="icon-circle-arrow-right icon-large"&gt;&lt;/i&gt; Next &lt;/button&gt; </code></pre>
{ "question_id": 11686007, "question_date": "2012-07-27T10:29:23.347Z", "question_score": 225, "tags": "twitter-bootstrap|twitter-bootstrap-rails|font-awesome", "answer_id": 12152157, "answer_date": "2012-08-28T02:48:45.560Z", "answer_score": 379 }
Please answer the following Stack Overflow question: Title: How can I time a code segment for testing performance with Pythons timeit? <p>I've a python script which works just as it should, but I need to write the execution time. I've googled that I should use <a href="https://docs.python.org/2/library/timeit.html" rel="noreferrer"><code>timeit</code></a> but I can't seem to get it to work.</p> <p>My Python script looks like this:</p> <pre><code>import sys import getopt import timeit import random import os import re import ibm_db import time from string import maketrans myfile = open("results_update.txt", "a") for r in range(100): rannumber = random.randint(0, 100) update = "update TABLE set val = %i where MyCount &gt;= '2010' and MyCount &lt; '2012' and number = '250'" % rannumber #print rannumber conn = ibm_db.pconnect("dsn=myDB","usrname","secretPWD") for r in range(5): print "Run %s\n" % r ibm_db.execute(query_stmt) query_stmt = ibm_db.prepare(conn, update) myfile.close() ibm_db.close(conn) </code></pre> <p>What I need is the time it takes to execute the query and write it to the file <code>results_update.txt</code>. The purpose is to test an update statement for my database with different indexes and tuning mechanisms.</p>
<p>You can use <a href="https://docs.python.org/3/library/time.html#time.time" rel="noreferrer"><code>time.time()</code></a> or <a href="https://docs.python.org/3/library/time.html#time.clock" rel="noreferrer"><code>time.clock()</code></a> before and after the block you want to time.</p> <pre><code>import time t0 = time.time() code_block t1 = time.time() total = t1-t0 </code></pre> <p>This method is not as exact as <a href="https://docs.python.org/3/library/timeit.html" rel="noreferrer"><code>timeit</code></a> (it does not average several runs) but it is straightforward. </p> <p><code>time.time()</code> (in Windows and Linux) and <code>time.clock()</code> (in Linux) are not precise enough for fast functions (you get total = 0). In this case or if you want to average the time elapsed by several runs, you have to manually call the function multiple times (As I think you already do in you example code and timeit does automatically when you set its <em>number</em> argument)</p> <pre><code>import time def myfast(): code n = 10000 t0 = time.time() for i in range(n): myfast() t1 = time.time() total_n = t1-t0 </code></pre> <p>In Windows, as Corey stated in the comment, <code>time.clock()</code> has much higher precision (microsecond instead of second) and is preferred over <code>time.time()</code>.</p>
{ "question_id": 2866380, "question_date": "2010-05-19T14:24:46.200Z", "question_score": 225, "tags": "python|testing|timeit|database-tuning", "answer_id": 2866456, "answer_date": "2010-05-19T14:32:35.007Z", "answer_score": 365 }
Please answer the following Stack Overflow question: Title: Docker-Compose persistent data MySQL <p>I can't seem to get MySQL data to persist if I run <code>$ docker-compose down</code> with the following <code>.yml</code></p> <pre><code>version: '2' services: # other services data: container_name: flask_data image: mysql:latest volumes: - /var/lib/mysql command: "true" mysql: container_name: flask_mysql restart: always image: mysql:latest environment: MYSQL_ROOT_PASSWORD: 'test_pass' # TODO: Change this MYSQL_USER: 'test' MYSQL_PASS: 'pass' volumes_from: - data ports: - "3306:3306" </code></pre> <p>My understanding is that in my <code>data</code> container using <code>volumes: - /var/lib/mysql</code> maps it to my local machines directory where mysql stores data to the container and because of this mapping the data should persist even if the containers are destroyed. And the <code>mysql</code> container is just a client interface into the db and can see the local directory because of <code>volumes_from: - data</code></p> <p>Attempted this answer and it did not work. <a href="https://stackoverflow.com/questions/34511336/docker-compose-persistent-data-trouble">Docker-Compose Persistent Data Trouble</a></p> <p><strong>EDIT</strong></p> <p>Changed my <code>.yml</code> as shown below and created a the dir <code>./data</code> but now when I run <code>docker-compose up --build</code> the <code>mysql</code> container wont start throws error saying</p> <pre><code> data: container_name: flask_data image: mysql:latest volumes: - ./data:/var/lib/mysql command: "true" mysql: container_name: flask_mysql restart: always image: mysql:latest environment: MYSQL_ROOT_PASSWORD: 'test_pass' # TODO: Change this MYSQL_USER: 'test' MYSQL_PASS: 'pass' volumes_from: - data ports: - "3306:3306" flask_mysql | mysqld: Can't create/write to file '/var/lib/mysql/is_writable' (Errcode: 13 - Permission denied) flask_mysql | 2016-08-26T22:29:21.182144Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details). flask_mysql | 2016-08-26T22:29:21.185392Z 0 [ERROR] --initialize specified but the data directory exists and is not writable. Aborting. </code></pre>
<p>The data container is a superfluous workaround. <a href="https://docs.docker.com/engine/tutorials/dockervolumes/" rel="noreferrer">Data-volumes</a> would do the trick for you. Alter your <code>docker-compose.yml</code> to:</p> <pre><code>version: '2' services: mysql: container_name: flask_mysql restart: always image: mysql:latest environment: MYSQL_ROOT_PASSWORD: 'test_pass' # TODO: Change this MYSQL_USER: 'test' MYSQL_PASS: 'pass' volumes: - my-datavolume:/var/lib/mysql volumes: my-datavolume: </code></pre> <p>Docker will create the volume for you in the <code>/var/lib/docker/volumes</code> folder. This volume persist as long as you are not typing <code>docker-compose down -v</code></p>
{ "question_id": 39175194, "question_date": "2016-08-26T22:00:50.653Z", "question_score": 225, "tags": "docker|docker-compose", "answer_id": 39208187, "answer_date": "2016-08-29T14:01:06.847Z", "answer_score": 334 }
Please answer the following Stack Overflow question: Title: How to increment a datetime by one day? <p>How to increment the day of a datetime?</p> <pre><code>for i in range(1, 35) date = datetime.datetime(2003, 8, i) print(date) </code></pre> <p>But I need pass through months and years correctly? Any ideas?</p>
<pre><code>date = datetime.datetime(2003,8,1,12,4,5) for i in range(5): date += datetime.timedelta(days=1) print(date) </code></pre>
{ "question_id": 3240458, "question_date": "2010-07-13T18:58:04.683Z", "question_score": 225, "tags": "python|datetime", "answer_id": 3240486, "answer_date": "2010-07-13T19:01:46.483Z", "answer_score": 365 }
Please answer the following Stack Overflow question: Title: jQuery - add additional parameters on submit (NOT ajax) <p>Using jQuery's 'submit' - is there a way to pass additional parameters to a form? I am NOT looking to do this with Ajax - this is normal, refresh-typical form submission.</p> <pre><code>$('#submit').click(function () { $('#event').submit(function () { data: { form['attendees'] = $('#attendance').sortable('toArray').toString(); }); }); </code></pre>
<p>This one did it for me:</p> <pre><code>var input = $("&lt;input&gt;") .attr("type", "hidden") .attr("name", "mydata").val("bla"); $('#form1').append(input); </code></pre> <p>is based on the Daff's answer, but added the NAME attribute to let it show in the form collection and changed VALUE to VAL Also checked the ID of the FORM (form1 in my case)</p> <p>used the Firefox firebug to check whether the element was inserted.</p> <p>Hidden elements do get posted back in the form collection, only read-only fields are discarded.</p> <p>Michel</p>
{ "question_id": 2530635, "question_date": "2010-03-27T19:29:50.327Z", "question_score": 225, "tags": "jquery|parameter-passing|form-submit", "answer_id": 2531379, "answer_date": "2010-03-27T23:49:40.660Z", "answer_score": 399 }
Please answer the following Stack Overflow question: Title: Lists in ConfigParser <p>The typical ConfigParser generated file looks like:</p> <pre><code>[Section] bar=foo [Section 2] bar2= baz </code></pre> <p>Now, is there a way to index lists like, for instance:</p> <pre><code>[Section 3] barList={ item1, item2 } </code></pre> <p>Related question: <a href="https://stackoverflow.com/questions/287757/pythons-configparser-unique-keys-per-section">Python’s ConfigParser unique keys per section</a></p>
<p>There is nothing stopping you from packing the list into a delimited string and then unpacking it once you get the string from the config. If you did it this way your config section would look like:</p> <pre><code>[Section 3] barList=item1,item2 </code></pre> <p>It's not pretty but it's functional for most simple lists.</p>
{ "question_id": 335695, "question_date": "2008-12-02T22:29:05.743Z", "question_score": 225, "tags": "python|configparser", "answer_id": 335754, "answer_date": "2008-12-02T22:56:44.517Z", "answer_score": 164 }
Please answer the following Stack Overflow question: Title: Get Android API level of phone currently running my application <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/2768806/programmatically-obtain-the-android-api-level-of-a-device">Programmatically obtain the Android API level of a device?</a> </p> </blockquote> <p>How do I get the Api level of the phone curently running my application? I am sure its simple but I can not find it as all my searches bring up tons of junk.</p>
<p>Check <a href="http://developer.android.com/reference/android/os/Build.VERSION.html" rel="noreferrer"><code>android.os.Build.VERSION</code></a>, which is a static class that holds various pieces of information about the Android OS a system is running.</p> <p>If you care about all versions possible (back to original Android version), as in <a href="http://developer.android.com/guide/topics/manifest/uses-sdk-element.html" rel="noreferrer"><code>minSdkVersion</code></a> is set to anything less than 4, then you will have to use <a href="http://developer.android.com/reference/android/os/Build.VERSION.html#SDK" rel="noreferrer"><code>android.os.Build.VERSION.SDK</code></a>, which is a <code>String</code> that can be converted to the integer of the release.</p> <p>If you are on at least API version 4 (Android 1.6 Donut), the current suggested way of getting the API level would be to check the value of <a href="http://developer.android.com/reference/android/os/Build.VERSION.html#SDK_INT" rel="noreferrer"><code>android.os.Build.VERSION.SDK_INT</code></a>, which is an integer.</p> <p>In either case, the integer you get maps to an enum value from all those defined in <a href="http://developer.android.com/reference/android/os/Build.VERSION_CODES.html" rel="noreferrer"><code>android.os.Build.VERSION_CODES</code></a>:</p> <pre><code>SDK_INT value Build.VERSION_CODES Human Version Name 1 BASE Android 1.0 (no codename) 2 BASE_1_1 Android 1.1 Petit Four 3 CUPCAKE Android 1.5 Cupcake 4 DONUT Android 1.6 Donut 5 ECLAIR Android 2.0 Eclair 6 ECLAIR_0_1 Android 2.0.1 Eclair 7 ECLAIR_MR1 Android 2.1 Eclair 8 FROYO Android 2.2 Froyo 9 GINGERBREAD Android 2.3 Gingerbread 10 GINGERBREAD_MR1 Android 2.3.3 Gingerbread 11 HONEYCOMB Android 3.0 Honeycomb 12 HONEYCOMB_MR1 Android 3.1 Honeycomb 13 HONEYCOMB_MR2 Android 3.2 Honeycomb 14 ICE_CREAM_SANDWICH Android 4.0 Ice Cream Sandwich 15 ICE_CREAM_SANDWICH_MR1 Android 4.0.3 Ice Cream Sandwich 16 JELLY_BEAN Android 4.1 Jellybean 17 JELLY_BEAN_MR1 Android 4.2 Jellybean 18 JELLY_BEAN_MR2 Android 4.3 Jellybean 19 KITKAT Android 4.4 KitKat 20 KITKAT_WATCH Android 4.4 KitKat Watch 21 LOLLIPOP Android 5.0 Lollipop 22 LOLLIPOP_MR1 Android 5.1 Lollipop 23 M Android 6.0 Marshmallow 24 N Android 7.0 Nougat 25 N_MR1 Android 7.1.1 Nougat 26 O Android 8.0 Oreo 27 O_MR1 Android 8 Oreo MR1 28 P Android 9 Pie 29 Q Android 10 10000 CUR_DEVELOPMENT Current Development Version </code></pre> <p>Note that some time between Android N and O, the Android SDK began aliasing <code>CUR_DEVELOPMENT</code> and the developer preview of the next major Android version to be the same <code>SDK_INT</code> value (<code>10000</code>).</p>
{ "question_id": 3993924, "question_date": "2010-10-22T04:38:24.340Z", "question_score": 225, "tags": "android|android-api-levels", "answer_id": 3993933, "answer_date": "2010-10-22T04:40:34.650Z", "answer_score": 435 }
Please answer the following Stack Overflow question: Title: Parse query string into an array <p>How can I turn a <strong>string</strong> below into an <strong>array</strong>?</p> <pre><code>pg_id=2&amp;parent_id=2&amp;document&amp;video </code></pre> <p>This is the array I am looking for,</p> <pre><code>array( 'pg_id' =&gt; 2, 'parent_id' =&gt; 2, 'document' =&gt; , 'video' =&gt; ) </code></pre>
<p>You want the <a href="http://www.php.net/manual/en/function.parse-str.php" rel="noreferrer"><code>parse_str</code></a> function, and you need to set the second parameter to have the data put in an array instead of into individual variables.</p> <pre><code>$get_string = "pg_id=2&amp;parent_id=2&amp;document&amp;video"; parse_str($get_string, $get_array); print_r($get_array); </code></pre>
{ "question_id": 5397726, "question_date": "2011-03-22T20:55:06.440Z", "question_score": 225, "tags": "php|arrays|string", "answer_id": 5397786, "answer_date": "2011-03-22T21:01:54.593Z", "answer_score": 377 }
Please answer the following Stack Overflow question: Title: How do you uninstall MySQL from Mac OS X? <p>I accidentally installed the PowerPC version of MySQL on my Intel Mac in Snow Leopard, and it installed without a problem but of course doesn't run properly. I just didn't pay enough attention. Now when I try to install the correct x86 version it says that it can't install because a newer version is already installed. A Google query led me to perform these actions/delete these files to uninstall it:</p> <pre><code>sudo rm /usr/local/mysql sudo rm -rf /usr/local/mysql* sudo rm -rf /Library/StartupItems/MySQLCOM sudo rm -rf /Library/PreferencePanes/MySQL* rm -rf ~/Library/PreferencePanes/MySQL* sudo rm -rf /Library/Receipts/mysql* sudo rm -rf /Library/Receipts/MySQL* </code></pre> <p>And finally removed the line MYSQLCOM=-YES- from <code>/etc/hostconfig</code></p> <p>They haven't seemed to help at all. I am still receiving the same message about there being a newer version. I tried installing an even newer version (the current Beta) and it also gave me the same message about a newer version already being installed. I can't uninstall it from the Prefs Pane because I never installed the PrefPane also.</p>
<p>Try running also</p> <pre><code>sudo rm -rf /var/db/receipts/com.mysql.* </code></pre>
{ "question_id": 1436425, "question_date": "2009-09-17T02:26:26.483Z", "question_score": 225, "tags": "mysql|macos|osx-snow-leopard", "answer_id": 1447758, "answer_date": "2009-09-19T04:40:39.533Z", "answer_score": 234 }
Please answer the following Stack Overflow question: Title: vuejs update parent data from child component <p>I'm starting to play with vuejs (2.0). I built a simple page with one component in it. The page has one Vue instance with data. On that page I registered and added the component to html. The component has one <code>input[type=text]</code>. I want that value to reflect on the parent (main Vue instance).</p> <p>How do I correctly update the component's parent data? Passing a bound prop from the parent is not good and throws some warnings to the console. They have something in their doc but it is not working.</p>
<p>Two-way binding has been deprecated in Vue 2.0 in favor of using a more event-driven architecture. In general, a child should not mutate its props. Rather, it should <a href="https://v2.vuejs.org/v2/api/#vm-emit" rel="nofollow noreferrer"><code>$emit</code></a> events and let the parent respond to those events.</p> <p>In your specific case, you could use a custom component with <code>v-model</code>. This is a special syntax which allows for something close to two-way binding, but is actually a shorthand for the event-driven architecture described above. You can read about it here -&gt; <a href="https://v2.vuejs.org/v2/guide/components.html#Form-Input-Components-using-Custom-Events" rel="nofollow noreferrer">https://v2.vuejs.org/v2/guide/components.html#Form-Input-Components-using-Custom-Events</a>.</p> <p>Here's a simple example:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>Vue.component('child', { template: '#child', //The child has a prop named 'value'. v-model will automatically bind to this prop props: ['value'], methods: { updateValue: function (value) { this.$emit('input', value); } } }); new Vue({ el: '#app', data: { parentValue: 'hello' } });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"&gt;&lt;/script&gt; &lt;div id="app"&gt; &lt;p&gt;Parent value: {{parentValue}}&lt;/p&gt; &lt;child v-model="parentValue"&gt;&lt;/child&gt; &lt;/div&gt; &lt;template id="child"&gt; &lt;input type="text" v-bind:value="value" v-on:input="updateValue($event.target.value)"&gt; &lt;/template&gt;</code></pre> </div> </div> </p> <hr /> <p>The docs state that</p> <pre><code>&lt;custom-input v-bind:value=&quot;something&quot; v-on:input=&quot;something = arguments[0]&quot;&gt;&lt;/custom-input&gt; </code></pre> <p>is equivalent to</p> <pre><code>&lt;custom-input v-model=&quot;something&quot;&gt;&lt;/custom-input&gt; </code></pre> <p>That is why the prop on the child needs to be named value, and why the child needs to $emit an event named <code>input</code>.</p>
{ "question_id": 40915436, "question_date": "2016-12-01T16:16:13.157Z", "question_score": 225, "tags": "javascript|vue.js|vue-component", "answer_id": 40915857, "answer_date": "2016-12-01T16:36:34.963Z", "answer_score": 242 }
Please answer the following Stack Overflow question: Title: How to hide the Google Invisible reCAPTCHA badge <p>When implementing the new Google Invisible reCATPTCHA, by default you get a little "protected by reCAPTCHA" badge in the bottom right of the screen that pops out when you roll over it.</p> <p><a href="https://i.stack.imgur.com/F8oS0.png" rel="noreferrer"><img src="https://i.stack.imgur.com/F8oS0.png" alt="enter image description here"></a></p> <p>I'd like to hide this.</p>
<p>Set the <code>data-badge</code> attribute to <code>inline</code></p> <pre><code>&lt;button type="submit" data-sitekey="your_site_key" data-callback="onSubmit" data-badge="inline" /&gt; </code></pre> <p>And add the following CSS</p> <pre><code>.grecaptcha-badge { display: none; } </code></pre>
{ "question_id": 44543157, "question_date": "2017-06-14T11:13:17.543Z", "question_score": 225, "tags": "javascript|recaptcha", "answer_id": 44543220, "answer_date": "2017-06-14T11:16:22.467Z", "answer_score": 35 }
Please answer the following Stack Overflow question: Title: Python Flask, how to set content type <p>I am using Flask and I return an XML file from a get request. How do I set the content type to xml ?</p> <p>e.g.</p> <pre><code>@app.route('/ajax_ddl') def ajax_ddl(): xml = 'foo' header("Content-type: text/xml") return xml </code></pre>
<p>Try like this:</p> <pre><code>from flask import Response @app.route('/ajax_ddl') def ajax_ddl(): xml = 'foo' return Response(xml, mimetype='text/xml') </code></pre> <p>The actual Content-Type is based on the mimetype parameter and the charset (defaults to UTF-8).</p> <p>Response (and request) objects are documented here: <a href="http://werkzeug.pocoo.org/docs/wrappers/" rel="noreferrer">http://werkzeug.pocoo.org/docs/wrappers/</a></p>
{ "question_id": 11773348, "question_date": "2012-08-02T08:03:16.640Z", "question_score": 225, "tags": "python|flask", "answer_id": 11774026, "answer_date": "2012-08-02T08:49:39.080Z", "answer_score": 318 }
Please answer the following Stack Overflow question: Title: How to make a variadic macro (variable number of arguments) <p>I want to write a macro in C that accepts any number of parameters, not a specific number</p> <p>example:</p> <pre><code>#define macro( X ) something_complicated( whatever( X ) ) </code></pre> <p>where <code>X</code> is any number of parameters</p> <p>I need this because <code>whatever</code> is overloaded and can be called with 2 or 4 parameters.</p> <p>I tried defining the macro twice, but the second definition overwrote the first one!</p> <p>The compiler I'm working with is g++ (more specifically, mingw)</p>
<p>C99 way, also supported by VC++ compiler.</p> <pre><code>#define FOO(fmt, ...) printf(fmt, ##__VA_ARGS__) </code></pre>
{ "question_id": 679979, "question_date": "2009-03-25T02:08:15.040Z", "question_score": 225, "tags": "c|g++|c-preprocessor|variadic", "answer_id": 679993, "answer_date": "2009-03-25T02:16:27.753Z", "answer_score": 331 }
Please answer the following Stack Overflow question: Title: Ternary operators in JavaScript without an "else" <p>I've always had to put <code>null</code> in the else conditions that don't have anything. Is there a way around it?</p> <p>For example,</p> <pre><code>condition ? x = true : null; </code></pre> <p>Basically, is there a way to do the following?</p> <pre><code>condition ? x = true; </code></pre> <p>Now it shows up as a syntax error.</p> <p>FYI, here is some real example code:</p> <pre><code>!defaults.slideshowWidth ? defaults.slideshowWidth = obj.find('img').width()+'px' : null; </code></pre>
<p>First of all, a ternary expression is not a replacement for an if/else construct - it's an equivalent to an if/else construct that <strong>returns</strong> a value. That is, an if/else clause is code, a ternary expression is an <strong>expression</strong>, meaning that it returns a value.</p> <p>This means several things:</p> <ul> <li>use ternary expressions only when you have a variable on the left side of the <code>=</code> that is to be assigned the return value</li> <li>only use ternary expressions when the returned value is to be one of two values (or use nested expressions if that is fitting)</li> <li>each part of the expression (after ? and after : ) should return a value without side effects (the expression <code>x = true</code> returns true as all expressions return the last value, but it also changes x without x having any effect on the returned value)</li> </ul> <p>In short - the 'correct' use of a ternary expression is</p> <pre><code>var resultofexpression = conditionasboolean ? truepart: falsepart; </code></pre> <p>Instead of your example <code>condition ? x=true : null ;</code>, where you use a ternary expression to set the value of <code>x</code>, you can use this:</p> <pre><code> condition &amp;&amp; (x = true); </code></pre> <p>This is still an expression and might therefore not pass validation, so an even better approach would be</p> <pre><code> void(condition &amp;&amp; x = true); </code></pre> <p>The last one will pass validation.</p> <p>But then again, if the expected value is a boolean, just use the result of the condition expression itself</p> <pre><code>var x = (condition); // var x = (foo == &quot;bar&quot;); </code></pre> <hr /> <h3>UPDATE</h3> <p>In relation to your sample, this is probably more appropriate:</p> <pre><code>defaults.slideshowWidth = defaults.slideshowWidth || obj.find('img').width()+'px'; </code></pre>
{ "question_id": 2932754, "question_date": "2010-05-28T21:50:58.107Z", "question_score": 225, "tags": "javascript|optimization|syntax-error", "answer_id": 2933472, "answer_date": "2010-05-29T02:08:28.917Z", "answer_score": 328 }
Please answer the following Stack Overflow question: Title: Cookies vs. sessions <p>I started using PHP a couple of months ago. For the sake of creating a login system for my website, I read about cookies and sessions and their differences (cookies are stored in the user's browser and sessions on the server). At that time, I preferred cookies (and who does not like cookies?!) and just said: "who cares? I don't have any good deal with storing it in my server", so, I went ahead and used cookies for my bachelor graduation project. However, after doin' the big part of my app, I heard that for the particular case of storing user's ID, sessions are more appropriate. So I started thinking about what would I say if the jury asks me why have you used cookies instead of sessions? I have just that reason (that I do not need to store internally information about the user). Is that enough <em>as a reason</em>? or it's more than that? <br/>Could you please tell me about advantages/disadvantages of using cookies for keeping User's ID?</p> <p>Thanks for you all in StackOverflow!</p>
<p>The concept is storing persistent data across page loads for a web visitor. Cookies store it directly on the client. Sessions use a cookie as a key of sorts, to associate with the data that is stored on the server side.</p> <p>It is preferred to use sessions because the actual values are hidden from the client, and you control when the data expires and becomes invalid. If it was all based on cookies, a user (or hacker) could manipulate their cookie data and then play requests to your site.</p> <p>Edit: I don't think there is any advantage to using cookies, other than simplicity. Look at it this way... Does the user have any reason to know their ID#? Typically I would say no, the user has no need for this information. Giving out information should be limited on a need to know basis. What if the user changes his cookie to have a different ID, how will your application respond? It's a security risk.</p> <p>Before sessions were all the rage, I basically had my own implementation. I stored a unique cookie value on the client, and stored my persistent data in the database along with that cookie value. Then on page requests I matched up those values and had my persistent data without letting the client control what that was.</p>
{ "question_id": 6253633, "question_date": "2011-06-06T14:36:25.803Z", "question_score": 225, "tags": "php|session|cookies", "answer_id": 6253698, "answer_date": "2011-06-06T14:40:50.867Z", "answer_score": 273 }
Please answer the following Stack Overflow question: Title: How to add hovering annotations to a plot <p>I am using matplotlib to make scatter plots. Each point on the scatter plot is associated with a named object. I would like to be able to see the name of an object when I hover my cursor over the point on the scatter plot associated with that object. In particular, it would be nice to be able to quickly see the names of the points that are outliers. The closest thing I have been able to find while searching here is the annotate command, but that appears to create a fixed label on the plot. Unfortunately, with the number of points that I have, the scatter plot would be unreadable if I labeled each point. Does anyone know of a way to create labels that only appear when the cursor hovers in the vicinity of that point?</p>
<p>It seems none of the other answers here actually answer the question. So here is a code that uses a <strong>scatter</strong> and shows an <strong>annotation</strong> upon <strong>hovering</strong> over the scatter points.</p> <pre><code>import matplotlib.pyplot as plt import numpy as np; np.random.seed(1) x = np.random.rand(15) y = np.random.rand(15) names = np.array(list("ABCDEFGHIJKLMNO")) c = np.random.randint(1,5,size=15) norm = plt.Normalize(1,4) cmap = plt.cm.RdYlGn fig,ax = plt.subplots() sc = plt.scatter(x,y,c=c, s=100, cmap=cmap, norm=norm) annot = ax.annotate("", xy=(0,0), xytext=(20,20),textcoords="offset points", bbox=dict(boxstyle="round", fc="w"), arrowprops=dict(arrowstyle="-&gt;")) annot.set_visible(False) def update_annot(ind): pos = sc.get_offsets()[ind["ind"][0]] annot.xy = pos text = "{}, {}".format(" ".join(list(map(str,ind["ind"]))), " ".join([names[n] for n in ind["ind"]])) annot.set_text(text) annot.get_bbox_patch().set_facecolor(cmap(norm(c[ind["ind"][0]]))) annot.get_bbox_patch().set_alpha(0.4) def hover(event): vis = annot.get_visible() if event.inaxes == ax: cont, ind = sc.contains(event) if cont: update_annot(ind) annot.set_visible(True) fig.canvas.draw_idle() else: if vis: annot.set_visible(False) fig.canvas.draw_idle() fig.canvas.mpl_connect("motion_notify_event", hover) plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/y3ll8.png" rel="noreferrer"><img src="https://i.stack.imgur.com/y3ll8.png" alt="enter image description here"></a></p> <p>Because people also want to use this solution for a line <code>plot</code> instead of a scatter, the following would be the same solution for <code>plot</code> (which works slightly differently).</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-css lang-css prettyprint-override"><code>import matplotlib.pyplot as plt import numpy as np; np.random.seed(1) x = np.sort(np.random.rand(15)) y = np.sort(np.random.rand(15)) names = np.array(list("ABCDEFGHIJKLMNO")) norm = plt.Normalize(1,4) cmap = plt.cm.RdYlGn fig,ax = plt.subplots() line, = plt.plot(x,y, marker="o") annot = ax.annotate("", xy=(0,0), xytext=(-20,20),textcoords="offset points", bbox=dict(boxstyle="round", fc="w"), arrowprops=dict(arrowstyle="-&gt;")) annot.set_visible(False) def update_annot(ind): x,y = line.get_data() annot.xy = (x[ind["ind"][0]], y[ind["ind"][0]]) text = "{}, {}".format(" ".join(list(map(str,ind["ind"]))), " ".join([names[n] for n in ind["ind"]])) annot.set_text(text) annot.get_bbox_patch().set_alpha(0.4) def hover(event): vis = annot.get_visible() if event.inaxes == ax: cont, ind = line.contains(event) if cont: update_annot(ind) annot.set_visible(True) fig.canvas.draw_idle() else: if vis: annot.set_visible(False) fig.canvas.draw_idle() fig.canvas.mpl_connect("motion_notify_event", hover) plt.show()</code></pre> </div> </div> </p> <p>In case someone is looking for a solution for lines in twin axes, refer to <a href="https://stackoverflow.com/questions/55891285/how-to-make-labels-appear-when-hovering-over-a-point-in-multiple-axis/55892690#55892690">How to make labels appear when hovering over a point in multiple axis?</a></p> <p>In case someone is looking for a solution for bar plots, please refer to e.g. <a href="https://stackoverflow.com/a/50560826/4124317">this answer</a>.</p>
{ "question_id": 7908636, "question_date": "2011-10-26T20:38:14.653Z", "question_score": 225, "tags": "python|pandas|matplotlib|seaborn|mplcursors", "answer_id": 47166787, "answer_date": "2017-11-07T20:23:41.403Z", "answer_score": 223 }
Please answer the following Stack Overflow question: Title: Angular 2 router no base href set <p>I am getting an error and can't find why. Here is the error:</p> <pre><code>EXCEPTION: Error during instantiation of LocationStrategy! (RouterOutlet -&gt; Router -&gt; Location -&gt; LocationStrategy). angular2.dev.js:23514 EXCEPTION: Error during instantiation of LocationStrategy! (RouterOutlet -&gt; Router -&gt; Location -&gt; LocationStrategy).BrowserDomAdapter.logError @ angular2.dev.js:23514BrowserDomAdapter.logGroup @ angular2.dev.js:23525ExceptionHandler.call @ angular2.dev.js:1145(anonymous function) @ angular2.dev.js:14801NgZone._notifyOnError @ angular2.dev.js:5796collection_1.StringMapWrapper.merge.onError @ angular2.dev.js:5700run @ angular2-polyfills.js:141(anonymous function) @ angular2.dev.js:5719zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:1511lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:1523lib$es6$promise$$internal$$publish @ angular2-polyfills.js:1494(anonymous function) @ angular2-polyfills.js:243microtask @ angular2.dev.js:5751run @ angular2-polyfills.js:138(anonymous function) @ angular2.dev.js:5719zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$asap$$flush @ angular2-polyfills.js:1305 angular2.dev.js:23514 ORIGINAL EXCEPTION: No base href set. Please provide a value for the APP_BASE_HREF token or add a base element to the document.BrowserDomAdapter.logError @ angular2.dev.js:23514ExceptionHandler.call @ angular2.dev.js:1154(anonymous function) @ angular2.dev.js:14801NgZone._notifyOnError @ angular2.dev.js:5796collection_1.StringMapWrapper.merge.onError @ angular2.dev.js:5700run @ angular2-polyfills.js:141(anonymous function) @ angular2.dev.js:5719zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:1511lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:1523lib$es6$promise$$internal$$publish @ angular2-polyfills.js:1494(anonymous function) @ angular2-polyfills.js:243microtask @ angular2.dev.js:5751run @ angular2-polyfills.js:138(anonymous function) @ angular2.dev.js:5719zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$asap$$flush @ angular2-polyfills.js:1305 angular2.dev.js:23514 ORIGINAL STACKTRACE:BrowserDomAdapter.logError @ angular2.dev.js:23514ExceptionHandler.call @ angular2.dev.js:1157(anonymous function) @ angular2.dev.js:14801NgZone._notifyOnError @ angular2.dev.js:5796collection_1.StringMapWrapper.merge.onError @ angular2.dev.js:5700run @ angular2-polyfills.js:141(anonymous function) @ angular2.dev.js:5719zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:1511lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:1523lib$es6$promise$$internal$$publish @ angular2-polyfills.js:1494(anonymous function) @ angular2-polyfills.js:243microtask @ angular2.dev.js:5751run @ angular2-polyfills.js:138(anonymous function) @ angular2.dev.js:5719zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$asap$$flush @ angular2-polyfills.js:1305 angular2.dev.js:23514 Error: No base href set. Please provide a value for the APP_BASE_HREF token or add a base element to the document. at new BaseException (angular2.dev.js:8080) at new PathLocationStrategy (router.dev.js:1203) at angular2.dev.js:1380 at Injector._instantiate (angular2.dev.js:11923) at Injector._instantiateProvider (angular2.dev.js:11859) at Injector._new (angular2.dev.js:11849) at InjectorDynamicStrategy.getObjByKeyId (angular2.dev.js:11733) at Injector._getByKeyDefault (angular2.dev.js:12048) at Injector._getByKey (angular2.dev.js:12002) at Injector._getByDependency (angular2.dev.js:11990) </code></pre> <p>Does anyone know why the router is throwing this? I am using angular2 beta</p> <p>here is my code:</p> <pre class="lang-ts prettyprint-override"><code>import {Component} from 'angular2/core'; import { RouteConfig, ROUTER_DIRECTIVES } from 'angular2/router'; import {LoginComponent} from './pages/login/login.component'; import {DashboardComponent} from './pages/dashboard/dashboard.component'; @Component({ selector: 'app', directives:[ROUTER_DIRECTIVES], template:` &lt;div class="wrapper"&gt; &lt;router-outlet&gt;&lt;/router-outlet&gt; &lt;/div&gt;` }) @RouteConfig([ { path: '/',redirectTo: '/dashboard' }, { path: '/login',name:'login',component: LoginComponent }, { path: '/dashboard',name:'dashboard',component: DashboardComponent,} ]) export class AppComponent { } </code></pre>
<p><a href="https://angular.io/docs/ts/latest/guide/router.html" rel="noreferrer">https://angular.io/docs/ts/latest/guide/router.html</a></p> <blockquote> <p>Add the base element just after the <code>&lt;head&gt;</code> tag. If the <code>app</code> folder is the application root, as it is for our application, set the <code>href</code> value <em>exactly</em> as shown here.</p> </blockquote> <p>The <code>&lt;base href="/"&gt;</code> tells the Angular router what is the static part of the URL. The router then only modifies the remaining part of the URL.</p> <pre class="lang-ts prettyprint-override"><code>&lt;head&gt; &lt;base href="/"&gt; ... &lt;/head&gt; </code></pre> <p>Alternatively add </p> <p><strong>>= Angular2 RC.6</strong></p> <pre class="lang-ts prettyprint-override"><code>import {APP_BASE_HREF} from '@angular/common'; @NgModule({ declarations: [AppComponent], imports: [routing /* or RouterModule */], providers: [{provide: APP_BASE_HREF, useValue : '/' }] ]); </code></pre> <p>in your bootstrap.</p> <p>In older versions the imports had to be like</p> <p><strong>&lt; Angular2 RC.6</strong></p> <pre class="lang-ts prettyprint-override"><code>import {APP_BASE_HREF} from '@angular/common'; bootstrap(AppComponent, [ ROUTER_PROVIDERS, {provide: APP_BASE_HREF, useValue : '/' }); ]); </code></pre> <p><strong>&lt; RC.0</strong></p> <pre class="lang-ts prettyprint-override"><code>import {provide} from 'angular2/core'; bootstrap(AppComponent, [ ROUTER_PROVIDERS, provide(APP_BASE_HREF, {useValue : '/' }); ]); </code></pre> <p><strong>&lt; beta.17</strong></p> <pre class="lang-ts prettyprint-override"><code>import {APP_BASE_HREF} from 'angular2/router'; </code></pre> <p><strong>>= beta.17</strong></p> <pre class="lang-ts prettyprint-override"><code>import {APP_BASE_HREF} from 'angular2/platform/common'; </code></pre> <p>See also <a href="https://stackoverflow.com/questions/36861628/location-and-hashlocationstrategy-stopped-working-in-beta-16/36861629#36861629">Location and HashLocationStrategy stopped working in beta.16</a></p>
{ "question_id": 34535163, "question_date": "2015-12-30T18:34:37.740Z", "question_score": 225, "tags": "angular|routes|href", "answer_id": 34535256, "answer_date": "2015-12-30T18:40:32.977Z", "answer_score": 409 }
Please answer the following Stack Overflow question: Title: Android Webview gives net::ERR_CACHE_MISS message <p>I built a web app and wants to create an android app that has a webview that shows my web app. After following the instructions from Google Developer to create an app, I successfully installed it on my phone with Android 5.1.1.</p> <p>However, when I run the app for the first time, the webview shows the message:</p> <blockquote> <p>Web page not available</p> <p>The Web page at [Lorem Ipsum URL] could not be loaded as:</p> <p>net::ERR_CACHE_MISS</p> </blockquote>
<p>Answers assembled! I wanted to just combine all the answers into one comprehensive one.</p> <p><strong>1.</strong> Check if <code>&lt;uses-permission android:name="android.permission.INTERNET" /&gt;</code> is present in <code>manifest.xml</code>. <strong>Make sure that it is nested under <code>&lt;manifest&gt;</code> and not <code>&lt;application&gt;</code></strong>. Thanks to <a href="https://stackoverflow.com/users/6629042/sajid45">sajid45</a> and <a href="https://stackoverflow.com/users/9701254/liyanis-velazquez">Liyanis Velazquez</a></p> <p><strong>2.</strong> Ensure that you are using <code>&lt;uses-permission android:name="android.permission.INTERNET"/&gt;</code> instead of the deprecated <code>&lt;uses-permission android:name="android.permission.internet"/&gt;</code>. Much thanks to <a href="https://stackoverflow.com/users/5133469/alan-shi">alan_shi</a> and <a href="https://stackoverflow.com/users/3903990/creos">creos</a>.</p> <p><strong>3.</strong> If minimum version is below KK, check that you have </p> <pre><code>if (18 &lt; Build.VERSION.SDK_INT ){ //18 = JellyBean MR2, KITKAT=19 mWeb.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); } </code></pre> <p>or </p> <pre><code>if (Build.VERSION.SDK_INT &gt;= 19) { mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); } </code></pre> <p>because proper webview is only added in KK (SDK 19). Thanks to <a href="https://stackoverflow.com/users/1310448/devavrata">Devavrata</a>, <a href="https://stackoverflow.com/users/6572459/mike-chanseong-kim">Mike ChanSeong Kim</a> and <a href="https://stackoverflow.com/users/9701254/liyanis-velazquez">Liyanis Velazquez</a></p> <p><strong>4.</strong> Ensure that you don't have <code>webView.getSettings().setBlockNetworkLoads (false);</code>. Thanks to <a href="https://stackoverflow.com/users/2197176/technikh">TechNikh</a> for pointing this out.</p> <p><strong>5.</strong> If all else fails, make sure that your Android Studio, Android SDK and the emulator image (if you are using one) is updated. And if you are still meeting the problem, just open a new question and make a comment below to your URL.</p>
{ "question_id": 30637654, "question_date": "2015-06-04T07:30:42.160Z", "question_score": 225, "tags": "android|android-studio|webview", "answer_id": 60647176, "answer_date": "2020-03-12T03:23:40.640Z", "answer_score": 57 }
Please answer the following Stack Overflow question: Title: Selecting multiple classes with jQuery <p>I’ve had a good look and can’t seem to find out how to select all elements matching certain classes in one jQuery selector statement such as this:</p> <pre><code>$('.myClass', '.myOtherClass').removeClass('theclass'); </code></pre> <p>Any ideas on how to achieve this? The only other option is to do</p> <pre><code>$('.myClass').removeClass('theclass'); $('.myOtherClass').removeClass('theclass'); </code></pre> <p>But I’m doing this with quite a few classes, so it requires much code.</p>
<p>This should work:</p> <p><code>$('.myClass, .myOtherClass').removeClass('theclass');</code></p> <p>You must add the multiple selectors all in the first argument to $(), otherwise you are giving jQuery a context in which to search, which is not what you want.</p> <p>It's the same as you would do in CSS.</p>
{ "question_id": 488305, "question_date": "2009-01-28T16:27:07.960Z", "question_score": 225, "tags": "javascript|jquery|jquery-selectors", "answer_id": 488324, "answer_date": "2009-01-28T16:29:25.707Z", "answer_score": 408 }
Please answer the following Stack Overflow question: Title: JavaScript data grid for millions of rows <p>I need to present a large number of rows of data (ie. millions of rows) to the user in a grid using JavaScript.</p> <p>The user shouldn't see pages or view only finite amounts of data at a time.</p> <p>Rather, it should appear that all of the data are available.</p> <p>Instead of downloading the data all at once, small chunks are downloaded as the user comes to them (ie. by scrolling through the grid).</p> <p>The rows will not be edited through this front end, so read-only grids are acceptable.</p> <p>What data grids, written in JavaScript, exist for this kind of seamless paging?</p>
<p>(<strong>Disclaimer: I am the author of SlickGrid</strong>)</p> <p><strong>UPDATE</strong> This has now been implemented in <a href="https://github.com/mleibman/SlickGrid" rel="noreferrer">SlickGrid</a>.</p> <p>Please see <a href="http://github.com/mleibman/SlickGrid/issues#issue/22" rel="noreferrer">http://github.com/mleibman/SlickGrid/issues#issue/22</a> for an ongoing discussion on making SlickGrid work with larger numbers of rows.</p> <p>The problem is that SlickGrid does not virtualize the scrollbar itself - the scrollable area's height is set to the total height of all the rows. The rows are still being added and removed as the user is scrolling, but the scrolling itself is done by the browser. That allows it to be very fast yet smooth (onscroll events are notoriously slow). The caveat is that there are bugs/limits in the browsers' CSS engines that limit the potential height of an element. For IE, that happens to be 0x123456 or 1193046 pixels. For other browsers it is higher. </p> <p>There is an experimental workaround in the "largenum-fix" branch that raises that limit significantly by populating the scrollable area with "pages" set to 1M pixels height and then using relative positioning within those pages. Since the height limit in the CSS engine seems to be different and significantly lower than in the actual layout engine, this gives us a much higher upper limit.</p> <p>I am still looking for a way to get to unlimited number of rows without giving up the performance edge that SlickGrid currently holds over other implementations.</p> <p>Rudiger, can you elaborate on how you solved this?</p>
{ "question_id": 2402953, "question_date": "2010-03-08T16:47:24.257Z", "question_score": 225, "tags": "javascript|jquery|html|datagrid|slickgrid", "answer_id": 2569488, "answer_date": "2010-04-02T22:18:18.437Z", "answer_score": 191 }
Please answer the following Stack Overflow question: Title: DbEntityValidationException - How can I easily tell what caused the error? <p>I have a project that uses Entity Framework. While calling <code>SaveChanges</code> on my <code>DbContext</code>, I get the following exception:</p> <blockquote> <p>System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.</p> </blockquote> <p>This is all fine and dandy, but I don't want to attach a debugger every time this exception occurs. More over, in production environments I cannot easily attach a debugger so I have to go to great lengths to reproduce these errors. </p> <p>How can I see the details hidden within the <code>DbEntityValidationException</code>?</p>
<p>The easiest solution is to override <code>SaveChanges</code> on your entities class. You can catch the <code>DbEntityValidationException</code>, unwrap the actual errors and create a new <code>DbEntityValidationException</code> with the improved message.</p> <ol> <li>Create a partial class next to your SomethingSomething.Context.cs file.</li> <li>Use the code at the bottom of this post. </li> <li>That's it. Your implementation will automatically use the overriden SaveChanges without any refactor work.</li> </ol> <p>Your exception message will now look like this:</p> <blockquote> <p>System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details. The validation errors are: The field PhoneNumber must be a string or array type with a maximum length of '12'; The LastName field is required.</p> </blockquote> <p>You can drop the overridden SaveChanges in any class that inherits from <code>DbContext</code>:</p> <pre><code>public partial class SomethingSomethingEntities { public override int SaveChanges() { try { return base.SaveChanges(); } catch (DbEntityValidationException ex) { // Retrieve the error messages as a list of strings. var errorMessages = ex.EntityValidationErrors .SelectMany(x =&gt; x.ValidationErrors) .Select(x =&gt; x.ErrorMessage);      // Join the list to a single string. var fullErrorMessage = string.Join("; ", errorMessages);      // Combine the original exception message with the new one. var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);      // Throw a new DbEntityValidationException with the improved exception message. throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors); } } } </code></pre> <p>The <code>DbEntityValidationException</code> also contains the entities that caused the validation errors. So if you require even more information, you can change the above code to output information about these entities.</p> <p><strong>See also: <a href="http://devillers.nl/improving-dbentityvalidationexception/">http://devillers.nl/improving-dbentityvalidationexception/</a></strong></p>
{ "question_id": 15820505, "question_date": "2013-04-04T19:54:47.010Z", "question_score": 225, "tags": "c#|entity-framework", "answer_id": 15820506, "answer_date": "2013-04-04T19:54:47.010Z", "answer_score": 440 }
Please answer the following Stack Overflow question: Title: Send POST request using NSURLSession <p><strong>Update:</strong> Solution found. You can read it at the end of the post.</p> <p>I'm trying to perform a POST request to a remote REST API using <code>NSURLSession</code>. The idea is to make a request with two parameters: <code>deviceId</code> and <code>textContent</code>.</p> <p>The problem is that those parameters are not recognized by the server. The server part works correctly because I've sent a POST using POSTMAN for Google Chrome and it worked perfectly.</p> <p>This is the code I'm using right now:</p> <pre><code>NSString *deviceID = [[NSUserDefaults standardUserDefaults] objectForKey:@"deviceID"]; NSString *textContent = @"New note"; NSString *noteDataString = [NSString stringWithFormat:@"deviceId=%@&amp;textContent=%@", deviceID, textContent]; NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration]; sessionConfiguration.HTTPAdditionalHeaders = @{ @"api-key" : @"API_KEY", @"Content-Type" : @"application/json" }; NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration]; NSURL *url = [NSURL URLWithString:@"http://url_to_manage_post_requests"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; request.HTTPBody = [noteDataString dataUsingEncoding:NSUTF8StringEncoding]; request.HTTPMethod = @"POST"; NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { // The server answers with an error because it doesn't receive the params }]; [postDataTask resume]; </code></pre> <p>I've tried the same procedure with a <code>NSURLSessionUploadTask</code>:</p> <pre><code>// ... NSURL *url = [NSURL URLWithString:@"http://url_to_manage_post_requests"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; request.HTTPMethod = @"POST"; NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:[noteDataString dataUsingEncoding:NSUTF8StringEncoding] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { // The server answers with an error because it doesn't receive the params }]; [uploadTask resume]; </code></pre> <p>Any ideas?</p> <h2>Solution</h2> <p>The problem with my approach was that I was sending the incorrect <code>Content-Type</code> header with all my requests. So the only change needed for the code to work correctly is to remove the <code>Content-Type = application/json</code> HTTP header. So the correct code would be this:</p> <pre><code>NSString *deviceID = [[NSUserDefaults standardUserDefaults] objectForKey:@"deviceID"]; NSString *textContent = @"New note"; NSString *noteDataString = [NSString stringWithFormat:@"deviceId=%@&amp;textContent=%@", deviceID, textContent]; NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration]; sessionConfiguration.HTTPAdditionalHeaders = @{ @"api-key" : @"API_KEY" }; NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration]; NSURL *url = [NSURL URLWithString:@"http://url_to_manage_post_requests"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; request.HTTPBody = [noteDataString dataUsingEncoding:NSUTF8StringEncoding]; request.HTTPMethod = @"POST"; NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { // The server answers with an error because it doesn't receive the params }]; [postDataTask resume]; </code></pre> <h2>Sending images along with other parameters</h2> <p>If you need to post images along with other parameters using <code>NSURLSession</code> here you have an example:</p> <pre><code>NSString *deviceID = [[NSUserDefaults standardUserDefaults] objectForKey:@"deviceID"]; NSString *textContent = @"This is a new note"; // Build the request body NSString *boundary = @"SportuondoFormBoundary"; NSMutableData *body = [NSMutableData data]; // Body part for "deviceId" parameter. This is a string. [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", @"deviceId"] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"%@\r\n", deviceID] dataUsingEncoding:NSUTF8StringEncoding]]; // Body part for "textContent" parameter. This is a string. [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", @"textContent"] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"%@\r\n", textContent] dataUsingEncoding:NSUTF8StringEncoding]]; // Body part for the attachament. This is an image. NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"ranking"], 0.6); if (imageData) { [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", @"image"] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:imageData]; [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; } [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; // Setup the session NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration]; sessionConfiguration.HTTPAdditionalHeaders = @{ @"api-key" : @"55e76dc4bbae25b066cb", @"Accept" : @"application/json", @"Content-Type" : [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary] }; // Create the session // We can use the delegate to track upload progress NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil]; // Data uploading task. We could use NSURLSessionUploadTask instead of NSURLSessionDataTask if we needed to support uploads in the background NSURL *url = [NSURL URLWithString:@"URL_TO_UPLOAD_TO"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; request.HTTPMethod = @"POST"; request.HTTPBody = body; NSURLSessionDataTask *uploadTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { // Process the response }]; [uploadTask resume]; </code></pre>
<p>You could try using a NSDictionary for the params. The following will send the parameters correctly to a JSON server.</p> <pre><code>NSError *error; NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil]; NSURL *url = [NSURL URLWithString:@"[JSON SERVER"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [request addValue:@"application/json" forHTTPHeaderField:@"Accept"]; [request setHTTPMethod:@"POST"]; NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: @"TEST IOS", @"name", @"IOS TYPE", @"typemap", nil]; NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&amp;error]; [request setHTTPBody:postData]; NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { }]; [postDataTask resume]; </code></pre> <p>Hope this helps (I'm trying to sort a CSRF authenticity issue with the above - but it does send the params in the NSDictionary).</p>
{ "question_id": 19099448, "question_date": "2013-09-30T16:43:18.730Z", "question_score": 225, "tags": "ios|objective-c|nsurlsession", "answer_id": 19101084, "answer_date": "2013-09-30T18:21:42.517Z", "answer_score": 170 }
Please answer the following Stack Overflow question: Title: JAX-RS / Jersey how to customize error handling? <p>I'm learning JAX-RS (aka, JSR-311) using Jersey. I've successfuly created a Root Resource and am playing around with parameters:</p> <pre><code>@Path("/hello") public class HelloWorldResource { @GET @Produces("text/html") public String get( @QueryParam("name") String name, @QueryParam("birthDate") Date birthDate) { // Return a greeting with the name and age } } </code></pre> <p>This works great, and handles any format in the current locale which is understood by the Date(String) constructor (like YYYY/mm/dd and mm/dd/YYYY). But if I supply a value which is invalid or not understood, I get a 404 response.</p> <p>For example:</p> <pre class="lang-none prettyprint-override"><code>GET /hello?name=Mark&amp;birthDate=X 404 Not Found </code></pre> <p>How can I customize this behavior? Maybe a different response code (probably "400 Bad Request")? What about logging an error? Maybe add a description of the problem ("bad date format") in a custom header to aid troubleshooting? Or return a whole Error response with details, along with a 5xx status code?</p>
<p>There are several approaches to customize the error handling behavior with JAX-RS. Here are three of the easier ways.</p> <p>The first approach is to create an Exception class that extends WebApplicationException.</p> <p>Example:</p> <pre><code>public class NotAuthorizedException extends WebApplicationException { public NotAuthorizedException(String message) { super(Response.status(Response.Status.UNAUTHORIZED) .entity(message).type(MediaType.TEXT_PLAIN).build()); } } </code></pre> <p>And to throw this newly create Exception you simply:</p> <pre><code>@Path("accounts/{accountId}/") public Item getItem(@PathParam("accountId") String accountId) { // An unauthorized user tries to enter throw new NotAuthorizedException("You Don't Have Permission"); } </code></pre> <p>Notice, you don't need to declare the exception in a throws clause because WebApplicationException is a runtime Exception. This will return a 401 response to the client.</p> <p>The second and easier approach is to simply construct an instance of the <code>WebApplicationException</code> directly in your code. This approach works as long as you don't have to implement your own application Exceptions. </p> <p>Example:</p> <pre><code>@Path("accounts/{accountId}/") public Item getItem(@PathParam("accountId") String accountId) { // An unauthorized user tries to enter throw new WebApplicationException(Response.Status.UNAUTHORIZED); } </code></pre> <p>This code too returns a 401 to the client.</p> <p>Of course, this is just a simple example. You can make the Exception much more complex if necessary, and you can generate what ever http response code you need to. </p> <p>One other approach is to wrap an existing Exception, perhaps an <code>ObjectNotFoundException</code> with an small wrapper class that implements the <code>ExceptionMapper</code> interface annotated with a <code>@Provider</code> annotation. This tells the JAX-RS runtime, that if the wrapped Exception is raised, return the response code defined in the <code>ExceptionMapper</code>. </p>
{ "question_id": 583973, "question_date": "2009-02-24T22:48:41.810Z", "question_score": 225, "tags": "java|rest|error-handling|jersey|jax-rs", "answer_id": 599131, "answer_date": "2009-03-01T02:40:38.847Z", "answer_score": 279 }
Please answer the following Stack Overflow question: Title: KeyboardEvent.keyCode deprecated. What does this mean in practice? <p>According to MDN, we should most definitely <strong>not</strong> be using the <code>.keyCode</code> property. It is deprecated:</p> <p><a href="https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode</a></p> <p>On W3 school, this fact is played down and there is only a side note saying that <code>.keyCode</code> is provided for compatibility only and that the latest version of the DOM Events Specification recommend using the <code>.key</code> property instead.</p> <p>The problem is that <code>.key</code> is not supported by browsers, so what should we using? Is there something I'm missing?</p>
<p>You have three ways to handle it, as it's written on the link you shared.</p> <pre class="lang-js prettyprint-override"><code>if (event.key !== undefined) { } else if (event.keyIdentifier !== undefined) { } else if (event.keyCode !== undefined) { } </code></pre> <p>you should contemplate them, that's the right way if you want cross browser support.</p> <p>It could be easier if you implement something like this.</p> <pre class="lang-js prettyprint-override"><code>var dispatchForCode = function(event, callback) { var code; if (event.key !== undefined) { code = event.key; } else if (event.keyIdentifier !== undefined) { code = event.keyIdentifier; } else if (event.keyCode !== undefined) { code = event.keyCode; } callback(code); }; </code></pre>
{ "question_id": 35394937, "question_date": "2016-02-14T17:40:49.760Z", "question_score": 225, "tags": "javascript|key|deprecated|keycode", "answer_id": 35395154, "answer_date": "2016-02-14T17:59:03.157Z", "answer_score": 70 }
Please answer the following Stack Overflow question: Title: What is the difference between Class.getResource() and ClassLoader.getResource()? <p>I wonder what the difference is between <code>Class.getResource()</code> and <code>ClassLoader.getResource()</code>?</p> <p><em>edit: I especially want to know if any caching is involved on file/directory level. As in "are directory listings cached in the Class version?"</em></p> <p>AFAIK the following should essentially do the same, but they are not:</p> <pre><code>getClass().getResource() getClass().getClassLoader().getResource() </code></pre> <p>I discovered this when fiddling with some report generation code that creates a new file in <code>WEB-INF/classes/</code> from an existing file in that directory. When using the method from Class, I could find files that were there at deployment using <code>getClass().getResource()</code>, but when trying to fetch the newly created file, I recieved a null object. Browsing the directory clearly shows that the new file is there. The filenames were prepended with a forward slash as in "/myFile.txt".</p> <p>The <code>ClassLoader</code> version of <code>getResource()</code> on the other hand did find the generated file. From this experience it seems that there is some kind of caching of the directory listing going on. Am I right, and if so, where is this documented?</p> <p>From the <a href="http://download.oracle.com/javase/1,5.0/docs/api/java/lang/Class.html#getResource%28java.lang.String%29">API docs</a> on <code>Class.getResource()</code></p> <blockquote> <p>Finds a resource with a given name. The rules for searching resources associated with a given class are implemented by the defining class loader of the class. This method delegates to this object's class loader. If this object was loaded by the bootstrap class loader, the method delegates to ClassLoader.getSystemResource(java.lang.String).</p> </blockquote> <p>To me, this reads "Class.getResource is really calling its own classloader's getResource()". Which would be the same as doing <code>getClass().getClassLoader().getResource()</code>. But it is obviously not. Could someone please provide me with some illumination into this matter?</p>
<p>To answer the question whether there is any caching going on.</p> <p>I investigated this point further by running a stand-alone Java application that continuously loaded a file from disk using the getResourceAsStream ClassLoader method. I was able to edit the file, and the changes were reflected immediately, i.e., the file was reloaded from disk without caching.</p> <p><strong>However:</strong> I'm working on a project with several maven modules and web projects that have dependencies on each other. I'm using IntelliJ as my IDE to compile and run the web projects.</p> <p>I noticed that the above seemed to no longer hold true, the reason being that the file that I was being loaded is now baked into a jar and deployed to the depending web project. I only noticed this after trying to change the file in my target folder, to no avail. This made it seem as though there was caching going on.</p>
{ "question_id": 6608795, "question_date": "2011-07-07T09:59:33.760Z", "question_score": 225, "tags": "java|classloader|getresource", "answer_id": 10597177, "answer_date": "2012-05-15T08:49:01.323Z", "answer_score": 7 }
Please answer the following Stack Overflow question: Title: What is the Angular equivalent to an AngularJS $watch? <p>In AngularJS you were able to specify watchers to observe changes in scope variables using the <code>$watch</code> function of the <code>$scope</code>. What is the equivalent of watching for variable changes (in, for example, component variables) in Angular?</p>
<p>In Angular 2, change detection is automatic... <code>$scope.$watch()</code> and <code>$scope.$digest()</code> R.I.P.</p> <p>Unfortunately, the Change Detection section of the dev guide is not written yet (there is a placeholder near the bottom of the <a href="https://angular.io/docs/ts/latest/guide/architecture.html" rel="noreferrer">Architecture Overview</a> page, in section "The Other Stuff").</p> <p>Here's my understanding of how change detection works:</p> <ul> <li>Zone.js "monkey patches the world" -- it intercepts all of the asynchronous APIs in the browser (when Angular runs). This is why we can use <code>setTimeout()</code> inside our components rather than something like <code>$timeout</code>... because <code>setTimeout()</code> is monkey patched.</li> <li>Angular builds and maintains a tree of "change detectors". There is one such change detector (class) per component/directive. (You can get access to this object by injecting <a href="https://angular.io/docs/ts/latest/api/core/index/ChangeDetectorRef-class.html" rel="noreferrer"><code>ChangeDetectorRef</code></a>.) These change detectors are created when Angular creates components. They keep track of the state of all of your bindings, for dirty checking. These are, in a sense, similar to the automatic <code>$watches()</code> that Angular 1 would set up for <code>{{}}</code> template bindings.<br>Unlike Angular 1, the change detection graph is a directed tree and cannot have cycles (this makes Angular 2 much more performant, as we'll see below).</li> <li>When an event fires (inside the Angular zone), the code we wrote (the event handler callback) runs. It can update whatever data it wants to -- the shared application model/state and/or the component's view state.</li> <li>After that, because of the hooks Zone.js added, it then runs Angular's change detection algorithm. By default (i.e., if you are not using the <code>onPush</code> change detection strategy on any of your components), every component in the tree is examined once (TTL=1)... from the top, in depth-first order. (Well, if you're in dev mode, change detection runs twice (TTL=2). See <a href="https://angular.io/docs/ts/latest/api/core/index/ApplicationRef-class.html#!#tick-anchor" rel="noreferrer">ApplicationRef.tick()</a> for more about this.) It performs dirty checking on all of your bindings, using those change detector objects. <ul> <li>Lifecycle hooks are called as part of change detection. <br>If the component data you want to watch is a primitive input property (String, boolean, number), you can implement <code>ngOnChanges()</code> to be notified of changes. <br>If the input property is a reference type (object, array, etc.), but the reference didn't change (e.g., you added an item to an existing array), you'll need to implement <code>ngDoCheck()</code> (see <a href="https://stackoverflow.com/a/34298708/215945">this SO answer</a> for more on this). <Br>You should only change the component's properties and/or properties of descendant components (because of the single tree walk implementation -- i.e., unidirectional data flow). Here's <a href="http://plnkr.co/edit/XWBSvE0NoQlRuOsXuOm0?p=preview" rel="noreferrer">a plunker</a> that violates that. Stateful pipes can also <a href="https://stackoverflow.com/questions/34456430/ngfor-doesnt-update-data-with-pipe-in-angular2/34497504#34497504">trip you up</a> here.</li> </ul></li> <li>For any binding changes that are found, the Components are updated, and then the DOM is updated. Change detection is now finished.</li> <li>The browser notices the DOM changes and updates the screen.</li> </ul> <p>Other references to learn more:</p> <ul> <li><a href="https://blog.angularindepth.com/angulars-digest-is-reborn-in-the-newer-version-of-angular-718a961ebd3e" rel="noreferrer">Angular’s $digest is reborn in the newer version of Angular</a> - explains how the ideas from AngularJS are mapped to Angular</li> <li><a href="https://blog.angularindepth.com/everything-you-need-to-know-about-change-detection-in-angular-8006c51d206f" rel="noreferrer">Everything you need to know about change detection in Angular</a> - explains in great detail how change detection works under the hood</li> <li><a href="http://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html" rel="noreferrer">Change Detection Explained</a> - Thoughtram blog Feb 22, 2016 - probably the best reference out there</li> <li>Savkin's <a href="https://www.youtube.com/watch?v=jvKGQSFQf10" rel="noreferrer">Change Detection Reinvented</a> video - definitely watch this one</li> <li><a href="http://blog.jhades.org/how-does-angular-2-change-detection-really-work/" rel="noreferrer">How does Angular 2 Change Detection Really Work?</a>- jhade's blog Feb 24, 2016</li> <li><a href="https://www.youtube.com/watch?v=3IqtmUscE_U" rel="noreferrer">Brian's video</a> and <a href="https://www.youtube.com/watch?v=V9Bbp6Hh2YE" rel="noreferrer">Miško's video</a> about Zone.js. Brian's is about Zone.js. Miško's is about how Angular 2 uses Zone.js to implement change detection. He also talks about change detection in general, and a little bit about <code>onPush</code>.</li> <li>Victor Savkins blog posts: <a href="http://victorsavkin.com/post/110170125256/change-detection-in-angular-2" rel="noreferrer">Change Detection in Angular 2</a>, <a href="http://victorsavkin.com/post/114168430846/two-phases-of-angular-2-applications" rel="noreferrer">Two phases of Angular 2 applications</a>, <a href="http://victorsavkin.com/post/110170125256/change-detection-in-angular-2" rel="noreferrer">Angular, Immutability and Encapsulation</a>. He covers a lot of ground quickly, but he can be terse at times, and you're left scratching your head, wondering about the missing pieces.</li> <li><a href="https://docs.google.com/document/d/1QKTbyVNPyRW-otJJVauON4TFMHpl0zNBPkJcTcfPJWg/edit" rel="noreferrer">Ultra Fast Change Detection</a> (Google doc) - very technical, very terse, but it describes/sketches the ChangeDetection classes that get built as part of the tree</li> </ul>
{ "question_id": 34569094, "question_date": "2016-01-02T18:13:09.827Z", "question_score": 225, "tags": "angularjs|angular|watch|angular2-changedetection", "answer_id": 34570122, "answer_date": "2016-01-02T19:58:30.027Z", "answer_score": 279 }
Please answer the following Stack Overflow question: Title: Use of ~ (tilde) in R programming Language <p>I saw in a tutorial about regression modeling the following command:</p> <pre><code>myFormula &lt;- Species ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width </code></pre> <p>What exactly does this command do, and what is the role of <code>~</code> (tilde) in the command?</p>
<p>The thing on the right of <code>&lt;-</code> is a <a href="https://www.rdocumentation.org/packages/stats/topics/formula" rel="noreferrer"><code>formula</code></a> object. It is often used to denote a statistical model, where the thing on the left of the <code>~</code> is the response and the things on the right of the <code>~</code> are the explanatory variables. So in English you'd say something like <em>"Species depends on Sepal Length, Sepal Width, Petal Length and Petal Width"</em>.</p> <p>The <code>myFormula &lt;-</code> part of that line stores the formula in an object called <code>myFormula</code> so you can use it in other parts of your R code.</p> <hr> <p><strong>Other common uses of formula objects in R</strong></p> <p>The <code>lattice</code> package uses them to <a href="https://www.rdocumentation.org/packages/lattice/topics/B_00_xyplot" rel="noreferrer">specify the variables to plot</a>.<br> The <code>ggplot2</code> package uses them to <a href="https://www.rdocumentation.org/packages/ggplot2/topics/facet_wrap" rel="noreferrer">specify panels for plotting</a>.<br> The <code>dplyr</code> package uses them for <a href="https://cran.r-project.org/web/packages/lazyeval/vignettes/lazyeval.html" rel="noreferrer">non-standard evaulation</a>.</p>
{ "question_id": 14976331, "question_date": "2013-02-20T09:27:57.883Z", "question_score": 225, "tags": "r|r-faq|r-formula", "answer_id": 14976479, "answer_date": "2013-02-20T09:35:03.090Z", "answer_score": 228 }
Please answer the following Stack Overflow question: Title: How do I catch a numpy warning like it's an exception (not just for testing)? <p>I have to make a Lagrange polynomial in Python for a project I'm doing. I'm doing a barycentric style one to avoid using an explicit for-loop as opposed to a Newton's divided difference style one. The problem I have is that I need to catch a division by zero, but Python (or maybe numpy) just makes it a warning instead of a normal exception.</p> <p>So, what I need to know how to do is to catch this warning as if it were an exception. The related questions to this I found on this site were answered not in the way I needed. Here's my code:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import warnings class Lagrange: def __init__(self, xPts, yPts): self.xPts = np.array(xPts) self.yPts = np.array(yPts) self.degree = len(xPts)-1 self.weights = np.array([np.product([x_j - x_i for x_j in xPts if x_j != x_i]) for x_i in xPts]) def __call__(self, x): warnings.filterwarnings("error") try: bigNumerator = np.product(x - self.xPts) numerators = np.array([bigNumerator/(x - x_j) for x_j in self.xPts]) return sum(numerators/self.weights*self.yPts) except Exception, e: # Catch division by 0. Only possible in 'numerators' array return yPts[np.where(xPts == x)[0][0]] L = Lagrange([-1,0,1],[1,0,1]) # Creates quadratic poly L(x) = x^2 L(1) # This should catch an error, then return 1. </code></pre> <p>When this code is executed, the output I get is:</p> <pre><code>Warning: divide by zero encountered in int_scalars </code></pre> <p>That's the warning I want to catch. It should occur inside the list comprehension.</p>
<p>It seems that your configuration is using the <code>print</code> option for <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.seterr.html" rel="noreferrer"><code>numpy.seterr</code></a>:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; np.array([1])/0 #'warn' mode __main__:1: RuntimeWarning: divide by zero encountered in divide array([0]) &gt;&gt;&gt; np.seterr(all='print') {'over': 'warn', 'divide': 'warn', 'invalid': 'warn', 'under': 'ignore'} &gt;&gt;&gt; np.array([1])/0 #'print' mode Warning: divide by zero encountered in divide array([0]) </code></pre> <p>This means that the warning you see is <strong>not</strong> a real warning, but it's just some characters printed to <code>stdout</code>(see the documentation for <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.seterr.html" rel="noreferrer"><code>seterr</code></a>). If you want to catch it you can:</p> <ol> <li>Use <code>numpy.seterr(all='raise')</code> which will directly raise the exception. This however changes the behaviour of all the operations, so it's a pretty big change in behaviour.</li> <li>Use <code>numpy.seterr(all='warn')</code>, which will transform the printed warning in a real warning and you'll be able to use the above solution to localize this change in behaviour.</li> </ol> <p>Once you actually have a warning, you can use the <code>warnings</code> module to control how the warnings should be treated:</p> <pre><code>&gt;&gt;&gt; import warnings &gt;&gt;&gt; &gt;&gt;&gt; warnings.filterwarnings('error') &gt;&gt;&gt; &gt;&gt;&gt; try: ... warnings.warn(Warning()) ... except Warning: ... print 'Warning was raised as an exception!' ... Warning was raised as an exception! </code></pre> <p>Read carefully the documentation for <a href="http://docs.python.org/2/library/warnings.html#warnings.filterwarnings" rel="noreferrer"><code>filterwarnings</code></a> since it allows you to filter only the warning you want and has other options. I'd also consider looking at <a href="http://docs.python.org/2/library/warnings.html#warnings.catch_warnings" rel="noreferrer"><code>catch_warnings</code></a> which is a context manager which automatically resets the original <code>filterwarnings</code> function:</p> <pre><code>&gt;&gt;&gt; import warnings &gt;&gt;&gt; with warnings.catch_warnings(): ... warnings.filterwarnings('error') ... try: ... warnings.warn(Warning()) ... except Warning: print 'Raised!' ... Raised! &gt;&gt;&gt; try: ... warnings.warn(Warning()) ... except Warning: print 'Not raised!' ... __main__:2: Warning: </code></pre>
{ "question_id": 15933741, "question_date": "2013-04-10T18:36:21.917Z", "question_score": 225, "tags": "python|exception|numpy|warnings|divide-by-zero", "answer_id": 15934081, "answer_date": "2013-04-10T18:53:50.580Z", "answer_score": 248 }
Please answer the following Stack Overflow question: Title: MySQL CONCAT returns NULL if any field contain NULL <p>I have following data in my table "devices" </p> <pre><code>affiliate_name affiliate_location model ip os_type os_version cs1 inter Dell 10.125.103.25 Linux Fedora cs2 inter Dell 10.125.103.26 Linux Fedora cs3 inter Dell 10.125.103.27 NULL NULL cs4 inter Dell 10.125.103.28 NULL NULL </code></pre> <p>I executed below query </p> <pre><code>SELECT CONCAT(`affiliate_name`,'-',`model`,'-',`ip`,'-',`os_type`,'-',`os_version`) AS device_name FROM devices </code></pre> <p>It returns result given below</p> <pre><code>cs1-Dell-10.125.103.25-Linux-Fedora cs2-Dell-10.125.103.26-Linux-Fedora (NULL) (NULL) </code></pre> <p>How to come out of this so that it should ignore NULL AND result should be</p> <pre><code>cs1-Dell-10.125.103.25-Linux-Fedora cs2-Dell-10.125.103.26-Linux-Fedora cs3-Dell-10.125.103.27- cs4-Dell-10.125.103.28- </code></pre>
<p>convert the <code>NULL</code> values with empty string by wrapping it in <code>COALESCE</code></p> <pre><code>SELECT CONCAT(COALESCE(`affiliate_name`,''),'-',COALESCE(`model`,''),'-',COALESCE(`ip`,''),'-',COALESCE(`os_type`,''),'-',COALESCE(`os_version`,'')) AS device_name FROM devices </code></pre>
{ "question_id": 15741314, "question_date": "2013-04-01T09:59:51.540Z", "question_score": 225, "tags": "mysql|sql|null|concat", "answer_id": 15741336, "answer_date": "2013-04-01T10:01:32.447Z", "answer_score": 367 }
Please answer the following Stack Overflow question: Title: Mac zip compress without __MACOSX folder? <p>When I compress files with the built in zip compressor in Mac OSX, it causes an extra folder titled &quot;__MACOSX&quot; to be created in the extracted zip.</p> <p>Can I adjust my settings to keep this folder from being created or do I need to purchase a third party compression tool?</p> <p><strong>UPDATE</strong>: I just found a freeware app for OSX that solves my problem: &quot;<a href="https://www.yellowmug.com/yemuzip/" rel="noreferrer">YemuZip</a>&quot;</p> <p><strong>UPDATE 2</strong>: YemuZip is no longer freeware.</p>
<p>When I had this problem I've done it from command line:</p> <pre><code>zip file.zip uncompressed </code></pre> <p><strong>EDIT</strong>, after many downvotes: I was using this option for some time ago and I don't know where I learnt it, so I can't give you a better explanation. Chris Johnson's <a href="https://stackoverflow.com/a/13665552/167365">answer</a> is correct, but I won't delete mine. As one comment says, it's more accurate to what OP is asking, as it compress without those files, instead of removing them from a compressed file. I find it easier to remember, too.</p>
{ "question_id": 10924236, "question_date": "2012-06-07T00:39:50.770Z", "question_score": 225, "tags": "macos|zip", "answer_id": 11413640, "answer_date": "2012-07-10T12:47:13.100Z", "answer_score": 117 }
Please answer the following Stack Overflow question: Title: Is there a CSS selector by class prefix? <p>I want to apply a CSS rule to any element whose one of the classes matches specified prefix.</p> <p>E.g. I want a rule that will apply to div that has class that starts with <code>status-</code> (A and C, but not B in following snippet):</p> <pre class="lang-html prettyprint-override"><code>&lt;div id='A' class='foo-class status-important bar-class'&gt;&lt;/div&gt; &lt;div id='B' class='foo-class bar-class'&gt;&lt;/div&gt; &lt;div id='C' class='foo-class status-low-priority bar-class'&gt;&lt;/div&gt; </code></pre> <p>Some sort of combination of:<br> <code>div[class|=status]</code> and <code>div[class~=status-]</code></p> <p>Is it doable under CSS 2.1? Is it doable under any CSS spec?</p> <p>Note: I do know I can use jQuery to emulate that.</p>
<p>It's not doable with CSS2.1, but it is possible with CSS3 attribute substring-matching selectors (which <em>are</em> supported in IE7+):</p> <pre><code>div[class^="status-"], div[class*=" status-"] </code></pre> <p>Notice the space character in the second attribute selector. This picks up <code>div</code> elements whose <code>class</code> attribute meets either of these conditions:</p> <ul> <li><p><code>[class^="status-"]</code> — starts with "status-"</p></li> <li><p><code>[class*=" status-"]</code> — contains the substring "status-" occurring directly after a space character. Class names are separated by whitespace <a href="http://www.w3.org/TR/html5/dom.html#classes" rel="noreferrer">per the HTML spec</a>, hence the significant space character. This checks any other classes after the first if multiple classes are specified, <em>and</em> adds a bonus of checking the first class in case the attribute value is space-padded (which can happen with some applications that output <code>class</code> attributes dynamically).</p></li> </ul> <p>Naturally, this also works in jQuery, as demonstrated <a href="https://stackoverflow.com/questions/4524412/jquery-selector-to-target-any-class-name-of-multiple-present-starting-with-a-p/4524477#4524477">here</a>.</p> <p>The reason you need to combine two attribute selectors as described above is because an attribute selector such as <code>[class*="status-"]</code> will match the following element, which may be undesirable:</p> <pre><code>&lt;div id='D' class='foo-class foo-status-bar bar-class'&gt;&lt;/div&gt; </code></pre> <p>If you can ensure that such a scenario will <strong>never</strong> happen, then you are free to use such a selector for the sake of simplicity. However, the combination above is much more robust.</p> <p>If you have control over the HTML source or the application generating the markup, it may be simpler to just make the <code>status-</code> prefix its own <code>status</code> class instead <a href="https://stackoverflow.com/questions/3338680/is-there-a-css-selector-by-class-prefix/3338690#3338690">as Gumbo suggests</a>.</p>
{ "question_id": 3338680, "question_date": "2010-07-26T20:22:08.693Z", "question_score": 225, "tags": "css|css-selectors", "answer_id": 8588532, "answer_date": "2011-12-21T10:42:11.553Z", "answer_score": 464 }
Please answer the following Stack Overflow question: Title: super() fails with error: TypeError "argument 1 must be type, not classobj" when parent does not inherit from object <p>I get some error that I can't figure out. Any clue what is wrong with my sample code?</p> <pre><code>class B: def meth(self, arg): print arg class C(B): def meth(self, arg): super(C, self).meth(arg) print C().meth(1) </code></pre> <p>I got the sample test code from help of 'super' built-in method. </p> <p>Here is the error:</p> <pre><code>Traceback (most recent call last): File "./test.py", line 10, in ? print C().meth(1) File "./test.py", line 8, in meth super(C, self).meth(arg) TypeError: super() argument 1 must be type, not classobj </code></pre> <p>FYI, here is the help(super) from python itself:</p> <pre><code>Help on class super in module __builtin__: class super(object) | super(type) -&gt; unbound super object | super(type, obj) -&gt; bound super object; requires isinstance(obj, type) | super(type, type2) -&gt; bound super object; requires issubclass(type2, type) | Typical use to call a cooperative superclass method: | class C(B): | def meth(self, arg): | super(C, self).meth(arg) | </code></pre>
<p>Your problem is that class B is not declared as a "new-style" class. Change it like so:</p> <pre><code>class B(object): </code></pre> <p>and it will work.</p> <p><code>super()</code> and all subclass/superclass stuff only works with new-style classes. I recommend you get in the habit of always typing that <code>(object)</code> on any class definition to make sure it is a new-style class.</p> <p>Old-style classes (also known as "classic" classes) are always of type <code>classobj</code>; new-style classes are of type <code>type</code>. This is why you got the error message you saw:</p> <p><code>TypeError: super() argument 1 must be type, not classobj</code></p> <p>Try this to see for yourself:</p> <pre><code>class OldStyle: pass class NewStyle(object): pass print type(OldStyle) # prints: &lt;type 'classobj'&gt; print type(NewStyle) # prints &lt;type 'type'&gt; </code></pre> <p>Note that in Python 3.x, all classes are new-style. You can still use the syntax from the old-style classes but you get a new-style class. So, in Python 3.x you won't have this problem.</p>
{ "question_id": 1713038, "question_date": "2009-11-11T04:36:05.310Z", "question_score": 225, "tags": "python|object|inheritance|parent|super", "answer_id": 1713052, "answer_date": "2009-11-11T04:40:10.923Z", "answer_score": 368 }
Please answer the following Stack Overflow question: Title: How can I set my default shell on a Mac, e.g. to Fish? <p>I do not like to retype <code>fish</code> every time I start terminal. I want <a href="https://en.wikipedia.org/wiki/Fish_(Unix_shell)" rel="noreferrer">Fish</a> on by default. How can I set the Fish shell as my default shell on a Mac?</p>
<p>These are applicable to macOS v10.12.5 (Sierra) (16F73) and probably some other recent and upcoming versions of macOS.</p> <ol> <li><p><code>chsh</code> is not enough to change the default shell. Make sure you press <kbd>Command</kbd> + <kbd>,</kbd> while your terminal is open and change the 'Shells open with' option to 'Default login shell.'</p> </li> <li><p>In case of Bash, make sure that you execute <code>echo $BASH_VERSION</code> to confirm you are running the intended version of Bash. <code>bash --version</code> does not give you correct information.</p> </li> </ol>
{ "question_id": 453236, "question_date": "2009-01-17T12:21:22.627Z", "question_score": 225, "tags": "macos|terminal|fish", "answer_id": 45119840, "answer_date": "2017-07-15T15:29:07.187Z", "answer_score": 39 }
Please answer the following Stack Overflow question: Title: JOIN queries vs multiple queries <p>Are JOIN queries faster than several queries? (You run your main query, and then you run many other SELECTs based on the results from your main query)</p> <p>I'm asking because JOINing them would complicate A LOT the design of my application</p> <p>If they are faster, can anyone approximate very roughly by how much? If it's 1.5x I don't care, but if it's 10x I guess I do.</p>
<p>This is way too vague to give you an answer relevant to your specific case. It depends on a lot of things. Jeff Atwood (founder of this site) actually <a href="http://www.codinghorror.com/blog/2009/06/all-abstractions-are-failed-abstractions.html" rel="noreferrer">wrote about this</a>. For the most part, though, if you have the right indexes and you properly do your JOINs it is usually going to be faster to do 1 trip than several.</p>
{ "question_id": 1067016, "question_date": "2009-07-01T02:23:49.307Z", "question_score": 225, "tags": "mysql|database|join|query-optimization", "answer_id": 1067021, "answer_date": "2009-07-01T02:27:07.243Z", "answer_score": 98 }
Please answer the following Stack Overflow question: Title: Python non-greedy regexes <p>How do I make a python regex like <code>"(.*)"</code> such that, given <code>"a (b) c (d) e"</code> python matches <code>"b"</code> instead of <code>"b) c (d"</code>?</p> <p>I know that I can use <code>"[^)]"</code> instead of <code>"."</code>, but I'm looking for a more general solution that keeps my regex a little cleaner. Is there any way to tell python "hey, match this as soon as possible"?</p>
<p>You seek the all-powerful <code>*?</code></p> <p>From the docs, <a href="http://docs.python.org/3/howto/regex.html#greedy-versus-non-greedy" rel="noreferrer">Greedy versus Non-Greedy</a></p> <blockquote> <p>the non-greedy qualifiers <code>*?</code>, <code>+?</code>, <code>??</code>, or <code>{m,n}?</code> [...] match as <em>little</em> text as possible.</p> </blockquote>
{ "question_id": 766372, "question_date": "2009-04-19T23:24:03.487Z", "question_score": 225, "tags": "python|regex|regex-greedy", "answer_id": 766377, "answer_date": "2009-04-19T23:27:21.917Z", "answer_score": 324 }
Please answer the following Stack Overflow question: Title: Appending a line to a file only if it does not already exist <p>I need to add the following line to the end of a config file:</p> <pre><code>include "/configs/projectname.conf" </code></pre> <p>to a file called <code>lighttpd.conf</code></p> <p>I am looking into using <code>sed</code> to do this, but I can't work out how.</p> <p>How would I only insert it if the line doesn't already exist?</p>
<p>Just keep it simple :)</p> <p><strong>grep</strong> + <strong>echo</strong> should suffice:</p> <pre><code>grep -qxF 'include "/configs/projectname.conf"' foo.bar || echo 'include "/configs/projectname.conf"' &gt;&gt; foo.bar </code></pre> <ul> <li><code>-q</code> be quiet</li> <li><code>-x</code> match the whole line</li> <li><code>-F</code> pattern is a plain string</li> <li><a href="https://linux.die.net/man/1/grep" rel="noreferrer">https://linux.die.net/man/1/grep</a></li> </ul> <p><em>Edit: incorporated @cerin and @thijs-wouters suggestions</em>.</p>
{ "question_id": 3557037, "question_date": "2010-08-24T13:40:18.743Z", "question_score": 225, "tags": "linux|sed|terminal", "answer_id": 3557165, "answer_date": "2010-08-24T13:53:07.210Z", "answer_score": 417 }
Please answer the following Stack Overflow question: Title: Git branching: master vs. origin/master vs. remotes/origin/master <p>I think I'm on the right track to understand the basic concepts of git.</p> <p>I've already set up and cloned a remote repository. I also created a server side empty repository, and linked my local repository to it.</p> <p>My problem is that I don't understand the difference between:</p> <ul> <li>origin/master vs. remotes/origin/master</li> </ul> <p>As far as I have understood, <strong>master</strong> is a local branch, and <strong>remotes/origin/master</strong> is a remote one. </p> <p>But what exactly is <strong>origin/master</strong>?</p>
<p>Take a clone of a remote repository and run <code>git branch -a</code> (to show all the branches git knows about). It will probably look something like this:</p> <pre><code>* master remotes/origin/HEAD -&gt; origin/master remotes/origin/master </code></pre> <p>Here, <code>master</code> is a branch in the local repository. <code>remotes/origin/master</code> is a branch named <code>master</code> on the remote named <code>origin</code>. You can refer to this as either <code>origin/master</code>, as in:</p> <pre><code>git diff origin/master..master </code></pre> <p>You can also refer to it as <code>remotes/origin/master</code>:</p> <pre><code>git diff remotes/origin/master..master </code></pre> <p>These are just two different ways of referring to the same thing (incidentally, both of these commands mean "show me the changes between the remote <code>master</code> branch and my <code>master</code> branch).</p> <p><code>remotes/origin/HEAD</code> is the <code>default branch</code> for the remote named <code>origin</code>. This lets you simply say <code>origin</code> instead of <code>origin/master</code>.</p>
{ "question_id": 10588291, "question_date": "2012-05-14T17:33:26.583Z", "question_score": 225, "tags": "git|git-branch|git-remote", "answer_id": 10588561, "answer_date": "2012-05-14T17:56:41.020Z", "answer_score": 233 }
Please answer the following Stack Overflow question: Title: Case insensitive replace <p>What's the easiest way to do a case-insensitive string replacement in Python?</p>
<p>The <code>string</code> type doesn't support this. You're probably best off using <a href="https://docs.python.org/3/library/re.html#re.sub" rel="noreferrer">the regular expression sub method</a> with the <a href="http://docs.python.org/library/re.html#re.IGNORECASE" rel="noreferrer">re.IGNORECASE</a> option.</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; insensitive_hippo = re.compile(re.escape('hippo'), re.IGNORECASE) &gt;&gt;&gt; insensitive_hippo.sub('giraffe', 'I want a hIPpo for my birthday') 'I want a giraffe for my birthday' </code></pre>
{ "question_id": 919056, "question_date": "2009-05-28T03:35:24.737Z", "question_score": 225, "tags": "python|string|case-insensitive", "answer_id": 919067, "answer_date": "2009-05-28T03:39:13.607Z", "answer_score": 265 }
Please answer the following Stack Overflow question: Title: Will iOS launch my app into the background if it was force-quit by the user? <p>I am triggering a background fetch by using the <code>content-available</code> flag on a push notification. I have the <code>fetch</code> and <code>remote-notification</code> <code>UIBackgroundModes</code> enabled.</p> <p>Here is the implementation I am using in my AppDelegate.m:</p> <pre><code>- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { NSLog(@"Remote Notification Recieved"); UILocalNotification *notification = [[UILocalNotification alloc] init]; notification.alertBody = @"Looks like i got a notification - fetch thingy"; [application presentLocalNotificationNow:notification]; completionHandler(UIBackgroundFetchResultNewData); } </code></pre> <p><strong>When the app is running in the background, it works fine.</strong> (The notification is received and the app triggered the "looks like i got a notification" local notification, as the code above should do). </p> <p>However, <strong>when the app is not running</strong> and a push notification is received with the <code>content-available</code> flag, <strong>the app is not launched</strong> and the <code>didRecieveRemoteNotification</code> delegate method is never called. </p> <p>The WWDC Video <em>Whats New With Multitasking</em> (#204 from WWDC 2013) shows this: <img src="https://i.imgur.com/9OHaGys.png" alt="enter image description here"></p> <p>It says that the application is "launched into background" when a push notification is received with the <code>content-available</code> flag.</p> <p>Why is my app not launching into the background?</p> <p><strong>So the real question is:</strong></p> <p>Will iOS perform background tasks after the user has force-quit the app?</p>
<p><strong><em>UPDATE2:</em></strong> </p> <p>You <em>can</em> achieve this using the new PushKit framework, introduced in iOS 8. Though PushKit is used for VoIP. So your usage should be for VoIP related otherwise there is risk of app rejection. (See <a href="https://stackoverflow.com/a/29231395/2446155">this answer</a>).</p> <hr> <p><strong><em>UDPDATE1:</em></strong></p> <p>The documentation has been clarified for <strong>iOS8</strong>. The documentation can be read <a href="https://developer.apple.com/reference/uikit/uiapplicationdelegate/1623013-application#discussion" rel="noreferrer">here</a>. Here is a relevant excerpt:</p> <blockquote> <p>Use this method to process incoming remote notifications for your app. Unlike the <code>application:didReceiveRemoteNotification:</code> method, which is called only when your app is running in the foreground, the system calls this method when your app is running in the foreground or background. In addition, if you enabled the remote notifications background mode, the system launches your app (or wakes it from the suspended state) and puts it in the background state when a push notification arrives. <strong>However, the system does not automatically launch your app if the user has force-quit it. In that situation, the user must relaunch your app or restart the device before the system attempts to launch your app automatically again.</strong></p> </blockquote> <hr> <p>Although this was not made clear by the WWDC video, a quick search on the developer forums turned this up:</p> <p><a href="https://devforums.apple.com/message/873265#873265" rel="noreferrer">https://devforums.apple.com/message/873265#873265</a> (login required)</p> <blockquote> <p>Also keep in mind that if you kill your app from the app switcher (i.e. swiping up to kill the app) then the OS will never relaunch the app regardless of push notification or background fetch. In this case the user has to manually relaunch the app once and then from that point forward the background activities will be invoked. -<a href="https://devforums.apple.com/people/pmarcos" rel="noreferrer">pmarcos</a></p> </blockquote> <p>That post was by an Apple employee so I think i can trust that this information is correct.</p> <p>So it looks like when the app is killed from the app switcher (by swiping up), the app will never be launched, even for scheduled background fetches.</p>
{ "question_id": 19068762, "question_date": "2013-09-28T15:53:50.283Z", "question_score": 225, "tags": "ios|ios7|push-notification|apple-push-notifications", "answer_id": 19202487, "answer_date": "2013-10-05T20:38:58.730Z", "answer_score": 218 }
Please answer the following Stack Overflow question: Title: How to shrink the .git folder <p>My current base has a total size of approx. 200MB.</p> <p>But my .git folder has an amazing size of 5GB (!). Since I push my work to an external server, i don't need any big local history...</p> <p>How can I shrink the .git folder to free up some space on my notebook? Can I delete all changes that are older, than 30 days?</p>
<p>You should not delete all changes older than 30 days (I think it's somehow possible exploiting Git, but really not recommended).</p> <p>You can call <code>git gc --aggressive --prune</code>, which will perform garbage collection in your repository and prune old objects. Do you have a lot of binary files (archives, images, executables) which change often? Those usually lead to huge <code>.git</code> folders (remember, Git stores snapshots for each revision and binary files compress badly)</p>
{ "question_id": 5613345, "question_date": "2011-04-10T17:05:50.660Z", "question_score": 225, "tags": "git", "answer_id": 5613380, "answer_date": "2011-04-10T17:09:54.203Z", "answer_score": 179 }
Please answer the following Stack Overflow question: Title: Explicitly calling return in a function or not <p>A while back <a href="https://stackoverflow.com/questions/10412720/rserve-return-type-in-case-of-multiple-statements/10413020#10413020">I got rebuked</a> by Simon Urbanek from the R core team (I believe) for recommending a user to explicitly calling <code>return</code> at the end of a function (his comment was deleted though):</p> <pre><code>foo = function() { return(value) } </code></pre> <p>instead he recommended:</p> <pre><code>foo = function() { value } </code></pre> <p>Probably in a situation like this it is required:</p> <pre><code>foo = function() { if(a) { return(a) } else { return(b) } } </code></pre> <p>His comment shed some light on why not calling <code>return</code> unless strictly needed is a good thing, but this was deleted. </p> <p>My question is: Why is not calling <code>return</code> faster or better, and thus preferable?</p>
<p><strong>Question was: Why is not (explicitly) calling return faster or better, and thus preferable?</strong></p> <p>There is no statement in R documentation making such an assumption.<br> The main page ?'function' says:</p> <pre><code>function( arglist ) expr return(value) </code></pre> <p><strong>Is it faster without calling return?</strong> </p> <p>Both <code>function()</code> and <code>return()</code> are primitive functions and the <code>function()</code> itself returns last evaluated value even without including <code>return()</code> function.</p> <p>Calling <code>return()</code> as <code>.Primitive('return')</code> with that last value as an argument will do the same job but needs one call more. So that this (often) unnecessary <code>.Primitive('return')</code> call can draw additional resources. Simple measurement however shows that the resulting difference is very small and thus can not be the reason for not using explicit return. The following plot is created from data selected this way:</p> <pre><code>bench_nor2 &lt;- function(x,repeats) { system.time(rep( # without explicit return (function(x) vector(length=x,mode="numeric"))(x) ,repeats)) } bench_ret2 &lt;- function(x,repeats) { system.time(rep( # with explicit return (function(x) return(vector(length=x,mode="numeric")))(x) ,repeats)) } maxlen &lt;- 1000 reps &lt;- 10000 along &lt;- seq(from=1,to=maxlen,by=5) ret &lt;- sapply(along,FUN=bench_ret2,repeats=reps) nor &lt;- sapply(along,FUN=bench_nor2,repeats=reps) res &lt;- data.frame(N=along,ELAPSED_RET=ret["elapsed",],ELAPSED_NOR=nor["elapsed",]) # res object is then visualized # R version 2.15 </code></pre> <p><img src="https://i.stack.imgur.com/qNjIS.png" alt="Function elapsed time comparison"></p> <p>The picture above may slightly difffer on your platform. Based on measured data, the size of returned object is not causing any difference, the number of repeats (even if scaled up) makes just a very small difference, which in real word with real data and real algorithm could not be counted or make your script run faster.</p> <p><strong>Is it better without calling return?</strong> </p> <p><code>Return</code> is good tool for clearly designing "leaves" of code where the routine should end, jump out of the function and return value.</p> <pre><code># here without calling .Primitive('return') &gt; (function() {10;20;30;40})() [1] 40 # here with .Primitive('return') &gt; (function() {10;20;30;40;return(40)})() [1] 40 # here return terminates flow &gt; (function() {10;20;return();30;40})() NULL &gt; (function() {10;20;return(25);30;40})() [1] 25 &gt; </code></pre> <p>It depends on strategy and programming style of the programmer what style he use, he can use no return() as it is not required.</p> <p>R core programmers uses both approaches ie. with and without explicit return() as it is possible to find in sources of 'base' functions.</p> <p>Many times only return() is used (no argument) returning NULL in cases to conditially stop the function.</p> <p>It is not clear if it is better or not as standard user or analyst using R can not see the real difference.</p> <p>My opinion is that the question should be: <em>Is there any danger in using explicit return coming from R implementation?</em></p> <p>Or, maybe better, user writing function code should always ask: <em>What is the effect in <strong>not</strong> using explicit return (or placing object to be returned as last leaf of code branch) in the function code?</em></p>
{ "question_id": 11738823, "question_date": "2012-07-31T11:12:55.697Z", "question_score": 225, "tags": "r", "answer_id": 11834490, "answer_date": "2012-08-06T19:19:23.583Z", "answer_score": 149 }
Please answer the following Stack Overflow question: Title: Create a completed Task <p>I want to create a completed <code>Task</code> (not <code>Task&lt;T&gt;</code>). Is there something built into .NET to do this?</p> <p>A related question: <a href="https://stackoverflow.com/questions/4245968/create-a-completed-taskt">Create a completed Task&lt;T&gt;</a></p>
<p>The <a href="https://msdn.microsoft.com/library/ms171868.aspx#v46">newest version of .Net (v4.6)</a> is adding just that, a built-in <a href="https://msdn.microsoft.com/en-us/library/system.threading.tasks.task.completedtask(v=vs.110).aspx">Task.CompletedTask</a>:</p> <pre><code>Task completedTask = Task.CompletedTask; </code></pre> <p>That property is implemented as a no-lock singleton so you would <em>almost</em> always be using the same completed task.</p>
{ "question_id": 14244114, "question_date": "2013-01-09T18:36:48.903Z", "question_score": 225, "tags": "c#|.net|async-await|task-parallel-library", "answer_id": 26226195, "answer_date": "2014-10-06T23:04:20.873Z", "answer_score": 268 }
Please answer the following Stack Overflow question: Title: URLs: Dash vs. Underscore <p>Is it better convention to use hyphens or underscores in your URLs?</p> <p>Should it be <code>/about_us</code> or <code>/about-us</code>?</p> <p>From usability point of view, I personally think <strong>/about-us</strong> is much better for end-user yet Google and most other websites (and javascript frameworks) use underscore naming pattern. Is it just matter of style? Are there any compatibility issues with dashes?</p>
<p>This is just a guess, but it seems they picked the one that people most probably <strong>wouldn't</strong> use in a name. This way you can have a name that includes a hyphenated word, and still use the underbar as a word delimiter, e.g. UseTwo-wayLinks could be converted to use_two-way_links.</p> <p>In your example, /about-us would be a directory named the hyphenated word "about-us" (if such a word existed, and /about_us would be a directory named the two-word phrase "about us" converted to a single string of non-white characters.</p>
{ "question_id": 119312, "question_date": "2008-09-23T05:51:50.857Z", "question_score": 225, "tags": "url|seo|naming-conventions", "answer_id": 119318, "answer_date": "2008-09-23T05:54:36.620Z", "answer_score": 31 }
Please answer the following Stack Overflow question: Title: How do I promisify native XHR? <p>I want to use (native) promises in my frontend app to perform XHR request but without all the tomfoolery of a massive framework.</p> <p>I want my xhr to return a promise but this doesn't work (giving me: <code>Uncaught TypeError: Promise resolver undefined is not a function</code>)</p> <pre class="lang-js prettyprint-override"><code>function makeXHRRequest (method, url, done) { var xhr = new XMLHttpRequest(); xhr.open(method, url); xhr.onload = function() { return new Promise().resolve(); }; xhr.onerror = function() { return new Promise().reject(); }; xhr.send(); } makeXHRRequest('GET', 'http://example.com') .then(function (datums) { console.log(datums); }); </code></pre>
<p>I'm assuming you know how to make a native XHR request (you can brush up <a href="https://stackoverflow.com/a/16825593/1216976">here</a> and <a href="https://gist.github.com/Zirak/3086939" rel="noreferrer">here</a>)</p> <p>Since <a href="http://caniuse.com/#feat=promises" rel="noreferrer">any browser that supports native promises</a> will also support <code>xhr.onload</code>, we can skip all the <code>onReadyStateChange</code> tomfoolery. Let's take a step back and start with a basic XHR request function using callbacks:</p> <pre class="lang-js prettyprint-override"><code>function makeRequest (method, url, done) { var xhr = new XMLHttpRequest(); xhr.open(method, url); xhr.onload = function () { done(null, xhr.response); }; xhr.onerror = function () { done(xhr.response); }; xhr.send(); } // And we'd call it as such: makeRequest('GET', 'http://example.com', function (err, datums) { if (err) { throw err; } console.log(datums); }); </code></pre> <p>Hurrah! This doesn't involve anything terribly complicated (like custom headers or POST data) but is enough to get us moving forwards.</p> <h2>The promise constructor</h2> <p>We can construct a promise like so:</p> <pre class="lang-js prettyprint-override"><code>new Promise(function (resolve, reject) { // Do some Async stuff // call resolve if it succeeded // reject if it failed }); </code></pre> <p>The promise constructor takes a function that will be passed two arguments (let's call them <code>resolve</code> and <code>reject</code>). You can think of these as callbacks, one for success and one for failure. Examples are awesome, let's update <code>makeRequest</code> with this constructor:</p> <pre class="lang-js prettyprint-override"><code>function makeRequest (method, url) { return new Promise(function (resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open(method, url); xhr.onload = function () { if (xhr.status &gt;= 200 &amp;&amp; xhr.status &lt; 300) { resolve(xhr.response); } else { reject({ status: xhr.status, statusText: xhr.statusText }); } }; xhr.onerror = function () { reject({ status: xhr.status, statusText: xhr.statusText }); }; xhr.send(); }); } // Example: makeRequest('GET', 'http://example.com') .then(function (datums) { console.log(datums); }) .catch(function (err) { console.error('Augh, there was an error!', err.statusText); }); </code></pre> <p>Now we can tap into the power of promises, chaining multiple XHR calls (and the <code>.catch</code> will trigger for an error on either call):</p> <pre class="lang-js prettyprint-override"><code>makeRequest('GET', 'http://example.com') .then(function (datums) { return makeRequest('GET', datums.url); }) .then(function (moreDatums) { console.log(moreDatums); }) .catch(function (err) { console.error('Augh, there was an error!', err.statusText); }); </code></pre> <p>We can improve this still further, adding both POST/PUT params and custom headers. Let's use an options object instead of multiple arguments, with the signature:</p> <pre class="lang-js prettyprint-override"><code>{ method: String, url: String, params: String | Object, headers: Object } </code></pre> <p><code>makeRequest</code> now looks something like this:</p> <pre class="lang-js prettyprint-override"><code>function makeRequest (opts) { return new Promise(function (resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open(opts.method, opts.url); xhr.onload = function () { if (xhr.status &gt;= 200 &amp;&amp; xhr.status &lt; 300) { resolve(xhr.response); } else { reject({ status: xhr.status, statusText: xhr.statusText }); } }; xhr.onerror = function () { reject({ status: xhr.status, statusText: xhr.statusText }); }; if (opts.headers) { Object.keys(opts.headers).forEach(function (key) { xhr.setRequestHeader(key, opts.headers[key]); }); } var params = opts.params; // We'll need to stringify if we've been given an object // If we have a string, this is skipped. if (params &amp;&amp; typeof params === 'object') { params = Object.keys(params).map(function (key) { return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]); }).join('&amp;'); } xhr.send(params); }); } // Headers and params are optional makeRequest({ method: 'GET', url: 'http://example.com' }) .then(function (datums) { return makeRequest({ method: 'POST', url: datums.url, params: { score: 9001 }, headers: { 'X-Subliminal-Message': 'Upvote-this-answer' } }); }) .catch(function (err) { console.error('Augh, there was an error!', err.statusText); }); </code></pre> <p>A more comprehensive approach can be found at <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#Example_using_new_XMLHttpRequest()" rel="noreferrer">MDN</a>.</p> <p>Alternatively, you could use the <a href="https://developer.mozilla.org/en-US/docs/Web/API/GlobalFetch/fetch" rel="noreferrer">fetch API</a> (<a href="https://github.com/github/fetch" rel="noreferrer">polyfill</a>).</p>
{ "question_id": 30008114, "question_date": "2015-05-02T22:18:32.747Z", "question_score": 225, "tags": "javascript|xmlhttprequest|promise", "answer_id": 30008115, "answer_date": "2015-05-02T22:18:32.747Z", "answer_score": 452 }
Please answer the following Stack Overflow question: Title: Does deleting a branch in git remove it from the history? <p>Coming from svn, just starting to become familiar with git.</p> <p>When a branch is deleted in git, is it removed from the history? </p> <p>In svn, you can easily recover a branch by reverting the delete operation (reverse merge). Like all deletes in svn, the branch is never really deleted, it's just removed from the current tree.</p> <p>If the branch is actually deleted from the history in git, what happens to the changes that were merged from that branch? Are they retained?</p>
<p>Branches are just pointers to commits in git. In git each commit has a complete source tree, it is a very different structure from svn where all branches and tags (by convention) live in separate 'folders' of the repository alongside the special 'trunk'.</p> <p>If the branch was merged into another branch before it was deleted then all of the commits will still be reachable from the other branch when the first branch is deleted. They remain exactly as they were.</p> <p>If the branch is deleted without being merged into another branch then the commits in that branch (up until the point where the forked from a commit that is still reachable) will cease to be visible.</p> <p>The commits will still be retained in the repository and it is possible to recover them immediately after the delete, but eventually they will be garbage collected.</p>
{ "question_id": 2613903, "question_date": "2010-04-10T15:43:14.633Z", "question_score": 225, "tags": "git|version-control|branch|revision-history", "answer_id": 2613954, "answer_date": "2010-04-10T15:57:03.043Z", "answer_score": 294 }