input_text
stringlengths
115
13.8k
output_text
stringlengths
24
15k
metadata
dict
Please answer the following Stack Overflow question: Title: How to make child process die after parent exits? <p>Suppose I have a process which spawns exactly one child process. Now when the parent process exits for whatever reason (normally or abnormally, by kill, ^C, assert failure or anything else) I want the child process to die. How to do that correctly?</p> <hr> <p>Some similar question on stackoverflow:</p> <ul> <li>(asked earlier) <a href="https://stackoverflow.com/questions/269494/how-can-i-cause-a-child-process-to-exit-when-the-parent-does">How can I cause a child process to exit when the parent does?</a></li> <li>(asked later) <a href="https://stackoverflow.com/questions/395877/are-child-processes-created-with-fork-automatically-killed-when-the-parent-is-k">Are child processes created with fork() automatically killed when the parent is killed?</a></li> </ul> <hr> <p>Some similar question on stackoverflow for <strong>Windows</strong>: </p> <ul> <li><a href="https://stackoverflow.com/questions/53208/how-do-i-automatically-destroy-child-processes-in-windows">How do I automatically destroy child processes in Windows?</a> </li> <li><a href="https://stackoverflow.com/questions/3342941/kill-child-process-when-parent-process-is-killed">Kill child process when parent process is killed</a></li> </ul>
<p>Child can ask kernel to deliver <code>SIGHUP</code> (or other signal) when parent dies by specifying option <code>PR_SET_PDEATHSIG</code> in <code>prctl()</code> syscall like this:</p> <p><code>prctl(PR_SET_PDEATHSIG, SIGHUP);</code></p> <p>See <code>man 2 prctl</code> for details.</p> <p>Edit: This is Linux-only</p>
{ "question_id": 284325, "question_date": "2008-11-12T15:37:51.153Z", "question_score": 236, "tags": "c|linux|unix|process|fork", "answer_id": 284443, "answer_date": "2008-11-12T16:12:14.440Z", "answer_score": 202 }
Please answer the following Stack Overflow question: Title: Math functions in AngularJS bindings <p>Is there a way to use math functions in AngularJS bindings?</p> <p>e.g. </p> <pre><code>&lt;p&gt;The percentage is {{Math.round(100*count/total)}}%&lt;/p&gt; </code></pre> <p>This fiddle shows the problem</p> <p><a href="http://jsfiddle.net/ricick/jtA99/1/" rel="noreferrer">http://jsfiddle.net/ricick/jtA99/1/</a></p>
<p>You have to inject <code>Math</code> into your scope, if you need to use it as <code>$scope</code> know nothing about Math.</p> <p>Simplest way, you can do</p> <pre><code>$scope.Math = window.Math; </code></pre> <p>in your controller. Angular way to do this correctly would be create a Math service, I guess.</p>
{ "question_id": 12740329, "question_date": "2012-10-05T05:56:46.457Z", "question_score": 236, "tags": "angularjs", "answer_id": 12740497, "answer_date": "2012-10-05T06:12:01.060Z", "answer_score": 335 }
Please answer the following Stack Overflow question: Title: What is this spring.jpa.open-in-view=true property in Spring Boot? <p>I saw <code>spring.jpa.open-in-view=true</code> property in Spring Boot documentation for JPA configuration.</p> <ul> <li>Is the <code>true</code> default value for this property if it's not provided at all?;</li> <li>What does this really do? I did not find any good explaining for it;</li> <li>Does it make you use <code>SessionFactory</code> instead of <code>EntityManagerFactory</code>? If yes, how can I tell it to allow me to use <code>EntityManagerFactory</code> instead?</li> </ul> <p>Thanks!</p>
<p>This property will register an <code>OpenEntityManagerInViewInterceptor</code>, which registers an <code>EntityManager</code> to the current thread, so you will have the same <code>EntityManager</code> until the web request is finished. It has nothing to do with a Hibernate <code>SessionFactory</code> etc.</p>
{ "question_id": 30549489, "question_date": "2015-05-30T17:58:08.767Z", "question_score": 236, "tags": "java|spring|jpa|spring-boot|spring-data", "answer_id": 30554785, "answer_date": "2015-05-31T07:06:48.840Z", "answer_score": 87 }
Please answer the following Stack Overflow question: Title: Can I inject a service into a directive in AngularJS? <p>I am trying to inject a service into a directive like below: </p> <pre><code> var app = angular.module('app',[]); app.factory('myData', function(){ return { name : "myName" } }); app.directive('changeIt',function($compile, myData){ return { restrict: 'C', link: function (scope, element, attrs) { scope.name = myData.name; } } }); </code></pre> <p>But this is returning me an error <code>Unknown provider: myDataProvider</code>. Could someone please look into the code and tell me if I am doing something wrong?</p>
<p>You can do injection on Directives, and it looks just like it does everywhere else.</p> <pre><code>app.directive('changeIt', ['myData', function(myData){ return { restrict: 'C', link: function (scope, element, attrs) { scope.name = myData.name; } } }]); </code></pre>
{ "question_id": 15569168, "question_date": "2013-03-22T11:24:46.887Z", "question_score": 236, "tags": "angularjs", "answer_id": 15573493, "answer_date": "2013-03-22T14:59:27.710Z", "answer_score": 389 }
Please answer the following Stack Overflow question: Title: What's the best free C++ profiler for Windows? <p>I'm looking for a profiler in order to find the bottleneck in my C++ code. I'd like to find a free, non-intrusive, and good profiling tool. I'm a game developer, and I use PIX for Xbox&nbsp;360 and found it very good, but it's not free. I know the Intel <a href="https://en.wikipedia.org/wiki/VTune" rel="noreferrer">VTune</a>, but it's not free either.</p>
<p><a href="https://gpuopen.com/archived/legacy-codexl/" rel="nofollow noreferrer">CodeXL</a> has now superseded the End Of Line'd <a href="https://web.archive.org/web/20120607044224/http://developer.amd.com/tools/CodeAnalyst/Pages/default.aspx" rel="nofollow noreferrer">AMD Code Analyst</a> and both are free, but not as advanced as VTune.</p> <p>There's also <a href="http://www.codersnotes.com/sleepy/" rel="nofollow noreferrer">Sleepy</a>, which is very simple, but does the job in many cases.</p> <p>Note: <strong>All three of the tools above are unmaintained since several years.</strong></p>
{ "question_id": 67554, "question_date": "2008-09-15T22:15:11.363Z", "question_score": 236, "tags": "c++|windows|profile", "answer_id": 67577, "answer_date": "2008-09-15T22:18:51.870Z", "answer_score": 139 }
Please answer the following Stack Overflow question: Title: When the keyboard appears, the Flutter widgets resize. How to prevent this? <p>I have a Column of Expanded widgets like this:</p> <pre><code> return new Container( child: new Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: &lt;Widget&gt;[ new Expanded( flex: 1, child: convertFrom, ), new Expanded( flex: 1, child: convertTo, ), new Expanded( flex: 1, child: description, ), ], ), ); </code></pre> <p>It looks like this:</p> <p><a href="https://i.stack.imgur.com/r5o7s.png" rel="noreferrer"><img src="https://i.stack.imgur.com/r5o7s.png" alt="enter image description here"></a></p> <p><code>convertFrom</code>, includes a TextField. When I tap on this text field, the Android keyboard appears on the screen. This changes the screen size, so the widgets resize like this:</p> <p><a href="https://i.stack.imgur.com/22ixQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/22ixQ.png" alt="enter image description here"></a></p> <p>Is there a way to have the keyboard "overlay" the screen so that my Column doesn't resize? If I don't use <code>Expanded</code> widgets and hardcode a height for each widget, the widgets don't resize, but I get the black-and-yellow striped error when the keyboard appears (because there isn't enough space). This also isn't flexible for all screen sizes.</p> <p>I'm not sure if this is an Android-specific or Flutter-specific.</p>
<p><strong>Updated Answer</strong></p> <p><code>resizeToAvoidBottomPadding</code> is now <em>deprecated</em>.</p> <p>The updated solution is to set <code>resizeToAvoidBottomInset</code> property to <code>false</code>.</p> <hr /> <p><strong>Original Answer</strong></p> <p>In your <code>Scaffold</code>, set <code>resizeToAvoidBottomPadding</code> property to <code>false</code>.</p>
{ "question_id": 46551268, "question_date": "2017-10-03T18:37:15.793Z", "question_score": 236, "tags": "keyboard|resize|widget|textfield|flutter", "answer_id": 46551390, "answer_date": "2017-10-03T18:45:36.117Z", "answer_score": 551 }
Please answer the following Stack Overflow question: Title: What does 'foo' really mean? <p>I hope this qualifies as a programming question, as in any programming tutorial, you eventually come across 'foo' in the code examples. (yeah, right?)</p> <p>what does 'foo' really mean?</p> <p>If it is meant to mean <strong>nothing</strong>, when did it begin to be used so?</p>
<p>See: <a href="https://www.rfc-editor.org/rfc/rfc3092" rel="nofollow noreferrer">RFC 3092: Etymology of &quot;Foo&quot;, D. Eastlake 3rd et al.</a></p> <p>Quoting only the relevant definitions from that RFC for brevity:</p> <blockquote> <ol start="2"> <li>Used very generally as a sample name for absolutely anything, esp. programs and files (esp. scratch files).</li> </ol> </blockquote> <blockquote> <ol start="3"> <li>First on the standard list of metasyntactic variables used in syntax examples (bar, baz, qux, quux, corge, grault, garply, waldo, fred, plugh, xyzzy, thud). [JARGON]</li> </ol> </blockquote>
{ "question_id": 53609, "question_date": "2008-09-10T08:21:02.223Z", "question_score": 236, "tags": "language-agnostic|coding-style", "answer_id": 566486, "answer_date": "2009-02-19T18:09:28.287Z", "answer_score": 139 }
Please answer the following Stack Overflow question: Title: How to create EditText with cross(x) button at end of it? <p>Is there any widget like <code>EditText</code> which contains a cross button, or is there any property for <code>EditText</code> by which it is created automatically? I want the cross button to delete whatever text written in <code>EditText</code>.</p>
<p>Use the following layout:</p> <pre><code>&lt;FrameLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="9dp" android:padding="5dp"&gt; &lt;EditText android:id="@+id/calc_txt_Prise" android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="numberDecimal" android:layout_marginTop="20dp" android:textSize="25dp" android:textColor="@color/gray" android:textStyle="bold" android:hint="@string/calc_txt_Prise" android:singleLine="true" /&gt; &lt;Button android:id="@+id/calc_clear_txt_Prise" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="10dp" android:layout_gravity="right|center_vertical" android:background="@drawable/delete" /&gt; &lt;/FrameLayout&gt; </code></pre> <p>You can also use the button's id and perform whatever action you want on its onClickListener method.</p>
{ "question_id": 6355096, "question_date": "2011-06-15T08:40:20.543Z", "question_score": 236, "tags": "android|android-edittext", "answer_id": 6355178, "answer_date": "2011-06-15T08:48:10.350Z", "answer_score": 170 }
Please answer the following Stack Overflow question: Title: Why do 64-bit DLLs go to System32 and 32-bit DLLs to SysWoW64 on 64-bit Windows? <p>I would like to know when do we need to place a file under </p> <p>C:\Windows\System32 or C:\Windows\SysWOW64, on a 64-bits windows system.</p> <p>I had two DLL's, one for 32-bit, one for 64-bit.</p> <p>Logically, I thought I'd place the 32-bit DLL under C:\Windows\System32, and the 64-bit DLL under C:\Windows\SysWOW64.</p> <p>To my surprise, it's <strong>the other way around</strong>! The <strong>32</strong>-bit one goes into C:\Windows\SysWOW<b>64</b>, and the <strong>64</strong>-bit DLL goes into C:\Windows\System<b>32</b>.</p> <p>Very confusing stuff. What's the reason behind this?</p>
<p>I believe the intent was to rename System32, but so many applications hard-coded for that path, that it wasn't feasible to remove it. </p> <p>SysWoW64 wasn't intended for the dlls of 64-bit systems, it's actually something like "Windows on Windows64", meaning the bits you need to run 32bit apps on a 64bit windows. </p> <p><a href="https://web.archive.org/web/20161017204646/https://www.sepago.com/blog/2008/04/20/windows-x64-all-the-same-yet-very-different-part-7-file-system-and-registry" rel="noreferrer">This article</a> explains a bit:</p> <p>"Windows x64 has a directory System32 that contains 64-bit DLLs (sic!). Thus native processes with a bitness of 64 find “their” DLLs where they expect them: in the System32 folder. A second directory, SysWOW64, contains the 32-bit DLLs. The file system redirector does the magic of hiding the real System32 directory for 32-bit processes and showing SysWOW64 under the name of System32."</p> <p>Edit: If you're talking about an installer, you really <strong><em>should not</em></strong> hard-code the path to the system folder. Instead, let Windows take care of it for you based on whether or not your installer is running on the emulation layer.</p>
{ "question_id": 949959, "question_date": "2009-06-04T11:30:43.417Z", "question_score": 236, "tags": "dll|32bit-64bit|system32|syswow64", "answer_id": 950011, "answer_date": "2009-06-04T11:40:40.683Z", "answer_score": 233 }
Please answer the following Stack Overflow question: Title: How to split data into 3 sets (train, validation and test)? <p>I have a pandas dataframe and I wish to divide it to 3 separate sets. I know that using <a href="http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.train_test_split.html" rel="noreferrer">train_test_split</a> from <code>sklearn.cross_validation</code>, one can divide the data in two sets (train and test). However, I couldn't find any solution about splitting the data into three sets. Preferably, I'd like to have the indices of the original data. </p> <p>I know that a workaround would be to use <code>train_test_split</code> two times and somehow adjust the indices. But is there a more standard / built-in way to split the data into 3 sets instead of 2?</p>
<p>Numpy solution. We will shuffle the whole dataset first (<code>df.sample(frac=1, random_state=42)</code>) and then split our data set into the following parts:</p> <ul> <li>60% - train set,</li> <li>20% - validation set,</li> <li>20% - test set</li> </ul> <hr /> <pre><code>In [305]: train, validate, test = \ np.split(df.sample(frac=1, random_state=42), [int(.6*len(df)), int(.8*len(df))]) In [306]: train Out[306]: A B C D E 0 0.046919 0.792216 0.206294 0.440346 0.038960 2 0.301010 0.625697 0.604724 0.936968 0.870064 1 0.642237 0.690403 0.813658 0.525379 0.396053 9 0.488484 0.389640 0.599637 0.122919 0.106505 8 0.842717 0.793315 0.554084 0.100361 0.367465 7 0.185214 0.603661 0.217677 0.281780 0.938540 In [307]: validate Out[307]: A B C D E 5 0.806176 0.008896 0.362878 0.058903 0.026328 6 0.145777 0.485765 0.589272 0.806329 0.703479 In [308]: test Out[308]: A B C D E 4 0.521640 0.332210 0.370177 0.859169 0.401087 3 0.333348 0.964011 0.083498 0.670386 0.169619 </code></pre> <p><code>[int(.6*len(df)), int(.8*len(df))]</code> - is an <code>indices_or_sections </code> array for <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.split.html" rel="noreferrer">numpy.split()</a>.</p> <p>Here is a small demo for <code>np.split()</code> usage - let's split 20-elements array into the following parts: 80%, 10%, 10%:</p> <pre><code>In [45]: a = np.arange(1, 21) In [46]: a Out[46]: array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]) In [47]: np.split(a, [int(.8 * len(a)), int(.9 * len(a))]) Out[47]: [array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]), array([17, 18]), array([19, 20])] </code></pre>
{ "question_id": 38250710, "question_date": "2016-07-07T16:26:26.693Z", "question_score": 236, "tags": "pandas|numpy|dataframe|machine-learning|scikit-learn", "answer_id": 38251213, "answer_date": "2016-07-07T16:56:12.720Z", "answer_score": 274 }
Please answer the following Stack Overflow question: Title: Foreign key constraints: When to use ON UPDATE and ON DELETE <p>I'm designing my database schema using MySQL Workbench, which is pretty cool because you can do diagrams and it converts them :P</p> <p>Anyways, I've decided to use InnoDB because of it's Foreign Key support. One thing I noticed though is that it allows you to set On Update and on Delete options for foreign keys. Can someone explain where "Restrict", "Cascade" and set null could be used in a simple example?</p> <p>For example, say I have a <code>user</code> table which includes a <code>userID</code>. And say I have a message table <code>message</code> which is a many-to-many which has 2 foreign keys (which reference the same primary key, <code>userID</code> in the <code>user</code> table). Is setting the On Update and On Delete options any useful in this case? If so, which one do I choose? If this isn't a good example, could you please come up with a good example to illustrate how these could be useful?</p> <p>Thanks</p>
<p>Do not hesitate to put constraints on the database. You'll be sure to have a consistent database, and that's one of the good reasons to use a database. Especially if you have several applications requesting it (or just one application but with a direct mode and a batch mode using different sources).</p> <p>With MySQL you do not have advanced constraints like you would have in postgreSQL but at least the foreign key constraints are quite advanced.</p> <p>We'll take an example, a company table with a user table containing people from theses company</p> <pre><code>CREATE TABLE COMPANY ( company_id INT NOT NULL, company_name VARCHAR(50), PRIMARY KEY (company_id) ) ENGINE=INNODB; CREATE TABLE USER ( user_id INT, user_name VARCHAR(50), company_id INT, INDEX company_id_idx (company_id), FOREIGN KEY (company_id) REFERENCES COMPANY (company_id) ON... ) ENGINE=INNODB; </code></pre> <p>Let's look at the <strong>ON UPDATE</strong> clause:</p> <ul> <li><strong>ON UPDATE RESTRICT</strong> : <em>the default</em> : if you try to update a company_id in table COMPANY the engine will reject the operation if one USER at least links on this company.</li> <li><strong>ON UPDATE NO ACTION</strong> : same as RESTRICT.</li> <li><strong>ON UPDATE CASCADE</strong> : <em>the best one usually</em> : if you update a company_id in a row of table COMPANY the engine will update it accordingly on all USER rows referencing this COMPANY (but no triggers activated on USER table, warning). The engine will track the changes for you, it's good.</li> <li><strong>ON UPDATE SET NULL</strong> : if you update a company_id in a row of table COMPANY the engine will set related USERs company_id to NULL (should be available in USER company_id field). I cannot see any interesting thing to do with that on an update, but I may be wrong.</li> </ul> <p>And now on the <strong>ON DELETE</strong> side:</p> <ul> <li><strong>ON DELETE RESTRICT</strong> : <em>the default</em> : if you try to delete a company_id Id in table COMPANY the engine will reject the operation if one USER at least links on this company, can save your life.</li> <li><strong>ON DELETE NO ACTION</strong> : same as RESTRICT</li> <li><strong>ON DELETE CASCADE</strong> : <em>dangerous</em> : if you delete a company row in table COMPANY the engine will delete as well the related USERs. This is dangerous but can be used to make automatic cleanups on secondary tables (so it can be something you want, but quite certainly not for a COMPANY&lt;->USER example)</li> <li><strong>ON DELETE SET NULL</strong> : <em>handful</em> : if you delete a COMPANY row the related USERs will automatically have the relationship to NULL. If Null is your value for users with no company this can be a good behavior, for example maybe you need to keep the users in your application, as authors of some content, but removing the company is not a problem for you.</li> </ul> <p>usually my default is: <strong>ON DELETE RESTRICT ON UPDATE CASCADE</strong>. with some <code>ON DELETE CASCADE</code> for track tables (logs--not all logs--, things like that) and <code>ON DELETE SET NULL</code> when the master table is a 'simple attribute' for the table containing the foreign key, like a JOB table for the USER table.</p> <p><strong>Edit</strong></p> <p>It's been a long time since I wrote that. Now I think I should add one important warning. MySQL has one big documented limitation with cascades. <strong>Cascades are not firing triggers</strong>. So if you were over confident enough in that engine to use triggers you should avoid cascades constraints.</p> <ul> <li><a href="http://dev.mysql.com/doc/refman/5.6/en/triggers.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.6/en/triggers.html</a> </li> </ul> <blockquote> <p>MySQL triggers activate only for changes made to tables by SQL statements. They do not activate for changes in views, nor by changes to tables made by APIs that do not transmit SQL statements to the MySQL Server</p> </blockquote> <ul> <li><a href="http://dev.mysql.com/doc/refman/5.6/en/stored-program-restrictions.html#stored-routines-trigger-restrictions" rel="noreferrer">http://dev.mysql.com/doc/refman/5.6/en/stored-program-restrictions.html#stored-routines-trigger-restrictions</a></li> </ul> <p><strong>==> See below the last edit, things are moving on this domain</strong></p> <blockquote> <p>Triggers are not activated by foreign key actions.</p> </blockquote> <p>And I do not think this will get fixed one day. Foreign key constraints are managed by the InnoDb storage and Triggers are managed by the MySQL SQL engine. Both are separated. Innodb is the only storage with constraint management, maybe they'll add triggers directly in the storage engine one day, maybe not.</p> <p>But I have my own opinion on which element you should choose between the poor trigger implementation and the very useful foreign keys constraints support. And once you'll get used to database consistency you'll love PostgreSQL.</p> <h3>12/2017-Updating this Edit about MySQL:</h3> <p>as stated by @IstiaqueAhmed in the comments, the situation has changed on this subject. So follow the link and check the real up-to-date situation (which may change again in the future).</p>
{ "question_id": 6720050, "question_date": "2011-07-16T20:30:49.530Z", "question_score": 236, "tags": "mysql|sql|database|foreign-keys", "answer_id": 6720458, "answer_date": "2011-07-16T21:47:50.673Z", "answer_score": 562 }
Please answer the following Stack Overflow question: Title: Manifest merger failed : uses-sdk:minSdkVersion 14 <p>Since downloading the latest SDK and installing Android Studio, my project fails to build. I get the following message:</p> <pre><code>Error:Gradle: Execution failed for task ':SampleProject:processProdDebugManifest'. &gt; Manifest merger failed : uses-sdk:minSdkVersion 14 cannot be smaller than version L declared in library com.android.support:support-v4:21.0.0-rc1 </code></pre>
<p><strong>Note: This has been updated to reflect the release of API 21, Lollipop. Be sure to download the latest SDK.</strong></p> <p>In one of my modules I had the following in build.gradle:</p> <pre><code>dependencies { compile 'com.android.support:support-v4:+' } </code></pre> <p>Changing this to</p> <pre><code>dependencies { // do not use dynamic updating. compile 'com.android.support:support-v4:21.0.0' } </code></pre> <p>fixed the issue. </p> <p>Make sure you're not doing a general inclusion of <code>com.android.support:support-v4:+</code> or any other support libraries (v7, v13, appcompat, etc), anywhere in your project.</p> <p>I'd assume the problem is <code>v4:+</code> picks up the <s>release candidate (21.0.0-rc1)</s> latest L release which obviously requires the L SDK. </p> <p><strong>Edit:</strong></p> <p>If you need to use the new views (CardView, RecyclerView, and Palette), the following should work:</p> <pre><code>compile "com.android.support:cardview-v7:21.0.0" compile "com.android.support:recyclerview-v7:21.0.0" compile "com.android.support:palette-v7:21.0.0" </code></pre> <p>(Credit to EddieRingle on /androiddev - <a href="http://www.reddit.com/r/androiddev/comments/297xli/howto_use_the_v21_support_libs_on_older_versions/" rel="noreferrer">http://www.reddit.com/r/androiddev/comments/297xli/howto_use_the_v21_support_libs_on_older_versions/</a>)</p> <p><strong>Another Edit</strong></p> <p>Be sure to see @murtuza's answer below regarding appcompat-v7 and upvote if it helps!</p>
{ "question_id": 24438170, "question_date": "2014-06-26T19:00:51.550Z", "question_score": 236, "tags": "android|android-studio|android-gradle-plugin|android-5.0-lollipop", "answer_id": 24438395, "answer_date": "2014-06-26T19:13:44.973Z", "answer_score": 312 }
Please answer the following Stack Overflow question: Title: Jenkins: Can comments be added to a Jenkinsfile? <p>Are comments possible in a Jenkinsfile? If so, what's the syntax?</p> <p>I am using the declarative pipeline syntax.</p> <p>I want to comment out the "post" section below until my SMTP server is working.</p> <pre><code>pipeline { agent { label 'docker-build-slave' } environment { IMAGE = 'registry.gitlab.com/XXXXX/bible-server' DOCKER_REGISTRY_CREDENTIALS = credentials('DOCKER_REGISTRY_CREDENTIALS') } options { timeout(10) } stages { stage('Test') { steps { sh 'yarn' sh 'npm test' } } stage('Build') { when { branch '*/master' } steps { sh 'docker login -u ${DOCKER_REGISTRY_CREDENTIALS_USR} -p ${DOCKER_REGISTRY_CREDENTIALS_PSW} registry.gitlab.com' sh 'docker build -t ${IMAGE}:${BRANCH_NAME} .' sh 'docker push ${IMAGE}:${BRANCH_NAME}' } } stage('Deploy') { when { branch '*/master' } steps { echo 'Deploying ..' } } } post { success { mail to: "[email protected]", subject:"SUCCESS: ${currentBuild.fullDisplayName}", body: "Yay, we passed." } failure { mail to: "[email protected]", subject:"FAILURE: ${currentBuild.fullDisplayName}", body: "Boo, we failed." } } } </code></pre>
<p>The Jenkinsfile is written in groovy which uses the Java (and C) form of comments:</p> <pre><code>/* this is a multi-line comment */ // this is a single line comment </code></pre>
{ "question_id": 42309957, "question_date": "2017-02-18T01:11:51.187Z", "question_score": 236, "tags": "jenkins|groovy|comments|jenkins-pipeline", "answer_id": 42310598, "answer_date": "2017-02-18T03:01:06.090Z", "answer_score": 373 }
Please answer the following Stack Overflow question: Title: Programmatically saving image to Django ImageField <p>Ok, I've tried about near everything and I cannot get this to work.</p> <ul> <li>I have a Django model with an ImageField on it</li> <li>I have code that downloads an image via HTTP (tested and works)</li> <li>The image is saved directly into the 'upload_to' folder (the upload_to being the one that is set on the ImageField)</li> <li>All I need to do is associate the already existing image file path with the ImageField</li> </ul> <p>I've written this code about 6 different ways.</p> <p>The problem I'm running into is all of the code that I'm writing results in the following behavior: (1) Django will make a 2nd file, (2) rename the new file, adding an _ to the end of the file name, then (3) not transfer any of the data over leaving it basically an empty re-named file. What's left in the 'upload_to' path is 2 files, one that is the actual image, and one that is the name of the image,but is empty, and of course the ImageField path is set to the empty file that Django try to create.</p> <p>In case that was unclear, I'll try to illustrate:</p> <pre><code>## Image generation code runs.... /Upload generated_image.jpg 4kb ## Attempt to set the ImageField path... /Upload generated_image.jpg 4kb generated_image_.jpg 0kb ImageField.Path = /Upload/generated_image_.jpg </code></pre> <p>How can I do this without having Django try to re-store the file? What I'd really like is something to this effect...</p> <pre><code>model.ImageField.path = generated_image_path </code></pre> <p>...but of course that doesn't work.</p> <p>And yes I've gone through the other questions here like <a href="https://stackoverflow.com/questions/811167/how-to-manually-assign-imagefield-in-django">this one</a> as well as the django doc on <a href="http://docs.djangoproject.com/en/dev/ref/files/file/#django.core.files.File.save" rel="noreferrer">File</a></p> <p><strong>UPDATE</strong> After further testing, it only does this behavior when running under Apache on Windows Server. While running under the 'runserver' on XP it does not execute this behavior. </p> <p>I am stumped.</p> <p>Here is the code which runs successfully on XP...</p> <pre><code>f = open(thumb_path, 'r') model.thumbnail = File(f) model.save() </code></pre>
<p>I have some code that fetches an image off the web and stores it in a model. The important bits are:</p> <pre><code>from django.core.files import File # you need this somewhere import urllib # The following actually resides in a method of my model result = urllib.urlretrieve(image_url) # image_url is a URL to an image # self.photo is the ImageField self.photo.save( os.path.basename(self.url), File(open(result[0], 'rb')) ) self.save() </code></pre> <p>That's a bit confusing because it's pulled out of my model and a bit out of context, but the important parts are:</p> <ul> <li>The image pulled from the web is <em>not</em> stored in the upload_to folder, it is instead stored as a tempfile by urllib.urlretrieve() and later discarded.</li> <li>The ImageField.save() method takes a filename (the os.path.basename bit) and a django.core.files.File object.</li> </ul> <p>Let me know if you have questions or need clarification.</p> <p>Edit: for the sake of clarity, here is the model (minus any required import statements):</p> <pre><code>class CachedImage(models.Model): url = models.CharField(max_length=255, unique=True) photo = models.ImageField(upload_to=photo_path, blank=True) def cache(self): """Store image locally if we have a URL""" if self.url and not self.photo: result = urllib.urlretrieve(self.url) self.photo.save( os.path.basename(self.url), File(open(result[0], 'rb')) ) self.save() </code></pre>
{ "question_id": 1308386, "question_date": "2009-08-20T19:42:39.063Z", "question_score": 236, "tags": "python|django|django-models", "answer_id": 1309682, "answer_date": "2009-08-21T01:32:50.963Z", "answer_score": 196 }
Please answer the following Stack Overflow question: Title: How to generate javadoc comments in Android Studio <p><strong>Can I use shortcut keys in Android studio to generate javadoc comments?</strong></p> <p>If not, what is the easiest way to generate javadoc comments?</p>
<p>I can't find any shortcut to generate javadoc comments. But if you type <code>/**</code> before the method declaration and press Enter, the javadoc comment block will be generated automatically.</p> <p>Read <a href="https://www.jetbrains.com/help/idea/working-with-code-documentation.html#add-new-comment" rel="noreferrer">this</a> for more information.</p>
{ "question_id": 17291785, "question_date": "2013-06-25T07:42:37.663Z", "question_score": 236, "tags": "android-studio|javadoc", "answer_id": 17355906, "answer_date": "2013-06-28T01:33:54.843Z", "answer_score": 424 }
Please answer the following Stack Overflow question: Title: Why does typeof array with objects return "object" and not "array"? <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/4775722/javascript-check-if-object-is-array">JavaScript: Check if object is array?</a> </p> </blockquote> <p>Why is an array of objects considered an object, and not an array? For example:</p> <pre><code>$.ajax({ url: 'http://api.twitter.com/1/statuses/user_timeline.json', data: { screen_name: 'mick__romney'}, dataType: 'jsonp', success: function(data) { console.dir(data); //Array[20] alert(typeof data); //Object } });​ </code></pre> <p><a href="http://jsfiddle.net/6JCcj/" rel="noreferrer">Fiddle</a></p>
<p>One of the weird behaviour and spec in Javascript is the typeof Array is <code>Object</code>.</p> <p>You can check if the variable is an array in couple of ways:</p> <pre><code>var isArr = data instanceof Array; var isArr = Array.isArray(data); </code></pre> <p>But the most reliable way is:</p> <pre><code>isArr = Object.prototype.toString.call(data) == '[object Array]'; </code></pre> <p>Since you tagged your question with jQuery, you can use jQuery <a href="http://api.jquery.com/jQuery.isArray/"><code>isArray</code></a> function:</p> <pre><code>var isArr = $.isArray(data); </code></pre>
{ "question_id": 12996871, "question_date": "2012-10-21T10:05:04.217Z", "question_score": 236, "tags": "javascript|jquery|arrays|object|typeof", "answer_id": 12996879, "answer_date": "2012-10-21T10:05:51.957Z", "answer_score": 341 }
Please answer the following Stack Overflow question: Title: Password masking console application <p>I tried the following code... </p> <pre><code>string pass = ""; Console.Write("Enter your password: "); ConsoleKeyInfo key; do { key = Console.ReadKey(true); // Backspace Should Not Work if (key.Key != ConsoleKey.Backspace) { pass += key.KeyChar; Console.Write("*"); } else { Console.Write("\b"); } } // Stops Receving Keys Once Enter is Pressed while (key.Key != ConsoleKey.Enter); Console.WriteLine(); Console.WriteLine("The Password You entered is : " + pass); </code></pre> <p>But this way the backspace functionality doesn't work while typing the password. Any suggestion?</p>
<p><code>Console.Write(&quot;\b \b&quot;);</code> will delete the asterisk character from the screen, but you do not have any code within your <code>else</code> block that removes the previously entered character from your <code>pass</code> string variable.</p> <p>Here's the relevant working code that should do what you require:</p> <pre><code>var pass = string.Empty; ConsoleKey key; do { var keyInfo = Console.ReadKey(intercept: true); key = keyInfo.Key; if (key == ConsoleKey.Backspace &amp;&amp; pass.Length &gt; 0) { Console.Write(&quot;\b \b&quot;); pass = pass[0..^1]; } else if (!char.IsControl(keyInfo.KeyChar)) { Console.Write(&quot;*&quot;); pass += keyInfo.KeyChar; } } while (key != ConsoleKey.Enter); </code></pre>
{ "question_id": 3404421, "question_date": "2010-08-04T09:59:24Z", "question_score": 236, "tags": "c#|passwords|console-application|user-input|masking", "answer_id": 3404522, "answer_date": "2010-08-04T10:13:43.487Z", "answer_score": 276 }
Please answer the following Stack Overflow question: Title: How can I conditionally require form inputs with AngularJS? <p>Suppose we're building an address book application (contrived example) with AngularJS.</p> <p>We have a form for contacts that has inputs for email and phone number, and we want to require <strong>one or the other</strong>, but <strong>not both</strong>: We only want the <code>email</code> input to be required if the <code>phone</code> input is empty or invalid, and vice versa.</p> <p>Angular has a <code>required</code> directive, but it's not clear from the documentation how to use it in this case. So how can we conditionally require a form field? Write a custom directive?</p>
<p>There's no need to write a custom directive. Angular's documentation is good but not complete. <a href="https://github.com/angular/angular.js/issues/1202" rel="noreferrer">In fact</a>, there is a directive called <code>ngRequired</code>, that takes an Angular expression.</p> <pre><code>&lt;input type='email' name='email' ng-model='contact.email' placeholder='[email protected]' ng-required='!contact.phone' /&gt; &lt;input type='text' ng-model='contact.phone' placeholder='(xxx) xxx-xxxx' ng-required='!contact.email' /&gt; </code></pre> <p>Here's a more complete example: <a href="http://jsfiddle.net/uptnx/1/" rel="noreferrer">http://jsfiddle.net/uptnx/1/</a></p>
{ "question_id": 13466133, "question_date": "2012-11-20T03:24:40.180Z", "question_score": 236, "tags": "forms|validation|angularjs", "answer_id": 13466134, "answer_date": "2012-11-20T03:24:40.180Z", "answer_score": 470 }
Please answer the following Stack Overflow question: Title: create multiple tag docker image <p>How can several tags be attached to one Docker image? Is it possible to create multiple tags using <strong>one Dockerfile</strong>?</p> <p>It is possible, <em>somehow</em>; for example <code>docker pull ubuntu</code> will get several images, some of which have multiple tags:</p> <pre><code>ubuntu 13.10 9f676bd305a4 2 weeks ago 182.1 MB ubuntu saucy 9f676bd305a4 2 weeks ago 182.1 MB ubuntu raring eb601b8965b8 2 weeks ago 170.2 MB ubuntu 13.04 eb601b8965b8 2 weeks ago 170.2 MB ubuntu 12.10 5ac751e8d623 2 weeks ago 161.4 MB ubuntu quantal 5ac751e8d623 2 weeks ago 161.4 MB ubuntu 10.04 9cc9ea5ea540 2 weeks ago 183 MB ubuntu lucid 9cc9ea5ea540 2 weeks ago 183 MB ubuntu 12.04 9cd978db300e 2 weeks ago 204.7 MB ubuntu latest 9cd978db300e 2 weeks ago 204.7 MB ubuntu precise 9cd978db300e 2 weeks ago 204.7 MB </code></pre>
<p>You can't create tags with Dockerfiles but you can create multiple tags on your images via the command line.</p> <p>Use this to list your image ids:</p> <pre><code>$ docker images </code></pre> <p>Then tag away:</p> <pre><code>$ docker tag 9f676bd305a4 ubuntu:13.10 $ docker tag 9f676bd305a4 ubuntu:saucy $ docker tag eb601b8965b8 ubuntu:raring ... </code></pre>
{ "question_id": 21928780, "question_date": "2014-02-21T08:10:07.157Z", "question_score": 236, "tags": "docker|tags", "answer_id": 23161348, "answer_date": "2014-04-18T19:58:22.393Z", "answer_score": 110 }
Please answer the following Stack Overflow question: Title: Is there a mechanism to loop x times in ES6 (ECMAScript 6) without mutable variables? <p>The typical way to loop <code>x</code> times in JavaScript is:</p> <pre><code>for (var i = 0; i &lt; x; i++) doStuff(i); </code></pre> <p>But I don't want to use the <code>++</code> operator or have any mutable variables at all. So is there a way, in ES6, to loop <code>x</code> times another way? I love Ruby's mechanism:</p> <pre><code>x.times do |i| do_stuff(i) end </code></pre> <p>Anything similar in JavaScript/ES6? I could kind of cheat and make my own generator:</p> <pre><code>function* times(x) { for (var i = 0; i &lt; x; i++) yield i; } for (var i of times(5)) { console.log(i); } </code></pre> <p>Of course I'm still using <code>i++</code>. At least it's out of sight :), but I'm hoping there's a better mechanism in ES6.</p>
<p>OK!</p> <p>The code below is written using ES6 syntaxes but could just as easily be written in ES5 or even less. ES6 is <strong>not</strong> a requirement to create a "mechanism to loop x times"</p> <hr> <p><strong>If you don't need the iterator in the callback</strong>, this is the most simple implementation</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const times = x =&gt; f =&gt; { if (x &gt; 0) { f() times (x - 1) (f) } } // use it times (3) (() =&gt; console.log('hi')) // or define intermediate functions for reuse let twice = times (2) // twice the power ! twice (() =&gt; console.log('double vision'))</code></pre> </div> </div> </p> <p><strong>If you do need the iterator</strong>, you can use a named inner function with a counter parameter to iterate for you</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const times = n =&gt; f =&gt; { let iter = i =&gt; { if (i === n) return f (i) iter (i + 1) } return iter (0) } times (3) (i =&gt; console.log(i, 'hi'))</code></pre> </div> </div> </p> <hr> <blockquote> <p>Stop reading here if you don't like learning more things ...</p> </blockquote> <p><strong>But something should feel off about those...</strong></p> <ul> <li>single branch <code>if</code> statements are ugly &mdash; <em>what happens on the other branch&nbsp;?</em></li> <li>multiple statements/expressions in the function bodies &mdash; <em>are procedure concerns being mixed&nbsp;?</em></li> <li>implicitly returned <code>undefined</code> &mdash; indication of impure, side-effecting function</li> </ul> <p><strong><em>"Isn't there a better way ?"</em></strong></p> <p>There is. Let's first revisit our initial implementation</p> <pre><code>// times :: Int -> (void -> void) -> void const times = x => f => { if (x > 0) { <b>f()</b> // has to be side-effecting function times (x - 1) (f) } }</code></pre> <p>Sure, it's simple, but notice how we just call <code>f()</code> and don't do anything with it. This really limits the type of function we can repeat multiple times. Even if we have the iterator available, <code>f(i)</code> isn't much more versatile.</p> <p>What if we start with a better kind of function repetition procedure ? Maybe something that makes better use of input and output.</p> <p><strong>Generic function repetition</strong></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>// repeat :: forall a. Int -&gt; (a -&gt; a) -&gt; a -&gt; a const repeat = n =&gt; f =&gt; x =&gt; { if (n &gt; 0) return repeat (n - 1) (f) (f (x)) else return x } // power :: Int -&gt; Int -&gt; Int const power = base =&gt; exp =&gt; { // repeat &lt;exp&gt; times, &lt;base&gt; * &lt;x&gt;, starting with 1 return repeat (exp) (x =&gt; base * x) (1) } console.log(power (2) (8)) // =&gt; 256</code></pre> </div> </div> </p> <p>Above, we defined a generic <code>repeat</code> function which takes an additional input which is used to start the repeated application of a single function.</p> <pre><code>// repeat 3 times, the function f, starting with x ... var result = repeat (3) (f) (x) // is the same as ... var result = f(f(f(x))) </code></pre> <hr> <p><strong>Implementing <code>times</code> with <code>repeat</code></strong></p> <p>Well this is easy now; almost all of the work is already done.</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>// repeat :: forall a. Int -&gt; (a -&gt; a) -&gt; a -&gt; a const repeat = n =&gt; f =&gt; x =&gt; { if (n &gt; 0) return repeat (n - 1) (f) (f (x)) else return x } // times :: Int -&gt; (Int -&gt; Int) -&gt; Int const times = n=&gt; f=&gt; repeat (n) (i =&gt; (f(i), i + 1)) (0) // use it times (3) (i =&gt; console.log(i, 'hi'))</code></pre> </div> </div> </p> <p>Since our function takes <code>i</code> as an input and returns <code>i + 1</code>, this effectively works as our iterator which we pass to <code>f</code> each time.</p> <p>We've fixed our bullet list of issues too</p> <ul> <li>No more ugly single branch <code>if</code> statements</li> <li>Single-expression bodies indicate nicely separated concerns</li> <li>No more useless, implicitly returned <code>undefined</code></li> </ul> <hr> <p><strong>JavaScript comma operator, the</strong></p> <p>In case you're having trouble seeing how the last example is working, it depends on your awareness of one of JavaScript's oldest battle axes; the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator" rel="noreferrer">comma operator</a> – in short, it evaluates expressions from left to right and <strong>returns</strong> the value of the last evaluated expression</p> <pre><code>(expr1 :: a, expr2 :: b, expr3 :: c) :: c </code></pre> <p>In our above example, I'm using</p> <pre><code>(i =&gt; (f(i), i + 1)) </code></pre> <p>which is just a succinct way of writing</p> <pre><code>(i =&gt; { f(i); return i + 1 }) </code></pre> <hr> <p><strong>Tail Call Optimisation</strong></p> <p>As sexy as the recursive implementations are, at this point it would be irresponsible for me to recommend them given that no <a href="https://v8project.blogspot.ca/2016/04/es6-es7-and-beyond.html" rel="noreferrer">JavaScript VM</a> I can think of supports proper tail call elimination – babel used to transpile it, but it's been in "broken; will reimplement" status for well over a year.</p> <pre><code>repeat (1e6) (someFunc) (x) // =&gt; RangeError: Maximum call stack size exceeded </code></pre> <p>As such, we should revisit our implementation of <code>repeat</code> to make it stack-safe.</p> <p>The code below <em>does</em> use mutable variables <code>n</code> and <code>x</code> but note that all mutations are localized to the <code>repeat</code> function – no state changes (mutations) are visible from outside of the function</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>// repeat :: Int -&gt; (a -&gt; a) -&gt; (a -&gt; a) const repeat = n =&gt; f =&gt; x =&gt; { let m = 0, acc = x while (m &lt; n) (m = m + 1, acc = f (acc)) return acc } // inc :: Int -&gt; Int const inc = x =&gt; x + 1 console.log (repeat (1e8) (inc) (0)) // 100000000</code></pre> </div> </div> </p> <p>This is going to have a lot of you saying "but that's not functional !" – I know, just relax. We can implement a Clojure-style <code>loop</code>/<code>recur</code> interface for constant-space looping using <em>pure expressions</em>; none of that <code>while</code> stuff.</p> <p>Here we abstract <code>while</code> away with our <code>loop</code> function – it looks for a special <code>recur</code> type to keep the loop running. When a non-<code>recur</code> type is encountered, the loop is finished and the result of the computation is returned</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const recur = (...args) =&gt; ({ type: recur, args }) const loop = f =&gt; { let acc = f () while (acc.type === recur) acc = f (...acc.args) return acc } const repeat = $n =&gt; f =&gt; x =&gt; loop ((n = $n, acc = x) =&gt; n === 0 ? acc : recur (n - 1, f (acc))) const inc = x =&gt; x + 1 const fibonacci = $n =&gt; loop ((n = $n, a = 0, b = 1) =&gt; n === 0 ? a : recur (n - 1, b, a + b)) console.log (repeat (1e7) (inc) (0)) // 10000000 console.log (fibonacci (100)) // 354224848179262000000</code></pre> </div> </div> </p>
{ "question_id": 30452263, "question_date": "2015-05-26T07:32:28.723Z", "question_score": 236, "tags": "javascript|generator|ecmascript-6|ecmascript-harmony", "answer_id": 30452949, "answer_date": "2015-05-26T08:08:09.953Z", "answer_score": 184 }
Please answer the following Stack Overflow question: Title: Passing Data to a Stateful Widget in Flutter <p>I'm wondering what the recommended way of passing data to a stateful widget, while creating it, is.</p> <p>The two styles I've seen are:</p> <pre><code>class ServerInfo extends StatefulWidget { Server _server; ServerInfo(Server server) { this._server = server; } @override State&lt;StatefulWidget&gt; createState() =&gt; new _ServerInfoState(_server); } class _ServerInfoState extends State&lt;ServerInfo&gt; { Server _server; _ServerInfoState(Server server) { this._server = server; } } </code></pre> <p>This method keeps a value both in <code>ServerInfo</code> and <code>_ServerInfoState</code>, which seems a bit wasteful.</p> <p>The other method is to use <code>widget._server</code>:</p> <pre><code>class ServerInfo extends StatefulWidget { Server _server; ServerInfo(Server server) { this._server = server; } @override State&lt;StatefulWidget&gt; createState() =&gt; new _ServerInfoState(); } class _ServerInfoState extends State&lt;ServerInfo&gt; { @override Widget build(BuildContext context) { widget._server = "10"; // Do something we the server value return null; } } </code></pre> <p>This seems a bit backwards as the state is no longer stored in <code>_ServerInfoSate</code> but instead in the widget.</p> <p>Is there a best practice for this?</p>
<p>Don't pass parameters to <code>State</code> using it's constructor. You should only access the parameters using <code>this.widget.myField</code>.</p> <p>Not only editing the constructor requires a lot of manual work ; it doesn't bring anything. There's no reason to duplicate all the fields of <code>Widget</code>.</p> <p><strong>EDIT :</strong></p> <p>Here's an example:</p> <pre><code>class ServerIpText extends StatefulWidget { final String serverIP; const ServerIpText ({ Key? key, this.serverIP }): super(key: key); @override _ServerIpTextState createState() =&gt; _ServerIpTextState(); } class _ServerIpTextState extends State&lt;ServerIpText&gt; { @override Widget build(BuildContext context) { return Text(widget.serverIP); } } class AnotherClass extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: ServerIpText(serverIP: &quot;127.0.0.1&quot;) ); } } </code></pre>
{ "question_id": 50818770, "question_date": "2018-06-12T13:43:39.360Z", "question_score": 236, "tags": "flutter|dart|statefulwidget|pass-data", "answer_id": 50818870, "answer_date": "2018-06-12T13:48:56.427Z", "answer_score": 450 }
Please answer the following Stack Overflow question: Title: pass **kwargs argument to another function with **kwargs <p>I do not understand the following example, let's say I have these functions:</p> <pre><code># python likes def save(filename, data, **kwargs): fo = openX(filename, &quot;w&quot;, **kwargs) # &lt;- #1 fo.write(data) fo.close() # python doesnt like def save2(filename, data, **kwargs): fo = openX(filename, &quot;w&quot;, kwargs) # &lt;- #2 fo.write(data) fo.close() def openX(filename, mode, **kwargs): #doing something fancy and returning a file object </code></pre> <p>Why is #1 the right solution and #2 the wrong one? <code>**kwargs</code> is basically a dict, so if I want to pass down the argument to openX I think the correct way would be without <code>**</code> and just giving the dict. But Python obviously doesn't like the second one and tells me I gave 3 instead of 2 arguments.</p> <p>So what's the reason behind this?</p>
<p>In the second example you provide 3 arguments: filename, mode and a dictionary (<code>kwargs</code>). But Python expects: 2 formal arguments plus keyword arguments.</p> <p>By prefixing the dictionary by '**' you unpack the dictionary <code>kwargs</code> to keywords arguments.</p> <p>A dictionary (type <code>dict</code>) is a single variable containing key-value pairs.</p> <p>"Keyword arguments" are key-value method-parameters.</p> <p>Any dictionary can by unpacked to keyword arguments by prefixing it with <code>**</code> during function call.</p>
{ "question_id": 9867562, "question_date": "2012-03-26T06:28:16.063Z", "question_score": 236, "tags": "python", "answer_id": 9867675, "answer_date": "2012-03-26T06:38:26.870Z", "answer_score": 229 }
Please answer the following Stack Overflow question: Title: ffmpeg overwrite output file if exists <p>I ran:</p> <pre><code>ffmpeg -i input.flac output.mp3 </code></pre> <p>This prompts:</p> <blockquote> <p>File 'output.mp3' already exists. Overwrite? [y/N] y</p> </blockquote> <p>How do I automatically say &quot;yes&quot;?</p>
<p>Use the <code>-y</code> option to automatically overwrite [<a href="https://ffmpeg.org/ffmpeg.html#Main-options" rel="noreferrer">docs</a>]:</p> <pre><code>ffmpeg -y -i input.flac output.mp3 </code></pre>
{ "question_id": 39788972, "question_date": "2016-09-30T10:08:09.440Z", "question_score": 236, "tags": "ffmpeg", "answer_id": 39789131, "answer_date": "2016-09-30T10:15:43.817Z", "answer_score": 444 }
Please answer the following Stack Overflow question: Title: Add a CSS class to <%= f.submit %> <p>My question is easy:</p> <pre><code>&lt;%= f.submit %&gt; </code></pre> <p>Where does the class declaration go? I'm getting errors on multiple attempts.</p>
<pre><code>&lt;%= f.submit 'name of button here', :class =&gt; 'submit_class_name_here' %&gt; </code></pre> <p>This should do. If you're getting an error, chances are that you're not supplying the name.</p> <p>Alternatively, you can style the button without a class:</p> <pre><code>form#form_id_here input[type=submit] </code></pre> <p>Try that, as well.</p>
{ "question_id": 5315967, "question_date": "2011-03-15T18:00:26.780Z", "question_score": 236, "tags": "ruby-on-rails|css|ruby-on-rails-3", "answer_id": 5316059, "answer_date": "2011-03-15T18:07:29.137Z", "answer_score": 379 }
Please answer the following Stack Overflow question: Title: Why is it faster to check if dictionary contains the key, rather than catch the exception in case it doesn't? <p>Imagine the code:</p> <pre><code>public class obj { // elided } public static Dictionary&lt;string, obj&gt; dict = new Dictionary&lt;string, obj&gt;(); </code></pre> <p><strong>Method 1</strong></p> <pre><code>public static obj FromDict1(string name) { if (dict.ContainsKey(name)) { return dict[name]; } return null; } </code></pre> <p><strong>Method 2</strong></p> <pre><code>public static obj FromDict2(string name) { try { return dict[name]; } catch (KeyNotFoundException) { return null; } } </code></pre> <p>I was curious if there is a difference in performance of these 2 functions, because the first one SHOULD be SLOWER than second one - given that it needs to check twice if the dictionary contains a value, while second function does need to access the dictionary only once but WOW, it's actually opposite:</p> <p>Loop for 1 000 000 values (with 100 000 existing and 900 000 non existing):</p> <blockquote> <p>first function: 306 milliseconds</p> <p>second function: 20483 milliseconds</p> </blockquote> <p>Why is that?</p> <p>EDIT: As you can notice in comments below this question, the performance of second function is actually slightly better than first one in case there are 0 non existing keys. But once there is at least 1 or more non existing keys, the performance of second one decrease rapidly.</p>
<p>On the one hand, <a href="http://msdn.microsoft.com/en-us/library/vstudio/ms229009.aspx" rel="noreferrer">throwing exceptions is inherently expensive</a>, because the stack has to be unwound etc.<br> On the other hand, accessing a value in a dictionary by its key is cheap, because it's a fast, O(1) operation.</p> <p>BTW: The correct way to do this is to use <a href="http://msdn.microsoft.com/en-us/library/bb347013.aspx" rel="noreferrer"><code>TryGetValue</code></a></p> <pre><code>obj item; if(!dict.TryGetValue(name, out item)) return null; return item; </code></pre> <p>This accesses the dictionary only once instead of twice.<br> If you really want to just return <code>null</code> if the key doesn't exist, the above code can be simplified further:</p> <pre><code>obj item; dict.TryGetValue(name, out item); return item; </code></pre> <p>This works, because <code>TryGetValue</code> sets <code>item</code> to <code>null</code> if no key with <code>name</code> exists.</p>
{ "question_id": 16101795, "question_date": "2013-04-19T09:47:16.507Z", "question_score": 236, "tags": "c#|performance|dictionary", "answer_id": 16101815, "answer_date": "2013-04-19T09:48:33.360Z", "answer_score": 408 }
Please answer the following Stack Overflow question: Title: Git: copy all files in a directory from another branch <p>How do I copy all files in a directory from another branch? I can list all of the files in that directory by doing </p> <pre><code>git ls-tree master:dirname </code></pre> <p>I can then copy all of the files individually by doing</p> <pre><code>git checkout master -- dirname/filename </code></pre> <p>However, using wildcards has so far been a total fail. This does nothing: </p> <pre><code>git checkout master -- dirname/*.png </code></pre> <p>Though I guess I can use a bash script to do that, there has to be an easier way, right?</p>
<p>As you are not trying to move the files around in the tree, you should be able to just checkout the directory:</p> <pre><code>git checkout master -- dirname </code></pre>
{ "question_id": 2668886, "question_date": "2010-04-19T15:55:02.997Z", "question_score": 236, "tags": "git|file|copy|branch", "answer_id": 2668947, "answer_date": "2010-04-19T16:04:50.533Z", "answer_score": 372 }
Please answer the following Stack Overflow question: Title: How can I pass variable into an evaluate function? <p>I'm trying to pass a variable into a <code>page.evaluate()</code> function in <a href="https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pageevaluatepagefunction-args" rel="noreferrer">Puppeteer</a>, but when I use the following very simplified example, the variable <code>evalVar</code> is undefined.</p> <p>I'm new to Puppeteer and can't find any examples to build on, so I need help passing that variable into the <code>page.evaluate()</code> function so I can use it inside.</p> <pre><code>const puppeteer = require('puppeteer'); (async() =&gt; { const browser = await puppeteer.launch({headless: false}); const page = await browser.newPage(); const evalVar = 'WHUT??'; try { await page.goto('https://www.google.com.au'); await page.waitForSelector('#fbar'); const links = await page.evaluate((evalVar) =&gt; { console.log('evalVar:', evalVar); // appears undefined const urls = []; hrefs = document.querySelectorAll('#fbar #fsl a'); hrefs.forEach(function(el) { urls.push(el.href); }); return urls; }) console.log('links:', links); } catch (err) { console.log('ERR:', err.message); } finally { // browser.close(); } })(); </code></pre>
<p>You have to pass the variable as an argument to the <code>pageFunction</code> like this:</p> <pre><code>const links = await page.evaluate((evalVar) =&gt; { console.log(evalVar); // 2. should be defined now … }, evalVar); // 1. pass variable as an argument </code></pre> <p>You can pass in multiple variables by passing more arguments to <code>page.evaluate()</code>:</p> <pre><code>await page.evaluate((a, b c) =&gt; { console.log(a, b, c) }, a, b, c) </code></pre> <p>The arguments must either be serializable as JSON or <a href="https://pptr.dev/#?show=api-class-jshandle" rel="noreferrer"><code>JSHandle</code></a>s of in-browser objects: <a href="https://pptr.dev/#?show=api-pageevaluatepagefunction-args" rel="noreferrer">https://pptr.dev/#?show=api-pageevaluatepagefunction-args</a></p>
{ "question_id": 46088351, "question_date": "2017-09-07T05:17:33.140Z", "question_score": 236, "tags": "javascript|web-scraping|evaluate|puppeteer", "answer_id": 46098448, "answer_date": "2017-09-07T14:04:55.870Z", "answer_score": 363 }
Please answer the following Stack Overflow question: Title: Visual Studio Disabling Missing XML Comment Warning <p>I have a project with over 500 <code>Missing XML Comment</code> warnings. I know I can remove the XML Comment feature, or paste empty comment snippets everywhere, but I'd prefer a generic solution where I can make one change that disables all warnings of this type.</p> <p>What I do just now is putting</p> <pre><code>///&lt;Summary&gt; /// ///&lt;/Summary&gt; </code></pre> <p>or </p> <pre><code>#pragma warning disable 1591 </code></pre> <p>was just curious if it would be possible.</p>
<p>As suggested above, in general I don't think that these warnings should be ignored (suppressed). To summarise, the ways around the warning would be to: </p> <ul> <li>Suppress the warning by changing the project <code>Properties</code> > <code>Build</code> > <code>Errors and warnings</code> > <code>Suppress warnings</code> by entering 1591</li> <li>Add the XML documentation tags (<a href="http://submain.com/products/ghostdoc.aspx" rel="noreferrer">GhostDoc</a> can be quite handy for that)</li> <li>Suppress the warning via compiler options</li> <li>Uncheck the "XML documentation file" checkbox in project <code>Properties</code> > <code>Build</code> > <code>Output</code></li> <li>Add <code>#pragma warning disable 1591</code> at the top of the respective file and <code>#pragma warning restore 1591</code> at the bottom</li> </ul>
{ "question_id": 7982525, "question_date": "2011-11-02T15:03:25.317Z", "question_score": 236, "tags": "visual-studio-2010|xml-comments", "answer_id": 8532145, "answer_date": "2011-12-16T09:28:11.797Z", "answer_score": 367 }
Please answer the following Stack Overflow question: Title: What are the debug memory fill patterns in Visual Studio C++ and Windows? <p>In Visual Studio, we've all had "baadf00d", have seen seen "CC" and "CD" when inspecting variables in the debugger in C++ during run-time.</p> <p>From what I understand, "CC" is in DEBUG mode only to indicate when a memory has been new() or alloc() and unitilialized. While "CD" represents delete'd or free'd memory. I've only seen "baadf00d" in RELEASE build (but I may be wrong).</p> <p>Once in a while, we get into a situation of tacking memory leaks, buffer overflows, etc and these kind of information comes in handy.</p> <p>Would somebody be kind enough to point out when and in what modes the memory are set to recognizable byte patterns for debugging purpose?</p>
<p>This link has more information:</p> <p><a href="https://en.wikipedia.org/wiki/Magic_number_(programming)#Debug_values" rel="noreferrer">https://en.wikipedia.org/wiki/Magic_number_(programming)#Debug_values</a></p> <pre> * 0xABABABAB : Used by Microsoft's HeapAlloc() to mark "no man's land" guard bytes after allocated heap memory * 0xABADCAFE : A startup to this value to initialize all free memory to catch errant pointers * 0xBAADF00D : Used by Microsoft's LocalAlloc(LMEM_FIXED) to mark uninitialised allocated heap memory * 0xBADCAB1E : Error Code returned to the Microsoft eVC debugger when connection is severed to the debugger * 0xBEEFCACE : Used by Microsoft .NET as a magic number in resource files * 0xCCCCCCCC : Used by Microsoft's C++ debugging runtime library to mark uninitialised stack memory * 0xCDCDCDCD : Used by Microsoft's C++ debugging runtime library to mark uninitialised heap memory * 0xDDDDDDDD : Used by Microsoft's C++ debugging heap to mark freed heap memory * 0xDEADDEAD : A Microsoft Windows STOP Error code used when the user manually initiates the crash. * 0xFDFDFDFD : Used by Microsoft's C++ debugging heap to mark "no man's land" guard bytes before and after allocated heap memory * 0xFEEEFEEE : Used by Microsoft's HeapFree() to mark freed heap memory </pre>
{ "question_id": 127386, "question_date": "2008-09-24T14:11:46.277Z", "question_score": 236, "tags": "debugging|visual-c++", "answer_id": 127404, "answer_date": "2008-09-24T14:14:34.710Z", "answer_score": 349 }
Please answer the following Stack Overflow question: Title: Android Endless List <p>How can I create a list where when you reach the end of the list I am notified so I can load more items? </p>
<p>One solution is to implement an <a href="http://developer.android.com/reference/android/widget/AbsListView.OnScrollListener.html" rel="noreferrer"><code>OnScrollListener</code></a> and make changes (like adding items, etc.) to the <a href="http://developer.android.com/reference/android/widget/ListAdapter.html" rel="noreferrer"><code>ListAdapter</code></a> at a convenient state in its <code>onScroll</code> method.</p> <p>The following <code>ListActivity</code> shows a list of integers, starting with 40, adding items when the user scrolls to the end of the list.</p> <pre><code>public class Test extends ListActivity implements OnScrollListener { Aleph0 adapter = new Aleph0(); protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setListAdapter(adapter); getListView().setOnScrollListener(this); } public void onScroll(AbsListView view, int firstVisible, int visibleCount, int totalCount) { boolean loadMore = /* maybe add a padding */ firstVisible + visibleCount &gt;= totalCount; if(loadMore) { adapter.count += visibleCount; // or any other amount adapter.notifyDataSetChanged(); } } public void onScrollStateChanged(AbsListView v, int s) { } class Aleph0 extends BaseAdapter { int count = 40; /* starting amount */ public int getCount() { return count; } public Object getItem(int pos) { return pos; } public long getItemId(int pos) { return pos; } public View getView(int pos, View v, ViewGroup p) { TextView view = new TextView(Test.this); view.setText("entry " + pos); return view; } } } </code></pre> <p>You should obviously use separate threads for long running actions (like loading web-data) and might want to indicate progress in the last list item (like the market or gmail apps do).</p>
{ "question_id": 1080811, "question_date": "2009-07-03T21:00:19.203Z", "question_score": 236, "tags": "android|list|listview", "answer_id": 1082523, "answer_date": "2009-07-04T16:27:29.473Z", "answer_score": 270 }
Please answer the following Stack Overflow question: Title: Mockito.any() pass Interface with Generics <p>is it possible to pass the type of an interface with generics?</p> <p>The interface:</p> <pre><code>public interface AsyncCallback&lt;T&gt; </code></pre> <p>In my test method:</p> <pre><code>Mockito.any(AsyncCallback.class) </code></pre> <p>Putting <code>&lt;ResponseX&gt;</code> behind or for <code>.class</code> didnt work.</p>
<p>There is a type-safe way: use <code>ArgumentMatchers.any()</code> and qualify it with the type:</p> <pre><code>ArgumentMatchers.&lt;AsyncCallback&lt;ResponseX&gt;&gt;any() </code></pre>
{ "question_id": 7917635, "question_date": "2011-10-27T14:41:15Z", "question_score": 236, "tags": "java|generics|mockito", "answer_id": 13932751, "answer_date": "2012-12-18T12:13:38.863Z", "answer_score": 412 }
Please answer the following Stack Overflow question: Title: Why do we usually use || over |? What is the difference? <p>I'm just wondering why we usually use logical OR <code>||</code> between two booleans not bitwise OR <code>|</code>, though they are both working well.</p> <p>I mean, look at the following:</p> <pre><code>if(true | true) // pass if(true | false) // pass if(false | true) // pass if(false | false) // no pass </code></pre> <pre><code>if(true || true) // pass if(true || false) // pass if(false || true) // pass if(false || false) // no pass </code></pre> <p>Can we use <code>|</code> instead of <code>||</code>? Same thing with <code>&amp;</code> and <code>&amp;&amp;</code>.</p>
<p>If you use the <code>||</code> and <code>&amp;&amp;</code> forms, rather than the <code>|</code> and <code>&amp;</code> forms of these operators, Java will not bother to evaluate the right-hand operand alone.</p> <p>It's a matter of if you want to short-circuit the evaluation or not -- <em>most</em> of the time you want to.</p> <p>A good way to illustrate the benefits of short-circuiting would be to consider the following example.</p> <pre><code>Boolean b = true; if(b || foo.timeConsumingCall()) { //we entered without calling timeConsumingCall() } </code></pre> <p>Another benefit, as Jeremy and Peter mentioned, for short-circuiting is the null reference check: </p> <pre><code>if(string != null &amp;&amp; string.isEmpty()) { //we check for string being null before calling isEmpty() } </code></pre> <p><a href="http://www.java-samples.com/showtutorial.php?tutorialid=65" rel="noreferrer">more info</a></p>
{ "question_id": 7101992, "question_date": "2011-08-18T03:19:01.337Z", "question_score": 236, "tags": "java|bitwise-operators", "answer_id": 7102013, "answer_date": "2011-08-18T03:22:27.473Z", "answer_score": 368 }
Please answer the following Stack Overflow question: Title: What is stack unwinding? <p>What is stack unwinding? Searched through but couldn't find enlightening answer!</p>
<p>Stack unwinding is usually talked about in connection with exception handling. Here's an example:</p> <pre><code>void func( int x ) { char* pleak = new char[1024]; // might be lost =&gt; memory leak std::string s( "hello world" ); // will be properly destructed if ( x ) throw std::runtime_error( "boom" ); delete [] pleak; // will only get here if x == 0. if x!=0, throw exception } int main() { try { func( 10 ); } catch ( const std::exception&amp; e ) { return 1; } return 0; } </code></pre> <p>Here memory allocated for <code>pleak</code> will be lost if an exception is thrown, while memory allocated to <code>s</code> will be properly released by <code>std::string</code> destructor in any case. The objects allocated on the stack are "unwound" when the scope is exited (here the scope is of the function <code>func</code>.) This is done by the compiler inserting calls to destructors of automatic (stack) variables.</p> <p>Now this is a very powerful concept leading to the technique called <a href="http://en.wikipedia.org/wiki/RAII" rel="noreferrer">RAII</a>, that is <strong><em>Resource Acquisition Is Initialization</em></strong>, that helps us manage resources like memory, database connections, open file descriptors, etc. in C++.</p> <p>Now that allows us to provide <a href="http://www.gotw.ca/gotw/056.htm" rel="noreferrer">exception safety guarantees</a>.</p>
{ "question_id": 2331316, "question_date": "2010-02-25T03:04:24.490Z", "question_score": 236, "tags": "c++|stack", "answer_id": 2331413, "answer_date": "2010-02-25T03:27:10.670Z", "answer_score": 178 }
Please answer the following Stack Overflow question: Title: How to log a method's execution time exactly in milliseconds? <p>Is there a way to determine how much time a method needs to execute (in milliseconds)?</p>
<pre><code>NSDate *methodStart = [NSDate date]; /* ... Do whatever you need to do ... */ NSDate *methodFinish = [NSDate date]; NSTimeInterval executionTime = [methodFinish timeIntervalSinceDate:methodStart]; NSLog(@"executionTime = %f", executionTime); </code></pre> <p><strong>Swift:</strong></p> <pre><code>let methodStart = NSDate() /* ... Do whatever you need to do ... */ let methodFinish = NSDate() let executionTime = methodFinish.timeIntervalSinceDate(methodStart) print("Execution time: \(executionTime)") </code></pre> <p><strong>Swift3:</strong></p> <pre><code>let methodStart = Date() /* ... Do whatever you need to do ... */ let methodFinish = Date() let executionTime = methodFinish.timeIntervalSince(methodStart) print("Execution time: \(executionTime)") </code></pre> <p>Easy to use and has sub-millisecond precision.</p>
{ "question_id": 2129794, "question_date": "2010-01-25T01:57:46.780Z", "question_score": 236, "tags": "ios|objective-c|optimization|time", "answer_id": 2129884, "answer_date": "2010-01-25T02:27:00.497Z", "answer_score": 452 }
Please answer the following Stack Overflow question: Title: My prerelease app has been "processing" for over a week in iTunes Connect, what gives? <p>I used Xcode 6.1.1 to upload a new version of a prerelease app to iTunes Connect so I could distribute it to my external beta testers. I've done this with two versions of the same app previously and it worked fine.</p> <p>But this time, the upload was stuck in "Processing" state for over a week. I tried again (same version, new build number) and it's now been over 24 hours with no change.</p> <p>The app passed validation fine.</p> <p>What gives?</p>
<p>Go to "Resources &amp; Help" in iTunes Connect. Select "Contact Us" and follow the wizard. I don't think anyone other than Apple can answer this. And this is what we have done in a similar situation in the past.</p>
{ "question_id": 27928471, "question_date": "2015-01-13T17:59:16.037Z", "question_score": 236, "tags": "ios|xcode6|app-store-connect|testflight", "answer_id": 27928539, "answer_date": "2015-01-13T18:02:50.093Z", "answer_score": 79 }
Please answer the following Stack Overflow question: Title: What is .gitignore? <p>I just created a Github repository and was wondering what the <code>.gitignore</code> file was for. I started by not creating one, but added one due to the fact that most repositories have one. Do I need to have one? Can/do I just ignore it, or does it have a use?</p>
<p><code>.gitignore</code> tells git which files (or patterns) it should ignore. It's usually used to avoid committing transient files from your working directory that aren't useful to other collaborators, such as compilation products, temporary files IDEs create, etc.</p> <p>You can find the full details <a href="http://git-scm.com/docs/gitignore">here</a>.</p>
{ "question_id": 27850222, "question_date": "2015-01-08T21:56:42.560Z", "question_score": 236, "tags": "git|github|gitignore", "answer_id": 27850270, "answer_date": "2015-01-08T21:59:17.423Z", "answer_score": 197 }
Please answer the following Stack Overflow question: Title: Remote rejected (shallow update not allowed) after changing Git remote URL <p>I have a project under Git version control that I worked on both a server and my local computer. I originally had the remote origin set as my local computer but I would now like to change that to BitBucket.</p> <p>On the server I used the command</p> <pre><code>git remote set-url origin bitbucket_address </code></pre> <p>But now when I try to push my project I get the error</p> <pre><code> ! [remote rejected] master -&gt; master (shallow update not allowed) </code></pre> <p>What is causing this and how do I fix it?</p>
<p>As it seems you have used <code>git clone --depth &lt;number&gt;</code> to clone your local version. This results in a <em>shallow clone</em>. One limitation of such a clone is that you can't push from it into a <strong>new</strong> repository.</p> <p>You now have two options:</p> <ol> <li>if you don't care about your missing history, take a look at <a href="http://stackoverflow.com/questions/29748197/how-to-clone-seed-kick-start-project-without-the-whole-history">this question</a></li> <li>if you want to keep your full history, then continue reading:</li> </ol> <p>So, you want to keep your history, eh? This means that you have to <em>unshallow</em> your repository. To do so you will need to add your old remote again.</p> <pre><code>git remote add old &lt;path-to-old-remote&gt; </code></pre> <p>After that we use <code>git fetch</code> to fetch the remaining history from the old remote (as suggested in <a href="https://stackoverflow.com/a/17937889/2274224">this answer</a>).</p> <pre><code>git fetch --unshallow old </code></pre> <p>And now you should be able to push into your new remote repository.</p> <hr /> <p><strong>Note</strong>: After <em>unshallowing</em> your clone you can obviously remove the old remote again.</p>
{ "question_id": 28983842, "question_date": "2015-03-11T10:16:23.037Z", "question_score": 236, "tags": "git", "answer_id": 28985327, "answer_date": "2015-03-11T11:23:04.410Z", "answer_score": 447 }
Please answer the following Stack Overflow question: Title: How do I clear the scrollback buffer in tmux? <p>I want to clear all scrollback history in a particular tmux pane.</p>
<p>This same question has been plaguing me for quite some time. Here's the best I've come up with. Put this into your .tmux.conf file:</p> <pre><code>bind -n C-k clear-history </code></pre> <p>This binds ctrl-k to the tmux clear-history command. The -n after bind makes it so you don't have to issue the tmux command prefix (ctrl-b by default). I use bash, so ctrl-l already does the equivalent of typing "clear" at the command line. With these two keys I get a nice ctrl-l, ctrl-k combo, which moves all the scroll buffer off the screen (the "clear") and then deletes all that history (the tmux "clear-history" command).</p> <p>It's not quite as nice as Terminal's, iTerm's, or Konsole's 1-key combos for clearing it out, but it's a world better than typing in clear-history all the time.</p>
{ "question_id": 10543684, "question_date": "2012-05-10T23:55:27.663Z", "question_score": 236, "tags": "terminal|tmux", "answer_id": 10553992, "answer_date": "2012-05-11T15:06:36.573Z", "answer_score": 251 }
Please answer the following Stack Overflow question: Title: Given a number, find the next higher number which has the exact same set of digits as the original number <p>I just bombed an interview and made pretty much zero progress on my interview question.</p> <blockquote> <p>Given a number, find the next higher number which has the exact same set of digits as the original number. For example: given 38276 return 38627</p> </blockquote> <p>I wanted to begin by finding the index of the first digit (from the right) that was less than the ones digit. Then I would rotate the last digits in the subset such that it was the next biggest number comprised of the same digits, but got stuck.</p> <p>The interviewer also suggested trying to swap digits one at a time, but I couldn't figure out the algorithm and just stared at a screen for like 20-30 minutes. Needless to say, I think I'm going to have to continue the job hunt.</p>
<p>You can do it in <code>O(n)</code> (where <code>n</code> is the number of digits) like this:</p> <p>Starting from the right, you find the first pair-of-digits such that the left-digit is smaller than the right-digit. Let's refer to the left-digit by "digit-x". Find the smallest number larger than digit-x to the right of digit-x, and place it immediately left of digit-x. Finally, sort the remaining digits in ascending order - since they were already in <em>descending</em> order, all you need to do is reverse them <em>(save for digit-x, which can be placed in the correct place in <code>O(n)</code>)</em>.</p> <p>An example will make this more clear:</p> <pre> 123456784987654321 start with a number 123456784 987654321 ^the first place from the right where the left-digit is less than the right Digit "x" is 4 123456784 987654321 ^find the smallest digit larger than 4 to the right 123456785 4 98764321 ^place it to the left of 4 123456785 4 12346789 123456785123446789 ^sort the digits to the right of 5. Since all of them except the '4' were already in descending order, all we need to do is reverse their order, and find the correct place for the '4' </pre> <hr> <p><strong>Proof of correctness:</strong></p> <p>Let's use capital letters to define digit-strings and lower-case for digits. The syntax <code>AB</code> means <em>"the concatenation of strings <code>A</code> and <code>B</code>"</em>. <code>&lt;</code> is lexicographical ordering, which is the same as integer ordering when the digit-strings are of equal length.</p> <p>Our original number N is of the form <code>AxB</code>, where <code>x</code> is a single digit and <code>B</code> is sorted descending.<br> The number found by our algorithm is <code>AyC</code>, where <code>y ∈ B</code> is the smallest digit <code>&gt; x</code> <em>(it must exist due to the way <code>x</code> was chosen, see above)</em>, and <code>C</code> is sorted ascending.</p> <p>Assume there is some number (using the same digits) <code>N'</code> such that <code>AxB &lt; N' &lt; AyC</code>. <code>N'</code> must begin with <code>A</code> or else it could not fall between them, so we can write it in the form <code>AzD</code>. Now our inequality is <code>AxB &lt; AzD &lt; AyC</code>, which is equivalent to <code>xB &lt; zD &lt; yC</code> where all three digit-strings contain the same digits.</p> <p>In order for that to be true, we must have <code>x &lt;= z &lt;= y</code>. Since <code>y</code> is the smallest digit <code>&gt; x</code>, <code>z</code> cannot be between them, so either <code>z = x</code> or <code>z = y</code>. Say <code>z = x</code>. Then our inequality is <code>xB &lt; xD &lt; yC</code>, which means <code>B &lt; D</code> where both <code>B</code> and <code>D</code> have the same digits. However, B is sorted descending, so there <em>is</em> no string with those digits larger than it. Thus we cannot have <code>B &lt; D</code>. Following the same steps, we see that if <code>z = y</code>, we cannot have <code>D &lt; C</code>.</p> <p>Therefore <code>N'</code> cannot exist, which means our algorithm correctly finds the next largest number.</p>
{ "question_id": 9368205, "question_date": "2012-02-20T20:50:03.897Z", "question_score": 236, "tags": "algorithm|digits", "answer_id": 9368616, "answer_date": "2012-02-20T21:23:44.003Z", "answer_score": 285 }
Please answer the following Stack Overflow question: Title: What actually causes a Stack Overflow error? <p>I've looked everywhere and can't find a solid answer. According to the documentation, Java throws a <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/StackOverflowError.html">java.lang.StackOverflowError</a> error under the following circumstance:</p> <blockquote> <p>Thrown when a stack overflow occurs because an application recurses too deeply.</p> </blockquote> <p>But this raises two questions:</p> <ul> <li>Aren't there other ways for a stack overflow to occur, not only through recursion?</li> <li>Does the StackOverflowError happen before the JVM actually overflows the stack or after?</li> </ul> <p>To elaborate on the second question:</p> <p>When Java throws the StackOverflowError, can you safely assume that the stack did not write into the heap? If you shrink the size of the stack or heap in a try/catch on a function that throws a stack overflow, can you continue working? Is this documented anywhere?</p> <p>Answers I am not looking for:</p> <ul> <li>A StackOverflow happens because of bad recursion.</li> <li>A StackOverflow happens when the heap meets the stack.</li> </ul>
<p>It seems you're thinking that a <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/StackOverflowError.html" rel="noreferrer">stackoverflow error</a> is like a buffer overflow exception in native programs, when there is a risk of writing into memory that had not been allocated for the buffer, and thus to corrupt some other memory locations. It's not the case at all.</p> <p>JVM has a given memory allocated for each stack of each thread, and if an attempt to call a method happens to fill this memory, JVM throws an error. Just like it would do if you were trying to write at index N of an array of length N. No memory corruption can happen. The stack can not write into the heap.</p> <p>A StackOverflowError is to the stack what an OutOfMemoryError is to the heap: it simply signals that there is no more memory available.</p> <h2><a href="http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html#jvms-6.3" rel="noreferrer">Description from Virtual Machine Errors (§6.3)</a></h2> <blockquote> <p><strong>StackOverflowError</strong>: The Java Virtual Machine implementation has run out of stack space for a thread, typically because the thread is doing an unbounded number of recursive invocations as a result of a fault in the executing program.</p> </blockquote>
{ "question_id": 22182669, "question_date": "2014-03-04T20:46:02.203Z", "question_score": 236, "tags": "java|jvm|stack-overflow", "answer_id": 22182774, "answer_date": "2014-03-04T20:51:14.790Z", "answer_score": 197 }
Please answer the following Stack Overflow question: Title: How do I get python's pprint to return a string instead of printing? <p>In other words, what's the sprintf equivalent to pprint? </p>
<p>The <a href="http://docs.python.org/library/pprint.html" rel="nofollow noreferrer">pprint</a> module has a function named <a href="http://docs.python.org/library/pprint.html#pprint.pformat" rel="nofollow noreferrer">pformat</a>, for just that purpose.</p> <p>From the documentation:</p> <blockquote> <p>Return the formatted representation of object as a string. indent, width and depth will be passed to the PrettyPrinter constructor as formatting parameters.</p> </blockquote> <p>Example:</p> <pre><code>&gt;&gt;&gt; import pprint &gt;&gt;&gt; people = [ ... {&quot;first&quot;: &quot;Brian&quot;, &quot;last&quot;: &quot;Kernighan&quot;}, ... {&quot;first&quot;: &quot;Dennis&quot;, &quot;last&quot;: &quot;Richie&quot;}, ... ] &gt;&gt;&gt; pprint.pformat(people, indent=4) &quot;[ { 'first': 'Brian', 'last': 'Kernighan'},\n { 'first': 'Dennis', 'last': 'Richie'}]&quot; </code></pre>
{ "question_id": 521532, "question_date": "2009-02-06T18:25:53.277Z", "question_score": 236, "tags": "python|pretty-print|pprint", "answer_id": 521545, "answer_date": "2009-02-06T18:28:30.260Z", "answer_score": 341 }
Please answer the following Stack Overflow question: Title: Obtain Bundle Identifier programmatically <p>How can I obtain a string of the Bundle Identifier programmatically from within my App?</p>
<p>Objective-C</p> <pre><code>NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier]; </code></pre> <p>Swift 1.2</p> <pre><code>let bundleIdentifier = NSBundle.mainBundle().bundleIdentifier </code></pre> <p>Swift 3.0</p> <pre><code>let bundleIdentifier = Bundle.main.bundleIdentifier </code></pre> <p>Xamarin.iOS</p> <pre><code>var bundleIdentifier = NSBundle.MainBundle.BundleIdentifier </code></pre>
{ "question_id": 8883102, "question_date": "2012-01-16T16:33:24.637Z", "question_score": 236, "tags": "ios|cocoa-touch", "answer_id": 8883166, "answer_date": "2012-01-16T16:37:40.790Z", "answer_score": 467 }
Please answer the following Stack Overflow question: Title: Background task, progress dialog, orientation change - is there any 100% working solution? <p>I download some data from internet in background thread (I use <code>AsyncTask</code>) and display a progress dialog while downloading. Orientation changes, Activity is restarted and then my AsyncTask is completed - I want to dismiss the progess dialog and start a new Activity. But calling dismissDialog sometimes throws an exception (probably because the Activity was destroyed and new Activity hasn't been started yet).</p> <p>What is the best way to handle this kind of problem (updating UI from background thread that works even if user changes orientation)? Did someone from Google provide some "official solution"?</p>
<p>Step #1: Make your <code>AsyncTask</code> a <code>static</code> nested class, or an entirely separate class, just not an inner (non-static nested) class.</p> <p>Step #2: Have the <code>AsyncTask</code> hold onto the <code>Activity</code> via a data member, set via the constructor and a setter.</p> <p>Step #3: When creating the <code>AsyncTask</code>, supply the current <code>Activity</code> to the constructor.</p> <p>Step #4: In <code>onRetainNonConfigurationInstance()</code>, return the <code>AsyncTask</code>, after detaching it from the original, now-going-away activity.</p> <p>Step #5: In <code>onCreate()</code>, if <code>getLastNonConfigurationInstance()</code> is not <code>null</code>, cast it to your <code>AsyncTask</code> class and call your setter to associate your new activity with the task.</p> <p>Step #6: Do not refer to the activity data member from <code>doInBackground()</code>.</p> <p>If you follow the above recipe, it will all work. <code>onProgressUpdate()</code> and <code>onPostExecute()</code> are suspended between the start of <code>onRetainNonConfigurationInstance()</code> and the end of the subsequent <code>onCreate()</code>.</p> <p><a href="http://github.com/commonsguy/cw-android/tree/master/Rotation/RotationAsync/" rel="noreferrer">Here is a sample project</a> demonstrating the technique.</p> <p>Another approach is to ditch the <code>AsyncTask</code> and move your work into an <code>IntentService</code>. This is particularly useful if the work to be done may be long and should go on regardless of what the user does in terms of activities (e.g., downloading a large file). You can use an ordered broadcast <code>Intent</code> to either have the activity respond to the work being done (if it is still in the foreground) or raise a <code>Notification</code> to let the user know if the work has been done. <a href="http://commonsware.com/blog/2010/08/11/activity-notification-ordered-broadcast.html" rel="noreferrer">Here is a blog post</a> with more on this pattern.</p>
{ "question_id": 3821423, "question_date": "2010-09-29T12:08:50.140Z", "question_score": 236, "tags": "android|orientation|android-orientation", "answer_id": 3821998, "answer_date": "2010-09-29T13:23:27.757Z", "answer_score": 337 }
Please answer the following Stack Overflow question: Title: How to stop unwanted UIButton animation on title change? <p>In iOS 7 my UIButton titles are animating in and out at the wrong time - late. This problem does not appear on iOS 6. I'm just using:</p> <pre><code>[self setTitle:text forState:UIControlStateNormal]; </code></pre> <p>I would prefer this happens instantly and without a blank frame. This blink is especially distracting and draws attention away from other animations.</p>
<p>This works for custom buttons:</p> <pre><code>[UIView setAnimationsEnabled:NO]; [_button setTitle:@"title" forState:UIControlStateNormal]; [UIView setAnimationsEnabled:YES]; </code></pre> <p>For system buttons you need to add this before re-enabling animations (thank you @Klaas):</p> <pre><code>[_button layoutIfNeeded]; </code></pre>
{ "question_id": 18946490, "question_date": "2013-09-22T17:10:01.690Z", "question_score": 236, "tags": "objective-c|swift|ios7|uibutton|uikit", "answer_id": 19303693, "answer_date": "2013-10-10T18:42:05.970Z", "answer_score": 169 }
Please answer the following Stack Overflow question: Title: Why can't my program compile under Windows 7 in French? <p>I'm running Windows 7 French and I'm trying to compile this really basic program, but Visual Studio is being stubborn and refuses to comply. I also tried compiling it with both GCC 4.7 and Clang trunk on <a href="http://coliru.stacked-crooked.net">Coliru</a> and I get more or less the same errors (output is below the code), though I think Coliru runs on an English OS so I wouldn't expect it to work anyway.</p> <p>What am I doing wrong? And how can I fix it?</p> <h3>Code</h3> <pre><code>#inclure &lt;iostream&gt; ent principal(ent argn, ent** argm) // entier, nombre d'arguments, valeur des arguments { std::cendehors &lt;&lt; "Bonjour le monde!\n"; renvoi SORTIE_SUCCÈS; } </code></pre> <h3>Output</h3> <pre><code>principal.cpp:1:6: erreur: prétraitement de la directive invalide #inclure #inclure &lt;iostream&gt; ^ principal.cpp:6:8: erreur: '\303' égaré dans le programme renvoi SORTIE_SUCCÈS; ^ principal.cpp:6:8: erreur: '\210' égaré dans le programme principal.cpp:3:5: erreur: «ent» ne désigne pas un type ent principal(ent argn, ent** argm) // entier, nombre d'arguments, value des arguments ^ </code></pre>
<p><a href="https://meta.stackexchange.com/questions/19478/the-many-memes-of-meta/221414#221414">Many problems are due to caching</a>, but yours is one of <a href="https://skeptics.stackexchange.com/questions/19836/has-phil-karlton-ever-said-there-are-only-two-hard-things-in-computer-science">the other kind of hard problems</a>: naming things. Yes, localization is hard.</p> <p>You didn't mention which variant of French you're using, but from the error message, I think you're using “French (France)” (what we users of civilized OSes call <code>fr_FR</code>). MS's <code>fr_FR</code> locale behaves in a very weird way: uppercase accented letters are mapped to their unaccented counterpart (for backward compatibility with some typewriter models). So you need to write <code>SORTIE_SUCCES</code> instead of <code>SORTIE_SUCCÈS</code>.</p> <p><a href="https://superuser.com/questions/589760/preserving-accented-letters-in-small-caps-in-french-in-word/589761#589761">A workaround is to use the “French (Monaco)” (<code>fr_MC</code>) language</a>, where uppercase accented letters work as expected. Unfortunately, the Monaco version of the compiler is very very expensive. You could also use the Canadian French, Belgian French or Swiss French version, but these all require that you submit a bilingual (<code>fr_CA</code> + <code>en_CA</code>), trilingual (<code>fr_BE</code> + <code>nl_BE</code> + <code>de_BE</code>) or quadrilingual (<code>fr_CH</code> + <code>it_CH</code> + <code>de_CH</code> + <code>rm_CH</code>) source file. African variants of French are out because they are too poor to afford a C++ compiler, however you could use C instead.</p> <p>Then there are other syntax errors in your program:</p> <ul> <li>You forgot to translate some keywords.</li> <li>Beware that the compiler and the documentation don't always use the same translation for the same word.</li> <li>You didn't account for the fact that adjectives come after the noun in French.</li> <li>You're using the wrong type of quotes.</li> </ul> <p>I wollun tried the following code in the C++ compiler included in Émaxe 51,70, and it wollun worked:</p> <pre><code>#inclure &lt;fluxes&gt; principal ent(argn ent, argm **ent) // entier, nombre d'arguments, valeur des arguments { norme::sortiec &lt;&lt; « Bonjour à tout le monde !\n » ; retourner SORTIE_SUCCÈS ; } </code></pre> <p>Some languages have better internationalization support than C++. For example, here's a program in <a href="http://fr.wikipedia.org/wiki/Logo_(langage)" rel="nofollow noreferrer">LOGO</a> (not to be confused with <a href="http://en.wikipedia.org/wiki/Logo_(programming_language)" rel="nofollow noreferrer">LOGO</a> of course).</p> <pre><code>pour exemple répète 18 [av 5 td 10] td 60 répète 18 [av 5 td 10] fin </code></pre>
{ "question_id": 22780466, "question_date": "2014-04-01T08:25:20.517Z", "question_score": 236, "tags": "c++|visual-studio-2013|french", "answer_id": 22793957, "answer_date": "2014-04-01T18:28:28.760Z", "answer_score": 62 }
Please answer the following Stack Overflow question: Title: Uncaught SyntaxError: Unexpected token : <p>I am running an AJAX call in my MooTools script, this works fine in Firefox but in Chrome I am getting a <code>Uncaught SyntaxError: Unexpected token :</code> error, I cannot determine why. Commenting out code to determine where the bad code is yields nothing, I am thinking it may be a problem with the JSON being returned. Checking in the console I see the JSON returned is this:</p> <pre><code>{"votes":47,"totalvotes":90} </code></pre> <p>I don't see any problems with it, why would this error occur?</p> <pre><code>vote.each(function(e){ e.set('send', { onRequest : function(){ spinner.show(); }, onComplete : function(){ spinner.hide(); }, onSuccess : function(resp){ var j = JSON.decode(resp); if (!j) return false; var restaurant = e.getParent('.restaurant'); restaurant.getElements('.votes')[0].set('html', j.votes + " vote(s)"); $$('#restaurants .restaurant').pop().set('html', "Total Votes: " + j.totalvotes); buildRestaurantGraphs(); } }); e.addEvent('submit', function(e){ e.stop(); this.send(); }); }); </code></pre>
<p>I have just solved the problem. There was something causing problems with a standard Request call, so this is the code I used instead:</p> <pre><code>vote.each(function(element){ element.addEvent('submit', function(e){ e.stop(); new Request.JSON({ url : e.target.action, onRequest : function(){ spinner.show(); }, onComplete : function(){ spinner.hide(); }, onSuccess : function(resp){ var j = resp; if (!j) return false; var restaurant = element.getParent('.restaurant'); restaurant.getElements('.votes')[0].set('html', j.votes + " vote(s)"); $$('#restaurants .restaurant').pop().set('html', "Total Votes: " + j.totalvotes); buildRestaurantGraphs(); } }).send(this); }); }); </code></pre> <p>If anyone knows why the standard Request object was giving me problems I would love to know.</p>
{ "question_id": 3143698, "question_date": "2010-06-29T18:37:56.880Z", "question_score": 235, "tags": "javascript|mootools|google-chrome", "answer_id": 3153134, "answer_date": "2010-06-30T20:27:32.083Z", "answer_score": 19 }
Please answer the following Stack Overflow question: Title: Convert Month Number to Month Name Function in SQL <p>I have months stored in SQL Server as 1,2,3,4,...12. I would like to display them as January,February etc. Is there a function in SQL Server like MonthName(1) = January? I am trying to avoid a CASE statement, if possible.</p>
<p>A little hacky but should work:</p> <pre><code>SELECT DATENAME(month, DATEADD(month, @mydate-1, CAST('2008-01-01' AS datetime))) </code></pre>
{ "question_id": 185520, "question_date": "2008-10-09T00:50:54.900Z", "question_score": 235, "tags": "sql|sql-server|tsql|sql-server-2005", "answer_id": 185548, "answer_date": "2008-10-09T01:03:33.283Z", "answer_score": 171 }
Please answer the following Stack Overflow question: Title: HashMap with multiple values under the same key <p>Is it possible for us to implement a HashMap with one key and two values. Just as HashMap? </p> <p>Please do help me, also by telling (if there is no way) any other way to implement the storage of three values with one as the key?</p>
<p>You could:</p> <ol> <li>Use a map that has a list as the value. <code>Map&lt;KeyType, List&lt;ValueType&gt;&gt;</code>.</li> <li>Create a new wrapper class and place instances of this wrapper in the map. <code>Map&lt;KeyType, WrapperType&gt;</code>.</li> <li>Use a tuple like class (saves creating lots of wrappers). <code>Map&lt;KeyType, Tuple&lt;Value1Type, Value2Type&gt;&gt;</code>.</li> <li>Use mulitple maps side-by-side.</li> </ol> <hr /> <h2>Examples</h2> <p><strong>1. Map with list as the value</strong></p> <pre><code>// create our map Map&lt;String, List&lt;Person&gt;&gt; peopleByForename = new HashMap&lt;&gt;(); // populate it List&lt;Person&gt; people = new ArrayList&lt;&gt;(); people.add(new Person(&quot;Bob Smith&quot;)); people.add(new Person(&quot;Bob Jones&quot;)); peopleByForename.put(&quot;Bob&quot;, people); // read from it List&lt;Person&gt; bobs = peopleByForename[&quot;Bob&quot;]; Person bob1 = bobs[0]; Person bob2 = bobs[1]; </code></pre> <p>The disadvantage with this approach is that the list is not bound to exactly two values.</p> <p><strong>2. Using wrapper class</strong></p> <pre><code>// define our wrapper class Wrapper { public Wrapper(Person person1, Person person2) { this.person1 = person1; this.person2 = person2; } public Person getPerson1() { return this.person1; } public Person getPerson2() { return this.person2; } private Person person1; private Person person2; } // create our map Map&lt;String, Wrapper&gt; peopleByForename = new HashMap&lt;&gt;(); // populate it peopleByForename.put(&quot;Bob&quot;, new Wrapper(new Person(&quot;Bob Smith&quot;), new Person(&quot;Bob Jones&quot;)); // read from it Wrapper bobs = peopleByForename.get(&quot;Bob&quot;); Person bob1 = bobs.getPerson1(); Person bob2 = bobs.getPerson2(); </code></pre> <p>The disadvantage to this approach is that you have to write a lot of boiler-plate code for all of these very simple container classes.</p> <p><strong>3. Using a tuple</strong></p> <pre><code>// you'll have to write or download a Tuple class in Java, (.NET ships with one) // create our map Map&lt;String, Tuple2&lt;Person, Person&gt; peopleByForename = new HashMap&lt;&gt;(); // populate it peopleByForename.put(&quot;Bob&quot;, new Tuple2(new Person(&quot;Bob Smith&quot;, new Person(&quot;Bob Jones&quot;)); // read from it Tuple&lt;Person, Person&gt; bobs = peopleByForename[&quot;Bob&quot;]; Person bob1 = bobs.Item1; Person bob2 = bobs.Item2; </code></pre> <p>This is the best solution in my opinion.</p> <p><strong>4. Multiple maps</strong></p> <pre><code>// create our maps Map&lt;String, Person&gt; firstPersonByForename = new HashMap&lt;&gt;(); Map&lt;String, Person&gt; secondPersonByForename = new HashMap&lt;&gt;(); // populate them firstPersonByForename.put(&quot;Bob&quot;, new Person(&quot;Bob Smith&quot;)); secondPersonByForename.put(&quot;Bob&quot;, new Person(&quot;Bob Jones&quot;)); // read from them Person bob1 = firstPersonByForename[&quot;Bob&quot;]; Person bob2 = secondPersonByForename[&quot;Bob&quot;]; </code></pre> <p>The disadvantage of this solution is that it's not obvious that the two maps are related, a programmatic error could see the two maps get out of sync.</p>
{ "question_id": 4956844, "question_date": "2011-02-10T12:06:12.217Z", "question_score": 235, "tags": "java", "answer_id": 4956870, "answer_date": "2011-02-10T12:08:11.020Z", "answer_score": 301 }
Please answer the following Stack Overflow question: Title: How to split a delimited string into an array in awk? <p>How to split the string when it contains pipe symbols <code>|</code> in it. I want to split them to be in array.</p> <p>I tried</p> <pre><code>echo "12:23:11" | awk '{split($0,a,":"); print a[3] a[2] a[1]}' </code></pre> <p>Which works fine. If my string is like <code>"12|23|11"</code> then how do I split them into an array?</p>
<p>Have you tried:</p> <pre><code>echo "12|23|11" | awk '{split($0,a,"|"); print a[3],a[2],a[1]}' </code></pre>
{ "question_id": 8009664, "question_date": "2011-11-04T13:10:29.247Z", "question_score": 235, "tags": "awk", "answer_id": 8009724, "answer_date": "2011-11-04T13:15:14.987Z", "answer_score": 363 }
Please answer the following Stack Overflow question: Title: How to implement sleep function in TypeScript? <p>I'm developing a website in Angular 2 using TypeScript and I was wondering if there was a way to implement <code>thread.sleep(ms)</code> functionality.</p> <p>My use case is to redirect the users after submitting a form after a few seconds which is very easy in JavaScript but I'm not sure how to do it in TypeScript.</p>
<p>You have to wait for TypeScript 2.0 with <code>async</code>/<code>await</code> for ES5 support as it now supported only for TS to ES6 compilation.</p> <p>You would be able to create delay function with <code>async</code>:</p> <pre><code>function delay(ms: number) { return new Promise( resolve =&gt; setTimeout(resolve, ms) ); } </code></pre> <p>And call it</p> <pre><code>await delay(1000); </code></pre> <p>BTW, you can await on <code>Promise</code> directly:</p> <pre><code>await new Promise(f =&gt; setTimeout(f, 1000)); </code></pre> <p><strong>Please note, that you can use <code>await</code> only inside <code>async</code> function.</strong></p> <p>If you can't (<em>let's say you are building nodejs application</em>), just place your code in the anonymous <code>async</code> function. Here is an example:</p> <pre><code> (async () =&gt; { // Do something before delay console.log('before delay') await delay(1000); // Do something after console.log('after delay') })(); </code></pre> <p>Example TS Application: <a href="https://github.com/v-andrew/ts-template" rel="noreferrer">https://github.com/v-andrew/ts-template</a></p> <p><strong>In OLD JS you have to use</strong></p> <pre><code>setTimeout(YourFunctionName, Milliseconds); </code></pre> <p>or</p> <pre><code>setTimeout( () =&gt; { /*Your Code*/ }, Milliseconds ); </code></pre> <p>However with every major browser supporting <code>async</code>/<code>await</code> it is less useful.</p> <blockquote> <p>Update: TypeScript 2.1 is here with <code>async/await</code>.</p> </blockquote> <p>Just do not forget that you need <code>Promise</code> implementation when you compile to ES5, where Promise is not natively available.</p> <blockquote> <p>PS</p> </blockquote> <p>You have to <a href="https://github.com/v-andrew/ts-template/blob/master/src/lib/common.ts" rel="noreferrer">export the function</a> if you want to use it outside of the original file.</p>
{ "question_id": 37764665, "question_date": "2016-06-11T14:07:11.283Z", "question_score": 235, "tags": "angular|typescript|sleep", "answer_id": 37764963, "answer_date": "2016-06-11T14:39:28.937Z", "answer_score": 406 }
Please answer the following Stack Overflow question: Title: Simplest way to detect a mobile device in PHP <p>What is the simplest way to tell if a user is using a mobile device to browse my site using PHP?</p> <p>I have come across many classes that you can use but I was hoping for a simple if condition! </p> <p>Is there a way I can do this?</p>
<p>Here is a source:</p> <ul> <li><a href="http://detectmobilebrowser.com/" rel="noreferrer">Detect Mobile Browser</a> </li> <li><a href="http://detectmobilebrowser.com/download/php" rel="noreferrer">Download PHP script</a></li> </ul> <p><strong>Code:</strong></p> <pre><code>&lt;?php $useragent=$_SERVER['HTTP_USER_AGENT']; if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$useragent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($useragent,0,4))) header('Location: http://detectmobilebrowser.com/mobile'); ?&gt; </code></pre>
{ "question_id": 4117555, "question_date": "2010-11-07T11:49:53.030Z", "question_score": 235, "tags": "php|mobile", "answer_id": 4117597, "answer_date": "2010-11-07T12:01:04.033Z", "answer_score": 360 }
Please answer the following Stack Overflow question: Title: Get list of JSON objects with Spring RestTemplate <p>I have two questions:</p> <ul> <li>How to map a list of JSON objects using Spring RestTemplate.</li> <li>How to map nested JSON objects.</li> </ul> <p>I am trying to consume <a href="https://bitpay.com/api/rates">https://bitpay.com/api/rates</a>, by following the tutorial from <a href="http://spring.io/guides/gs/consuming-rest/">http://spring.io/guides/gs/consuming-rest/</a>.</p>
<p>Maybe this way...</p> <pre><code>ResponseEntity&lt;Object[]&gt; responseEntity = restTemplate.getForEntity(urlGETList, Object[].class); Object[] objects = responseEntity.getBody(); MediaType contentType = responseEntity.getHeaders().getContentType(); HttpStatus statusCode = responseEntity.getStatusCode(); </code></pre> <p>Controller code for the <code>RequestMapping</code></p> <pre><code>@RequestMapping(value="/Object/getList/", method=RequestMethod.GET) public @ResponseBody List&lt;Object&gt; findAllObjects() { List&lt;Object&gt; objects = new ArrayList&lt;Object&gt;(); return objects; } </code></pre> <p><code>ResponseEntity</code> is an extension of <code>HttpEntity</code> that adds a <code>HttpStatus</code> status code. Used in <code>RestTemplate</code> as well <code>@Controller</code> methods. In <code>RestTemplate</code> this class is returned by <code>getForEntity()</code> and <code>exchange()</code>.</p>
{ "question_id": 23674046, "question_date": "2014-05-15T09:17:51.047Z", "question_score": 235, "tags": "java|spring|resttemplate", "answer_id": 23675418, "answer_date": "2014-05-15T10:18:58.600Z", "answer_score": 247 }
Please answer the following Stack Overflow question: Title: Change cursor to hand when mouse goes over a row in table <p>How do I change the cursor pointer to hand when my mouse goes over a <code>&lt;tr&gt;</code> in a <code>&lt;table&gt;</code></p> <pre><code>&lt;table class="sortable" border-style:&gt; &lt;tr&gt; &lt;th class="tname"&gt;Name&lt;/th&gt;&lt;th class="tage"&gt;Age&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt;&lt;td class="tname"&gt;Jennifer&lt;/td&gt;&lt;td class="tage"&gt;24&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td class="tname"&gt;Kate&lt;/td&gt;&lt;td class="tage"&gt;36&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td class="tname"&gt;David&lt;/td&gt;&lt;td class="tage"&gt;25&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td class="tname"&gt;Mark&lt;/td&gt;&lt;td class="tage"&gt;40&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt; </code></pre>
<p>You can do this with CSS actually.</p> <pre><code>.sortable tr { cursor: pointer; } </code></pre>
{ "question_id": 9287693, "question_date": "2012-02-15T04:01:09.207Z", "question_score": 235, "tags": "html|css|mouse-cursor", "answer_id": 9287738, "answer_date": "2012-02-15T04:06:22.260Z", "answer_score": 396 }
Please answer the following Stack Overflow question: Title: Visual Studio Code how to resolve merge conflicts with git? <p>I tried to merge my branch with another branch and there was a merge conflict. In Visual Studio Code (version 1.2.1) I resolved all of the issues, however when I try to commit it keeps giving me this message:</p> <blockquote> <p>You should first resolve the un-merged changes before committing your changes.</p> </blockquote> <p>I've tried googling it but I can't find out why it won't let me commit my changes, all of the conflicts have disappeared.</p>
<p>After trial and error I discovered that you need to stage the file that had the merge conflict, then you can commit the merge.</p>
{ "question_id": 38216541, "question_date": "2016-07-06T04:56:05.633Z", "question_score": 235, "tags": "git|visual-studio|merge|visual-studio-code", "answer_id": 38216625, "answer_date": "2016-07-06T05:05:01.957Z", "answer_score": 167 }
Please answer the following Stack Overflow question: Title: Split a string by a delimiter in python <p>How to split this string where <code>__</code> is the delimiter</p> <pre><code>MATCHES__STRING </code></pre> <p>To get an output of <code>['MATCHES', 'STRING']</code>?</p>
<p>You can use the <a href="https://docs.python.org/3/library/stdtypes.html#str.split" rel="noreferrer"><code>str.split</code></a> method: <code>string.split('__')</code></p> <pre><code>&gt;&gt;&gt; &quot;MATCHES__STRING&quot;.split(&quot;__&quot;) ['MATCHES', 'STRING'] </code></pre>
{ "question_id": 3475251, "question_date": "2010-08-13T08:46:07.463Z", "question_score": 235, "tags": "python|string|list|split", "answer_id": 3475270, "answer_date": "2010-08-13T08:48:55.263Z", "answer_score": 385 }
Please answer the following Stack Overflow question: Title: How to write a CSS hack for IE 11? <p>How can I hack or write css only for IE 11? I have a website that looks bad in IE 11.I just search here and there but didnt find any solution yet.</p> <p>Is there any css selector?</p>
<p>Use a combination of Microsoft specific CSS rules to filter IE11:</p> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;IE10/11 Media Query Test&lt;/title&gt; &lt;meta charset="utf-8"&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt; &lt;style&gt; @media all and (-ms-high-contrast:none) { .foo { color: green } /* IE10 */ *::-ms-backdrop, .foo { color: red } /* IE11 */ } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="foo"&gt;Hi There!!!&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Filters such as this work because of the following:</p> <blockquote> <p>When a user agent cannot parse the selector (i.e., it is not valid CSS 2.1), it must ignore the selector and the following declaration block (if any) as well. </p> </blockquote> <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-html lang-html prettyprint-override"><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;IE10/11 Media Query Test&lt;/title&gt; &lt;meta charset="utf-8"&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt; &lt;style&gt; @media all and (-ms-high-contrast:none) { .foo { color: green } /* IE10 */ *::-ms-backdrop, .foo { color: red } /* IE11 */ } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="foo"&gt;Hi There!!!&lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p><strong>References</strong></p> <ul> <li><a href="https://stackoverflow.com/questions/9900311/how-do-i-target-only-internet-explorer-10-for-certain-situations-like-internet-e/17099988#17099988">How do I target only Internet Explorer 10 for certain situations like Internet Explorer-specific CSS or Internet Explorer-specific JavaScript code?</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/ie/hh772373" rel="noreferrer">Microsoft Extensions to CSS</a></li> <li><a href="http://www.w3.org/TR/CSS2/syndata.html#rule-sets" rel="noreferrer">CSS 2.1:Rule sets, declaration blocks, and selectors</a></li> </ul>
{ "question_id": 20541306, "question_date": "2013-12-12T10:45:44.580Z", "question_score": 235, "tags": "css|css-selectors|internet-explorer-11|css-hack", "answer_id": 22085269, "answer_date": "2014-02-28T02:53:47.467Z", "answer_score": 321 }
Please answer the following Stack Overflow question: Title: Angular 2 Hover event <p>In the new <strong>Angular2</strong> framework, does anyone know the proper way to do a hover like an event? </p> <p>In <strong>Angular1</strong> there was <code>ng-Mouseover</code>, but that doesn't seem to have been carried over. </p> <p>I've looked through the docs and haven't found anything.</p>
<p>If you want to perform a hover like event on any HTML element, then you can do it like this.</p> <p><strong>HTML</strong></p> <pre class="lang-html prettyprint-override"><code> &lt;div (mouseenter) =&quot;mouseEnter('div a') &quot; (mouseleave) =&quot;mouseLeave('div A')&quot;&gt; &lt;h2&gt;Div A&lt;/h2&gt; &lt;/div&gt; &lt;div (mouseenter) =&quot;mouseEnter('div b')&quot; (mouseleave) =&quot;mouseLeave('div B')&quot;&gt; &lt;h2&gt;Div B&lt;/h2&gt; &lt;/div&gt; </code></pre> <p><strong>Component</strong></p> <pre class="lang-typescript prettyprint-override"><code>import { Component } from '@angular/core'; @Component({ moduleId: module.id, selector: 'basic-detail', templateUrl: 'basic.component.html', }) export class BasicComponent{ mouseEnter(div : string){ console.log(&quot;mouse enter : &quot; + div); } mouseLeave(div : string){ console.log('mouse leave :' + div); } } </code></pre> <p>You should use both <code>mouseenter</code> and <code>mouseleave</code> events in order to fully implement functional hover events in angular 2.</p>
{ "question_id": 37686772, "question_date": "2016-06-07T18:32:30.540Z", "question_score": 235, "tags": "javascript|angular|events|hover", "answer_id": 40041496, "answer_date": "2016-10-14T10:57:05.300Z", "answer_score": 300 }
Please answer the following Stack Overflow question: Title: android pick images from gallery <p>I want to create a picture chooser from gallery. I use code </p> <pre><code> intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(intent, TFRequestCodes.GALLERY); </code></pre> <p>My problem is that in this activity and video files are displayed. Is there a way to filter displayed files so that no video files will be displayed in this activity?</p>
<p>Absolutely. Try this:</p> <pre><code>Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE); </code></pre> <p>Don't forget also to create the constant <strong>PICK_IMAGE</strong>, so you can recognize when the user comes back from the image gallery Activity:</p> <pre><code>public static final int PICK_IMAGE = 1; @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == PICK_IMAGE) { //TODO: action } } </code></pre> <p>That's how I call the image gallery. Put it in and see if it works for you.</p> <p>EDIT:</p> <p>This brings up the Documents app. To allow the user to also use any gallery apps they might have installed:</p> <pre><code> Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT); getIntent.setType("image/*"); Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); pickIntent.setType("image/*"); Intent chooserIntent = Intent.createChooser(getIntent, "Select Image"); chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent}); startActivityForResult(chooserIntent, PICK_IMAGE); </code></pre>
{ "question_id": 5309190, "question_date": "2011-03-15T08:33:46.763Z", "question_score": 235, "tags": "android|gallery|action", "answer_id": 5309217, "answer_date": "2011-03-15T08:36:28.460Z", "answer_score": 403 }
Please answer the following Stack Overflow question: Title: Custom Adapter for List View <p>I want to create a <code>custom adapter</code> for my list view. Is there any article that can walk me through how to create one and also explain how it works?</p>
<pre><code>public class ListAdapter extends ArrayAdapter&lt;Item&gt; { private int resourceLayout; private Context mContext; public ListAdapter(Context context, int resource, List&lt;Item&gt; items) { super(context, resource, items); this.resourceLayout = resource; this.mContext = context; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { LayoutInflater vi; vi = LayoutInflater.from(mContext); v = vi.inflate(resourceLayout, null); } Item p = getItem(position); if (p != null) { TextView tt1 = (TextView) v.findViewById(R.id.id); TextView tt2 = (TextView) v.findViewById(R.id.categoryId); TextView tt3 = (TextView) v.findViewById(R.id.description); if (tt1 != null) { tt1.setText(p.getId()); } if (tt2 != null) { tt2.setText(p.getCategory().getId()); } if (tt3 != null) { tt3.setText(p.getDescription()); } } return v; } } </code></pre> <p>This is a class I had used for my project. You need to have a collection of your items which you want to display, in my case it's <code>&lt;Item&gt;</code>. You need to override <code>View getView(int position, View convertView, ViewGroup parent)</code> method.</p> <p><code>R.layout.itemlistrow</code> defines the row of the <code>ListView</code>.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:orientation="vertical" android:layout_width="fill_parent"&gt; &lt;TableRow android:layout_width="fill_parent" android:id="@+id/TableRow01" android:layout_height="wrap_content"&gt; &lt;TextView android:textColor="#FFFFFF" android:id="@+id/id" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="id" android:textStyle="bold" android:gravity="left" android:layout_weight="1" android:typeface="monospace" android:height="40sp" /&gt; &lt;/TableRow&gt; &lt;TableRow android:layout_height="wrap_content" android:layout_width="fill_parent"&gt; &lt;TextView android:textColor="#FFFFFF" android:id="@+id/categoryId" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="categoryId" android:layout_weight="1" android:height="20sp" /&gt; &lt;TextView android:layout_height="wrap_content" android:layout_width="fill_parent" android:layout_weight="1" android:textColor="#FFFFFF" android:gravity="right" android:id="@+id/description" android:text="description" android:height="20sp" /&gt; &lt;/TableRow&gt; &lt;/TableLayout&gt; </code></pre> <p>In the <code>MainActivity</code> define <code>ListView</code>like this, </p> <pre><code>ListView yourListView = (ListView) findViewById(R.id.itemListView); // get data from the table by the ListAdapter ListAdapter customAdapter = new ListAdapter(this, R.layout.itemlistrow, List&lt;yourItem&gt;); yourListView .setAdapter(customAdapter); </code></pre>
{ "question_id": 8166497, "question_date": "2011-11-17T11:40:52.653Z", "question_score": 235, "tags": "android|listview|android-tablelayout|custom-adapter", "answer_id": 8166802, "answer_date": "2011-11-17T12:05:11.343Z", "answer_score": 335 }
Please answer the following Stack Overflow question: Title: Difference between a virtual function and a pure virtual function <p>What is the difference between a pure virtual function and a virtual function? </p> <p>I know "Pure Virtual Function is a Virtual function with no body", but what does this mean and what is actually done by the line below:</p> <pre><code>virtual void virtualfunctioname() = 0 </code></pre>
<p>A virtual function makes its class a <em>polymorphic base class</em>. Derived classes can override virtual functions. Virtual functions called through base class pointers/references will be resolved at run-time. That is, the <em>dynamic type</em> of the object is used instead of its <em>static type</em>: </p> <pre><code> Derived d; Base&amp; rb = d; // if Base::f() is virtual and Derived overrides it, Derived::f() will be called rb.f(); </code></pre> <p>A pure virtual function is a virtual function whose declaration ends in <code>=0</code>:</p> <pre><code>class Base { // ... virtual void f() = 0; // ... </code></pre> <p>A pure virtual function implicitly makes the class it is defined for <em>abstract</em> (unlike in Java where you have a keyword to explicitly declare the class abstract). Abstract classes cannot be instantiated. Derived classes need to override/implement all inherited pure virtual functions. If they do not, they too will become abstract.</p> <p>An interesting 'feature' of C++ is that a class can define a pure virtual function that has an implementation. (<a href="https://stackoverflow.com/q/2609299/140719">What that's good for is debatable</a>.)</p> <hr> <p>Note that C++11 brought a new use for the <code>delete</code> and <code>default</code> keywords which looks similar to the syntax of pure virtual functions:</p> <pre><code>my_class(my_class const &amp;) = delete; my_class&amp; operator=(const my_class&amp;) = default; </code></pre> <p>See <a href="https://stackoverflow.com/q/5513881">this question</a> and <a href="https://stackoverflow.com/q/13576055">this one</a> for more info on this use of <code>delete</code> and <code>default</code>. </p>
{ "question_id": 2652198, "question_date": "2010-04-16T10:33:51.053Z", "question_score": 235, "tags": "c++|function|pure-virtual", "answer_id": 2652223, "answer_date": "2010-04-16T10:37:48.690Z", "answer_score": 288 }
Please answer the following Stack Overflow question: Title: How to get a float result by dividing two integer values using T-SQL? <p>Using T-SQL and Microsoft SQL Server I would like to specify the number of decimal digits when I do a division between 2 integer numbers like:</p> <pre><code>select 1/3 </code></pre> <p>That currently returns <code>0</code>. I would like it to return <code>0,33</code>.</p> <p>Something like:</p> <pre><code>select round(1/3, -2) </code></pre> <p>But that doesn't work. How can I achieve the desired result?</p>
<p>The suggestions from stb and xiowl are fine if you're looking for a constant. If you need to use existing fields or parameters which are integers, you can cast them to be floats first:</p> <pre><code>SELECT CAST(1 AS float) / CAST(3 AS float) </code></pre> <p>or </p> <pre><code>SELECT CAST(MyIntField1 AS float) / CAST(MyIntField2 AS float) </code></pre>
{ "question_id": 11719044, "question_date": "2012-07-30T09:51:43.003Z", "question_score": 235, "tags": "sql-server|sql-server-2008|division|rounding", "answer_id": 11721188, "answer_date": "2012-07-30T12:05:44.533Z", "answer_score": 364 }
Please answer the following Stack Overflow question: Title: django MultiValueDictKeyError error, how do I deal with it <p>I'm trying to save a object to my database, but it's throwing a <code>MultiValueDictKeyError</code> error.</p> <p>The problems lies within the form, the <code>is_private</code> is represented by a checkbox. If the check box is NOT selected, obviously nothing is passed. This is where the error gets chucked.</p> <p>How do I properly deal with this exception, and catch it? </p> <p>The line is</p> <pre><code>is_private = request.POST['is_private'] </code></pre>
<p>Use the MultiValueDict's <code>get</code> method. This is also present on standard dicts and is a way to fetch a value while providing a default if it does not exist.</p> <pre><code>is_private = request.POST.get('is_private', False) </code></pre> <p>Generally,</p> <pre><code>my_var = dict.get(&lt;key&gt;, &lt;default&gt;) </code></pre>
{ "question_id": 5895588, "question_date": "2011-05-05T09:40:14.630Z", "question_score": 235, "tags": "python|django|exception", "answer_id": 5895670, "answer_date": "2011-05-05T09:47:33.950Z", "answer_score": 361 }
Please answer the following Stack Overflow question: Title: How to create Android Facebook Key Hash? <p>I do not understand this process at all. I have been able to navigate to the folder containing the keytool in the Java SDK. Although I keep getting the error openssl not recognised as an internal or external command. The problem is even if I can get this to work, what would I do and with what afterwards?</p>
<p>Here is what you need to do -</p> <p>Download openSSl from <a href="http://code.google.com/p/openssl-for-windows/downloads/detail?name=openssl-0.9.8k_WIN32.zip" rel="noreferrer">Code</a> Extract it. create a folder- OpenSSL in C:/ and copy the extracted code here.</p> <p>detect debug.keystore file path. If u didn't find, then do a search in C:/ and use the Path in the command in next step.</p> <p>detect your keytool.exe path and go to that dir/ in command prompt and run this command in 1 line-</p> <pre><code>$ keytool -exportcert -alias androiddebugkey -keystore "C:\Documents and Settings\Administrator.android\debug.keystore" | "C:\OpenSSL\bin\openssl" sha1 -binary |"C:\OpenSSL\bin\openssl" base64 </code></pre> <p>it will ask for password, put android that's all. u will get a key-hash</p>
{ "question_id": 7506392, "question_date": "2011-09-21T20:44:16.933Z", "question_score": 235, "tags": "java|android|facebook", "answer_id": 7506445, "answer_date": "2011-09-21T20:48:32.007Z", "answer_score": 297 }
Please answer the following Stack Overflow question: Title: How can I keep a container running on Kubernetes? <p>I'm now trying to run a simple container with shell (/bin/bash) on a Kubernetes cluster.</p> <p>I thought that there was a way to keep a container running on a Docker container by using <code>pseudo-tty</code> and detach option (<code>-td</code> option on <code>docker run</code> command).</p> <p>For example,</p> <pre><code>$ sudo docker run -td ubuntu:latest </code></pre> <p>Is there an option like this in Kubernetes?</p> <p>I've tried running a container by using a <code>kubectl run-container</code> command like:</p> <pre><code>kubectl run-container test_container ubuntu:latest --replicas=1 </code></pre> <p>But the container exits for a few seconds (just like launching with the <code>docker run</code> command without options I mentioned above). And ReplicationController launches it again repeatedly.</p> <p>Is there a way to keep a container running on Kubernetes like the <code>-td</code> options in the <code>docker run</code> command?</p>
<p>A container exits when its main process exits. Doing something like:</p> <pre><code>docker run -itd debian </code></pre> <p>to hold the container open is frankly a hack that should only be used for quick tests and examples. If you just want a container for testing for a few minutes, I would do:</p> <pre><code>docker run -d debian sleep 300 </code></pre> <p>Which has the advantage that the container will automatically exit if you forget about it. Alternatively, you could put something like this in a <code>while</code> loop to keep it running forever, or just run an application such as <code>top</code>. All of these should be easy to do in Kubernetes.</p> <p>The real question is why would you want to do this? Your container should be providing a service, whose process will keep the container running in the background.</p>
{ "question_id": 31870222, "question_date": "2015-08-07T05:20:51.157Z", "question_score": 235, "tags": "docker|containers|kubernetes|google-kubernetes-engine", "answer_id": 31879013, "answer_date": "2015-08-07T13:31:24.813Z", "answer_score": 74 }
Please answer the following Stack Overflow question: Title: No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator <p>I am trying to consume an API using Retrofit and Jackson to deserialize. I am getting the onFailure error <code>No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator</code>.</p>
<p><strong>Reason:</strong> This error occurs because jackson library doesn't know how to create your model which doesn't have an empty constructor and the model contains constructor with parameters which didn't annotated its parameters with <code>@JsonProperty(&quot;field_name&quot;)</code>. By default java compiler creates empty constructor if you didn't add constructor to your class.</p> <p><strong>Solution:</strong> Add an empty constructor to your model or annotate constructor parameters with <code>@JsonProperty(&quot;field_name&quot;)</code></p> <p>If you use a Kotlin data class then also can annotate with <code>@JsonProperty(&quot;field_name&quot;)</code> or register <a href="https://github.com/FasterXML/jackson-module-kotlin" rel="noreferrer">jackson module kotlin</a> to <code>ObjectMapper</code>.</p> <p>You can create your models using <a href="http://www.jsonschema2pojo.org/" rel="noreferrer">http://www.jsonschema2pojo.org/</a>.</p>
{ "question_id": 53191468, "question_date": "2018-11-07T14:29:25.363Z", "question_score": 235, "tags": "android|kotlin|jackson|retrofit2", "answer_id": 53192674, "answer_date": "2018-11-07T15:34:24.140Z", "answer_score": 231 }
Please answer the following Stack Overflow question: Title: Dictionary: Get list of values for list of keys <p>Is there a built-in/quick way to use a list of keys to a dictionary to get a list of corresponding items?</p> <p>For instance I have:</p> <pre><code>&gt;&gt;&gt; mydict = {'one': 1, 'two': 2, 'three': 3} &gt;&gt;&gt; mykeys = ['three', 'one'] </code></pre> <p>How can I use <code>mykeys</code> to get the corresponding values in the dictionary as a list?</p> <pre><code>&gt;&gt;&gt; mydict.WHAT_GOES_HERE(mykeys) [3, 1] </code></pre>
<p>A list comprehension seems to be a good way to do this:</p> <pre><code>&gt;&gt;&gt; [mydict[x] for x in mykeys] [3, 1] </code></pre>
{ "question_id": 18453566, "question_date": "2013-08-26T21:45:38.043Z", "question_score": 235, "tags": "python|list|dictionary|key", "answer_id": 18453567, "answer_date": "2013-08-26T21:45:38.043Z", "answer_score": 262 }
Please answer the following Stack Overflow question: Title: Updating state on props change in React Form <p>I am having trouble with a React form and managing the state properly. I have a time input field in a form (in a modal). The initial value is set as a state variable in <code>getInitialState</code>, and is passed in from a parent component. This in itself works fine.</p> <p>The problem comes when I want to update the default start_time value through the parent component. The update itself happens in the parent component through <code>setState start_time: new_time</code>. However in my form, the default <code>start_time</code> value never changes, since it is only defined once in <code>getInitialState</code>.</p> <p>I have tried to use <code>componentWillUpdate</code> to force a change in state through <code>setState start_time: next_props.start_time</code>, which did actually work, but it gave me <code>Uncaught RangeError: Maximum call stack size exceeded</code> errors.</p> <p>So my question is, what's the correct way of updating state in this case? Am I thinking about this wrong somehow?</p> <p>Current Code:</p> <pre><code>@ModalBody = React.createClass getInitialState: -&gt; start_time: @props.start_time.format(&quot;HH:mm&quot;) #works but takes long and causes: #&quot;Uncaught RangeError: Maximum call stack size exceeded&quot; componentWillUpdate: (next_props, next_state) -&gt; @setState(start_time: next_props.start_time.format(&quot;HH:mm&quot;)) fieldChanged: (fieldName, event) -&gt; stateUpdate = {} stateUpdate[fieldName] = event.target.value @setState(stateUpdate) render: -&gt; React.DOM.div className: &quot;modal-body&quot; React.DOM.form null, React.createElement FormLabelInputField, type: &quot;time&quot; id: &quot;start_time&quot; label_name: &quot;Start Time&quot; value: @state.start_time onChange: @fieldChanged.bind(null, &quot;start_time&quot;) @FormLabelInputField = React.createClass render: -&gt; React.DOM.div className: &quot;form-group&quot; React.DOM.label htmlFor: @props.id @props.label_name + &quot;: &quot; React.DOM.input className: &quot;form-control&quot; type: @props.type id: @props.id value: @props.value onChange: @props.onChange </code></pre>
<blockquote> <blockquote> <p>componentWillReceiveProps is depcricated since react 16: use <a href="https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops" rel="noreferrer">getDerivedStateFromProps</a> instead</p> </blockquote> </blockquote> <p>If I understand correctly, you have a parent component that is passing <code>start_time</code> down to the <code>ModalBody</code> component which assigns it to its own state? And you want to update that time from the parent, not a child component.</p> <p><a href="https://web.archive.org/web/20170101062930/http://reactjs.cn/react/tips/props-in-getInitialState-as-anti-pattern.html" rel="noreferrer">React has some tips on dealing with this scenario.</a> (Note, this is an old article that has since been removed from the web. Here's a link to the current <a href="https://reactjs.org/docs/components-and-props.html" rel="noreferrer">doc on component props</a>).</p> <blockquote> <p>Using props to generate state in <code>getInitialState</code> often leads to duplication of &quot;source of truth&quot;, i.e. where the real data is. This is because <code>getInitialState</code> is only invoked when the component is first created.</p> <p>Whenever possible, compute values on-the-fly to ensure that they don't get out of sync later on and cause maintenance trouble.</p> </blockquote> <p>Basically, whenever you assign parent's <code>props</code> to a child's <code>state</code> the render method isn't always called on prop update. You have to invoke it manually, using the <code>componentWillReceiveProps</code> method.</p> <pre><code>componentWillReceiveProps(nextProps) { // You don't have to do this check first, but it can help prevent an unneeded render if (nextProps.startTime !== this.state.startTime) { this.setState({ startTime: nextProps.startTime }); } } </code></pre>
{ "question_id": 32414308, "question_date": "2015-09-05T14:39:45.373Z", "question_score": 235, "tags": "reactjs", "answer_id": 32414771, "answer_date": "2015-09-05T15:29:59.843Z", "answer_score": 315 }
Please answer the following Stack Overflow question: Title: How to create a windows service from java app <p>I've just inherited a java application that needs to be installed as a service on XP and vista. It's been about 8 years since I've used windows in any form and I've never had to create a service, let alone from something like a java app (I've got a jar for the app and a single dependency jar - log4j). What is the magic necessary to make this run as a service? I've got the source, so code modifications, though preferably avoided, are possible.</p>
<p>I've had some luck with <a href="http://wrapper.tanukisoftware.org/doc/english/introduction.html" rel="noreferrer">the Java Service Wrapper</a></p>
{ "question_id": 68113, "question_date": "2008-09-16T00:06:34.937Z", "question_score": 235, "tags": "java|windows-services", "answer_id": 68140, "answer_date": "2008-09-16T00:11:11.727Z", "answer_score": 74 }
Please answer the following Stack Overflow question: Title: Read a file in Node.js <p>I'm quite puzzled with reading files in Node.js. </p> <pre><code>fs.open('./start.html', 'r', function(err, fileToRead){ if (!err){ fs.readFile(fileToRead, {encoding: 'utf-8'}, function(err,data){ if (!err){ console.log('received data: ' + data); response.writeHead(200, {'Content-Type': 'text/html'}); response.write(data); response.end(); }else{ console.log(err); } }); }else{ console.log(err); } }); </code></pre> <p>File <code>start.html</code> is in the same directory with file that tries to open and read it.</p> <p>However, in the console I get:</p> <blockquote> <p>{ [Error: ENOENT, open './start.html'] errno: 34, code: 'ENOENT', path: './start.html' }</p> </blockquote> <p>Any ideas?</p>
<p>Use <code>path.join(__dirname, '/start.html')</code>; </p> <pre><code>var fs = require('fs'), path = require('path'), filePath = path.join(__dirname, 'start.html'); fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ if (!err) { console.log('received data: ' + data); response.writeHead(200, {'Content-Type': 'text/html'}); response.write(data); response.end(); } else { console.log(err); } }); </code></pre> <p>Thanks to dc5.</p>
{ "question_id": 18386361, "question_date": "2013-08-22T16:43:34.650Z", "question_score": 235, "tags": "node.js", "answer_id": 19722356, "answer_date": "2013-11-01T07:13:08.430Z", "answer_score": 289 }
Please answer the following Stack Overflow question: Title: What is the largest Safe UDP Packet Size on the Internet <p>I've read a number of articles about UDP packet sizes but have been unable to come to a conclusion on whats correct.</p> <p>A number of services restrict the largest UDP packet to 512 bytes (like dns)</p> <p>Given the minimum <a href="http://en.wikipedia.org/wiki/Maximum_transmission_unit" rel="noreferrer" title="Maximum Transmission Unit">MTU</a> on the internet is 576 , and the size of the IPv4 header is 20 bytes, and the UDP header 8 bytes. This leaves 548 bytes available for user data </p> <p>Would I be able to use packets up to the size of 548 without packet fragmentation? Or is there something the creators of DNS knew about, and that why they restricted it to 512 bytes.</p> <p>Could I even go higher than 548 bytes safely?</p>
<p>It is true that a <em>typical</em> IPv4 header is 20 bytes, and the UDP header is 8 bytes. However it is possible to include IP options which can increase the size of the IP header to as much as 60 bytes. In addition, sometimes it is necessary for intermediate nodes to encapsulate datagrams inside of another protocol such as <a href="http://en.wikipedia.org/wiki/IPsec" rel="noreferrer" title="Internet Protocol Security">IPsec</a> (used for VPNs and the like) in order to route the packet to its destination. So if you do not know the <a href="http://en.wikipedia.org/wiki/Maximum_transmission_unit" rel="noreferrer" title="Maximum Transmission Unit">MTU</a> on your particular network path, it is best to leave a reasonable margin for other header information that you may not have anticipated. A 512-byte UDP payload is generally considered to do that, although even that does not leave quite enough space for a maximum size IP header.</p>
{ "question_id": 1098897, "question_date": "2009-07-08T15:39:49.327Z", "question_score": 235, "tags": "networking|sockets|udp|ipv4", "answer_id": 1099359, "answer_date": "2009-07-08T17:07:49.743Z", "answer_score": 153 }
Please answer the following Stack Overflow question: Title: Performing Inserts and Updates with Dapper <p>I am interested in using Dapper - but from what I can tell it only supports Query and Execute. I do not see that Dapper includes a way of Inserting and Updating objects.</p> <p>Given that our project (most projects?) need to do inserts and updates, what is the best practice for doing Inserts and Updates alongside dapper?</p> <p>Preferably we would not have to resort to the ADO.NET method of parameter building, etc.</p> <p>The best answer I can come up with at this point is to use LinqToSQL for inserts and updates. Is there a better answer?</p>
<p>We are looking at building a few helpers, still deciding on APIs and if this goes in core or not. See: <a href="https://code.google.com/archive/p/dapper-dot-net/issues/6" rel="noreferrer">https://code.google.com/archive/p/dapper-dot-net/issues/6</a> for progress.</p> <p>In the mean time you can do the following</p> <pre><code>val = &quot;my value&quot;; cnn.Execute(&quot;insert into Table(val) values (@val)&quot;, new {val}); cnn.Execute(&quot;update Table set val = @val where Id = @id&quot;, new {val, id = 1}); </code></pre> <p>etcetera</p> <p>See also my blog post: <a href="http://samsaffron.com/archive/2012/01/16/that-annoying-insert-problem-getting-data-into-the-db-using-dapper" rel="noreferrer">That annoying INSERT problem</a></p> <p><strong>Update</strong></p> <p>As pointed out in the comments, there are now several extensions available in the <strong><a href="https://github.com/DapperLib/Dapper.Contrib" rel="noreferrer">Dapper.Contrib</a></strong> project in the form of these <code>IDbConnection</code> extension methods:</p> <pre><code>T Get&lt;T&gt;(id); IEnumerable&lt;T&gt; GetAll&lt;T&gt;(); int Insert&lt;T&gt;(T obj); int Insert&lt;T&gt;(Enumerable&lt;T&gt; list); bool Update&lt;T&gt;(T obj); bool Update&lt;T&gt;(Enumerable&lt;T&gt; list); bool Delete&lt;T&gt;(T obj); bool Delete&lt;T&gt;(Enumerable&lt;T&gt; list); bool DeleteAll&lt;T&gt;(); </code></pre>
{ "question_id": 5957774, "question_date": "2011-05-10T23:54:29.647Z", "question_score": 235, "tags": "c#|orm|dapper", "answer_id": 5964462, "answer_date": "2011-05-11T12:45:30.387Z", "answer_score": 248 }
Please answer the following Stack Overflow question: Title: Show spinner GIF during an $http request in AngularJS? <p>I am using the <code>$http</code> service of AngularJS to make an Ajax request. </p> <p>How can a spinner GIF (or another type of busy indicator) be shown while the Ajax request is executing?</p> <p>I don't see anything like an <code>ajaxstartevent</code> in the AngularJS documentation.</p>
<p><strong>Here are the <s>current</s> past AngularJS incantations:</strong></p> <pre><code>angular.module('SharedServices', []) .config(function ($httpProvider) { $httpProvider.responseInterceptors.push('myHttpInterceptor'); var spinnerFunction = function (data, headersGetter) { // todo start the spinner here //alert('start spinner'); $('#mydiv').show(); return data; }; $httpProvider.defaults.transformRequest.push(spinnerFunction); }) // register the interceptor as a service, intercepts ALL angular ajax http calls .factory('myHttpInterceptor', function ($q, $window) { return function (promise) { return promise.then(function (response) { // do something on success // todo hide the spinner //alert('stop spinner'); $('#mydiv').hide(); return response; }, function (response) { // do something on error // todo hide the spinner //alert('stop spinner'); $('#mydiv').hide(); return $q.reject(response); }); }; }); //regular angular initialization continued below.... angular.module('myApp', [ 'myApp.directives', 'SharedServices']). //....... </code></pre> <p><strong>Here is the rest of it (HTML / CSS)....using</strong></p> <pre><code>$('#mydiv').show(); $('#mydiv').hide(); </code></pre> <p><strong>to toggle it. NOTE: the above is used in the angular module at beginning of post</strong></p> <pre><code>#mydiv { position:absolute; top:0; left:0; width:100%; height:100%; z-index:1000; background-color:grey; opacity: .8; } .ajax-loader { position: absolute; left: 50%; top: 50%; margin-left: -32px; /* -1 * image width / 2 */ margin-top: -32px; /* -1 * image height / 2 */ display: block; } &lt;div id="mydiv"&gt; &lt;img src="lib/jQuery/images/ajax-loader.gif" class="ajax-loader"/&gt; &lt;/div&gt; </code></pre>
{ "question_id": 15033195, "question_date": "2013-02-22T21:08:21.327Z", "question_score": 235, "tags": "angularjs|ajax|busyindicator", "answer_id": 15976991, "answer_date": "2013-04-12T17:00:59.417Z", "answer_score": 88 }
Please answer the following Stack Overflow question: Title: Common xlabel/ylabel for matplotlib subplots <p>I have the following plot:</p> <pre><code>fig,ax = plt.subplots(5,2,sharex=True,sharey=True,figsize=fig_size) </code></pre> <p>and now I would like to give this plot common x-axis labels and y-axis labels. With "common", I mean that there should be one big x-axis label below the whole grid of subplots, and one big y-axis label to the right. I can't find anything about this in the documentation for <code>plt.subplots</code>, and my googlings suggest that I need to make a big <code>plt.subplot(111)</code> to start with - but how do I then put my 5*2 subplots into that using <code>plt.subplots</code>?</p>
<p>This looks like what you actually want. It applies the same approach of <a href="https://stackoverflow.com/a/6981055/3753826">this answer</a> to your specific case:</p> <pre><code>import matplotlib.pyplot as plt fig, ax = plt.subplots(nrows=3, ncols=3, sharex=True, sharey=True, figsize=(6, 6)) fig.text(0.5, 0.04, 'common X', ha='center') fig.text(0.04, 0.5, 'common Y', va='center', rotation='vertical') </code></pre> <p><img src="https://i.stack.imgur.com/IrJNO.png" alt="Multiple plots with common axes label" /></p>
{ "question_id": 16150819, "question_date": "2013-04-22T15:25:51Z", "question_score": 235, "tags": "python|matplotlib", "answer_id": 26892326, "answer_date": "2014-11-12T16:56:58.210Z", "answer_score": 312 }
Please answer the following Stack Overflow question: Title: How to preserve timezone when parsing date/time strings with strptime()? <p>I have a CSV dumpfile from a Blackberry IPD backup, created using IPDDump. The date/time strings in here look something like this (where <code>EST</code> is an Australian time-zone):</p> <pre class="lang-none prettyprint-override"><code>Tue Jun 22 07:46:22 EST 2010 </code></pre> <p>I need to be able to parse this date in Python. At first, I tried to use the <code>strptime()</code> function from datettime.</p> <pre><code>&gt;&gt;&gt; datetime.datetime.strptime('Tue Jun 22 12:10:20 2010 EST', '%a %b %d %H:%M:%S %Y %Z') </code></pre> <p>However, for some reason, the <code>datetime</code> object that comes back doesn't seem to have any <code>tzinfo</code> associated with it.</p> <p>I did read on <a href="http://www.enricozini.org/2009/debian/using-python-datetime/" rel="noreferrer">this page</a> that apparently <code>datetime.strptime</code> silently discards <code>tzinfo</code>, however, I checked the documentation, and I can't find anything to that effect documented <a href="http://docs.python.org/library/datetime.html" rel="noreferrer">here</a>.</p> <p>Is there any way to get <code>strptime()</code> to play nicely with timezones?</p>
<p>The <a href="http://docs.python.org/library/datetime.html#datetime.datetime.strptime" rel="noreferrer"><code>datetime</code> module documentation</a> says:</p> <blockquote> <p>Return a datetime corresponding to date_string, parsed according to format. This is equivalent to <code>datetime(*(time.strptime(date_string, format)[0:6]))</code>.</p> </blockquote> <p>See that <code>[0:6]</code>? That gets you <code>(year, month, day, hour, minute, second)</code>. Nothing else. No mention of timezones.</p> <p>Interestingly, [Win XP SP2, Python 2.6, 2.7] passing your example to <code>time.strptime</code> doesn't work but if you strip off the " %Z" and the " EST" it does work. Also using "UTC" or "GMT" instead of "EST" works. "PST" and "MEZ" don't work. Puzzling.</p> <p>It's worth noting this has been updated as of version 3.2 and the same documentation now also states the following:</p> <blockquote> <p>When the %z directive is provided to the strptime() method, an aware datetime object will be produced. The tzinfo of the result will be set to a timezone instance.</p> </blockquote> <p>Note that this doesn't work with %Z, so the case is important. See the following example:</p> <pre><code>In [1]: from datetime import datetime In [2]: start_time = datetime.strptime('2018-04-18-17-04-30-AEST','%Y-%m-%d-%H-%M-%S-%Z') In [3]: print("TZ NAME: {tz}".format(tz=start_time.tzname())) TZ NAME: None In [4]: start_time = datetime.strptime('2018-04-18-17-04-30-+1000','%Y-%m-%d-%H-%M-%S-%z') In [5]: print("TZ NAME: {tz}".format(tz=start_time.tzname())) TZ NAME: UTC+10:00 </code></pre>
{ "question_id": 3305413, "question_date": "2010-07-22T02:42:08.213Z", "question_score": 235, "tags": "python|datetime|timezone", "answer_id": 3306887, "answer_date": "2010-07-22T08:08:36.430Z", "answer_score": 87 }
Please answer the following Stack Overflow question: Title: CSS grid wrapping <p>Is it possible to make a CSS grid wrap without using media queries?</p> <p>In my case, I have a non-deterministic number of items that I want placed in a grid and I want that grid to wrap. Using Flexbox, I'm unable to reliably space things nicely. I'd like to avoid a bunch of media queries too.</p> <p>Here's <a href="https://codepen.io/kentcdodds/pen/MpZKgx" rel="noreferrer">some sample code</a>:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.grid { display: grid; grid-gap: 10px; grid-auto-flow: column; grid-template-columns: 186px 186px 186px 186px; } .grid &gt; * { background-color: green; height: 200px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="grid"&gt; &lt;div&gt;1&lt;/div&gt; &lt;div&gt;2&lt;/div&gt; &lt;div&gt;3&lt;/div&gt; &lt;div&gt;4&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>And here's a GIF image:</p> <p><a href="https://i.stack.imgur.com/1I4gN.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/1I4gN.gif" alt="GIF image of what I&#39;m seeing"></a></p> <p>As a side-note, if anyone can tell me how I could avoid specifying the width of all the items like I am with <code>grid-template-columns</code> that would be great. I'd prefer the children to specify their own width.</p>
<p>Use either <a href="https://www.w3.org/TR/css-grid-1/#valdef-repeat-auto-fill" rel="noreferrer"><code>auto-fill</code></a> or <a href="https://www.w3.org/TR/css-grid-1/#valdef-repeat-auto-fit" rel="noreferrer"><code>auto-fit</code></a> as the first argument of the <a href="https://www.w3.org/TR/css-grid-1/#funcdef-repeat" rel="noreferrer"><code>repeat()</code></a> notation.</p> <p><a href="https://www.w3.org/TR/css-grid-1/#typedef-auto-repeat" rel="noreferrer"><code>&lt;auto-repeat&gt;</code></a> variant of the <code>repeat()</code> notation:</p> <pre><code>repeat( [ auto-fill | auto-fit ] , [ &lt;line-names&gt;? &lt;fixed-size&gt; ]+ &lt;line-names&gt;? ) </code></pre> <hr /> <h2><code>auto-fill</code></h2> <blockquote> <p>When <code>auto-fill</code> is given as the repetition number, if the grid container has a <a href="https://www.w3.org/TR/css-sizing-3/#definite" rel="noreferrer">definite</a> size or max size in the relevant axis, then the number of repetitions is the largest possible positive integer that does not cause the grid to overflow its grid container.</p> <p><sup><em><a href="https://www.w3.org/TR/css-grid-1/#valdef-repeat-auto-fill" rel="noreferrer">https://www.w3.org/TR/css-grid-1/#valdef-repeat-auto-fill</a></em></sup></p> </blockquote> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.grid { display: grid; grid-gap: 10px; grid-template-columns: repeat(auto-fill, 186px); } .grid&gt;* { background-color: green; height: 200px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="grid"&gt; &lt;div&gt;1&lt;/div&gt; &lt;div&gt;2&lt;/div&gt; &lt;div&gt;3&lt;/div&gt; &lt;div&gt;4&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>The grid will repeat as many tracks as possible without overflowing its container.</p> <p><a href="https://i.stack.imgur.com/1bPKS.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1bPKS.png" alt="Using auto-fill as the repetition number of the repeat() notation" /></a></p> <p>In this case, given the example above <em>(see image)</em>, only 5 tracks can fit the grid-container without overflowing. There are only 4 items in our grid, so a fifth one is created as an empty track within the remaining space.</p> <p>The rest of the remaining space, track #6, ends the explicit grid. This means there was not enough space to place another track.</p> <hr /> <h2><code>auto-fit</code></h2> <blockquote> <p>The <code>auto-fit</code> keyword behaves the same as <code>auto-fill</code>, except that after <a href="https://www.w3.org/TR/css-grid-1/#auto-placement-algo" rel="noreferrer">grid item placement</a> any empty repeated tracks are collapsed.</p> <p><sup><em><a href="https://www.w3.org/TR/css-grid-1/#valdef-repeat-auto-fit" rel="noreferrer">https://www.w3.org/TR/css-grid-1/#valdef-repeat-auto-fit</a></em></sup></p> </blockquote> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.grid { display: grid; grid-gap: 10px; grid-template-columns: repeat(auto-fit, 186px); } .grid&gt;* { background-color: green; height: 200px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="grid"&gt; &lt;div&gt;1&lt;/div&gt; &lt;div&gt;2&lt;/div&gt; &lt;div&gt;3&lt;/div&gt; &lt;div&gt;4&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>The grid will still repeat as many tracks as possible without overflowing its container, but the empty tracks will be collapsed to <code>0</code>.</p> <p>A collapsed track is treated as having a fixed track sizing function of <code>0px</code>.</p> <p><a href="https://i.stack.imgur.com/Cj7qh.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Cj7qh.png" alt="Using auto-fit as the repetition number of the repeat() notation" /></a></p> <p>Unlike the <code>auto-fill</code> image example, the empty fifth track is collapsed, ending the explicit grid right after the 4th item.</p> <hr /> <h2><code>auto-fill</code> vs <code>auto-fit</code></h2> <p>The difference between the two is noticeable when the <a href="https://www.w3.org/TR/css-grid-1/#valdef-grid-template-columns-minmax" rel="noreferrer"><code>minmax()</code></a> function is used.</p> <p>Use <code>minmax(186px, 1fr)</code> to range the items from <code>186px</code> to a <a href="https://www.w3.org/TR/css-grid-1/#fr-unit" rel="noreferrer">fraction of the leftover space in the grid container</a>.</p> <p>When using <code>auto-fill</code>, the items will grow once there is no space to place empty tracks.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.grid { display: grid; grid-gap: 10px; grid-template-columns: repeat(auto-fill, minmax(186px, 1fr)); } .grid&gt;* { background-color: green; height: 200px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="grid"&gt; &lt;div&gt;1&lt;/div&gt; &lt;div&gt;2&lt;/div&gt; &lt;div&gt;3&lt;/div&gt; &lt;div&gt;4&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>When using <code>auto-fit</code>, the items will grow to fill the remaining space because all the empty tracks will be collapsed to <code>0px</code>.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.grid { display: grid; grid-gap: 10px; grid-template-columns: repeat(auto-fit, minmax(186px, 1fr)); } .grid&gt;* { background-color: green; height: 200px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="grid"&gt; &lt;div&gt;1&lt;/div&gt; &lt;div&gt;2&lt;/div&gt; &lt;div&gt;3&lt;/div&gt; &lt;div&gt;4&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <hr /> <p>Playground:</p> <h2><a href="https://codepen.io/rickyruiz/pen/KemeoX" rel="noreferrer">CodePen</a></h2> <p>Inspecting auto-fill tracks</p> <p><a href="https://i.imgur.com/RL358r3.gif" rel="noreferrer"><img src="https://i.imgur.com/RL358r3.gif" alt="auto-fill" /></a></p> <hr /> <p>Inspecting auto-fit tracks</p> <p><a href="https://i.imgur.com/XeXrUll.gif" rel="noreferrer"><img src="https://i.imgur.com/XeXrUll.gif" alt="auto-fit" /></a></p>
{ "question_id": 43129360, "question_date": "2017-03-30T22:21:59.667Z", "question_score": 235, "tags": "html|css|css-grid", "answer_id": 43129507, "answer_date": "2017-03-30T22:38:14.253Z", "answer_score": 411 }
Please answer the following Stack Overflow question: Title: Error TF30063: You are not authorized to access ... \DefaultCollection <p>I'm using <a href="https://tfspreview.com/" rel="noreferrer">TFS Preview</a> (Team Foundation Service) with one of my projects with Visual Studio 2012. I'm also using an on-premises TFS server with most of my projects. When I use my on-premises TFS after using TFS preview and go back to using TFS preview, I get this error:</p> <blockquote> <p>TF30063: You are not authorized to access MyProject\DefaultCollection.</p> </blockquote> <p>If I go to <em>Team</em> → <em>Disconnect TFS</em> and then connect to TFS preview again, I'm able to see a "Loading identifiers" loading screen coming up, but in the end I don't get to enter my credentials to TFS preview (my Microsoft account) and as a result, the TF30063 error still occurs.</p> <p>I suspect this has something to do with my Microsoft account (i.e. Live ID). I'm logged in to Windows with the same Microsoft account that I use at TFS preview. I have logged in to other sites (Windows Development Center, MSDN, etc.) with other Microsoft accounts, but I verified that if I log out of these services and re-login with the correct Microsoft account, I still get the TF30063 error when I try to log in to TFS preview from Visual Studio.</p>
<p>I solved this issue by using the browser from within Visual Studio, View->Other Windows->Web Browser; <code>Ctrl+Alt+R</code> (or * <code>Ctrl+W, W</code>* in VS versions before VS2010) to navigate to the TFS page and log out of the wrong account and log back in.</p> <p>For me, the issue was caused by using another live-id to unlock a windows phone for development. Somehow the credentials got cached, it seems.</p>
{ "question_id": 12685111, "question_date": "2012-10-02T05:46:25.697Z", "question_score": 235, "tags": "visual-studio-2012|tfs|azure-devops", "answer_id": 13989712, "answer_date": "2012-12-21T11:54:13.307Z", "answer_score": 193 }
Please answer the following Stack Overflow question: Title: How do I view the list of functions a Linux shared library is exporting? <p>I want to view the exported functions of a shared library on Linux.</p> <p>What command allows me to do this?</p> <p>(On Windows I use the program depends)</p>
<p>What you need is <code>nm</code> and its <code>-D</code> option:</p> <pre><code>$ nm -D /usr/lib/libopenal.so.1 . . . 00012ea0 T alcSetThreadContext 000140f0 T alcSuspendContext U atanf U calloc . . . </code></pre> <p>Exported sumbols are indicated by a <code>T</code>. Required symbols that must be loaded from other shared objects have a <code>U</code>. Note that the symbol table does not include just functions, but exported variables as well.</p> <p>See the <code>nm</code> <a href="http://linux.die.net/man/1/nm" rel="noreferrer">manual page</a> for more information.</p>
{ "question_id": 4514745, "question_date": "2010-12-22T23:44:15.713Z", "question_score": 235, "tags": "linux|export|shared-libraries", "answer_id": 4514781, "answer_date": "2010-12-22T23:50:06.117Z", "answer_score": 381 }
Please answer the following Stack Overflow question: Title: Dropping Unique constraint from MySQL table <p>How can I drop the "Unique Key Constraint" on a column of a MySQL table using phpMyAdmin?</p>
<p>A unique constraint is also an index. </p> <p>First use <code>SHOW INDEX FROM tbl_name</code> to find out the name of the index. The name of the index is stored in the column called <code>key_name</code> in the results of that query.</p> <p>Then you can use <a href="http://dev.mysql.com/doc/refman/5.0/en/drop-index.html" rel="noreferrer">DROP INDEX</a>:</p> <pre><code>DROP INDEX index_name ON tbl_name </code></pre> <p>or the <a href="http://dev.mysql.com/doc/refman/5.1/en/alter-table.html" rel="noreferrer">ALTER TABLE</a> syntax:</p> <pre><code>ALTER TABLE tbl_name DROP INDEX index_name </code></pre>
{ "question_id": 3487691, "question_date": "2010-08-15T14:07:48.113Z", "question_score": 235, "tags": "mysql", "answer_id": 3487726, "answer_date": "2010-08-15T14:15:30.810Z", "answer_score": 405 }
Please answer the following Stack Overflow question: Title: Styling input buttons for iPad and iPhone <p>I'm using CSS to style the input buttons on my website, but on IOS devices the styling is replaced by Mac's default buttons. Is there a way to style buttons for iOS, or a way to maybe make a hyperlink that behaves like a submit button?</p>
<p>You may be looking for </p> <pre><code>-webkit-appearance: none; </code></pre> <ul> <li>Safari CSS notes on <a href="https://developer.apple.com/library/safari/documentation/appleapplications/reference/safaricssref/Articles/StandardCSSProperties.html#//apple_ref/css/property/-webkit-appearance" rel="noreferrer"><code>-webkit-appearance</code></a></li> <li>Mozilla Developer Network's <a href="https://developer.mozilla.org/en-US/docs/CSS/-moz-appearance" rel="noreferrer"><code>-moz-appearance</code></a> </li> </ul>
{ "question_id": 5449412, "question_date": "2011-03-27T13:09:50.830Z", "question_score": 235, "tags": "iphone|css|ios|ipad", "answer_id": 5452829, "answer_date": "2011-03-27T22:10:32.743Z", "answer_score": 557 }
Please answer the following Stack Overflow question: Title: Reshaping data.frame from wide to long format <p>I have some trouble to convert my <code>data.frame</code> from a wide table to a long table. At the moment it looks like this:</p> <pre><code>Code Country 1950 1951 1952 1953 1954 AFG Afghanistan 20,249 21,352 22,532 23,557 24,555 ALB Albania 8,097 8,986 10,058 11,123 12,246 </code></pre> <p>Now I would like to transform this <code>data.frame</code> into a long <code>data.frame</code>. Something like this:</p> <pre><code>Code Country Year Value AFG Afghanistan 1950 20,249 AFG Afghanistan 1951 21,352 AFG Afghanistan 1952 22,532 AFG Afghanistan 1953 23,557 AFG Afghanistan 1954 24,555 ALB Albania 1950 8,097 ALB Albania 1951 8,986 ALB Albania 1952 10,058 ALB Albania 1953 11,123 ALB Albania 1954 12,246 </code></pre> <p>I have looked at and already tried using the <code>melt()</code> and the <code>reshape()</code> functions as some people were suggesting in similar questions. However, so far I only get messy results.</p> <p>If it is possible I would like to do it with the <code>reshape()</code> function since it looks a little bit nicer to handle.</p>
<p><code>reshape()</code> takes a while to get used to, just as <code>melt</code>/<code>cast</code>. Here is a solution with reshape, assuming your data frame is called <code>d</code>:</p> <pre><code>reshape(d, direction = "long", varying = list(names(d)[3:7]), v.names = "Value", idvar = c("Code", "Country"), timevar = "Year", times = 1950:1954) </code></pre>
{ "question_id": 2185252, "question_date": "2010-02-02T15:36:12.590Z", "question_score": 235, "tags": "r|dataframe|reshape|r-faq", "answer_id": 2185525, "answer_date": "2010-02-02T16:07:59.630Z", "answer_score": 130 }
Please answer the following Stack Overflow question: Title: Why does my Spring Boot App always shutdown immediately after starting? <p>This is my first Spring Boot code. Unfortunately, it always shuts down. I was expecting it to run continuously so that my web client can get some data from the browser.</p> <pre><code>package hello; import org.springframework.boot.*; import org.springframework.boot.autoconfigure.*; import org.springframework.stereotype.*; import org.springframework.web.bind.annotation.*; @Controller @EnableAutoConfiguration public class SampleController { @RequestMapping("/") @ResponseBody String home() { return "Hello World!"; } public static void main(String[] args) throws Exception { SpringApplication.run(SampleController.class, args); } } [@localhost initial]$ java -jar build/libs/gs-spring-boot-0.1.0.jar . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.0.0.RC4) 2014-03-13 09:20:24.805 INFO 14650 --- [ main] hello.SampleController : Starting SampleController on localhost.localdomain with PID 14650 (/home/xxx/dev/gs-spring-boot/initial/build/libs/gs-spring-boot-0.1.0.jar started by xxx) 2014-03-13 09:20:25.002 INFO 14650 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@b9eec: startup date [Thu Mar 13 09:20:24 EDT 2014]; root of context hierarchy 2014-03-13 09:20:28.833 INFO 14650 --- [ main] o.s.b.a.e.jmx.EndpointMBeanExporter : Registering beans for JMX exposure on startup 2014-03-13 09:20:30.148 INFO 14650 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 0 2014-03-13 09:20:30.154 INFO 14650 --- [ main] o.s.b.a.e.jmx.EndpointMBeanExporter : Located managed bean 'requestMappingEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=requestMappingEndpoint] 2014-03-13 09:20:30.316 INFO 14650 --- [ main] o.s.b.a.e.jmx.EndpointMBeanExporter : Located managed bean 'environmentEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=environmentEndpoint] 2014-03-13 09:20:30.335 INFO 14650 --- [ main] o.s.b.a.e.jmx.EndpointMBeanExporter : Located managed bean 'healthEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=healthEndpoint] 2014-03-13 09:20:30.351 INFO 14650 --- [ main] o.s.b.a.e.jmx.EndpointMBeanExporter : Located managed bean 'beansEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=beansEndpoint] 2014-03-13 09:20:30.376 INFO 14650 --- [ main] o.s.b.a.e.jmx.EndpointMBeanExporter : Located managed bean 'infoEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=infoEndpoint] 2014-03-13 09:20:30.400 INFO 14650 --- [ main] o.s.b.a.e.jmx.EndpointMBeanExporter : Located managed bean 'metricsEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=metricsEndpoint] 2014-03-13 09:20:30.413 INFO 14650 --- [ main] o.s.b.a.e.jmx.EndpointMBeanExporter : Located managed bean 'traceEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=traceEndpoint] 2014-03-13 09:20:30.428 INFO 14650 --- [ main] o.s.b.a.e.jmx.EndpointMBeanExporter : Located managed bean 'dumpEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=dumpEndpoint] 2014-03-13 09:20:30.450 INFO 14650 --- [ main] o.s.b.a.e.jmx.EndpointMBeanExporter : Located managed bean 'autoConfigurationAuditEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=autoConfigurationAuditEndpoint] 2014-03-13 09:20:30.465 INFO 14650 --- [ main] o.s.b.a.e.jmx.EndpointMBeanExporter : Located managed bean 'shutdownEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=shutdownEndpoint] 2014-03-13 09:20:30.548 INFO 14650 --- [ main] o.s.b.a.e.jmx.EndpointMBeanExporter : Located managed bean 'configurationPropertiesReportEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=configurationPropertiesReportEndpoint] 2014-03-13 09:20:30.589 INFO 14650 --- [ main] hello.SampleController : Started SampleController in 7.396 seconds (JVM running for 9.569) 2014-03-13 09:20:30.608 INFO 14650 --- [ Thread-2] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@b9eec: startup date [Thu Mar 13 09:20:24 EDT 2014]; root of context hierarchy 2014-03-13 09:20:30.610 INFO 14650 --- [ Thread-2] o.s.c.support.DefaultLifecycleProcessor : Stopping beans in phase 0 2014-03-13 09:20:30.624 INFO 14650 --- [ Thread-2] o.s.b.a.e.jmx.EndpointMBeanExporter : Unregistering JMX-exposed beans on shutdown </code></pre> <p>Please advise. </p> <p>Thanks</p> <p>P.S. build.gradle is the fault.</p> <pre><code>dependencies { // tag::jetty[] compile("org.springframework.boot:spring-boot-starter-web") { **exclude module: "spring-boot-starter-tomcat"** } </code></pre> <p>Once I took off the above line in bold, everything works. My application context now is correct. Thanks Dave</p> <pre><code> . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.0.0.RC4) 2014-03-13 13:58:08.965 INFO 7307 --- [ main] hello.Application : Starting Application on with PID 7307 (/ladev/home/xxx/dev/gs-spring-boot/initial/build/libs/gs-spring-boo t-0.1.0.jar started by xxx) 2014-03-13 13:58:09.021 INFO 7307 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshi ng org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@45490eb5: startup date [Thu Mar 13 13:58:09 MDT 2014]; root of context hierarchy 2014-03-13 13:58:09.653 INFO 7307 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overridi ng bean definition for bean 'beanNameViewResolver': replacing [Root bean: class [null]; scope=; abstract=fal se; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanNam e=org.springframework.boot.actuate.autoconfigure.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/actuate/autoconfigure/ErrorMvcAutoConfiguration$WhitelabelErrorView Configuration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconf igure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; in itMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/au toconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]] </code></pre>
<p>Resolution: the app is not a webapp because it doesn't have an embedded container (e.g. Tomcat) on the classpath. Adding one fixed it. If you are using <strong>Maven</strong>, then add this in <code>pom.xml</code>:</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt; &lt;/dependency&gt; </code></pre> <p>For <strong>Gradle</strong> (<code>build.gradle</code>) it looks like</p> <pre><code>dependencies { compile 'org.springframework.boot:spring-boot-starter-web' } </code></pre>
{ "question_id": 22380119, "question_date": "2014-03-13T13:27:18.917Z", "question_score": 235, "tags": "java|spring|spring-boot", "answer_id": 22409655, "answer_date": "2014-03-14T15:42:57.707Z", "answer_score": 476 }
Please answer the following Stack Overflow question: Title: add created_at and updated_at fields to mongoose schemas <p>Is there a way to add created_at and <code>updated_at</code> fields to a mongoose schema, without having to pass them in everytime new <code>MyModel()</code> is called?</p> <p>The <code>created_at</code> field would be a date and only added when a document is created. The <code>updated_at</code> field would be updated with new date whenever <code>save()</code> is called on a document.</p> <p>I have tried this in my schema, but the field does not show up unless I explicitly add it:</p> <pre><code>var ItemSchema = new Schema({ name : { type: String, required: true, trim: true }, created_at : { type: Date, required: true, default: Date.now } }); </code></pre>
<p>As of Mongoose 4.0 you can now set a timestamps option on the Schema to have Mongoose handle this for you:</p> <pre><code>var thingSchema = new Schema({..}, { timestamps: true }); </code></pre> <p>You can change the name of the fields used like so:</p> <pre><code>var thingSchema = new Schema({..}, { timestamps: { createdAt: 'created_at' } }); </code></pre> <p><a href="http://mongoosejs.com/docs/guide.html#timestamps">http://mongoosejs.com/docs/guide.html#timestamps</a></p>
{ "question_id": 12669615, "question_date": "2012-10-01T08:13:47.047Z", "question_score": 235, "tags": "node.js|mongodb|express|mongoose", "answer_id": 33242994, "answer_date": "2015-10-20T17:25:27.657Z", "answer_score": 255 }
Please answer the following Stack Overflow question: Title: Git Push error: refusing to update checked out branch <p>I have solved some merge conflicts, committed then tried to Push my changes and received the following error:</p> <pre><code>c:\Program Files (x86)\Git\bin\git.exe push --recurse-submodules=check "origin" master:master Done remote: error: refusing to update checked out branch: refs/heads/master remote: error: By default, updating the current branch in a non-bare repository remote: error: is denied, because it will make the index and work tree inconsistent remote: error: with what you pushed, and will require 'git reset --hard' to match remote: error: the work tree to HEAD. remote: error: remote: error: You can set 'receive.denyCurrentBranch' configuration variable to remote: error: 'ignore' or 'warn' in the remote repository to allow pushing into remote: error: its current branch; however, this is not recommended unless you remote: error: arranged to update its work tree to match what you pushed in some remote: error: other way. remote: error: remote: error: To squelch this message and still keep the default behaviour, set remote: error: 'receive.denyCurrentBranch' configuration variable to 'refuse'. To C:/Development/GIT_Repo/Project ! [remote rejected] master -&gt; master (branch is currently checked out) error: failed to push some refs to 'C:/Development/GIT_Repo/Project' </code></pre> <p>Does anyone know what could be causing this error?</p>
<p>Reason:You are pushing to a Non-Bare Repository</p> <p>There are two types of repositories: <a href="https://stackoverflow.com/q/5540883/3803682">bare and non-bare</a></p> <p>Bare repositories do not have a working copy and you can push to them. Those are the types of repositories you get in Github! If you want to create a bare repository, you can use</p> <pre><code>git init --bare </code></pre> <p><del>So, in short, <strong>you can't push to a non-bare repository</strong></del> (Edit: Well, you can't push to the currently checked out branch of a repository. With a bare repository, you can push to any branch since none are checked out. Although possible, pushing to non-bare repositories is not common). What you can do, is to fetch and merge from the other repository. This is how the <code>pull request</code> that you can see in Github works. You ask them to pull from you, and you don't force-push into them.</p> <hr> <p><strong>Update</strong>: Thanks to VonC for pointing this out, in the latest git versions (currently 2.3.0), <a href="https://stackoverflow.com/a/28262104/912144">pushing to the checked out branch of a non-bare repository is possible</a>. Nevertheless, you still cannot push to a <em>dirty</em> working tree, which is not a safe operation anyway.</p>
{ "question_id": 11117823, "question_date": "2012-06-20T10:40:18.267Z", "question_score": 235, "tags": "git|git-push", "answer_id": 11117928, "answer_date": "2012-06-20T10:47:46.270Z", "answer_score": 282 }
Please answer the following Stack Overflow question: Title: Take a full page screenshot with Firefox on the command-line <p>I'm running Firefox on a Xvfb in a VPS. What I want to do is to take a full page screenshot of the page.</p> <p>I can redirect Firefox to particular page using</p> <pre><code>firefox http://google.com </code></pre> <p>and take a screenshot (inside X) using ImageMagick</p> <pre><code>import root -window output.jpg </code></pre> <p>The problem is, most of the page need scrolling and I can't know the height beforehand.</p> <p>The other way is to pick a very big height (like 4000px) and then process the image and remove the useless part. But that's unnecessary processing.</p> <p>I found many Firefox add-ons, but I'm looking for a solution that can be programmed using the Shell Command line.</p> <p>Edit: I ended up writing my own <a href="https://github.com/omarabid/CmdShots" rel="noreferrer">FireFox extension</a> for doing this.</p>
<p>The <a href="https://mail.mozilla.org/pipermail/firefox-dev/2018-March/006249.html" rel="noreferrer">Developer Toolbar GCLI and <kbd>Shift</kbd>+<kbd>F2</kbd> shortcut were removed in Firefox version 60</a>. To take a screenshot in 60 or newer:</p> <ul> <li>press <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>K</kbd> to open the developer console (<kbd>⌥ Option</kbd>+<kbd>⌘ Command</kbd>+<kbd>K</kbd> on macOS)</li> <li>type <code>:screenshot</code> or <code>:screenshot --fullpage</code></li> </ul> <p><a href="https://blog.nightly.mozilla.org/2018/08/23/screenshots-from-the-console/" rel="noreferrer">Find out more regarding screenshots and other features</a></p> <hr /> <p>For Firefox versions &lt; 60:</p> <p>Press <kbd>Shift</kbd>+<kbd>F2</kbd> or go to <strong>Tools &gt; Web Developer &gt; Developer Toolbar</strong> to open a command line. Write:</p> <pre><code>screenshot </code></pre> <p>and press <strong>Enter</strong> in order to take a screenshot.</p> <p>To fully answer the question, you can even save the whole page, not only the visible part of it:</p> <pre><code>screenshot --fullpage </code></pre> <p>And to copy the screenshot to clipboard, use <code>--clipboard</code> option:</p> <pre><code>screenshot --clipboard --fullpage </code></pre> <p><a href="http://support.mozilla.org/es/questions/947227" rel="noreferrer">Firefox 18</a> changes the way arguments are passed to commands, you have to add &quot;--&quot; before them.</p> <p><a href="https://stackoverflow.com/questions/13158083/take-a-full-page-screenshot-with-firefox-on-the-command-line/14830242?noredirect=1#comment118932922_14830242" title="Thank you, TylerH!">Firefox 88.0</a> has a new method for taking screenshots. If <code>extensions.screenshots.disabled</code> is set to <code>false</code> in <strong>about:config</strong>, you can right-click the screen and select <strong>Take Screenshot</strong>. There's also a screenshot menu button you can add to your menu via customization.</p> <p>You can find some documentation and the full list of commands <a href="https://developer.mozilla.org/en-US/docs/Tools/GCLI" rel="noreferrer">here</a>.</p> <p><sub>PS. The screenshots are saved into the <em>downloads</em> directory by default.</sub></p>
{ "question_id": 13158083, "question_date": "2012-10-31T12:34:37.543Z", "question_score": 235, "tags": "shell|firefox|command-line|screenshot", "answer_id": 14830242, "answer_date": "2013-02-12T10:22:16.980Z", "answer_score": 494 }
Please answer the following Stack Overflow question: Title: What is the easiest way to use SVG images in Android? <p>I have found a myriad of libraries in order to use SVG images in Android and avoid the frustrating creation of different resolutions and dropping files for each resolution. This becomes very annoying when the app has many icons or images.</p> <p>What would be a step-by-step process of the simplest-to-use library for using SVG images in Android?</p> <p>Also I use Android Studio and <a href="https://en.wikipedia.org/wiki/Adobe_Illustrator" rel="noreferrer">Illustrator</a> for generating my icons and images.</p>
<p>First you need to import SVG files by the following simple steps.</p> <ol> <li>Right click on your project's drawable folder (app/res/drawable)</li> <li>Click <kbd>New</kbd></li> <li>Select <em>Vector Asset</em></li> </ol> <p>If the image is available in your computer then select the local <code>svg</code> file.</p> <p>After that, select the image path. An option to change the size of the image is also available at the right side of dialog if you want to. In this way, the SVG image is imported in your project.</p> <p>After that, for using this image, use the same procedure:</p> <pre><code>@drawable/yourimagename </code></pre>
{ "question_id": 30923205, "question_date": "2015-06-18T18:38:37.427Z", "question_score": 235, "tags": "android|svg|androidsvg", "answer_id": 39266840, "answer_date": "2016-09-01T08:48:56.243Z", "answer_score": 493 }
Please answer the following Stack Overflow question: Title: Different ways of loading a file as an InputStream <p>What's the difference between:</p> <pre><code>InputStream is = this.getClass().getClassLoader().getResourceAsStream(fileName) </code></pre> <p>and</p> <pre><code>InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName) </code></pre> <p>and</p> <pre><code>InputStream is = this.getClass().getResourceAsStream(fileName) </code></pre> <p>When are each one more appropriate to use than the others?</p> <p>The file that I want to read is in the classpath as my class that reads the file. My class and the file are in the same jar and packaged up in an EAR file, and deployed in WebSphere 6.1.</p>
<p>There are subtle differences as to how the <code>fileName</code> you are passing is interpreted. Basically, you have 2 different methods: <code>ClassLoader.getResourceAsStream()</code> and <code>Class.getResourceAsStream()</code>. These two methods will locate the resource differently.</p> <p>In <code>Class.getResourceAsStream(path)</code>, the path is interpreted as a path local to the package of the class you are calling it from. For example calling, <code>String.class.getResourceAsStream(&quot;myfile.txt&quot;)</code> will look for a file in your classpath at the following location: <code>&quot;java/lang/myfile.txt&quot;</code>. If your path starts with a <code>/</code>, then it will be considered an absolute path, and will start searching from the root of the classpath. So calling <code>String.class.getResourceAsStream(&quot;/myfile.txt&quot;)</code> will look at the following location in your class path <code>./myfile.txt</code>.</p> <p><code>ClassLoader.getResourceAsStream(path)</code> will consider all paths to be absolute paths. So calling <code>String.class.getClassLoader().getResourceAsStream(&quot;myfile.txt&quot;)</code> and <code>String.class.getClassLoader().getResourceAsStream(&quot;/myfile.txt&quot;)</code> will both look for a file in your classpath at the following location: <code>./myfile.txt</code>.</p> <p>Everytime I mention a location in this post, it could be a location in your filesystem itself, or inside the corresponding jar file, depending on the Class and/or ClassLoader you are loading the resource from.</p> <p>In your case, you are loading the class from an Application Server, so your should use <code>Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName)</code> instead of <code>this.getClass().getClassLoader().getResourceAsStream(fileName)</code>. <code>this.getClass().getResourceAsStream()</code> will also work.</p> <p>Read <a href="http://www.javaworld.com/javaworld/javaqa/2003-08/01-qa-0808-property.html" rel="noreferrer">this article</a> for more detailed information about that particular problem.</p> <hr /> <h2>Warning for users of Tomcat 7 and below</h2> <p>One of the answers to this question states that my explanation seems to be incorrect for Tomcat 7. I've tried to look around to see why that would be the case.</p> <p>So I've looked at the source code of Tomcat's <code>WebAppClassLoader</code> for several versions of Tomcat. The implementation of <code>findResource(String name)</code> (which is utimately responsible for producing the URL to the requested resource) is virtually identical in Tomcat 6 and Tomcat 7, but is different in Tomcat 8.</p> <p>In versions 6 and 7, the implementation does not attempt to normalize the resource name. This means that in these versions, <code>classLoader.getResourceAsStream(&quot;/resource.txt&quot;)</code> may not produce the same result as <code>classLoader.getResourceAsStream(&quot;resource.txt&quot;)</code> event though it should (since that what the Javadoc specifies). <a href="https://github.com/apache/tomcat/blob/7.0.96/java/org/apache/catalina/loader/WebappClassLoaderBase.java" rel="noreferrer">[source code]</a></p> <p>In version 8 though, the resource name is normalized to guarantee that the absolute version of the resource name is the one that is used. Therefore, in Tomcat 8, the two calls described above should always return the same result. <a href="https://github.com/apache/tomcat/blob/8.5.45/java/org/apache/catalina/loader/WebappClassLoaderBase.java" rel="noreferrer">[source code]</a></p> <p>As a result, you have to be extra careful when using <code>ClassLoader.getResourceAsStream()</code> or <code>Class.getResourceAsStream()</code> on Tomcat versions earlier than 8. And you must also keep in mind that <code>class.getResourceAsStream(&quot;/resource.txt&quot;)</code> actually calls <code>classLoader.getResourceAsStream(&quot;resource.txt&quot;)</code> (the leading <code>/</code> is stripped).</p>
{ "question_id": 676250, "question_date": "2009-03-24T05:32:43.560Z", "question_score": 235, "tags": "java|inputstream", "answer_id": 676273, "answer_date": "2009-03-24T05:52:21.640Z", "answer_score": 305 }
Please answer the following Stack Overflow question: Title: Why is the default value of the string type null instead of an empty string? <p>It's quite annoying to test all my strings for <code>null</code> before I can safely apply methods like <code>ToUpper()</code>, <code>StartWith()</code> etc...</p> <p>If the default value of <code>string</code> were the empty string, I would not have to test, and I would feel it to be more consistent with the other value types like <code>int</code> or <code>double</code> for example. Additionally <code>Nullable&lt;String&gt;</code> would make sense.</p> <p>So why did the designers of C# choose to use <code>null</code> as the default value of strings?</p> <p>Note: This relates to <a href="https://stackoverflow.com/questions/265875/default-string-initialization-null-or-empty">this question</a>, but is more focused on the why instead of what to do with it.</p>
<blockquote> <p>Why is the default value of the string type null instead of an empty string?</p> </blockquote> <p>Because <code>string</code> is a <strong>reference type</strong> and the default value for all reference types is <code>null</code>. </p> <blockquote> <p>It's quite annoying to test all my strings for null before I can safely apply methods like ToUpper(), StartWith() etc...</p> </blockquote> <p>That is consistent with the behaviour of reference types. Before invoking their instance members, one should put a check in place for a null reference.</p> <blockquote> <p>If the default value of string were the empty string, I would not have to test, and I would feel it to be more consistent with the other value types like int or double for example.</p> </blockquote> <p>Assigning the default value to a specific reference type other than <code>null</code> would make it <strong>inconsistent</strong>.</p> <blockquote> <p>Additionally <code>Nullable&lt;String&gt;</code> would make sense.</p> </blockquote> <p><a href="http://msdn.microsoft.com/en-us/library/1t3y8s4s%28v=vs.110%29.aspx" rel="noreferrer"><code>Nullable&lt;T&gt;</code></a> works with the value types. Of note is the fact that <code>Nullable</code> was not introduced on the original <a href="http://msdn.microsoft.com/en-us/library/b3h38hb0(v=vs.80).aspx" rel="noreferrer">.NET platform</a> so there would have been a lot of broken code had they changed that rule.(<em>Courtesy <a href="https://stackoverflow.com/users/109749/jcolebrand">@jcolebrand</a>)</em></p>
{ "question_id": 14337551, "question_date": "2013-01-15T12:17:11.787Z", "question_score": 235, "tags": "c#|string|default-value", "answer_id": 14337561, "answer_date": "2013-01-15T12:17:51.433Z", "answer_score": 328 }
Please answer the following Stack Overflow question: Title: Can functions be passed as parameters? <p>In Java I can do something like </p> <pre><code>derp(new Runnable { public void run () { /* run this sometime later */ } }) </code></pre> <p>and "run" the code in the method later. It's a pain to handle (anonymous inner class), but it can be done.</p> <p>Does Go have something that can facilitate a function/callback being passed in as a parameter?</p>
<p>Yes, consider some of these examples:</p> <pre><code>package main import "fmt" // convert types take an int and return a string value. type convert func(int) string // value implements convert, returning x as string. func value(x int) string { return fmt.Sprintf("%v", x) } // quote123 passes 123 to convert func and returns quoted string. func quote123(fn convert) string { return fmt.Sprintf("%q", fn(123)) } func main() { var result string result = value(123) fmt.Println(result) // Output: 123 result = quote123(value) fmt.Println(result) // Output: "123" result = quote123(func(x int) string { return fmt.Sprintf("%b", x) }) fmt.Println(result) // Output: "1111011" foo := func(x int) string { return "foo" } result = quote123(foo) fmt.Println(result) // Output: "foo" _ = convert(foo) // confirm foo satisfies convert at runtime // fails due to argument type // _ = convert(func(x float64) string { return "" }) } </code></pre> <p>Play: <a href="http://play.golang.org/p/XNMtrDUDS0">http://play.golang.org/p/XNMtrDUDS0</a></p> <p>Tour: <a href="https://tour.golang.org/moretypes/25">https://tour.golang.org/moretypes/25</a> (Function Closures)</p>
{ "question_id": 12655464, "question_date": "2012-09-29T18:45:33.923Z", "question_score": 235, "tags": "function|go", "answer_id": 12655719, "answer_date": "2012-09-29T19:18:35.287Z", "answer_score": 315 }
Please answer the following Stack Overflow question: Title: Handling exceptions from Java ExecutorService tasks <p>I'm trying to use Java's <code>ThreadPoolExecutor</code> class to run a large number of heavy weight tasks with a fixed number of threads. Each of the tasks has many places during which it may fail due to exceptions.</p> <p>I've subclassed <code>ThreadPoolExecutor</code> and I've overridden the <code>afterExecute</code> method which is supposed to provide any uncaught exceptions encountered while running a task. However, I can't seem to make it work.</p> <p>For example:</p> <pre><code>public class ThreadPoolErrors extends ThreadPoolExecutor { public ThreadPoolErrors() { super( 1, // core threads 1, // max threads 1, // timeout TimeUnit.MINUTES, // timeout units new LinkedBlockingQueue&lt;Runnable&gt;() // work queue ); } protected void afterExecute(Runnable r, Throwable t) { super.afterExecute(r, t); if(t != null) { System.out.println("Got an error: " + t); } else { System.out.println("Everything's fine--situation normal!"); } } public static void main( String [] args) { ThreadPoolErrors threadPool = new ThreadPoolErrors(); threadPool.submit( new Runnable() { public void run() { throw new RuntimeException("Ouch! Got an error."); } } ); threadPool.shutdown(); } } </code></pre> <p>The output from this program is "Everything's fine--situation normal!" even though the only Runnable submitted to the thread pool throws an exception. Any clue to what's going on here?</p> <p>Thanks!</p>
<p>From the <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadPoolExecutor.html" rel="noreferrer">docs</a>:</p> <blockquote> <p>Note: When actions are enclosed in tasks (such as FutureTask) either explicitly or via methods such as submit, these task objects catch and maintain computational exceptions, and so they do not cause abrupt termination, and the internal exceptions are not passed to this method.</p> </blockquote> <p>When you submit a Runnable, it'll get wrapped in a Future.</p> <p>Your afterExecute should be something like this:</p> <pre><code>public final class ExtendedExecutor extends ThreadPoolExecutor { // ... protected void afterExecute(Runnable r, Throwable t) { super.afterExecute(r, t); if (t == null &amp;&amp; r instanceof Future&lt;?&gt;) { try { Future&lt;?&gt; future = (Future&lt;?&gt;) r; if (future.isDone()) { future.get(); } } catch (CancellationException ce) { t = ce; } catch (ExecutionException ee) { t = ee.getCause(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } } if (t != null) { System.out.println(t); } } } </code></pre>
{ "question_id": 2248131, "question_date": "2010-02-11T22:09:49.287Z", "question_score": 235, "tags": "java|multithreading|exception|executorservice|threadpoolexecutor", "answer_id": 2248203, "answer_date": "2010-02-11T22:21:05.923Z", "answer_score": 170 }
Please answer the following Stack Overflow question: Title: Install / upgrade gradle on Mac OS X <p>How do I install/upgrade <a href="https://gradle.org/" rel="noreferrer">gradle</a> for Mac?</p>
<p>As mentioned in <a href="http://www.jayway.com/2013/05/12/getting-started-with-gradle/" rel="noreferrer">this tutorial</a>, it's as simple as:</p> <p>To install</p> <pre><code>brew install gradle </code></pre> <p>To upgrade </p> <pre><code>brew upgrade gradle </code></pre> <p>(using <a href="http://brew.sh/" rel="noreferrer">Homebrew</a> of course)</p> <p>Also see (finally) <a href="https://gradle.org/install/" rel="noreferrer">updated docs</a>.</p> <p>Cheers :)!</p>
{ "question_id": 28928106, "question_date": "2015-03-08T15:21:32.693Z", "question_score": 235, "tags": "macos|build|gradle|build.gradle", "answer_id": 28928107, "answer_date": "2015-03-08T15:21:32.693Z", "answer_score": 458 }
Please answer the following Stack Overflow question: Title: WPF Databinding: How do I access the "parent" data context? <p>I have a list (see below) contained in a window. The window's <code>DataContext</code> has two properties, <code>Items</code> and <code>AllowItemCommand</code>.</p> <p>How do I get the binding for the <code>Hyperlink</code>'s <code>Command</code> property needs to resolve against the window's <code>DataContext</code>?</p> <pre><code>&lt;ListView ItemsSource="{Binding Items}"&gt; &lt;ListView.View&gt; &lt;GridView&gt; &lt;GridViewColumn Header="Action"&gt; &lt;GridViewColumn.CellTemplate&gt; &lt;DataTemplate&gt; &lt;StackPanel&gt; &lt;TextBlock&gt; &lt;!-- this binding is not working --&gt; &lt;Hyperlink Command="{Binding AllowItemCommand}" CommandParameter="{Binding .}"&gt; &lt;TextBlock Text="Allow" /&gt; &lt;/Hyperlink&gt; &lt;/TextBlock&gt; &lt;/StackPanel&gt; &lt;/DataTemplate&gt; &lt;/GridViewColumn.CellTemplate&gt; &lt;/GridViewColumn&gt; &lt;/GridView&gt; &lt;/ListView.View&gt; &lt;/ListView&gt; </code></pre>
<p>You could try something like this:</p> <pre><code>...Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.AllowItemCommand}" ... </code></pre>
{ "question_id": 1127933, "question_date": "2009-07-14T20:46:43.683Z", "question_score": 235, "tags": "wpf|data-binding|datacontext", "answer_id": 1127964, "answer_date": "2009-07-14T20:51:38.837Z", "answer_score": 456 }
Please answer the following Stack Overflow question: Title: How to get the current branch within Github Actions? <p>I'm building Docker images with Github Actions and want to tag images with the branch name.</p> <p>I found the <code>GITHUB_REF</code> variable, but it results in <code>refs/heads/feature-branch-1</code> and I need only <code>feature-branch-1</code>.</p>
<p>I added a separate step for extracting branch name from <code>$GITHUB_REF</code> and set it to the step output</p> <pre class="lang-yaml prettyprint-override"><code>- name: Extract branch name shell: bash run: echo &quot;##[set-output name=branch;]$(echo ${GITHUB_REF#refs/heads/})&quot; id: extract_branch </code></pre> <p>after that, I can use it in the next steps with</p> <pre class="lang-yaml prettyprint-override"><code>- name: Push to ECR id: ecr uses: jwalton/gh-ecr-push@master with: access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} region: us-west-2 image: eng:${{ steps.extract_branch.outputs.branch }} </code></pre>
{ "question_id": 58033366, "question_date": "2019-09-20T18:15:20.293Z", "question_score": 235, "tags": "github|github-actions", "answer_id": 58035262, "answer_date": "2019-09-20T21:15:37.570Z", "answer_score": 231 }
Please answer the following Stack Overflow question: Title: Hide Up & Down Arrow Buttons (Spinner) in Input Number - Firefox 29 <p>On Firefox 28, I'm using <code>&lt;input type="number"&gt;</code> works great because it brings up the numerical keyboard on input fields which should only contain numbers.</p> <p>In Firefox 29, using number inputs displays spin buttons at the right side of the field, which looks like crap in my design. I really don't need the buttons, because they are useless when you need to write something like a 6~10 digit number anyway.</p> <p>Is it possible to disable this with CSS or jQuery?</p>
<p>According to <a href="https://jwatt.org/2013/12/11/input-type-number-coming-to-mozilla" rel="noreferrer">this blog post</a>, you need to set <code>-moz-appearance:textfield;</code> on the <code>input</code>.<div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>input[type=number]::-webkit-outer-spin-button, input[type=number]::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; } input[type=number] { -moz-appearance:textfield; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;input type="number" step="0.01"/&gt;</code></pre> </div> </div> </p>
{ "question_id": 23372903, "question_date": "2014-04-29T18:48:57.813Z", "question_score": 235, "tags": "css|firefox|input|spinner", "answer_id": 23374725, "answer_date": "2014-04-29T20:33:43.803Z", "answer_score": 598 }
Please answer the following Stack Overflow question: Title: How to set environment via `ng serve` in Angular 6 <p>I am trying to update my Angular 5.2 app to Angular 6. I successfully followed instructions in the Angular update guide (including the update of <code>angular-cli</code> to v6), and now I am trying to serve the app via</p> <pre><code>ng serve --env=local </code></pre> <p>But this gives me error:</p> <blockquote> <p>Unknown option: '--env'</p> </blockquote> <p>I use multiple environments (<code>dev/local/prod</code>), and this is the way it was working in Angular 5.2. How can I set the environment now in Angular 6?</p>
<p>You need to use the new <code>configuration</code> option (this works for <code>ng build</code> and <code>ng serve</code> as well)</p> <pre><code>ng serve --configuration=local </code></pre> <p>or</p> <pre><code>ng serve -c local </code></pre> <p>If you look at your <code>angular.json</code> file, you'll see that you have finer control over settings for each configuration (aot, optimizer, environment files,...)</p> <pre><code>"configurations": { "production": { "optimization": true, "outputHashing": "all", "sourceMap": false, "extractCss": true, "namedChunks": false, "aot": true, "extractLicenses": true, "vendorChunk": false, "buildOptimizer": true, "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.prod.ts" } ] } } </code></pre> <p>You can get more info <a href="https://github.com/angular/angular-cli/wiki/stories-application-environments" rel="noreferrer">here</a> for managing environment specific configurations. </p> <p>As pointed in the other response below, if you need to add a new 'environment', you need to add a new configuration to the <strong>build</strong> task and, depending on your needs, to the <strong>serve</strong> and <strong>test</strong> tasks as well.</p> <p><strong>Adding a new environment</strong></p> <p><strong>Edit</strong>: To make it clear, file replacements must be specified in the <code>build</code> section. So if you want to use <code>ng serve</code> with a specific <code>environment</code> file (say <strong>dev2</strong>), you first need to modify the <code>build</code> section to add a new <strong>dev2</strong> configuration </p> <pre><code>"build": { "configurations": { "dev2": { "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.dev2.ts" } /* You can add all other options here, such as aot, optimization, ... */ ], "serviceWorker": true }, </code></pre> <p>Then modify your <code>serve</code> section to add a new configuration as well, pointing to the <strong>dev2</strong> <code>build</code> configuration you just declared</p> <pre><code>"serve": "configurations": { "dev2": { "browserTarget": "projectName:build:dev2" } </code></pre> <p>Then you can use <code>ng serve -c dev2</code>, which will use the dev2 config file</p>
{ "question_id": 50174584, "question_date": "2018-05-04T12:07:23.860Z", "question_score": 235, "tags": "angular|angular6|angular-cli", "answer_id": 50174679, "answer_date": "2018-05-04T12:12:54.880Z", "answer_score": 433 }
Please answer the following Stack Overflow question: Title: iOS 7 Navigation Bar text and arrow color <p>I want to set background for Navigation Bar to be <strong>black</strong> and all colors inside it to be <strong>white</strong>.<br/></p> <p>So, I used this code :</p> <pre><code>[[UINavigationBar appearance] setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys: [UIColor whiteColor], NSForegroundColorAttributeName, [UIColor whiteColor], NSForegroundColorAttributeName, [NSValue valueWithUIOffset:UIOffsetMake(0, -1)], NSForegroundColorAttributeName, [UIFont fontWithName:@&quot;Arial-Bold&quot; size:0.0], NSFontAttributeName, nil]]; </code></pre> <p>But back button <strong>text color</strong>, <strong>arrow</strong> and <strong>bar button</strong> have still default <strong>blue color</strong>.<br/> How to change those colors like on image below?<br/></p> <p><a href="https://i.stack.imgur.com/xwOa0.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xwOa0.jpg" alt="navigation bar" /></a></p>
<p>Behavior from some of the properties of <code>UINavigationBar</code> has changed from <strong>iOS 7</strong>. You can see in the image shown below :</p> <p><img src="https://i.stack.imgur.com/DtNbN.png" alt="enter image description here"></p> <hr> <p>Two beautiful links I'd like to share with you. For more details you can go through these links :</p> <ol> <li><a href="https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/TransitionGuide/index.html">iOS 7 UI Transition Guide</a>.</li> <li><a href="http://www.appdesignvault.com/ios-7-update/">How to Update Your App for iOS 7</a>.</li> </ol> <hr> <p><strong>Apple Documentation</strong> for <a href="https://developer.apple.com/library/ios/documentation/uikit/reference/UINavigationBar_Class/Reference/UINavigationBar.html#//apple_ref/occ/instp/UINavigationBar/barTintColor">barTintColor</a> says :</p> <blockquote> <p>This color is made translucent by default unless you set the translucent property to NO.</p> </blockquote> <p><strong>Sample Code :</strong></p> <pre><code>self.navigationController.navigationBar.barTintColor = [UIColor blackColor]; self.navigationController.navigationBar.tintColor = [UIColor whiteColor]; [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}]; self.navigationController.navigationBar.translucent = NO; </code></pre>
{ "question_id": 19029833, "question_date": "2013-09-26T13:35:05.033Z", "question_score": 235, "tags": "iphone|ios|objective-c|uinavigationbar|ios7", "answer_id": 19029973, "answer_date": "2013-09-26T13:41:52.917Z", "answer_score": 755 }
Please answer the following Stack Overflow question: Title: Use child_process.execSync but keep output in console <p>I'd like to use the <code>execSync</code> method which was added in NodeJS 0.12 but still have the output in the console window from which i ran the Node script.</p> <p>E.g. if I run a NodeJS script which has the following line I'd like to see the full output of the rsync command "live" inside the console:</p> <pre><code>require('child_process').execSync('rsync -avAXz --info=progress2 "/src" "/dest"'); </code></pre> <p>I understand that <code>execSync</code> returns the ouput of the command and that I could print that to the console after execution but this way I don't have "live" output...</p>
<p>You can pass the <a href="https://nodejs.org/api/child_process.html#child_process_options_stdio" rel="noreferrer">parent´s stdio to the child process</a> if that´s what you want:</p> <pre><code>require('child_process').execSync( 'rsync -avAXz --info=progress2 "/src" "/dest"', {stdio: 'inherit'} ); </code></pre>
{ "question_id": 30134236, "question_date": "2015-05-08T23:23:22.647Z", "question_score": 235, "tags": "node.js|child-process", "answer_id": 31104898, "answer_date": "2015-06-28T21:23:13.337Z", "answer_score": 476 }
Please answer the following Stack Overflow question: Title: How to see the CREATE VIEW code for a view in PostgreSQL? <p>Is there an easy way to see the code used to create a view using the PostgreSQL command-line client?</p> <p>Something like the <code>SHOW CREATE VIEW</code> from MySQL.</p>
<p>Kept having to return here to look up <code>pg_get_viewdef</code> (how to remember that!!), so searched for a more memorable command... and got it:</p> <pre><code>\d+ viewname </code></pre> <p>You can see similar sorts of commands by typing <code>\?</code> at the pgsql command line.</p> <p>Bonus tip: The emacs command <code>sql-postgres</code> makes pgsql a lot more pleasant (edit, copy, paste, command history).</p>
{ "question_id": 14634322, "question_date": "2013-01-31T20:13:57.590Z", "question_score": 235, "tags": "postgresql|view|definition", "answer_id": 15421053, "answer_date": "2013-03-14T22:02:54.457Z", "answer_score": 293 }
Please answer the following Stack Overflow question: Title: Difference between MongoDB and Mongoose <p>I wanted to use the mongodb database, but I noticed that there are two different databases with either their own website and installation methods: mongodb and mongoose. So I came up asking myself this question: "Which one do I use?".</p> <p>So in order to answer this question I ask the community if you could explain what are the differences between these two? And if possible pros and cons? Because they really look very similar to me. </p>
<p>I assume you already know that MongoDB is a NoSQL database system which stores data in the form of BSON documents. Your question, however is about the packages for Node.js.</p> <p>In terms of Node.js, <a href="https://www.npmjs.com/package/mongodb" rel="noreferrer">mongodb</a> is the <strong>native driver</strong> for interacting with a mongodb instance and <a href="https://www.npmjs.com/package/mongoose" rel="noreferrer">mongoose</a> is an <strong>Object modeling tool</strong> for MongoDB.</p> <p><code>mongoose</code> is built on top of the <code>mongodb</code> driver to provide programmers with a way to model their data.</p> <p><strong>EDIT:</strong> I do not want to comment on which is better, as this would make this answer opinionated. However I will list some advantages and disadvantages of using both approaches.</p> <p>Using <code>mongoose</code>, a user can define the schema for the documents in a particular collection. It provides a lot of convenience in the creation and management of data in MongoDB. On the downside, learning mongoose can take some time, and has some limitations in handling schemas that are quite complex.</p> <p>However, if your collection schema is unpredictable, or you want a Mongo-shell like experience inside Node.js, then go ahead and use the <code>mongodb</code> driver. It is the simplest to pick up. The downside here is that you will have to write larger amounts of code for validating the data, and the risk of errors is higher.</p>
{ "question_id": 28712248, "question_date": "2015-02-25T06:01:01.777Z", "question_score": 235, "tags": "node.js|mongodb|mongoose", "answer_id": 28712309, "answer_date": "2015-02-25T06:06:46.053Z", "answer_score": 356 }
Please answer the following Stack Overflow question: Title: What is the difference between _tmain() and main() in C++? <p>If I run my C++ application with the following main() method everything is OK:</p> <pre><code>int main(int argc, char *argv[]) { cout &lt;&lt; "There are " &lt;&lt; argc &lt;&lt; " arguments:" &lt;&lt; endl; // Loop through each argument and print its number and value for (int i=0; i&lt;argc; i++) cout &lt;&lt; i &lt;&lt; " " &lt;&lt; argv[i] &lt;&lt; endl; return 0; } </code></pre> <p>I get what I expect and my arguments are printed out.</p> <p>However, if I use _tmain:</p> <pre><code>int _tmain(int argc, char *argv[]) { cout &lt;&lt; "There are " &lt;&lt; argc &lt;&lt; " arguments:" &lt;&lt; endl; // Loop through each argument and print its number and value for (int i=0; i&lt;argc; i++) cout &lt;&lt; i &lt;&lt; " " &lt;&lt; argv[i] &lt;&lt; endl; return 0; } </code></pre> <p>It just displays the first character of each argument.</p> <p>What is the difference causing this?</p>
<p><code>_tmain</code> does not exist in C++. <code>main</code> does.</p> <p><code>_tmain</code> is a Microsoft extension.</p> <p><code>main</code> is, according to the C++ standard, the program's entry point. It has one of these two signatures:</p> <pre><code>int main(); int main(int argc, char* argv[]); </code></pre> <p>Microsoft has added a wmain which replaces the second signature with this:</p> <pre><code>int wmain(int argc, wchar_t* argv[]); </code></pre> <p>And then, to make it easier to switch between Unicode (UTF-16) and their multibyte character set, they've defined <code>_tmain</code> which, if Unicode is enabled, is compiled as <code>wmain</code>, and otherwise as <code>main</code>.</p> <p>As for the second part of your question, the first part of the puzzle is that your main function is wrong. <code>wmain</code> should take a <code>wchar_t</code> argument, not <code>char</code>. Since the compiler doesn't enforce this for the <code>main</code> function, you get a program where an array of <code>wchar_t</code> strings are passed to the <code>main</code> function, which interprets them as <code>char</code> strings.</p> <p>Now, in UTF-16, the character set used by Windows when Unicode is enabled, all the ASCII characters are represented as the pair of bytes <code>\0</code> followed by the ASCII value.</p> <p>And since the x86 CPU is little-endian, the order of these bytes are swapped, so that the ASCII value comes first, then followed by a null byte.</p> <p>And in a char string, how is the string usually terminated? Yep, by a null byte. So your program sees a bunch of strings, each one byte long.</p> <p>In general, you have three options when doing Windows programming:</p> <ul> <li>Explicitly use Unicode (call wmain, and for every Windows API function which takes char-related arguments, call the <code>-W</code> version of the function. Instead of CreateWindow, call CreateWindowW). And instead of using <code>char</code> use <code>wchar_t</code>, and so on</li> <li>Explicitly disable Unicode. Call main, and CreateWindowA, and use <code>char</code> for strings.</li> <li>Allow both. (call _tmain, and CreateWindow, which resolve to main/_tmain and CreateWindowA/CreateWindowW), and use TCHAR instead of char/wchar_t.</li> </ul> <p>The same applies to the string types defined by windows.h: LPCTSTR resolves to either LPCSTR or LPCWSTR, and for every other type that includes char or wchar_t, a -T- version always exists which can be used instead.</p> <p>Note that all of this is Microsoft specific. TCHAR is not a standard C++ type, it is a macro defined in windows.h. wmain and _tmain are also defined by Microsoft only.</p>
{ "question_id": 895827, "question_date": "2009-05-21T23:45:01.560Z", "question_score": 235, "tags": "c++|unicode|arguments", "answer_id": 895894, "answer_date": "2009-05-22T00:09:28.873Z", "answer_score": 370 }
Please answer the following Stack Overflow question: Title: Android: Vertical alignment for multi line EditText (Text area) <p>I want to have 5 lines for the height of the text area. I am using the following code.</p> <pre><code>&lt;EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" android:singleLine="false" android:lines="5" android:layout_marginLeft="10dip" android:layout_marginRight="10dip" /&gt; </code></pre> <p>The text area looks fine, but the problem is that the cursor is blinking in the middle of the text field. I want it to blink at first line, at the first character of the text field.</p>
<p>Use <code>android:gravity="top"</code></p>
{ "question_id": 2446544, "question_date": "2010-03-15T10:57:18.363Z", "question_score": 235, "tags": "android|android-edittext|vertical-alignment|multiline", "answer_id": 2447236, "answer_date": "2010-03-15T13:01:24.110Z", "answer_score": 379 }