input_text
stringlengths
115
13.8k
output_text
stringlengths
24
15k
metadata
dict
Please answer the following Stack Overflow question: Title: Java: Getting a substring from a string starting after a particular character <p>I have a string:</p> <pre><code>/abc/def/ghfj.doc </code></pre> <p>I would like to extract <code>ghfj.doc</code> from this, i.e. the substring after the last <code>/</code>, or first <code>/</code> from right.</p> <p>Could someone please provide some help?</p>
<pre class="lang-java prettyprint-override"><code>String example = &quot;/abc/def/ghfj.doc&quot;; System.out.println(example.substring(example.lastIndexOf(&quot;/&quot;) + 1)); </code></pre>
{ "question_id": 14316487, "question_date": "2013-01-14T10:14:11.280Z", "question_score": 239, "tags": "java|string|substring", "answer_id": 14316548, "answer_date": "2013-01-14T10:17:42.680Z", "answer_score": 377 }
Please answer the following Stack Overflow question: Title: Compare given date with today <p>I have following</p> <pre><code>$var = "2010-01-21 00:00:00.0" </code></pre> <p>I'd like to compare this date against today's date (i.e. I'd like to know if this <code>$var</code> is before today or equals today or not)</p> <p>What function would I need to use?</p>
<pre><code>strtotime($var); </code></pre> <p>Turns it into a time value</p> <pre><code>time() - strtotime($var); </code></pre> <p>Gives you the seconds since <code>$var</code></p> <pre><code>if((time()-(60*60*24)) &lt; strtotime($var)) </code></pre> <p>Will check if <code>$var</code> has been within the last day.</p>
{ "question_id": 2113940, "question_date": "2010-01-21T23:57:55.233Z", "question_score": 239, "tags": "php|date|datetime", "answer_id": 2113951, "answer_date": "2010-01-21T23:59:54.177Z", "answer_score": 308 }
Please answer the following Stack Overflow question: Title: React - Display loading screen while DOM is rendering? <p>This is an example from Google Adsense application page. The loading screen displayed before the main page showed after.</p> <p><a href="https://i.stack.imgur.com/ngk1r.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/ngk1r.gif" alt="enter image description here"></a></p> <p>I don't know how to do the same thing with React because if I make loading screen rendered by React component, it doesn't display while page is loading because it has to wait for DOM rendered before.</p> <p><strong>Updated</strong>:</p> <p>I made an example of my approach by putting screen loader in <code>index.html</code> and remove it in React <code>componentDidMount()</code> lifecycle method.</p> <p><a href="https://nguyenbathanh.github.io" rel="noreferrer">Example</a> and <a href="https://github.com/nguyenbathanh/react-loading-screen" rel="noreferrer">react-loading-screen</a>.</p>
<p>This could be done by placing the loading icon in your html file (<code>index.html</code> for example), so that users see the icon immediately after the html file has been loaded.</p> <p>When your app finishes loading, you could simply remove that loading icon in a lifecycle hook, I usually do that in <code>componentDidMount</code>.</p>
{ "question_id": 40987309, "question_date": "2016-12-06T03:23:50.817Z", "question_score": 239, "tags": "reactjs|asynchronous|redux|react-dom", "answer_id": 40988672, "answer_date": "2016-12-06T05:51:59.050Z", "answer_score": 145 }
Please answer the following Stack Overflow question: Title: Why is my asynchronous function returning Promise { <pending> } instead of a value? <p>My code:</p> <pre><code>let AuthUser = data =&gt; { return google.login(data.username, data.password).then(token =&gt; { return token } ) } </code></pre> <p>And when i try to run something like this:</p> <pre><code>let userToken = AuthUser(data) console.log(userToken) </code></pre> <p>I'm getting:</p> <pre><code>Promise { &lt;pending&gt; } </code></pre> <p>But why?</p> <p>My main goal is to get token from <code>google.login(data.username, data.password)</code> which returns a promise, into a variable. And only then preform some actions.</p>
<p>The promise will always log pending as long as its results are not resolved yet. You must call <code>.then</code> on the promise to capture the results regardless of the promise state (resolved or still pending):</p> <pre><code>let AuthUser = function(data) { return google.login(data.username, data.password).then(token =&gt; { return token } ) } let userToken = AuthUser(data) console.log(userToken) // Promise { &lt;pending&gt; } userToken.then(function(result) { console.log(result) // "Some User token" }) </code></pre> <p>Why is that?</p> <p>Promises are forward direction only; You can only resolve them once. The resolved value of a <code>Promise</code> is passed to its <code>.then</code> or <code>.catch</code> methods.</p> <h1>Details</h1> <p>According to the Promises/A+ spec:</p> <blockquote> <p>The promise resolution procedure is an abstract operation taking as input a promise and a value, which we denote as [[Resolve]](promise, x). If x is a thenable, it attempts to make promise adopt the state of x, under the assumption that x behaves at least somewhat like a promise. Otherwise, it fulfills promise with the value x.</p> <p>This treatment of thenables allows promise implementations to interoperate, as long as they expose a Promises/A+-compliant then method. It also allows Promises/A+ implementations to “assimilate” nonconformant implementations with reasonable then methods.</p> </blockquote> <p>This spec is a little hard to parse, so let's break it down. The rule is:</p> <p>If the function in the <code>.then</code> handler returns a value, then the <code>Promise</code> resolves with that value. If the handler returns another <code>Promise</code>, then the original <code>Promise</code> resolves with the resolved value of the chained <code>Promise</code>. The next <code>.then</code> handler will always contain the resolved value of the chained promise returned in the preceding <code>.then</code>.</p> <p>The way it actually works is described below in more detail:</p> <p><strong>1. The return of the <code>.then</code> function will be the resolved value of the promise.</strong></p> <pre><code>function initPromise() { return new Promise(function(res, rej) { res("initResolve"); }) } initPromise() .then(function(result) { console.log(result); // "initResolve" return "normalReturn"; }) .then(function(result) { console.log(result); // "normalReturn" }); </code></pre> <p><strong>2. If the <code>.then</code> function returns a <code>Promise</code>, then the resolved value of that chained promise is passed to the following <code>.then</code>.</strong></p> <pre><code>function initPromise() { return new Promise(function(res, rej) { res("initResolve"); }) } initPromise() .then(function(result) { console.log(result); // "initResolve" return new Promise(function(resolve, reject) { setTimeout(function() { resolve("secondPromise"); }, 1000) }) }) .then(function(result) { console.log(result); // "secondPromise" }); </code></pre>
{ "question_id": 38884522, "question_date": "2016-08-10T22:24:25.660Z", "question_score": 239, "tags": "javascript|node.js|promise", "answer_id": 38884856, "answer_date": "2016-08-10T22:56:44.137Z", "answer_score": 343 }
Please answer the following Stack Overflow question: Title: Initialize a long in Java <p><a href="http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html" rel="noreferrer">Primitive Data Types - oracle doc</a> says the range of <strong><code>long</code></strong> in Java is <code>-9,223,372,036,854,775,808</code> to <code>9,223,372,036,854,775,807</code>. But when I do something like this in my eclipse</p> <pre><code>long i = 12345678910; </code></pre> <p>it shows me "<code>The literal 12345678910 of type int is out of range</code>" error.</p> <p><strong>There are 2 questions.</strong></p> <p>1) How do I initialize the <strong><code>long</code></strong> with the value <code>12345678910</code>?</p> <p>2) Are all numeric literals by default of type <strong><code>int</code></strong>? </p>
<ol> <li>You should add <code>L</code>: <code>long i = 12345678910L;</code>.</li> <li>Yes.</li> </ol> <p>BTW: it doesn't have to be an upper case L, but lower case is confused with <code>1</code> many times :).</p>
{ "question_id": 6834037, "question_date": "2011-07-26T17:28:11.303Z", "question_score": 239, "tags": "java|long-integer", "answer_id": 6834049, "answer_date": "2011-07-26T17:29:13.770Z", "answer_score": 468 }
Please answer the following Stack Overflow question: Title: How to reload the current route with the angular 2 router <p>I am using angular 2 with <code>hashlocation</code> strategy.</p> <p>The component is loaded with that route:</p> <pre class="lang-js prettyprint-override"><code>&quot;departments/:id/employees&quot; </code></pre> <p>So far fine.</p> <p>After I do a successful batch save of multiple edited table rows I want to reload the current route URL via:</p> <pre class="lang-js prettyprint-override"><code>this.router.navigate([`departments/${this.id}/employees`]); </code></pre> <p>But nothing happens, why?</p>
<p>If your navigate() doesn't change the URL that already shown on the address bar of your browser, the router has nothing to do. It's not the router's job to refresh the data. If you want to refresh the data, create a service injected into the component and invoke the load function on the service. If the new data will be retrieved, it'll update the view via bindings.</p>
{ "question_id": 40983055, "question_date": "2016-12-05T20:48:15.643Z", "question_score": 239, "tags": "angular|typescript", "answer_id": 40983262, "answer_date": "2016-12-05T21:01:08.933Z", "answer_score": 60 }
Please answer the following Stack Overflow question: Title: Adding an .env file to React Project <p>I'm trying to hide my API Key for when I commit to github, and I've looked through the forum for guidance, especially the following post:</p> <p><a href="https://stackoverflow.com/questions/48699820/how-do-i-hide-api-key-in-create-react-app">How do I hide API key in create-react-app?</a></p> <p>I made the changes and restarted yarn. I'm not sure what I'm doing wrong––I added an <code>.env</code> file to the root of my project (I named it <code>process.env</code>) and in the file I just put <code>REACT_APP_API_KEY = 'my-secret-api-key'</code>. </p> <p>I'm thinking it might be the way I'm adding the key to my <code>fetch</code> in App.js, and I've tried multiple formats, including without using the template literal, but my project will still not compile.</p> <p>Any help is much appreciated.</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>performSearch = (query = 'germany') =&gt; { fetch(`https://api.unsplash.com/search/photos?query=${query}&amp;client_id=${REACT_APP_API_KEY}`) .then(response =&gt; response.json()) .then(responseData =&gt; { this.setState({ results: responseData.results, loading: false }); }) .catch(error =&gt; { console.log('Error fetching and parsing data', error); }); }</code></pre> </div> </div> </p>
<p>4 steps</p> <ol> <li><p><code>npm install dotenv --save</code></p> </li> <li><p>Next add the following line to your app.</p> <p><code>require('dotenv').config()</code></p> </li> <li><p>Then create a <code>.env</code> file at the root directory of your application and add the variables to it.</p> </li> </ol> <pre><code>// contents of .env REACT_APP_API_KEY = 'my-secret-api-key' </code></pre> <ol start="4"> <li>Finally, add <code>.env</code> to your <code>.gitignore</code> file so that Git ignores it and it never ends up on GitHub.</li> </ol> <p>If you are using <a href="https://github.com/facebook/create-react-app" rel="noreferrer">create-react-app</a> then you only need step 3 and 4 but keep in mind variable needs to start with <code>REACT_APP_</code> for it to work.</p> <p>Reference: <a href="https://create-react-app.dev/docs/adding-custom-environment-variables/" rel="noreferrer">https://create-react-app.dev/docs/adding-custom-environment-variables/</a></p> <p><strong>NOTE</strong> - <strong>Need to restart application after adding variable in .env file.</strong></p> <p>Reference - <a href="https://medium.com/@thejasonfile/using-dotenv-package-to-create-environment-variables-33da4ac4ea8f" rel="noreferrer">https://medium.com/@thejasonfile/using-dotenv-package-to-create-environment-variables-33da4ac4ea8f</a></p>
{ "question_id": 49579028, "question_date": "2018-03-30T17:50:25.430Z", "question_score": 239, "tags": "reactjs|environment-variables|api-key", "answer_id": 49579700, "answer_date": "2018-03-30T18:42:30.153Z", "answer_score": 319 }
Please answer the following Stack Overflow question: Title: Why a function checking if a string is empty always returns true? <p>I have a function isNotEmpty which returns true if the string is not empty and false if the string is empty. I've found out that it is not working if I pass an empty string through it. </p> <pre><code>function isNotEmpty($input) { $strTemp = $input; $strTemp = trim($strTemp); if(strTemp != '') //Also tried this "if(strlen($strTemp) &gt; 0)" { return true; } return false; } </code></pre> <p>The validation of the string using isNotEmpty is done:</p> <pre><code>if(isNotEmpty($userinput['phoneNumber'])) { //validate the phone number } else { echo "Phone number not entered&lt;br/&gt;"; } </code></pre> <p>If the string is empty the else doesn't execute, I don't understand why, can someone please shed some light on this please.</p>
<p>Simple problem actually. Change:</p> <pre><code>if (strTemp != '') </code></pre> <p>to </p> <pre><code>if ($strTemp != '') </code></pre> <p>Arguably you may also want to change it to:</p> <pre><code>if ($strTemp !== '') </code></pre> <p>since <code>!= ''</code> will return true if you pass is numeric 0 and a few other cases due to <a href="http://sldn.softlayer.com/01/2009/php-type-conversions-for-comparison/" rel="noreferrer">PHP's automatic type conversion</a>.</p> <p>You <strong>should not</strong> use the built-in <a href="http://www.php.net/empty" rel="noreferrer">empty()</a> function for this; see comments and the <a href="https://secure.php.net/manual/en/types.comparisons.php" rel="noreferrer">PHP type comparison tables</a>.</p>
{ "question_id": 718986, "question_date": "2009-04-05T14:18:11.697Z", "question_score": 239, "tags": "php|string|validation", "answer_id": 719002, "answer_date": "2009-04-05T14:29:15.557Z", "answer_score": 336 }
Please answer the following Stack Overflow question: Title: How can I disable a button in a jQuery dialog from a function? <p>I have a jQuery dialog that requires the user to enter certain information. In this form, I have a "continue" button. I would like this "continue" button to only be enabled once all the fields have content in them, else it will remain disabled.</p> <p>I wrote a function that is called everytime a field status has changed. However, I don't know how to enable and disable the dialog button from this function. What should I do?</p> <p>Oops and I forgot to mention that these buttons were created as follows:</p> <pre><code>$(function() { $("#dialog").dialog({ bgiframe: true, height: 'auto', width: 700, show: 'clip', hide: 'clip', modal: true, buttons: { 'Add to request list': function() { $(this).dialog('close'); $('form').submit(); }, 'Cancel': function() { $(this).dialog('close'); } } }) }); </code></pre>
<p>You would want to set the <a href="http://www.w3schools.com/jsref/prop_select_disabled.asp" rel="noreferrer">disabled property</a></p> <pre><code> $('#continueButton').attr("disabled", true); </code></pre> <p><strong>Update</strong>: Ahha, I see the complexity now. The <a href="http://docs.jquery.com/UI/Dialog" rel="noreferrer">jQuery Dialog</a> had a single line that will be of use (under the "buttons" section.</p> <pre><code> var buttons = $('.selector').dialog('option', 'buttons'); </code></pre> <p>You'll need to get the buttons collection from the dialog, loop through that to find which one you need, and then set the disabled attribute as I showed above.</p>
{ "question_id": 577548, "question_date": "2009-02-23T12:58:44.450Z", "question_score": 239, "tags": "jquery|jquery-ui", "answer_id": 577558, "answer_date": "2009-02-23T13:04:06.900Z", "answer_score": 261 }
Please answer the following Stack Overflow question: Title: How to request Google to re-crawl my website? <p>Does someone know a way to request Google to re-crawl a website? If possible, this shouldn't last months. My site is showing an old title in Google's search results. How can I show it with the correct title and description? </p>
<p>There are two options. The first (and better) one is using the Fetch as Google option in Webmaster Tools that <a href="https://stackoverflow.com/users/482591/mike-flynn">Mike Flynn</a> commented about. Here are detailed instructions:</p> <ol> <li>Go to: <a href="https://www.google.com/webmasters/tools/" rel="noreferrer">https://www.google.com/webmasters/tools/</a> and log in</li> <li>If you haven't already, add and verify the site with the "Add a Site" button</li> <li>Click on the site name for the one you want to manage</li> <li>Click Crawl -> Fetch as Google</li> <li>Optional: if you want to do a specific page only, type in the URL</li> <li>Click Fetch</li> <li>Click Submit to Index</li> <li>Select either "URL" or "URL and its direct links"</li> <li>Click OK and you're done.</li> </ol> <p>With the option above, as long as every page can be reached from some link on the initial page or a page that it links to, Google should recrawl the whole thing. If you want to explicitly tell it a list of pages to crawl on the domain, you can follow the directions to <a href="https://support.google.com/sites/answer/100283?hl=en" rel="noreferrer">submit a sitemap</a>.</p> <p>Your second (and generally slower) option is, as <a href="https://stackoverflow.com/users/349260/seanbreeden">seanbreeden</a> pointed out, submitting here: <a href="http://www.google.com/addurl/" rel="noreferrer">http://www.google.com/addurl/</a></p> <p>Update 2019:</p> <ol> <li>Login to - <a href="https://search.google.com/search-console/" rel="noreferrer">Google Search Console</a></li> <li>Add a site and verify it with the available methods.</li> <li>After verification from the console, click on URL Inspection.</li> <li>In the Search bar on top, enter your website URL or custom URLs for inspection and enter.</li> <li>After Inspection, it'll show an option to <strong>Request Indexing</strong></li> <li>Click on it and GoogleBot will add your website in a Queue for crawling.</li> </ol>
{ "question_id": 9466360, "question_date": "2012-02-27T14:09:13.627Z", "question_score": 239, "tags": "seo|web-crawler", "answer_id": 15278642, "answer_date": "2013-03-07T18:11:59.123Z", "answer_score": 454 }
Please answer the following Stack Overflow question: Title: How can I use a conditional expression (expression with if and else) in a list comprehension? <p>I have a list comprehension that produces list of odd numbers of a given range:</p> <pre><code>[x for x in range(1, 10) if x % 2] </code></pre> <p>That makes a filter that removes the even numbers. Instead, I'd like to use conditional logic, so that even numbers are treated differently, but still contribute to the list. I tried this code, but it fails:</p> <pre><code>&gt;&gt;&gt; [x for x in range(1, 10) if x % 2 else x * 100] File &quot;&lt;stdin&gt;&quot;, line 1 [x for x in range(1, 10) if x % 2 else x * 100] ^ SyntaxError: invalid syntax </code></pre> <p>I know that Python expressions allow a syntax like that:</p> <pre><code>1 if 0 is 0 else 3 </code></pre> <p>How can I use it inside the list comprehension?</p>
<p><code>x if y else z</code> is the syntax for the expression you're returning for each element. Thus you need:</p> <pre><code>[ x if x%2 else x*100 for x in range(1, 10) ] </code></pre> <p>The confusion arises from the fact you're using a <em>filter</em> in the first example, but not in the second. In the second example you're only <em>mapping</em> each value to another, using a ternary-operator expression.</p> <p>With a filter, you need:</p> <pre><code>[ EXP for x in seq if COND ] </code></pre> <p>Without a filter you need:</p> <pre><code>[ EXP for x in seq ] </code></pre> <p>and in your second example, the expression is a "complex" one, which happens to involve an <code>if-else</code>.</p>
{ "question_id": 17321138, "question_date": "2013-06-26T13:17:25.297Z", "question_score": 239, "tags": "python|list-comprehension|conditional-operator", "answer_id": 17321170, "answer_date": "2013-06-26T13:18:58.253Z", "answer_score": 447 }
Please answer the following Stack Overflow question: Title: Replace part of a string with another string <p>How do I replace part of a string with another string using the <strong>standard C++ libraries</strong>?</p> <pre><code>QString s(&quot;hello $name&quot;); // Example using Qt. s.replace(&quot;$name&quot;, &quot;Somename&quot;); </code></pre>
<p>There's a function to find a substring within a string (<a href="http://en.cppreference.com/w/cpp/string/basic_string/find" rel="noreferrer"><code>find</code></a>), and a function to replace a particular range in a string with another string (<a href="http://en.cppreference.com/w/cpp/string/basic_string/replace" rel="noreferrer"><code>replace</code></a>), so you can combine those to get the effect you want:</p> <pre><code>bool replace(std::string&amp; str, const std::string&amp; from, const std::string&amp; to) { size_t start_pos = str.find(from); if(start_pos == std::string::npos) return false; str.replace(start_pos, from.length(), to); return true; } std::string string("hello $name"); replace(string, "$name", "Somename"); </code></pre> <hr> <p>In response to a comment, I think <code>replaceAll</code> would probably look something like this:</p> <pre><code>void replaceAll(std::string&amp; str, const std::string&amp; from, const std::string&amp; to) { if(from.empty()) return; size_t start_pos = 0; while((start_pos = str.find(from, start_pos)) != std::string::npos) { str.replace(start_pos, from.length(), to); start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx' } } </code></pre>
{ "question_id": 3418231, "question_date": "2010-08-05T19:06:13.010Z", "question_score": 239, "tags": "c++|string|replace|substring|std", "answer_id": 3418285, "answer_date": "2010-08-05T19:11:29.717Z", "answer_score": 354 }
Please answer the following Stack Overflow question: Title: Android Material and appcompat Manifest merger failed <p>I have next grade </p> <pre><code>dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:28.0.0-rc01' implementation 'com.android.support.constraint:constraint-layout:1.1.2' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' implementation 'com.google.android.material:material:1.0.0-rc01' } </code></pre> <p>But when I want to build app I get next log:</p> <pre><code>Manifest merger failed : Attribute application@appComponentFactory value=(android.support.v4.app.CoreComponentFactory) from [com.android.support:support-compat:28.0.0-alpha3] AndroidManifest.xml:22:18-91 is also present at [androidx.core:core:1.0.0-alpha3] AndroidManifest.xml:22:18-86 value=(androidx.core.app.CoreComponentFactory). Suggestion: add 'tools:replace="android:appComponentFactory"' to &lt;application&gt; element at AndroidManifest.xml:5:5-19:19 to override. </code></pre> <p>Okey! Go to manifest and do it:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="ru.chopcode.myapplication"&gt; &lt;application tools:replace="android:appComponentFactory" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"&gt; &lt;/application&gt; &lt;/manifest&gt; </code></pre> <p>Then I get this error in my Logcat:</p> <pre><code>Manifest merger failed with multiple errors, see logs that I have Linked with it </code></pre>
<p>Just change "rc01" in first and last line inside dependencies to "alpha1" This is working for me</p>
{ "question_id": 51793345, "question_date": "2018-08-10T19:58:28.567Z", "question_score": 239, "tags": "android|android-gradle-plugin|build.gradle|gradle-plugin", "answer_id": 51793660, "answer_date": "2018-08-10T20:27:38.103Z", "answer_score": 15 }
Please answer the following Stack Overflow question: Title: Read values into a shell variable from a pipe <p>I am trying to get bash to process data from stdin that gets piped into, but no luck. What I mean is none of the following work:</p> <pre><code>echo "hello world" | test=($(&lt; /dev/stdin)); echo test=$test test= echo "hello world" | read test; echo test=$test test= echo "hello world" | test=`cat`; echo test=$test test= </code></pre> <p>where I want the output to be <code>test=hello world</code>. I've tried putting "" quotes around <code>"$test"</code> that doesn't work either.</p>
<p>Use</p> <pre><code>IFS= read var &lt;&lt; EOF $(foo) EOF </code></pre> <p>You <em>can</em> trick <code>read</code> into accepting from a pipe like this:</p> <pre><code>echo "hello world" | { read test; echo test=$test; } </code></pre> <p>or even write a function like this:</p> <pre><code>read_from_pipe() { read "$@" &lt;&amp;0; } </code></pre> <p>But there's no point - your variable assignments may not last! A pipeline may spawn a subshell, where the environment is inherited by value, not by reference. This is why <code>read</code> doesn't bother with input from a pipe - it's undefined.</p> <p>FYI, <a href="http://www.etalabs.net/sh_tricks.html" rel="noreferrer">http://www.etalabs.net/sh_tricks.html</a> is a nifty collection of the cruft necessary to fight the oddities and incompatibilities of bourne shells, sh.</p>
{ "question_id": 2746553, "question_date": "2010-04-30T17:51:55.010Z", "question_score": 239, "tags": "linux|bash|pipe", "answer_id": 6779351, "answer_date": "2011-07-21T16:19:55Z", "answer_score": 192 }
Please answer the following Stack Overflow question: Title: Javascript reduce() on Object <p>There is nice Array method <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/Reduce" rel="noreferrer"><code>reduce()</code></a> to get one value from the Array. Example:</p> <pre><code>[0,1,2,3,4].reduce(function(previousValue, currentValue, index, array){ return previousValue + currentValue; }); </code></pre> <p>What is the best way to achieve the same with objects? I'd like to do this:</p> <pre><code>{ a: {value:1}, b: {value:2}, c: {value:3} }.reduce(function(previous, current, index, array){ return previous.value + current.value; }); </code></pre> <p>However, Object does not seem to have any <code>reduce()</code> method implemented.</p>
<p>What you actually want in this case are the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values" rel="noreferrer"><code>Object.values</code></a>. Here is a concise <strong>ES6</strong> implementation with that in mind:</p> <pre><code>const add = { a: {value:1}, b: {value:2}, c: {value:3} } const total = Object.values(add).reduce((t, {value}) =&gt; t + value, 0) console.log(total) // 6 </code></pre> <p>or simply:</p> <pre><code>const add = { a: 1, b: 2, c: 3 } const total = Object.values(add).reduce((t, n) =&gt; t + n) console.log(total) // 6 </code></pre>
{ "question_id": 15748656, "question_date": "2013-04-01T17:53:04.083Z", "question_score": 239, "tags": "javascript|arrays|object|reduce", "answer_id": 45784629, "answer_date": "2017-08-20T16:54:31.740Z", "answer_score": 124 }
Please answer the following Stack Overflow question: Title: Remove URL parameters without refreshing page <p>I am trying to remove everything after the "?" in the browser url on document ready. </p> <p>Here is what I am trying:</p> <pre><code>jQuery(document).ready(function($) { var url = window.location.href; url = url.split('?')[0]; }); </code></pre> <p>I can do this and see it the below works:</p> <pre><code>jQuery(document).ready(function($) { var url = window.location.href; alert(url.split('?')[0]); }); </code></pre>
<h2>TL;DR</h2> <p>1- To <strong>modify</strong> current URL and <strong>add / inject</strong> it <em>(the new modified URL)</em> as a new URL entry to history list, use <code>pushState</code>:</p> <pre><code>window.history.pushState({}, document.title, &quot;/&quot; + &quot;my-new-url.html&quot;); </code></pre> <p>2- To <strong>replace</strong> current URL <strong>without adding</strong> it to history entries, use <code>replaceState</code>:</p> <pre><code>window.history.replaceState({}, document.title, &quot;/&quot; + &quot;my-new-url.html&quot;); </code></pre> <p>3- <strong>Depending</strong> on your <strong>business logic</strong>, <code>pushState</code> will be useful in cases such as:</p> <ul> <li><p>you want to support the browser's <strong>back button</strong></p> </li> <li><p>you want to <strong>create</strong> a <strong>new</strong> URL, <strong>add</strong>/insert/push the <strong>new URL</strong> to <strong>history</strong> entries, and make it current URL</p> </li> <li><p>allowing users to <strong>bookmark</strong> the page with the same parameters (to show the same contents)</p> </li> <li><p>to programmatically <strong>access</strong> the <strong>data</strong> through the <code>stateObj</code> then parse from the anchor</p> </li> </ul> <hr /> <p>As I understood from your comment, you want to clean your URL without redirecting again.</p> <p>Note that you cannot change the whole URL. You can just change what comes after the domain's name. This means that you cannot change <code>www.example.com/</code> but you can change what comes after <code>.com/</code></p> <pre><code>www.example.com/old-page-name =&gt; can become =&gt; www.example.com/myNewPaage20180322.php </code></pre> <h2>Background</h2> <p>We can use:</p> <p>1- <a href="https://developer.mozilla.org/en-US/docs/Web/API/History/pushState" rel="noreferrer">The pushState() method</a> if you want to add <em>a new</em> modified URL to history entries.</p> <p>2- <a href="https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState" rel="noreferrer">The replaceState() method</a> if you want to update/replace <em>current</em> history entry.</p> <blockquote> <p><code>.replaceState()</code> operates exactly like <code>.pushState()</code> except that <code>.replaceState()</code> <strong>modifies the current history</strong> entry instead of creating a new one. Note that this doesn't prevent the creation of a new entry in the global browser history.</p> </blockquote> <hr> <blockquote> <p><code>.replaceState()</code> is particularly useful when you want to <strong>update</strong> the state object or <strong>URL</strong> of the current history entry in response to some user action.</p> </blockquote> <hr /> <h2>Code</h2> <p>To do that I will use <a href="https://developer.mozilla.org/en-US/docs/Web/API/History/pushState" rel="noreferrer">The pushState() method</a> for this example which works similarly to the following format:</p> <pre><code>var myNewURL = &quot;my-new-URL.php&quot;;//the new URL window.history.pushState(&quot;object or string&quot;, &quot;Title&quot;, &quot;/&quot; + myNewURL ); </code></pre> <p>Feel free to replace <code>pushState</code> with <code>replaceState</code> based on your requirements.</p> <p>You can substitute the paramter <code>&quot;object or string&quot;</code> with <code>{}</code> and <code>&quot;Title&quot;</code> with <code>document.title</code> so the final statment will become:</p> <pre><code>window.history.pushState({}, document.title, &quot;/&quot; + myNewURL ); </code></pre> <hr /> <h2>Results</h2> <p>The previous two lines of code will make a URL such as:</p> <pre><code>https://domain.tld/some/randome/url/which/will/be/deleted/ </code></pre> <p>To become:</p> <pre><code>https://domain.tld/my-new-url.php </code></pre> <hr /> <h2>Action</h2> <p>Now let's try a different approach. Say you need to keep the file's name. The file name comes after the last <code>/</code> and before the query string <code>?</code>.</p> <pre><code>http://www.someDomain.com/really/long/address/keepThisLastOne.php?name=john </code></pre> <p>Will be:</p> <pre><code>http://www.someDomain.com/keepThisLastOne.php </code></pre> <p>Something like this will get it working:</p> <pre><code> //fetch new URL //refineURL() gives you the freedom to alter the URL string based on your needs. var myNewURL = refineURL(); //here you pass the new URL extension you want to appear after the domains '/'. Note that the previous identifiers or &quot;query string&quot; will be replaced. window.history.pushState(&quot;object or string&quot;, &quot;Title&quot;, &quot;/&quot; + myNewURL ); //Helper function to extract the URL between the last '/' and before '?' //If URL is www.example.com/one/two/file.php?user=55 this function will return 'file.php' //pseudo code: edit to match your URL settings function refineURL() { //get full URL var currURL= window.location.href; //get current address //Get the URL between what's after '/' and befor '?' //1- get URL after'/' var afterDomain= currURL.substring(currURL.lastIndexOf('/') + 1); //2- get the part before '?' var beforeQueryString= afterDomain.split(&quot;?&quot;)[0]; return beforeQueryString; } </code></pre> <hr /> <h2><strong>UPDATE:</strong></h2> <p>For one liner fans, try this out in your console/firebug and this page URL will change:</p> <pre><code> window.history.pushState(&quot;object or string&quot;, &quot;Title&quot;, &quot;/&quot;+window.location.href.substring(window.location.href.lastIndexOf('/') + 1).split(&quot;?&quot;)[0]); </code></pre> <p>This page URL will change from:</p> <pre><code>http://stackoverflow.com/questions/22753052/remove-url-parameters-without-refreshing-page/22753103#22753103 </code></pre> <p>To</p> <pre><code>http://stackoverflow.com/22753103#22753103 </code></pre> <hr /> <p><strong>Note:</strong> as <em>Samuel Liew</em> indicated in the comments below, this feature has been introduced only for <code>HTML5</code>.</p> <p>An alternative approach would be to actually redirect your page (but you will lose the query string `?', is it still needed or the data has been processed?).</p> <pre><code>window.location.href = window.location.href.split(&quot;?&quot;)[0]; //&quot;http://www.newurl.com&quot;; </code></pre> <hr /> <p><strong>Note 2:</strong></p> <p>Firefox seems to ignore <code>window.history.pushState({}, document.title, '');</code> when the last argument is an empty string. Adding a slash (<code>'/'</code>) worked as expected and removed the whole query part of the url string. Chrome seems to be fine with an empty string.</p>
{ "question_id": 22753052, "question_date": "2014-03-31T03:12:10.620Z", "question_score": 239, "tags": "javascript|jquery", "answer_id": 22753103, "answer_date": "2014-03-31T03:18:31.213Z", "answer_score": 359 }
Please answer the following Stack Overflow question: Title: SQL Server dynamic PIVOT query? <p>I've been tasked with coming up with a means of translating the following data:</p> <pre><code>date category amount 1/1/2012 ABC 1000.00 2/1/2012 DEF 500.00 2/1/2012 GHI 800.00 2/10/2012 DEF 700.00 3/1/2012 ABC 1100.00 </code></pre> <p>into the following:</p> <pre><code>date ABC DEF GHI 1/1/2012 1000.00 2/1/2012 500.00 2/1/2012 800.00 2/10/2012 700.00 3/1/2012 1100.00 </code></pre> <p>The blank spots can be NULLs or blanks, either is fine, and the categories would need to be dynamic. Another possible caveat to this is that we'll be running the query in a limited capacity, which means temp tables are out. I've tried to research and have landed on <code>PIVOT</code> but as I've never used that before I really don't understand it, despite my best efforts to figure it out. Can anyone point me in the right direction?</p>
<p>Dynamic SQL PIVOT:</p> <pre><code>create table temp ( date datetime, category varchar(3), amount money ) insert into temp values ('1/1/2012', 'ABC', 1000.00) insert into temp values ('2/1/2012', 'DEF', 500.00) insert into temp values ('2/1/2012', 'GHI', 800.00) insert into temp values ('2/10/2012', 'DEF', 700.00) insert into temp values ('3/1/2012', 'ABC', 1100.00) DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX); SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.category) FROM temp c FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') set @query = 'SELECT date, ' + @cols + ' from ( select date , amount , category from temp ) x pivot ( max(amount) for category in (' + @cols + ') ) p ' execute(@query) drop table temp </code></pre> <p>Results:</p> <pre><code>Date ABC DEF GHI 2012-01-01 00:00:00.000 1000.00 NULL NULL 2012-02-01 00:00:00.000 NULL 500.00 800.00 2012-02-10 00:00:00.000 NULL 700.00 NULL 2012-03-01 00:00:00.000 1100.00 NULL NULL </code></pre>
{ "question_id": 10404348, "question_date": "2012-05-01T21:05:07.637Z", "question_score": 239, "tags": "sql|sql-server|tsql|pivot", "answer_id": 10404455, "answer_date": "2012-05-01T21:13:29.113Z", "answer_score": 297 }
Please answer the following Stack Overflow question: Title: How to get a reversed list view on a list in Java? <p>I want to have a reversed list view on a list (in a similar way than <code>List#sublist</code> provides a sublist view on a list). Is there some function which provides this functionality?</p> <p>I don't want to make any sort of copy of the list nor modify the list.</p> <p>It would be enough if I could get at least a reverse iterator on a list in this case though.</p> <hr> <p>Also, I know how to implement this myself. I'm just asking if Java already provides something like this.</p> <p>Demo implementation:</p> <pre><code>static &lt;T&gt; Iterable&lt;T&gt; iterableReverseList(final List&lt;T&gt; l) { return new Iterable&lt;T&gt;() { public Iterator&lt;T&gt; iterator() { return new Iterator&lt;T&gt;() { ListIterator&lt;T&gt; listIter = l.listIterator(l.size()); public boolean hasNext() { return listIter.hasPrevious(); } public T next() { return listIter.previous(); } public void remove() { listIter.remove(); } }; } }; } </code></pre> <hr> <p>I just have found out that some <code>List</code> implementations have <code>descendingIterator()</code> which is what I need. Though there is no general such implementation for <code>List</code>. Which is kind of strange because the implementation I have seen in <code>LinkedList</code> is general enough to work with any <code>List</code>.</p>
<p><a href="https://github.com/google/guava" rel="noreferrer">Guava</a> provides this: <a href="http://google.github.io/guava/releases/snapshot/api/docs/com/google/common/collect/Lists.html#reverse%28java.util.List%29" rel="noreferrer">Lists.reverse(List)</a></p> <pre><code>List&lt;String&gt; letters = ImmutableList.of("a", "b", "c"); List&lt;String&gt; reverseView = Lists.reverse(letters); System.out.println(reverseView); // [c, b, a] </code></pre> <p>Unlike <code>Collections.reverse</code>, this is purely a <em>view</em>... it doesn't alter the ordering of elements in the original list. Additionally, with an original list that is modifiable, changes to both the original list and the view are reflected in the other.</p>
{ "question_id": 3962766, "question_date": "2010-10-18T19:45:27.867Z", "question_score": 239, "tags": "java|list|collections|iterator|reverse", "answer_id": 3962803, "answer_date": "2010-10-18T19:50:06.370Z", "answer_score": 223 }
Please answer the following Stack Overflow question: Title: Detect if an input has text in it using CSS -- on a page I am visiting and do not control? <p>Is there a way to detect whether or not an input has text in it via CSS? I've tried using the <code>:empty</code> pseudo-class, and I've tried using <code>[value=""]</code>, neither of which worked. I can't seem to find a single solution to this.</p> <p>I imagine this must be possible, considering we have pseudo-classes for <code>:checked</code>, and <code>:indeterminate</code>, both of which are kind of similar thing. </p> <p>Please note: <strong>I'm doing this for a "Stylish" style</strong>, which can't utilize JavaScript.</p> <p>Also note, that Stylish is used, client-side, on pages that the user does not control.</p>
<p><em>Stylish</em> cannot do this because CSS cannot do this. <strong>CSS has no (pseudo) selectors for <code>&lt;input&gt;</code> value(s).</strong> See:</p> <ul> <li><a href="http://www.w3.org/TR/selectors/" rel="noreferrer">The W3C selector spec</a></li> <li><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes" rel="noreferrer">The Mozilla/Firefox supported selectors</a></li> <li><a href="http://fmbip.com/litmus/#css3-selectors" rel="noreferrer">Cross-browser, CSS3 support table</a></li> </ul> <p>The <code>:empty</code> selector refers only to child nodes, not input values.<br> <code>[value=""]</code> <em>does</em> work; but only for the <em>initial</em> state. This is because a node's <code>value</code> <em>attribute</em> (that CSS sees), is not the same as the node's <code>value</code> <em>property</em> (Changed by the user or DOM javascript, and submitted as form data).</p> <p>Unless you care only about the initial state, <strong>you <em>must</em> use a userscript or Greasemonkey script.</strong> Fortunately this is not hard. The following script will work in Chrome, or Firefox with Greasemonkey or Scriptish installed, or in any browser that supports userscripts (i.e. most browsers, except IE).</p> <p>See a demo of the limits of CSS plus the javascript solution at <a href="http://jsbin.com/isesis/1" rel="noreferrer"><strong>this jsBin page</strong></a>.</p> <pre class="lang-js prettyprint-override"><code>// ==UserScript== // @name _Dynamically style inputs based on whether they are blank. // @include http://YOUR_SERVER.COM/YOUR_PATH/* // @grant GM_addStyle // ==/UserScript== /*- The @grant directive is needed to work around a design change introduced in GM 1.0. It restores the sandbox. */ var inpsToMonitor = document.querySelectorAll ( "form[name='JustCSS'] input[name^='inp']" ); for (var J = inpsToMonitor.length - 1; J &gt;= 0; --J) { inpsToMonitor[J].addEventListener ("change", adjustStyling, false); inpsToMonitor[J].addEventListener ("keyup", adjustStyling, false); inpsToMonitor[J].addEventListener ("focus", adjustStyling, false); inpsToMonitor[J].addEventListener ("blur", adjustStyling, false); inpsToMonitor[J].addEventListener ("mousedown", adjustStyling, false); //-- Initial update. note that IE support is NOT needed. var evt = document.createEvent ("HTMLEvents"); evt.initEvent ("change", false, true); inpsToMonitor[J].dispatchEvent (evt); } function adjustStyling (zEvent) { var inpVal = zEvent.target.value; if (inpVal &amp;&amp; inpVal.replace (/^\s+|\s+$/g, "") ) zEvent.target.style.background = "lime"; else zEvent.target.style.background = "inherit"; } </code></pre>
{ "question_id": 16952526, "question_date": "2013-06-06T01:56:30.683Z", "question_score": 239, "tags": "css|input|is-empty|stylish", "answer_id": 16957328, "answer_date": "2013-06-06T08:34:59.927Z", "answer_score": 74 }
Please answer the following Stack Overflow question: Title: close vs shutdown socket? <p>In C, I understood that if we close a socket, it means the socket will be destroyed and can be re-used later.</p> <p>How about shutdown? The description said it closes half of a duplex connection to that socket. But will that socket be destroyed like <code>close</code> system call? </p>
<p>This is <a href="https://beej.us/guide/bgnet/html/#close-and-shutdownget-outta-my-face" rel="noreferrer">explained</a> in Beej's networking guide. <code>shutdown</code> is a flexible way to block communication in one or both directions. When the second parameter is <code>SHUT_RDWR</code>, it will block both sending and receiving (like <code>close</code>). However, <code>close</code> is the way to actually destroy a socket.</p> <p>With <code>shutdown</code>, you will still be able to receive pending data the peer already sent (thanks to Joey Adams for noting this).</p>
{ "question_id": 4160347, "question_date": "2010-11-11T23:38:21.660Z", "question_score": 239, "tags": "c|sockets|networking", "answer_id": 4160356, "answer_date": "2010-11-11T23:39:46.277Z", "answer_score": 214 }
Please answer the following Stack Overflow question: Title: What does `return` keyword mean inside `forEach` function? <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$('button').click(function () { [1, 2, 3, 4, 5].forEach(function (n) { if (n == 3) { // it should break out here and doesn't alert anything after return false } alert(n) }) })</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;button&gt;Click me&lt;/button&gt;</code></pre> </div> </div> </p> <p>My question: Why does it still alert next number although I call <code>return</code>? Just like: <em>Ignore the code below and continue with next element</em></p>
<p>From the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Description" rel="noreferrer">Mozilla Developer Network</a>:</p> <blockquote> <p>There is no way to stop or break a <code>forEach()</code> loop other than by throwing an exception. If you need such behavior, the <code>forEach()</code> method is the wrong tool.</p> <p>Early termination may be accomplished with:</p> <ul> <li>A simple loop</li> <li>A <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of" rel="noreferrer"><code>for</code>...<code>of</code></a> loop</li> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every" rel="noreferrer"><code>Array.prototype.every()</code></a></li> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some" rel="noreferrer"><code>Array.prototype.some()</code></a></li> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find" rel="noreferrer"><code>Array.prototype.find()</code></a></li> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex" rel="noreferrer"><code>Array.prototype.findIndex()</code></a></li> </ul> <p>The other Array methods: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every" rel="noreferrer"><code>every()</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some" rel="noreferrer"><code>some()</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find" rel="noreferrer"><code>find()</code></a>, and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex" rel="noreferrer"><code>findIndex()</code></a> test the array elements with a predicate returning a truthy value to determine if further iteration is required.</p> </blockquote>
{ "question_id": 34653612, "question_date": "2016-01-07T11:08:07.657Z", "question_score": 239, "tags": "javascript|arrays", "answer_id": 34653650, "answer_date": "2016-01-07T11:10:47.863Z", "answer_score": 334 }
Please answer the following Stack Overflow question: Title: How do I add a custom script to my package.json file that runs a javascript file? <p>I want to be able to execute the command <code>script1</code> in a project directory that will run <code>node script1.js</code>.</p> <p><code>script1.js</code> is a file in the same directory. The command needs to be specific to the project directory, meaning that if I send someone else the project folder, they will be able to run the same command. </p> <p>So far I've tried adding:</p> <pre><code>"scripts": { "script1": "node script1.js" } </code></pre> <p>to my package.json file but when I try running <code>script1</code> I get the following output:</p> <pre><code>zsh: command not found: script1 </code></pre> <p>Does anyone know the steps necessary to add the script mentioned above to the project folder?</p> <p>*Note: the command can not be added to the bash profile (cannot be a machine specific command)</p> <p>Please let me know if you need any clarification. </p>
<h2>Custom Scripts</h2> <p><code>npm run-script &lt;custom_script_name&gt;</code></p> <p><em>or</em></p> <p><code>npm run &lt;custom_script_name&gt;</code></p> <p>In your example, you would want to run <code>npm run-script script1</code> or <code>npm run script1</code>.</p> <p>See <a href="https://docs.npmjs.com/cli/run-script" rel="noreferrer">https://docs.npmjs.com/cli/run-script</a></p> <h2>Lifecycle Scripts</h2> <p>Node also allows you to run custom scripts for certain lifecycle events, like after <code>npm install</code> is run. These can be found <a href="https://docs.npmjs.com/misc/scripts" rel="noreferrer">here</a>. </p> <p>For example: </p> <pre><code>"scripts": { "postinstall": "electron-rebuild", }, </code></pre> <p>This would run <code>electron-rebuild</code> after a <code>npm install</code> command.</p>
{ "question_id": 36433461, "question_date": "2016-04-05T17:45:59.453Z", "question_score": 239, "tags": "javascript|node.js|package.json|run-script", "answer_id": 41899945, "answer_date": "2017-01-27T17:42:31.563Z", "answer_score": 357 }
Please answer the following Stack Overflow question: Title: Moment js get first and last day of current month <p>How do I get the first and last day and time of the current month in the following format in moment.js:</p> <blockquote> <p>2016-09-01 00:00</p> </blockquote> <p>I can get the current date and time like this: <code>moment().format('YYYY-MM-DD h:m')</code> which will output in the above format.</p> <p>However I need to get the date and time of the first and last day of the current month, any way to do this?</p> <p><strong>EDIT:</strong> My question is different from <a href="https://stackoverflow.com/questions/26131003/moment-js-start-and-end-of-given-month">this</a> one because that asks for a given month that the user already has whereas I am asking for the <strong>current</strong> month along with asking for a specific format of the date that is not mentioned in the other so called 'duplicate'.</p>
<p>In case anyone missed the comments on the original question, you can use built-in methods (works as of Moment 1.7):</p> <pre><code>const startOfMonth = moment().startOf('month').format('YYYY-MM-DD hh:mm'); const endOfMonth = moment().endOf('month').format('YYYY-MM-DD hh:mm'); </code></pre>
{ "question_id": 39267623, "question_date": "2016-09-01T09:22:46.667Z", "question_score": 239, "tags": "javascript|date|momentjs", "answer_id": 43011797, "answer_date": "2017-03-25T02:20:05.680Z", "answer_score": 616 }
Please answer the following Stack Overflow question: Title: No tests found for given includes Error, when running Parameterized Unit test in Android Studio <p>I have tried to run Parameterized Unit Tests in Android Studio, as shown below:</p> <pre class="lang-java prettyprint-override"><code>import android.test.suitebuilder.annotation.SmallTest; import junit.framework.TestCase; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; import java.util.Arrays; import java.util.Collection; @RunWith(Parameterized.class) @SmallTest public class FibonacciTest extends TestCase { @Parameters public static Collection&lt;Object[]&gt; data() { return Arrays.asList(new Object[][] { {0, 0}, {1, 1}, {2, 1}, {3, 2}, {4, 3}, {5, 5}, {6, 8} }); } @Parameter // first data value (0) is default public /* NOT private */ int fInput; @Parameter(value = 1) public /* NOT private */ int fExpected; @Test public void test() { assertEquals(fExpected, Fibonacci.calculate(fInput)); } } </code></pre> <p>The result is an error stating <code>No Test Run</code>. However, if I remove the Parameterized tests, and change them to individual tests, it works.</p> <p>Can anyone shed some light on why this is not working? Ar Parameterized unit tests not supported in Android development yet?</p> <p>Below is the error with stack trace:</p> <pre class="lang-none prettyprint-override"><code>FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':app:testDebug'. &gt; No tests found for given includes: [com.example.......FibonacciTest] * Try: Run with --info or --debug option to get more log output. * Exception is: org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:testDebug'. at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46) at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35) at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:64) at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58) at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:42) at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52) at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53) at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43) at org.gradle.api.internal.AbstractTask.executeWithoutThrowingTaskFailure(AbstractTask.java:310) at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.executeTask(AbstractTaskPlanExecutor.java:79) at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:63) at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:51) at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:23) at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:88) at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37) at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62) at org.gradle.execution.DefaultBuildExecuter.access$200(DefaultBuildExecuter.java:23) at org.gradle.execution.DefaultBuildExecuter$2.proceed(DefaultBuildExecuter.java:68) at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32) at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62) at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:55) at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:149) at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:106) at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:86) at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:90) at org.gradle.tooling.internal.provider.runner.BuildModelActionRunner.run(BuildModelActionRunner.java:54) at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35) at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41) at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:28) at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:49) at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36) at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120) at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37) at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120) at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26) at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120) at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34) at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120) at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74) at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72) at org.gradle.util.Swapper.swap(Swapper.java:38) at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72) at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120) at org.gradle.launcher.daemon.server.health.DaemonHealthTracker.execute(DaemonHealthTracker.java:47) at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120) at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:66) at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36) at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120) at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:71) at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36) at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120) at org.gradle.launcher.daemon.server.health.HintGCAfterBuild.execute(HintGCAfterBuild.java:41) at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120) at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50) at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:246) at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54) at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40) Caused by: org.gradle.api.GradleException: No tests found for given includes: [com.example........FibonacciTest] at org.gradle.api.internal.tasks.testing.NoMatchingTestsReporter.afterSuite(NoMatchingTestsReporter.java:35) at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35) at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24) at org.gradle.internal.event.BroadcastDispatch.dispatch(BroadcastDispatch.java:87) at org.gradle.internal.event.BroadcastDispatch.dispatch(BroadcastDispatch.java:31) at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93) at com.sun.proxy.$Proxy46.afterSuite(Unknown Source) at org.gradle.api.internal.tasks.testing.results.TestListenerAdapter.completed(TestListenerAdapter.java:48) at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35) at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24) at org.gradle.internal.event.BroadcastDispatch.dispatch(BroadcastDispatch.java:87) at org.gradle.internal.event.BroadcastDispatch.dispatch(BroadcastDispatch.java:31) at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93) at com.sun.proxy.$Proxy45.completed(Unknown Source) at org.gradle.api.internal.tasks.testing.results.StateTrackingTestResultProcessor.completed(StateTrackingTestResultProcessor.java:69) at org.gradle.api.internal.tasks.testing.results.AttachParentTestResultProcessor.completed(AttachParentTestResultProcessor.java:52) at org.gradle.api.internal.tasks.testing.processors.TestMainAction.run(TestMainAction.java:51) at org.gradle.api.internal.tasks.testing.detection.DefaultTestExecuter.execute(DefaultTestExecuter.java:75) at org.gradle.api.tasks.testing.Test.executeTests(Test.java:527) at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:75) at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.doExecute(AnnotationProcessingTaskFactory.java:226) at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:219) at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:208) at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:589) at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:572) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:80) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:61) ... 57 more BUILD FAILED Total time: 4.153 secs No tests found for given includes: [com.example......FibonacciTest] </code></pre>
<p>Add to your build.gradle:</p> <pre><code>test { useJUnitPlatform() } </code></pre>
{ "question_id": 30474767, "question_date": "2015-05-27T06:29:14.997Z", "question_score": 239, "tags": "android|android-studio|unit-testing|junit|parameterized-unit-test", "answer_id": 57309718, "answer_date": "2019-08-01T13:06:05.407Z", "answer_score": 402 }
Please answer the following Stack Overflow question: Title: HttpClient - A task was cancelled? <p>It works fine when have one or two tasks however throws an error "A task was cancelled" when we have more than one task listed.</p> <p><img src="https://i.stack.imgur.com/zZojw.png" alt="enter image description here"></p> <pre><code>List&lt;Task&gt; allTasks = new List&lt;Task&gt;(); allTasks.Add(....); allTasks.Add(....); Task.WaitAll(allTasks.ToArray(), configuration.CancellationToken); private static Task&lt;T&gt; HttpClientSendAsync&lt;T&gt;(string url, object data, HttpMethod method, string contentType, CancellationToken token) { HttpRequestMessage httpRequestMessage = new HttpRequestMessage(method, url); HttpClient httpClient = new HttpClient(); httpClient.Timeout = new TimeSpan(Constants.TimeOut); if (data != null) { byte[] byteArray = Encoding.ASCII.GetBytes(Helper.ToJSON(data)); MemoryStream memoryStream = new MemoryStream(byteArray); httpRequestMessage.Content = new StringContent(new StreamReader(memoryStream).ReadToEnd(), Encoding.UTF8, contentType); } return httpClient.SendAsync(httpRequestMessage).ContinueWith(task =&gt; { var response = task.Result; return response.Content.ReadAsStringAsync().ContinueWith(stringTask =&gt; { var json = stringTask.Result; return Helper.FromJSON&lt;T&gt;(json); }); }).Unwrap(); } </code></pre>
<p>There's 2 likely reasons that a <code>TaskCanceledException</code> would be thrown:</p> <ol> <li>Something called <code>Cancel()</code> on the <code>CancellationTokenSource</code> associated with the cancellation token before the task completed.</li> <li>The request timed out, i.e. didn't complete within the timespan you specified on <code>HttpClient.Timeout</code>.</li> </ol> <p>My guess is it was a timeout. (If it was an explicit cancellation, you probably would have figured that out.) You can be more certain by inspecting the exception:</p> <pre><code>try { var response = task.Result; } catch (TaskCanceledException ex) { // Check ex.CancellationToken.IsCancellationRequested here. // If false, it's pretty safe to assume it was a timeout. } </code></pre>
{ "question_id": 29179848, "question_date": "2015-03-21T06:15:49.607Z", "question_score": 239, "tags": "c#|task-parallel-library|dotnet-httpclient", "answer_id": 29214208, "answer_date": "2015-03-23T15:33:08.950Z", "answer_score": 352 }
Please answer the following Stack Overflow question: Title: How do I update Ruby Gems from behind a Proxy (ISA-NTLM) <p>The firewall I'm behind is running Microsoft ISA server in NTLM-only mode. Hash anyone have success getting their Ruby gems to install/update via Ruby SSPI gem or other method?</p> <p>... or am I just being lazy?</p> <p>Note: rubysspi-1.2.4 does not work.</p> <p>This also works for "igem", part of the IronRuby project</p>
<p>I wasn't able to get mine working from the command-line switch but I have been able to do it just by setting my <code>HTTP_PROXY</code> environment variable. (Note that case seems to be important). I have a batch file that has a line like this in it:</p> <pre><code>SET HTTP_PROXY=http://%USER%:%PASSWORD%@%SERVER%:%PORT% </code></pre> <p>I set the four referenced variables before I get to this line obviously. As an example if my username is "wolfbyte", my password is "secret" and my proxy is called "pigsy" and operates on port 8080:</p> <pre><code>SET HTTP_PROXY=http://wolfbyte:secret@pigsy:8080 </code></pre> <p>You might want to be careful how you manage that because it stores your password in plain text in the machine's session but I don't think it should be too much of an issue.</p>
{ "question_id": 4418, "question_date": "2008-08-07T05:21:16.807Z", "question_score": 239, "tags": "ruby|proxy|rubygems|ironruby", "answer_id": 4431, "answer_date": "2008-08-07T05:49:00.557Z", "answer_score": 218 }
Please answer the following Stack Overflow question: Title: Split string, convert ToList<int>() in one line <p>I have a string that has numbers</p> <pre><code>string sNumbers = "1,2,3,4,5"; </code></pre> <p>I can split it then convert it to <code>List&lt;int&gt;</code></p> <pre><code>sNumbers.Split( new[] { ',' } ).ToList&lt;int&gt;(); </code></pre> <p>How can I convert string array to integer list? So that I'll be able to convert <code>string[]</code> to <code>IEnumerable</code></p>
<pre><code>var numbers = sNumbers?.Split(',')?.Select(Int32.Parse)?.ToList(); </code></pre> <p>Recent versions of C# (v6+) allow you to do null checks in-line using the <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators#null-conditional-operators--and-" rel="noreferrer">null-conditional operator</a></p>
{ "question_id": 911717, "question_date": "2009-05-26T17:00:15.983Z", "question_score": 239, "tags": "c#|list|split", "answer_id": 911729, "answer_date": "2009-05-26T17:03:03.997Z", "answer_score": 578 }
Please answer the following Stack Overflow question: Title: Can you "compile" PHP code and upload a binary-ish file, which will just be run by the byte code interpreter? <p>I know that PHP is compiled to byte code before it is run on the server, and then that byte code can be cached so that the whole script doesn't have to be re-interpreted with every web access.</p> <p>But can you "compile" PHP code and upload a binary-ish file, which will just be run by the byte code interpreter?</p>
<p>After this question was asked, Facebook launched <strong>HipHop for PHP</strong> which is probably the best-tested PHP compiler to date (seeing as it ran one of the world’s 10 biggest websites). However, Facebook discontinued it in favour of HHVM, which is a virtual machine, not a compiler.</p> <p>Beyond that, googling <code>PHP compiler</code> turns up a number of 3rd party solutions.</p> <p><a href="https://www.peachpie.io/" rel="noreferrer">PeachPie</a></p> <ul> <li><a href="https://github.com/peachpiecompiler/peachpie" rel="noreferrer">PeachPie GitHub</a></li> <li>compiles PHP to .NET and .NET Core</li> <li>can be compiled into self-contained binary file</li> <li>runs on Mac, Linux, Windows, Windows Core, ARM, ...</li> </ul> <p><a href="http://v4.php-compiler.net/" rel="noreferrer">Phalanger</a></p> <ul> <li><a href="https://github.com/devsense/phalanger/" rel="noreferrer">GitHub</a> (download), <a href="http://en.wikipedia.org/wiki/Phalanger_%28compiler%29" rel="noreferrer">Wikipedia</a></li> <li>compiles to .NET (CIL) looks discontinued from July 2017 and doesn't seem to support PHP 7. </li> </ul> <p><a href="https://github.com/pbiggar/phc" rel="noreferrer">phc</a></p> <ul> <li>compiles to native binaries</li> <li>not very active now (February 2014) – last version in 2011, last change in summer 2013</li> </ul> <p><a href="http://www.roadsend.com/" rel="noreferrer">Roadsend PHP Compiler</a></p> <ul> <li><a href="https://github.com/weyrick/roadsend-php" rel="noreferrer">GitHub</a>, <a href="https://github.com/weyrick/roadsend-php-raven" rel="noreferrer">GitHub of a rewrite</a></li> <li>free, open source implementation of PHP with compiler</li> <li>compiles to native binaries (Windows, Linux)</li> <li><a href="http://roadsend-php.blogspot.cz/2010/08/current-status.html" rel="noreferrer">discontinued since 2010 till contributors found</a> – website down, stays on GitHub where last change is from early 2012</li> </ul> <p><a href="http://www.php.net/manual/en/book.bcompiler.php" rel="noreferrer">bcompiler</a></p> <ul> <li>PECL extension of PHP</li> <li>experimental</li> <li>compiles to PHP bytecode, but can wrap it in Windows binary that loads PHP interpreter (see <a href="http://www.php.net/manual/en/function.bcompiler-write-exe-footer.php" rel="noreferrer"><code>bcompiler_write_exe_footer()</code> manual</a>)</li> <li>looks discontinued now (February 2014) – last change in 2011</li> </ul> <p><a href="http://www.projectzero.org/" rel="noreferrer">Project Zero</a></p> <ul> <li><a href="http://en.wikipedia.org/wiki/Project_Zero" rel="noreferrer">Wikipedia</a>, <a href="http://www.ibm.com/developerworks/ibm/zero/" rel="noreferrer">IBM</a></li> <li>incubator of changes for <a href="https://www.ibm.com/developerworks/websphere/zones/smash/" rel="noreferrer">WebSphere sMash</a></li> <li>supported by IBM</li> <li>compiles to Java bytecode</li> <li>looks discontinued now (February 2014) – website down, looks like big hype in 2008 and 2009</li> </ul> <p><a href="http://www.bambalam.se/bamcompile/" rel="noreferrer">Bambalam</a></p> <ul> <li>compiles to stand-alone Windows binaries</li> <li>the binaries contain bytecode and a launcher</li> <li>looks discontinued now (February 2014) – last change in 2006</li> </ul> <p><a href="http://sourceforge.net/projects/binaryphp/" rel="noreferrer">BinaryPHP</a></p> <ul> <li>compiles to C++</li> <li>looks discontinued now (February 2014) – last change in 2003</li> </ul>
{ "question_id": 1408417, "question_date": "2009-09-11T00:23:28.577Z", "question_score": 239, "tags": "php|bytecode", "answer_id": 1408499, "answer_date": "2009-09-11T00:52:18.127Z", "answer_score": 247 }
Please answer the following Stack Overflow question: Title: How do I parse a YAML file in Ruby? <p>I would like to know how to parse a YAML file with the following contents:</p> <pre><code>--- javascripts: - fo_global: - lazyload-min - holla-min </code></pre> <p>Currently I am trying to parse it this way:</p> <pre><code>@custom_asset_packages_yml = (File.exists?("#{RAILS_ROOT}/config/asset_packages.yml") ? YAML.load_file("#{RAILS_ROOT}/config/asset_packages.yml") : nil) if !@custom_asset_packages_yml.nil? @custom_asset_packages_yml['javascripts'].each{ |js| js['fo_global'].each{ |script| script } } end </code></pre> <p>But it doesn't seem to work and gives me an error that the value is nil.</p> <pre><code>You have a nil object when you didn't expect it! You might have expected an instance of Array. The error occurred while evaluating nil.each </code></pre> <p>If I try this, it puts out the entire string (fo_globallazyload-minholla-min):</p> <pre><code>if !@custom_asset_packages_yml.nil? @custom_asset_packages_yml['javascripts'].each{ |js| js['fo_global'] } end </code></pre>
<p>Maybe I'm missing something, but why try to parse the file? Why not just load the YAML and examine the object(s) that result?</p> <p>If your sample YAML is in <code>some.yml</code>, then this:</p> <pre><code>require 'yaml' thing = YAML.load_file('some.yml') puts thing.inspect </code></pre> <p>gives me </p> <pre><code>{"javascripts"=&gt;[{"fo_global"=&gt;["lazyload-min", "holla-min"]}]} </code></pre>
{ "question_id": 3877004, "question_date": "2010-10-06T21:21:52.007Z", "question_score": 239, "tags": "ruby|yaml", "answer_id": 3877355, "answer_date": "2010-10-06T22:21:59.207Z", "answer_score": 504 }
Please answer the following Stack Overflow question: Title: [ :Unexpected operator in shell programming <p>My code:</p> <pre><code> #!/bin/sh #filename:choose.sh read choose [ "$choose" == "y" -o "$choose" == "Y" ] &amp;&amp; echo "Yes" &amp;&amp; exit 0 [ "$choose" == "n" -o "$choose" == "N" ] &amp;&amp; echo "No" &amp;&amp; exit 0 echo "Wrong Input" &amp;&amp; exit 0 </code></pre> <p>But when I execute </p> <pre><code> sh ./choose.sh </code></pre> <p>terminal prompt me that</p> <pre><code> [: 4: n: :Unexpected operator [: 5: n: :Unexpected operator </code></pre> <p>Is there any mistake in my bash script? Thanks!</p>
<p>There is no mistake in your <strong>bash</strong> script. But you are executing it with <strong>sh</strong> which has a less extensive syntax ;)</p> <p>So, run <code>bash ./choose.sh</code> instead :)</p>
{ "question_id": 3411048, "question_date": "2010-08-05T01:03:54.920Z", "question_score": 239, "tags": "linux|bash|shell", "answer_id": 3411061, "answer_date": "2010-08-05T01:08:02.093Z", "answer_score": 402 }
Please answer the following Stack Overflow question: Title: rsync error: failed to set times on "/foo/bar": Operation not permitted <p>I'm getting a confusing error from rsync and the initial things I'm finding from web searches (as well as all the usual chmod'ing) are not solving it:</p> <pre><code>rsync: failed to set times on "/foo/bar": Operation not permitted (1) rsync error: some files could not be transferred (code 23) at /SourceCache/rsync/rsync-35.2/rsync/main.c(992) [sender=2.6.9] </code></pre> <p>It seems to be working despite that error, but it would be nice to get rid of that.</p>
<p>If <code>/foo/bar</code> is on NFS (or possibly some FUSE filesystem), that might be the problem.</p> <p>Either way, adding <code>-O</code> / <code>--omit-dir-times</code> to your command line will avoid it trying to set modification times on directories.</p>
{ "question_id": 667992, "question_date": "2009-03-20T21:01:46.340Z", "question_score": 239, "tags": "rsync|file-transfer", "answer_id": 668049, "answer_date": "2009-03-20T21:20:24.643Z", "answer_score": 323 }
Please answer the following Stack Overflow question: Title: Using Html.ActionLink to call action on different controller <p>I am trying to navigate between controllers using <code>ActionLink</code>. I will tell my problem with an example.</p> <p>I am on Index view of Hat controller, and I am trying to use below code to create a link to Details action of Product controller.</p> <pre><code>&lt;%= Html.ActionLink("Details", "Details", "Product", new { id=item.ID }) %&gt; </code></pre> <p>Instead of creating a link to Details on Product controller, this generates a link to Details action under Hat controller and appends a Length parameter to the end of it:</p> <pre><code>Hat/Details/9?Length=7 </code></pre> <p>I am not able to use <code>HTML.ActionLink</code> to switch between controllers because of this problem. I will appreciate if you can point me to what I am doing wrong. Thanks</p> <p>PS: I am using the default route setting that comes with MVC</p> <pre><code>routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" } ); </code></pre>
<p>What you want is this overload :</p> <pre><code>//linkText, actionName, controllerName, routeValues, htmlAttributes &lt;%=Html.ActionLink("Details", "Details", "Product", new {id = item.ID}, null) %&gt; </code></pre>
{ "question_id": 776781, "question_date": "2009-04-22T11:35:55.533Z", "question_score": 239, "tags": "asp.net-mvc", "answer_id": 777237, "answer_date": "2009-04-22T13:37:07.600Z", "answer_score": 423 }
Please answer the following Stack Overflow question: Title: Install Android App Bundle on device <p>I built my project using the new Android App Bundle format. With APK files, I can download the APK to my device, open it, and immediately install the app. I downloaded my app as a bundle (.aab format) and my Nexus 5X running Android 8.1 can't open the file. Is there any way to install AABs on devices in the same convenient manner as APKs? </p>
<h3>Short answer:</h3> <p>Not directly.</p> <h3>Longer answer:</h3> <p>Android App Bundles is the default publishing format for apps on the Google Play Store. But Android devices require <code>.apk</code> files to install applications.</p> <p>The Play Store or any other source that you're installing from will extract apks from the bundle, sign each one and then install them specific to the target device.</p> <p>The conversion from .aab to .apk is done via <a href="https://github.com/google/bundletool" rel="noreferrer">bundletool</a>.</p> <p>You can use <a href="https://support.google.com/googleplay/android-developer/answer/9303479?hl=en-GB" rel="noreferrer">Internal App Sharing</a> to upload a debuggable build of your app to the Play Store and share it with testers.</p>
{ "question_id": 50419286, "question_date": "2018-05-18T21:07:09.307Z", "question_score": 239, "tags": "android|android-app-bundle", "answer_id": 50465619, "answer_date": "2018-05-22T10:38:25.933Z", "answer_score": 214 }
Please answer the following Stack Overflow question: Title: How do I query using fields inside the new PostgreSQL JSON datatype? <p>I am looking for some docs and/or examples for the new JSON functions in PostgreSQL 9.2. </p> <p>Specifically, given a series of JSON records:</p> <pre><code>[ {name: "Toby", occupation: "Software Engineer"}, {name: "Zaphod", occupation: "Galactic President"} ] </code></pre> <p>How would I write the SQL to find a record by name?</p> <p>In vanilla SQL:</p> <pre><code>SELECT * from json_data WHERE "name" = "Toby" </code></pre> <p>The official dev manual is quite sparse:</p> <ul> <li><a href="http://www.postgresql.org/docs/devel/static/datatype-json.html">http://www.postgresql.org/docs/devel/static/datatype-json.html</a></li> <li><a href="http://www.postgresql.org/docs/devel/static/functions-json.html">http://www.postgresql.org/docs/devel/static/functions-json.html</a></li> </ul> <h3>Update I</h3> <p>I've put together a <a href="https://gist.github.com/2715918">gist detailing what is currently possible with PostgreSQL 9.2</a>. Using some custom functions, it is possible to do things like:</p> <pre><code>SELECT id, json_string(data,'name') FROM things WHERE json_string(data,'name') LIKE 'G%'; </code></pre> <h3>Update II</h3> <p>I've now moved my JSON functions into their own project:</p> <p><a href="https://github.com/tobyhede/postsql"><strong>PostSQL</strong></a> - a set of functions for transforming PostgreSQL and PL/v8 into a totally awesome JSON document store</p>
<h3>Postgres 9.2</h3> <p>I quote <a href="https://archives.postgresql.org/pgsql-hackers/2012-01/msg01764.php" rel="noreferrer">Andrew Dunstan on the pgsql-hackers list</a>:</p> <blockquote> <p>At some stage there will possibly be some json-processing (as opposed to json-producing) functions, but not in 9.2.</p> </blockquote> <p>Doesn't prevent him from providing an example implementation in PLV8 that should solve your problem. (Link is dead now, see modern <a href="https://plv8.github.io/" rel="noreferrer">PLV8</a> instead.)</p> <h3>Postgres 9.3</h3> <p>Offers an arsenal of new functions and operators to add &quot;json-processing&quot;.</p> <ul> <li><a href="https://www.postgresql.org/docs/9.3/functions-json.html" rel="noreferrer">The manual on new JSON functionality.</a></li> <li><a href="https://wiki.postgresql.org/wiki/What%27s_new_in_PostgreSQL_9.3#JSON:_Additional_functionality" rel="noreferrer">The Postgres Wiki on new features in pg 9.3</a>.</li> </ul> <p>The answer to the <strong>original question</strong> in Postgres 9.3:</p> <pre class="lang-sql prettyprint-override"><code>SELECT * FROM json_array_elements( '[{&quot;name&quot;: &quot;Toby&quot;, &quot;occupation&quot;: &quot;Software Engineer&quot;}, {&quot;name&quot;: &quot;Zaphod&quot;, &quot;occupation&quot;: &quot;Galactic President&quot;} ]' ) AS elem WHERE elem-&gt;&gt;'name' = 'Toby'; </code></pre> <p>Advanced example:</p> <ul> <li><a href="https://stackoverflow.com/questions/26877241/query-combinations-with-nested-array-of-records-in-json-datatype/26880705#26880705">Query combinations with nested array of records in JSON datatype</a></li> </ul> <p>For bigger tables you may want to add an expression index to increase performance:</p> <ul> <li><a href="https://stackoverflow.com/questions/18404055/index-for-finding-element-in-json-array">Index for finding an element in a JSON array</a></li> </ul> <h3>Postgres 9.4</h3> <p>Adds <strong><code>jsonb</code></strong> (b for &quot;binary&quot;, values are stored as native Postgres types) and yet more functionality for <em>both</em> types. In addition to expression indexes mentioned above, <code>jsonb</code> also supports <a href="https://www.postgresql.org/docs/9.4/datatype-json.html#JSON-INDEXING" rel="noreferrer">GIN, btree and hash indexes</a>, GIN being the most potent of these.</p> <ul> <li>The manual on <a href="https://www.postgresql.org/docs/9.4/datatype-json.html" rel="noreferrer"><code>json</code> and <code>jsonb</code> data types</a> and <a href="https://www.postgresql.org/docs/current/functions-json.html" rel="noreferrer">functions</a>.</li> <li><a href="https://wiki.postgresql.org/wiki/What%27s_new_in_PostgreSQL_9.4#JSONB_Binary_JSON_storage" rel="noreferrer">The Postgres Wiki on JSONB in pg 9.4</a></li> </ul> <p>The manual goes as far as suggesting:</p> <blockquote> <p>In general, <strong>most applications should prefer to store JSON data as <code>jsonb</code></strong>, unless there are quite specialized needs, such as legacy assumptions about ordering of object keys.</p> </blockquote> <p>Bold emphasis mine.</p> <p><a href="https://wiki.postgresql.org/wiki/What%27s_new_in_PostgreSQL_9.4#GIN_indexes_now_faster_and_smaller" rel="noreferrer">Performance benefits from general improvements to GIN indexes.</a></p> <h3>Postgres 9.5</h3> <p>Complete <code>jsonb</code> functions and operators. Add more functions to manipulate <code>jsonb</code> in place and for display.</p> <ul> <li><a href="https://www.postgresql.org/docs/9.5/release-9-5.html#AEN126466" rel="noreferrer">Major good news in the release notes of Postgres 9.5.</a></li> </ul>
{ "question_id": 10560394, "question_date": "2012-05-12T01:45:13.270Z", "question_score": 239, "tags": "sql|json|postgresql|postgresql-9.2|postgresql-9.3", "answer_id": 10560761, "answer_date": "2012-05-12T03:10:59.240Z", "answer_score": 194 }
Please answer the following Stack Overflow question: Title: Is there a compatibility list for Angular / Angular-CLI and Node.js? <p>I periodically run into the problem, having to spin up old Angular projects with deprecated dependencies of Angular.</p> <p>Because I unsually run the latest Node.js version (at least lates LTS version) I often had the problem, that I wasn't able to get the old projects running. I solved this by using a node version manager, but still I often have the problem that I'm not sure what is the best Node.js version to use for Angular Version X.</p> <p>Sadly the <a href="https://blog.angular.io/tagged/release%20notes" rel="noreferrer">official release notes</a> handle this topic shabbily and are not a true help, especially if you like to know as of which Angular Version you can't use a specific Node.js version anymore...</p> <p><strong>Is there a complete compatibility list to check which Angular version is compatible with which Node.js version?</strong></p>
<pre><code>|Angular CLI| Angular | NodeJS |TypeScript | RxJS Version | |-----------|--------------------|------------------------------ |-----------|-----------------------------------------| |- |2.x |6.0.x or later minor |2.0.x |5.0.x/5.1.x/5.2.x/5.3.x/5.4.x/5.5.x | |1.0.6 |4.x |6.9.x or later minor |2.2.x |5.0.x/5.1.x/5.2.x/5.3.x/5.4.x/5.5.x | |1.1.3 |4.x |6.9.x or later minor |2.3.x |5.0.x/5.1.x/5.2.x/5.3.x/5.4.x/5.5.x | |1.2.7 |4.x |6.9.x or later minor |2.3.x |5.0.x/5.1.x/5.2.x/5.3.x/5.4.x/5.5.x | |1.3.2 |4.2.x or later minor|6.9.x or later minor |2.4.x |5.0.x/5.1.x/5.2.x/5.3.x/5.4.x/5.5.x | |1.4.10 |4.2.x or later minor|6.9.x/8.9.x or later minor |2.4.x |5.0.x/5.1.x/5.2.x/5.3.x/5.4.x/5.5.x | |(1.5.6) |5.0.x |6.9.x/8.9.x or later minor |2.4.x |5.5.x | |1.5.6 |5.1.x |6.9.x/8.9.x or later minor |2.5.x |5.5.x | |1.6.7 |5.2.x or later minor|6.9.x/8.9.x or later minor |2.5.x |5.5.x | |1.7.4 |5.2.x or later minor|6.9.x/8.9.x or later minor |2.5.x |5.5.x | |6.0.8 |6.0.x |8.9.x or later minor |2.7.x |6.0.x/6.1.x/6.2.x/6.3.x/6.4.x/6.5.x/6.6.x| |6.1.5 |6.1.x |8.9.x or later minor |2.7.x |6.2.x/6.3.x/6.4.x/6.5.x/6.6.x | |6.2.9 |6.1.x |8.9.x or later minor |2.9.x |6.2.x/6.3.x/6.4.x/6.5.x/6.6.x | |7.0.7 |7.0.x |8.9.x/10.9.x or later minor |3.1.x |6.3.x/6.4.x/6.5.x/6.6.x | |7.1.4 |7.1.x |8.9.x/10.9.x or later minor |3.1.x |6.3.x/6.4.x/6.5.x/6.6.x | |7.2.4 |7.2.x |8.9.x/10.9.x or later minor |3.2.x |6.3.x/6.4.x/6.5.x/6.6.x | |7.3.9 |7.2.x |8.9.x/10.9.x or later minor |3.2.x |6.3.x/6.4.x/6.5.x/6.6.x | |8.0.6 |8.0.x |10.9.x or later minor |3.4.x |6.4.x/6.5.x/6.6.x | |8.1.3 |8.1.x |10.9.x or later minor |3.4.x |6.4.x/6.5.x/6.6.x | |8.2.2 |8.2.x |10.9.x or later minor |3.4.x |6.4.x/6.5.x/6.6.x | |8.3.25 |8.2.x |10.9.x or later minor |3.5.x |6.4.x/6.5.x/6.6.x | |9.0.7 |9.0.7 |10.13.x/12.11.x or later minor |3.6.x/3.7.x|6.5.x/6.6.x | |9.x |9.x |10.13.x/12.11.x or later minor |3.6.x-3.8.x|6.5.x/6.6.x | |10.x |10.x |10.13.x/12.11.x or later minor |3.9.x |6.5.x/6.6.x | |10.1.x |10.1.x |10.13.x/12.11.x or later minor |3.9.x/4.0.x|6.6.x | |10.2.x |10.2.x |10.13.x/12.11.x or later minor |3.9.x/4.0.x|6.6.x | |11.0.7 |11.0.x |10.13.x/12.11.x or later minor |4.0.x |6.6.x | |11.1.x |11.1.x |10.13.x/12.11.x or later minor |4.0.x/4.1.x|6.6.x | |11.2.x |11.2.x |10.13.x/12.11.x or later minor |4.0.x/4.1.x|6.6.x | |12.0.x |12.0.x |12.14.x/14.15.x or later minor |4.2.x |6.6.x | |12.1.x |12.1.x |12.14.x/14.15.x or later minor |4.2.x/4.3.x|6.6.x | |12.2.x |12.2.x |12.14.x/14.15.x or later minor |4.2.x/4.3.x|6.6.x/7.0.x or later minor version | |13.0.x |13.0.x |12.20.x/14.15.x/16.10.x or later minor version|4.4.x |6.6.x/7.4.x or later minor version | |13.1.x |13.1.x |12.20.x/14.15.x/16.10.x or later minor version|4.4.x/4.5.x|6.6.x/7.4.x or later minor version | |13.2.x |13.2.x |12.20.x/14.15.x/16.10.x or later minor version|4.4.x/4.5.x|6.6.x/7.4.x or later minor version | |13.3.x |13.3.x |12.20.x/14.15.x/16.10.x or later minor version|4.4.x/4.7.x|6.6.x/7.4.x or later minor version | |14.0.x |14.0.x |14.15.x/^16.10.x or later minor version |4.6.x/4.8.x|6.6.x/7.4.x or later minor version | |-----------|--------------------|----------------------------------------------|-----------|-----------------------------------------| </code></pre> <p>ref: <a href="https://gist.github.com/LayZeeDK/c822cc812f75bb07b7c55d07ba2719b3" rel="noreferrer">https://gist.github.com/LayZeeDK/c822cc812f75bb07b7c55d07ba2719b3</a></p>
{ "question_id": 60248452, "question_date": "2020-02-16T12:28:52.517Z", "question_score": 239, "tags": "node.js|angular|angular-cli", "answer_id": 60258560, "answer_date": "2020-02-17T08:36:00.773Z", "answer_score": 555 }
Please answer the following Stack Overflow question: Title: Fastest Way to Find Distance Between Two Lat/Long Points <p>I currently have just under a million locations in a mysql database all with longitude and latitude information.</p> <p>I am trying to find the distance between one point and many other points via a query. It's not as fast as I want it to be especially with 100+ hits a second. </p> <p>Is there a faster query or possibly a faster system other than mysql for this? I'm using this query:</p> <pre><code>SELECT name, ( 3959 * acos( cos( radians(42.290763) ) * cos( radians( locations.lat ) ) * cos( radians(locations.lng) - radians(-71.35368)) + sin(radians(42.290763)) * sin( radians(locations.lat)))) AS distance FROM locations WHERE active = 1 HAVING distance &lt; 10 ORDER BY distance; </code></pre> <p><em>Note: The provided distance is in <strong>Miles</strong>. If you need <strong>Kilometers</strong>, use <code>6371</code> instead of <code>3959</code>.</em></p>
<ul> <li><p>Create your points using <code>Point</code> values of <code>Geometry</code> data types in <code>MyISAM</code> table. <a href="https://dev.mysql.com/doc/relnotes/mysql/5.7/en/news-5-7-5.html#mysqld-5-7-5-spatial-support" rel="nofollow noreferrer">As of Mysql 5.7.5, <code>InnoDB</code> tables now also support <code>SPATIAL</code> indices.</a></p> </li> <li><p>Create a <code>SPATIAL</code> index on these points</p> </li> <li><p>Use <code>MBRContains()</code> to find the values:</p> <pre><code> SELECT * FROM table WHERE MBRContains(LineFromText(CONCAT( '(' , @lon + 10 / ( 111.1 / cos(RADIANS(@lat))) , ' ' , @lat + 10 / 111.1 , ',' , @lon - 10 / ( 111.1 / cos(RADIANS(@lat))) , ' ' , @lat - 10 / 111.1 , ')' ) ,mypoint) </code></pre> </li> </ul> <p>, or, in <code>MySQL 5.1</code> and above:</p> <pre><code> SELECT * FROM table WHERE MBRContains ( LineString ( Point ( @lon + 10 / ( 111.1 / COS(RADIANS(@lat))), @lat + 10 / 111.1 ), Point ( @lon - 10 / ( 111.1 / COS(RADIANS(@lat))), @lat - 10 / 111.1 ) ), mypoint ) </code></pre> <p>This will select all points approximately within the box <code>(@lat +/- 10 km, @lon +/- 10km)</code>.</p> <p>This actually is not a box, but a spherical rectangle: latitude and longitude bound segment of the sphere. This may differ from a plain rectangle on the <strong>Franz Joseph Land</strong>, but quite close to it on most inhabited places.</p> <ul> <li><p>Apply additional filtering to select everything inside the circle (not the square)</p> </li> <li><p>Possibly apply additional fine filtering to account for the big circle distance (for large distances)</p> </li> </ul>
{ "question_id": 1006654, "question_date": "2009-06-17T12:22:41.247Z", "question_score": 239, "tags": "mysql|location|gis", "answer_id": 1006668, "answer_date": "2009-06-17T12:25:00.383Z", "answer_score": 120 }
Please answer the following Stack Overflow question: Title: ActiveModel::ForbiddenAttributesError when creating new user <p>I have this model in Ruby but it throws a <code>ActiveModel::ForbiddenAttributesError</code></p> <pre><code>class User &lt; ActiveRecord::Base attr_accessor :password validates :username, :presence =&gt; true, :uniqueness =&gt; true, :length =&gt; {:in =&gt; 3..20} VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :email, presence: true, :uniqueness =&gt; true, format: { with: VALID_EMAIL_REGEX } validates :password, :confirmation =&gt; true validates_length_of :password, :in =&gt; 6..20, :on =&gt; :create before_save :encrypt_password after_save :clear_password def encrypt_password if password.present? self.salt = BCrypt::Engine.generate_salt self.encrypted_password= BCrypt::Engine.hash_secret(password, salt) end end def clear_password self.password = nil end end </code></pre> <p>when I run this action</p> <pre><code> def create @user = User.new(params[:user]) if @user.save flash[:notice] = "You Signed up successfully" flash[:color]= "valid" else flash[:notice] = "Form is invalid" flash[:color]= "invalid" end render "new" end </code></pre> <p>on <code>ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-linux]</code>.</p> <p>Can you please tell me how to get rid of this error or establish a proper user registration form?</p>
<p>I guess you are using Rails 4. If so, the needed parameters must be marked as required.</p> <p>You might want to do it like this:</p> <pre class="lang-rb prettyprint-override"><code>class UsersController &lt; ApplicationController def create @user = User.new(user_params) # ... end private def user_params params.require(:user).permit(:username, :email, :password, :salt, :encrypted_password) end end </code></pre>
{ "question_id": 17335329, "question_date": "2013-06-27T05:41:33.237Z", "question_score": 239, "tags": "ruby-on-rails|rails-activerecord", "answer_id": 17335871, "answer_date": "2013-06-27T06:21:16.810Z", "answer_score": 427 }
Please answer the following Stack Overflow question: Title: How do you view ALL text from an ntext or nvarchar(max) in SSMS? <p>How do you view ALL text from an NTEXT or NVARCHAR(max) in SQL Server Management Studio? By default, it only seems to return the first few hundred characters (255?) but sometimes I just want a quick way of viewing the whole field, without having to write a program to do it. Even SSMS 2012 still has this problem :(</p>
<p>In newer versions of SSMS it can be configured in the <strong>(Query/Query Options/Results/Grid/Maximum Characters Retrieved)</strong> menu:</p> <p><a href="https://i.stack.imgur.com/9ZiYl.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9ZiYl.png" alt="enter image description here" /></a></p> <hr /> <h2>Old versions of SSMS</h2> <p><a href="http://msdn.microsoft.com/en-us/library/ms190078.aspx" rel="noreferrer">Options (Query Results/SQL Server/Results to Grid Page)</a></p> <blockquote> <blockquote> <p>To change the options for the current queries, click Query Options on the Query menu, or right-click in the SQL Server Query window and select Query Options.</p> </blockquote> </blockquote> <p>...</p> <blockquote> <blockquote> <p><strong>Maximum Characters Retrieved</strong><br /> Enter a number from 1 through 65535 to specify the maximum number of characters that will be displayed in each cell.</p> </blockquote> </blockquote> <p>Maximum is, as you see, 64k. The default is much smaller.</p> <p>BTW <a href="http://msdn.microsoft.com/en-us/library/ms178782" rel="noreferrer">Results to Text</a> has even more drastic limitation:</p> <blockquote> <blockquote> <p><strong>Maximum number of characters displayed in each column</strong><br /> This value defaults to 256. Increase this value to display larger result sets without truncation. The maximum value is 8,192.</p> </blockquote> </blockquote>
{ "question_id": 11897950, "question_date": "2012-08-10T08:26:51.257Z", "question_score": 239, "tags": "sql-server|sql-server-2008|tsql|ssms", "answer_id": 11897999, "answer_date": "2012-08-10T08:30:18.820Z", "answer_score": 118 }
Please answer the following Stack Overflow question: Title: Find all controls in WPF Window by type <p>I'm looking for a way to find all controls on Window by their type,</p> <p><em>for example:</em> find all <code>TextBoxes</code>, find all controls implementing specific interface etc.</p>
<p>This should do the trick:</p> <pre><code>public static IEnumerable&lt;T&gt; FindVisualChilds&lt;T&gt;(DependencyObject depObj) where T : DependencyObject { if (depObj == null) yield return (T)Enumerable.Empty&lt;T&gt;(); for (int i = 0; i &lt; VisualTreeHelper.GetChildrenCount(depObj); i++) { DependencyObject ithChild = VisualTreeHelper.GetChild(depObj, i); if (ithChild == null) continue; if (ithChild is T t) yield return t; foreach (T childOfChild in FindVisualChilds&lt;T&gt;(ithChild)) yield return childOfChild; } } </code></pre> <p>then you enumerate over the controls like so</p> <pre><code>foreach (TextBlock tb in FindVisualChildren&lt;TextBlock&gt;(window)) { // do something with tb here } </code></pre>
{ "question_id": 974598, "question_date": "2009-06-10T09:40:43.003Z", "question_score": 239, "tags": "c#|.net|wpf", "answer_id": 978352, "answer_date": "2009-06-10T21:53:22.167Z", "answer_score": 461 }
Please answer the following Stack Overflow question: Title: pip: force install ignoring dependencies <p>Is there any way to force install a pip python package ignoring all it's dependencies that cannot be satisfied?</p> <p>(I don't care how "wrong" it is to do so, I just need to do it, any logic and reasoning aside...)</p>
<p>pip has a <code>--no-dependencies</code> switch. You should use that.</p> <p>For more information, run <code>pip install -h</code>, where you'll see this line: </p> <pre><code>--no-deps, --no-dependencies Ignore package dependencies </code></pre>
{ "question_id": 12759761, "question_date": "2012-10-06T12:21:56.430Z", "question_score": 239, "tags": "python|pip", "answer_id": 12759996, "answer_date": "2012-10-06T12:55:19.617Z", "answer_score": 362 }
Please answer the following Stack Overflow question: Title: How do I get logs from all pods of a Kubernetes replication controller? <p>Running <code>kubectl logs</code> shows me the stderr/stdout of one Kubernetes container. </p> <p>How can I get the aggregated stderr/stdout of a set of pods, preferably those created by a certain replication controller?</p>
<p>You can use labels</p> <pre><code>kubectl logs -l app=elasticsearch </code></pre> <p>And you'd probably want to specify <code>--all-containers --ignore-errors</code> in order to:</p> <ul> <li>Include logs from pods with multiple containers</li> <li>Continue to next pod on fatal error (e.g. logs could not be retrieved)</li> </ul>
{ "question_id": 33069736, "question_date": "2015-10-11T20:20:59.437Z", "question_score": 239, "tags": "logging|kubernetes|google-kubernetes-engine", "answer_id": 44448420, "answer_date": "2017-06-09T02:38:04.523Z", "answer_score": 333 }
Please answer the following Stack Overflow question: Title: Dynamic instantiation from string name of a class in dynamically imported module? <p>In python, I have to instantiate certain class, knowing its name in a string, but this class 'lives' in a dynamically imported module. An example follows:</p> <p>loader-class script:</p> <pre><code>import sys class loader: def __init__(self, module_name, class_name): # both args are strings try: __import__(module_name) modul = sys.modules[module_name] instance = modul.class_name() # obviously this doesn't works, here is my main problem! except ImportError: # manage import error </code></pre> <p>some-dynamically-loaded-module script:</p> <pre><code>class myName: # etc... </code></pre> <p>I use this arrangement to make any dynamically-loaded-module to be used by the loader-class following certain predefined behaviours in the dyn-loaded-modules...</p>
<p>You can use <a href="http://docs.python.org/2/library/functions.html#getattr" rel="noreferrer">getattr</a></p> <pre><code>getattr(module, class_name) </code></pre> <p>to access the class. More complete code:</p> <pre><code>module = __import__(module_name) class_ = getattr(module, class_name) instance = class_() </code></pre> <p>As mentioned <a href="https://stackoverflow.com/questions/4821104/python-dynamic-instantiation-from-string-name-of-a-class-in-dynamically-imported/4821120#comment18605113_4821120">below</a>, we may use importlib</p> <pre><code>import importlib module = importlib.import_module(module_name) class_ = getattr(module, class_name) instance = class_() </code></pre>
{ "question_id": 4821104, "question_date": "2011-01-27T19:49:57.950Z", "question_score": 239, "tags": "python", "answer_id": 4821120, "answer_date": "2011-01-27T19:51:58.263Z", "answer_score": 335 }
Please answer the following Stack Overflow question: Title: RuntimeError on windows trying python multiprocessing <p>I am trying my very first formal python program using Threading and Multiprocessing on a windows machine. I am unable to launch the processes though, with python giving the following message. The thing is, I am not launching my threads in the <strong>main</strong> module. The threads are handled in a separate module inside a class.</p> <p><strong>EDIT</strong>: By the way this code runs fine on ubuntu. Not quite on windows</p> <pre><code>RuntimeError: Attempt to start a new process before the current process has finished its bootstrapping phase. This probably means that you are on Windows and you have forgotten to use the proper idiom in the main module: if __name__ == '__main__': freeze_support() ... The "freeze_support()" line can be omitted if the program is not going to be frozen to produce a Windows executable. </code></pre> <p>My original code is pretty long, but I was able to reproduce the error in an abridged version of the code. It is split in two files, the first is the main module and does very little other than import the module which handles processes/threads and calls a method. The second module is where the meat of the code is.</p> <hr> <p><strong>testMain.py:</strong></p> <pre><code>import parallelTestModule extractor = parallelTestModule.ParallelExtractor() extractor.runInParallel(numProcesses=2, numThreads=4) </code></pre> <hr> <p><strong>parallelTestModule.py:</strong></p> <pre><code>import multiprocessing from multiprocessing import Process import threading class ThreadRunner(threading.Thread): """ This class represents a single instance of a running thread""" def __init__(self, name): threading.Thread.__init__(self) self.name = name def run(self): print self.name,'\n' class ProcessRunner: """ This class represents a single instance of a running process """ def runp(self, pid, numThreads): mythreads = [] for tid in range(numThreads): name = "Proc-"+str(pid)+"-Thread-"+str(tid) th = ThreadRunner(name) mythreads.append(th) for i in mythreads: i.start() for i in mythreads: i.join() class ParallelExtractor: def runInParallel(self, numProcesses, numThreads): myprocs = [] prunner = ProcessRunner() for pid in range(numProcesses): pr = Process(target=prunner.runp, args=(pid, numThreads)) myprocs.append(pr) # if __name__ == 'parallelTestModule': #This didnt work # if __name__ == '__main__': #This obviously doesnt work # multiprocessing.freeze_support() #added after seeing error to no avail for i in myprocs: i.start() for i in myprocs: i.join() </code></pre>
<p>On Windows the subprocesses will import (i.e. execute) the main module at start. You need to insert an <code>if __name__ == '__main__':</code> guard in the main module to avoid creating subprocesses recursively. </p> <p>Modified <code>testMain.py</code>:</p> <pre><code>import parallelTestModule if __name__ == '__main__': extractor = parallelTestModule.ParallelExtractor() extractor.runInParallel(numProcesses=2, numThreads=4) </code></pre>
{ "question_id": 18204782, "question_date": "2013-08-13T08:59:14.670Z", "question_score": 239, "tags": "python|windows|multiprocessing", "answer_id": 18205006, "answer_date": "2013-08-13T09:10:38.467Z", "answer_score": 356 }
Please answer the following Stack Overflow question: Title: How to store printStackTrace into a string <p>How can I get the <code>e.printStackTrace()</code> and store it into a <code>String</code> variable? I want to use the string generated by <code>e.printStackTrace()</code> later in my program.</p> <p>I'm still new to Java so I'm not too familiar with <code>StringWriter</code> that I think will be the solution. Or if you have any other ideas please let me know. Thanks</p>
<p>Something along the lines of </p> <pre><code>StringWriter errors = new StringWriter(); ex.printStackTrace(new PrintWriter(errors)); return errors.toString(); </code></pre> <p>Ought to be what you need. </p> <p>Relevant documentation:</p> <ul> <li><a href="https://docs.oracle.com/javase/7/docs/api/java/io/StringWriter.html" rel="noreferrer">StringWriter</a></li> <li><a href="https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html" rel="noreferrer">PrintWriter</a></li> <li><a href="https://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html" rel="noreferrer">Throwable</a></li> </ul>
{ "question_id": 4812570, "question_date": "2011-01-27T03:55:39.903Z", "question_score": 239, "tags": "java|stack-trace", "answer_id": 4812589, "answer_date": "2011-01-27T03:59:58.880Z", "answer_score": 485 }
Please answer the following Stack Overflow question: Title: Remove duplicate dict in list in Python <p>I have a list of dicts, and I'd like to remove the dicts with identical key and value pairs.</p> <p>For this list: <code>[{'a': 123}, {'b': 123}, {'a': 123}]</code></p> <p>I'd like to return this: <code>[{'a': 123}, {'b': 123}]</code></p> <p>Another example:</p> <p>For this list: <code>[{'a': 123, 'b': 1234}, {'a': 3222, 'b': 1234}, {'a': 123, 'b': 1234}]</code></p> <p>I'd like to return this: <code>[{'a': 123, 'b': 1234}, {'a': 3222, 'b': 1234}]</code></p>
<p>Try this:</p> <pre><code>[dict(t) for t in {tuple(d.items()) for d in l}] </code></pre> <p>The strategy is to convert the list of dictionaries to a list of tuples where the tuples contain the items of the dictionary. Since the tuples can be hashed, you can remove duplicates using <code>set</code> (using a <em>set comprehension</em> here, older python alternative would be <code>set(tuple(d.items()) for d in l)</code>) and, after that, re-create the dictionaries from tuples with <code>dict</code>.</p> <p>where:</p> <ul> <li><code>l</code> is the original list</li> <li><code>d</code> is one of the dictionaries in the list</li> <li><code>t</code> is one of the tuples created from a dictionary</li> </ul> <p>Edit: If you want to preserve ordering, the one-liner above won't work since <code>set</code> won't do that. However, with a few lines of code, you can also do that:</p> <pre><code>l = [{'a': 123, 'b': 1234}, {'a': 3222, 'b': 1234}, {'a': 123, 'b': 1234}] seen = set() new_l = [] for d in l: t = tuple(d.items()) if t not in seen: seen.add(t) new_l.append(d) print new_l </code></pre> <p>Example output:</p> <pre><code>[{'a': 123, 'b': 1234}, {'a': 3222, 'b': 1234}] </code></pre> <p>Note: As pointed out by @alexis it might happen that two dictionaries with the same keys and values, don't result in the same tuple. That could happen if they go through a different adding/removing keys history. If that's the case for your problem, then consider sorting <code>d.items()</code> as he suggests.</p>
{ "question_id": 9427163, "question_date": "2012-02-24T07:46:41.090Z", "question_score": 239, "tags": "python|list|dictionary", "answer_id": 9427216, "answer_date": "2012-02-24T07:51:31.650Z", "answer_score": 376 }
Please answer the following Stack Overflow question: Title: Save string to the NSUserDefaults? <p>How to save a string into the <code>NSUserDefaults</code>?</p>
<pre><code>NSString *valueToSave = @"someValue"; [[NSUserDefaults standardUserDefaults] setObject:valueToSave forKey:@"preferenceName"]; [[NSUserDefaults standardUserDefaults] synchronize]; </code></pre> <p>to get it back later</p> <pre><code>NSString *savedValue = [[NSUserDefaults standardUserDefaults] stringForKey:@"preferenceName"]; </code></pre>
{ "question_id": 3074483, "question_date": "2010-06-19T05:33:37.957Z", "question_score": 239, "tags": "ios|swift|objective-c|cocoa-touch|nsuserdefaults", "answer_id": 3074489, "answer_date": "2010-06-19T05:37:30.050Z", "answer_score": 466 }
Please answer the following Stack Overflow question: Title: warning about too many open figures <p>In a script where I create many figures with <code>fix, ax = plt.subplots(...)</code>, I get the warning <em>RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (<code>matplotlib.pyplot.figure</code>) are retained until explicitly closed and may consume too much memory.</em> </p> <p>However, I don't understand <em>why</em> I get this warning, because after saving the figure with <code>fig.savefig(...)</code>, I delete it with <code>fig.clear(); del fig</code>. At no point in my code, I have more than one figure open at a time. Still, I get the warning about too many open figures. What does that mean / how can I avoid getting the warning?</p>
<p>Use <code>.clf</code> or <code>.cla</code> on your figure object instead of creating a <em>new</em> figure. From <a href="https://stackoverflow.com/a/8228808/249341">@DavidZwicker</a></p> <p>Assuming you have imported <code>pyplot</code> as</p> <pre><code>import matplotlib.pyplot as plt </code></pre> <p><a href="http://matplotlib.org/1.3.0/api/pyplot_api.html#matplotlib.pyplot.cla" rel="noreferrer"><code>plt.cla()</code> clears an axis</a>, i.e. the currently active axis in the current figure. It leaves the other axes untouched.</p> <p><a href="http://matplotlib.org/1.3.0/api/pyplot_api.html#matplotlib.pyplot.clf" rel="noreferrer"><code>plt.clf()</code> clears the entire current figure</a> with all its axes, but leaves the window opened, such that it may be reused for other plots.</p> <p><a href="http://matplotlib.org/1.3.0/api/pyplot_api.html#matplotlib.pyplot.close" rel="noreferrer"><code>plt.close()</code> closes a window</a>, which will be the current window, if not specified otherwise. <code>plt.close('all')</code> will close all open figures.</p> <p>The reason that <code>del fig</code> does not work is that the <code>pyplot</code> state-machine keeps a reference to the figure around (as it must if it is going to know what the 'current figure' is). This means that even if you delete <em>your</em> ref to the figure, there is at least one live ref, hence it will never be garbage collected.</p> <p>Since I'm polling on the collective wisdom here for this answer, @JoeKington mentions in the comments that <a href="http://matplotlib.org/1.3.0/api/pyplot_api.html#matplotlib.pyplot.close" rel="noreferrer"><code>plt.close(fig)</code></a> will remove a specific figure instance from the pylab state machine (<a href="https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/_pylab_helpers.py" rel="noreferrer">plt._pylab_helpers.Gcf</a>) and allow it to be garbage collected. </p>
{ "question_id": 21884271, "question_date": "2014-02-19T15:00:45.077Z", "question_score": 239, "tags": "python|python-3.x|matplotlib", "answer_id": 21884375, "answer_date": "2014-02-19T15:04:46.633Z", "answer_score": 296 }
Please answer the following Stack Overflow question: Title: Temporarily change current working directory in bash to run a command <p>I know I can use <code>cd</code> command to change my working directory in bash. </p> <p>But if I do this command:</p> <pre><code>cd SOME_PATH &amp;&amp; run_some_command </code></pre> <p>Then the working directory will be changed permanently. Is there some way to change the working directory just temporarily like this?</p> <pre><code>PWD=SOME_PATH run_some_command </code></pre>
<p>You can run the <code>cd</code> and the executable in a subshell by enclosing the command line in a pair of parentheses:</p> <pre><code>(cd SOME_PATH &amp;&amp; exec_some_command) </code></pre> <p>Demo:</p> <pre><code>$ pwd /home/abhijit $ (cd /tmp &amp;&amp; pwd) # directory changed in the subshell /tmp $ pwd # parent shell's pwd is still the same /home/abhijit </code></pre>
{ "question_id": 10382141, "question_date": "2012-04-30T10:28:21.550Z", "question_score": 239, "tags": "bash|shell|terminal|working-directory", "answer_id": 10382170, "answer_date": "2012-04-30T10:30:33.433Z", "answer_score": 427 }
Please answer the following Stack Overflow question: Title: Only get hash value using md5sum (without filename) <p>I use <a href="https://linux.die.net/man/1/md5sum" rel="noreferrer">md5sum</a> to generate a hash value for a file. But I only need to receive the hash value, not the file name.</p> <pre><code>md5=`md5sum ${my_iso_file}` echo ${md5} </code></pre> <p>Output:</p> <pre><code>3abb17b66815bc7946cefe727737d295 ./iso/somefile.iso </code></pre> <p>How can I 'strip' the file name and only retain the value?</p>
<p>Using <a href="https://en.wikipedia.org/wiki/AWK" rel="noreferrer">AWK</a>:</p> <pre><code>md5=`md5sum ${my_iso_file} | awk '{ print $1 }'` </code></pre>
{ "question_id": 3679296, "question_date": "2010-09-09T18:07:26.660Z", "question_score": 239, "tags": "bash|shell|md5sum", "answer_id": 3679803, "answer_date": "2010-09-09T19:16:27.473Z", "answer_score": 219 }
Please answer the following Stack Overflow question: Title: jquery 3.0 url.indexOf error <p>I am getting following error from jQuery once it has been updated to <code>v3.0.0</code>.</p> <p><code>jquery.js:9612 Uncaught TypeError: url.indexOf is not a function</code></p> <p>Any Idea why?</p>
<p><strong>Update</strong> all your code that calls <code>load</code> function like,</p> <pre><code>$(window).load(function() { ... }); </code></pre> <p><strong>To</strong></p> <pre><code>$(window).on('load', function() { ... }); </code></pre> <hr/> <blockquote> <p>jquery.js:9612 Uncaught TypeError: url.indexOf is not a function</p> </blockquote> <p>This error message comes from <code>jQuery.fn.load</code> function.</p> <p>I've come across the same issue on my application. After some digging, I found this statement in <a href="https://blog.jquery.com/2015/07/13/jquery-3-0-and-jquery-compat-3-0-alpha-versions-released/" rel="noreferrer">jQuery blog</a>,</p> <blockquote> <p>.load, .unload, and .error, deprecated since jQuery 1.8, <strong>are no more</strong>. Use .on() to register listeners.</p> </blockquote> <p>I simply just change how my jQuery objects call the <code>load</code> function like above. And everything works as expected.</p>
{ "question_id": 37738732, "question_date": "2016-06-10T01:47:56.233Z", "question_score": 239, "tags": "jquery|jquery-3", "answer_id": 37915907, "answer_date": "2016-06-20T06:31:41.870Z", "answer_score": 619 }
Please answer the following Stack Overflow question: Title: How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift? <p>How to generate a date time stamp, using the format standards for <a href="http://en.wikipedia.org/wiki/ISO_8601" rel="noreferrer">ISO 8601</a> and <a href="https://www.rfc-editor.org/rfc/rfc3339" rel="noreferrer">RFC 3339</a>?</p> <p>The goal is a string that looks like this:</p> <pre><code>&quot;2015-01-01T00:00:00.000Z&quot; </code></pre> <p>Format:</p> <ul> <li>year, month, day, as &quot;XXXX-XX-XX&quot;</li> <li>the letter &quot;T&quot; as a separator</li> <li>hour, minute, seconds, milliseconds, as &quot;XX:XX:XX.XXX&quot;.</li> <li>the letter &quot;Z&quot; as a zone designator for zero offset, a.k.a. UTC, GMT, Zulu time.</li> </ul> <p>Best case:</p> <ul> <li>Swift source code that is simple, short, and straightforward.</li> <li>No need to use any additional framework, subproject, cocoapod, C code, etc.</li> </ul> <p>I've searched StackOverflow, Google, Apple, etc. and haven't found a Swift answer to this.</p> <p>The classes that seem most promising are <a href="https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/index.html" rel="noreferrer"><code>NSDate</code></a>, <a href="https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/index.html" rel="noreferrer"><code>NSDateFormatter</code></a>, <a href="https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSTimeZone_Class/index.html" rel="noreferrer"><code>NSTimeZone</code></a>.</p> <p>Related Q&amp;A: <a href="https://stackoverflow.com/questions/16254575/how-do-i-get-iso-8601-date-in-ios">How do I get an ISO 8601 date on iOS?</a></p> <p>Here's the best I've come up with so far:</p> <pre><code>var now = NSDate() var formatter = NSDateFormatter() formatter.dateFormat = &quot;yyyy-MM-dd'T'HH:mm:ss.SSS'Z'&quot; formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) println(formatter.stringFromDate(now)) </code></pre>
<p><strong>Swift 4 • iOS 11.2.1 or later</strong></p> <pre><code>extension ISO8601DateFormatter { convenience init(_ formatOptions: Options) { self.init() self.formatOptions = formatOptions } } </code></pre> <hr /> <pre><code>extension Formatter { static let iso8601withFractionalSeconds = ISO8601DateFormatter([.withInternetDateTime, .withFractionalSeconds]) } </code></pre> <hr /> <pre><code>extension Date { var iso8601withFractionalSeconds: String { return Formatter.iso8601withFractionalSeconds.string(from: self) } } </code></pre> <hr /> <pre><code>extension String { var iso8601withFractionalSeconds: Date? { return Formatter.iso8601withFractionalSeconds.date(from: self) } } </code></pre> <hr /> <p>Usage:</p> <pre><code>Date().description(with: .current) // Tuesday, February 5, 2019 at 10:35:01 PM Brasilia Summer Time&quot; let dateString = Date().iso8601withFractionalSeconds // &quot;2019-02-06T00:35:01.746Z&quot; if let date = dateString.iso8601withFractionalSeconds { date.description(with: .current) // &quot;Tuesday, February 5, 2019 at 10:35:01 PM Brasilia Summer Time&quot; print(date.iso8601withFractionalSeconds) // &quot;2019-02-06T00:35:01.746Z\n&quot; } </code></pre> <hr /> <p><strong>iOS 9 • Swift 3 or later</strong></p> <pre><code>extension Formatter { static let iso8601withFractionalSeconds: DateFormatter = { let formatter = DateFormatter() formatter.calendar = Calendar(identifier: .iso8601) formatter.locale = Locale(identifier: &quot;en_US_POSIX&quot;) formatter.timeZone = TimeZone(secondsFromGMT: 0) formatter.dateFormat = &quot;yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX&quot; return formatter }() } </code></pre> <hr /> <blockquote> <p><strong>Codable Protocol</strong></p> <p>If you need to encode and decode this format when working with Codable protocol you can create your own custom date encoding/decoding strategies:</p> </blockquote> <pre><code>extension JSONDecoder.DateDecodingStrategy { static let iso8601withFractionalSeconds = custom { let container = try $0.singleValueContainer() let string = try container.decode(String.self) guard let date = Formatter.iso8601withFractionalSeconds.date(from: string) else { throw DecodingError.dataCorruptedError(in: container, debugDescription: &quot;Invalid date: &quot; + string) } return date } } </code></pre> <p>and the encoding strategy</p> <pre><code>extension JSONEncoder.DateEncodingStrategy { static let iso8601withFractionalSeconds = custom { var container = $1.singleValueContainer() try container.encode(Formatter.iso8601withFractionalSeconds.string(from: $0)) } } </code></pre> <hr /> <p>Playground Testing</p> <pre><code>let dates = [Date()] // [&quot;Feb 8, 2019 at 9:48 PM&quot;] </code></pre> <p>encoding</p> <pre><code>let encoder = JSONEncoder() encoder.dateEncodingStrategy = .iso8601withFractionalSeconds let data = try! encoder.encode(dates) print(String(data: data, encoding: .utf8)!) </code></pre> <p>decoding</p> <pre><code>let decoder = JSONDecoder() decoder.dateDecodingStrategy = .iso8601withFractionalSeconds let decodedDates = try! decoder.decode([Date].self, from: data) // [&quot;Feb 8, 2019 at 9:48 PM&quot;] </code></pre> <p><a href="https://i.stack.imgur.com/lkYVY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/lkYVY.png" alt="enter image description here" /></a></p>
{ "question_id": 28016578, "question_date": "2015-01-19T00:58:31.917Z", "question_score": 239, "tags": "date|swift|time|iso8601|rfc3339", "answer_id": 28016692, "answer_date": "2015-01-19T01:18:32.743Z", "answer_score": 469 }
Please answer the following Stack Overflow question: Title: jQuery map vs. each <p>In jQuery, the <code>map</code> and <code>each</code> functions seem to do the same thing. Are there any practical differences between the two? When would you choose to use one instead of the other?</p>
<p>The <a href="http://docs.jquery.com/Utilities/jQuery.each" rel="noreferrer"><code>each</code></a> method is meant to be an immutable iterator, where as the <a href="http://docs.jquery.com/Utilities/jQuery.map" rel="noreferrer"><code>map</code></a> method can be used as an iterator, but is really meant to manipulate the supplied array and return a new array.</p> <p>Another important thing to note is that the <code>each</code> function returns the original array while the <code>map</code> function returns a new array. If you overuse the return value of the map function you can potentially waste a lot of memory.</p> <p>For example:</p> <pre><code>var items = [1,2,3,4]; $.each(items, function() { alert('this is ' + this); }); var newItems = $.map(items, function(i) { return i + 1; }); // newItems is [2,3,4,5] </code></pre> <p>You can also use the map function to remove an item from an array. For example:</p> <pre><code>var items = [0,1,2,3,4,5,6,7,8,9]; var itemsLessThanEqualFive = $.map(items, function(i) { // removes all items &gt; 5 if (i &gt; 5) return null; return i; }); // itemsLessThanEqualFive = [0,1,2,3,4,5] </code></pre> <p>You'll also note that the <code>this</code> is not mapped in the <code>map</code> function. You will have to supply the first parameter in the callback (eg we used <code>i</code> above). Ironically, the callback arguments used in the each method are the reverse of the callback arguments in the map function so be careful.</p> <pre><code>map(arr, function(elem, index) {}); // versus each(arr, function(index, elem) {}); </code></pre>
{ "question_id": 749084, "question_date": "2009-04-14T19:48:03.970Z", "question_score": 239, "tags": "javascript|jquery", "answer_id": 749119, "answer_date": "2009-04-14T19:55:09.007Z", "answer_score": 276 }
Please answer the following Stack Overflow question: Title: The difference between fork(), vfork(), exec() and clone() <p>I was looking to find the difference between these four on Google and I expected there to be a huge amount of information on this, but there really wasn't any solid comparison between the four calls.</p> <p>I set about trying to compile a kind of basic at-a-glance look at the differences between these system calls and here's what I got. Is all this information correct/am I missing anything important ?</p> <p><code>Fork</code> : The fork call basically makes a duplicate of the current process, identical in almost every way (not everything is copied over, for example, resource limits in some implementations but the idea is to create as close a copy as possible).</p> <p>The new process (child) gets a different process ID (PID) and has the PID of the old process (parent) as its parent PID (PPID). Because the two processes are now running exactly the same code, they can tell which is which by the return code of fork - the child gets 0, the parent gets the PID of the child. This is all, of course, assuming the fork call works - if not, no child is created and the parent gets an error code.</p> <p><code>Vfork</code>: The basic difference between <code>vfork()</code> and <code>fork()</code> is that when a new process is created with <code>vfork()</code>, the parent process is temporarily suspended, and the child process might borrow the parent's address space. This strange state of affairs continues until the child process either exits, or calls <code>execve()</code>, at which point the parent process continues.</p> <p>This means that the child process of a <code>vfork()</code> must be careful to avoid unexpectedly modifying variables of the parent process. In particular, the child process must not return from the function containing the <code>vfork()</code> call, and it must not call <code>exit()</code> (if it needs to exit, it should use <code>_exit()</code>; actually, this is also true for the child of a normal <code>fork()</code>).</p> <p><code>Exec</code>: The exec call is a way to basically replace the entire current process with a new program. It loads the program into the current process space and runs it from the entry point. <code>exec()</code> replaces the current process with a the executable pointed by the function. Control never returns to the original program unless there is an <code>exec()</code> error.</p> <p><code>Clone</code>: <code>clone()</code>, as <code>fork()</code>, creates a new process. Unlike <code>fork()</code>, these calls allow the child process to share parts of its execution context with the calling process, such as the memory space, the table of file descriptors, and the table of signal handlers.</p> <p>When the child process is created with <code>clone()</code>, it executes the function application <em>fn(arg)</em> (This differs from <code>fork()</code>, where execution continues in the child from the point of the original <code>fork()</code> call.) The <em>fn</em> argument is a pointer to a function that is called by the child process at the beginning of its execution. The <em>arg</em> argument is passed to the <em>fn</em> function.</p> <p>When the <em>fn(arg)</em> function application returns, the child process terminates. The integer returned by <em>fn</em> is the exit code for the child process. The child process may also terminate explicitly by calling <code>exit(2)</code> or after receiving a fatal signal.</p> <p>Information gotten from:</p> <ul> <li><a href="https://stackoverflow.com/questions/1653340/exec-and-fork">Differences between fork and exec</a></li> <li><a href="http://www.allinterview.com/showanswers/59616.html" rel="nofollow noreferrer">http://www.allinterview.com/showanswers/59616.html</a></li> <li><a href="http://www.unixguide.net/unix/programming/1.1.2.shtml" rel="nofollow noreferrer">http://www.unixguide.net/unix/programming/1.1.2.shtml</a></li> <li><a href="http://linux.about.com/library/cmd/blcmdl2_clone.htm" rel="nofollow noreferrer">http://linux.about.com/library/cmd/blcmdl2_clone.htm</a></li> </ul> <p>Thanks for taking the time to read this ! :)</p>
<ul> <li><p><code>vfork()</code> is an obsolete optimization. Before good memory management, <code>fork()</code> made a full copy of the parent's memory, so it was pretty expensive. since in many cases a <code>fork()</code> was followed by <code>exec()</code>, which discards the current memory map and creates a new one, it was a needless expense. Nowadays, <code>fork()</code> doesn't copy the memory; it's simply set as "copy on write", so <code>fork()</code>+<code>exec()</code> is just as efficient as <code>vfork()</code>+<code>exec()</code>.</p></li> <li><p><code>clone()</code> is the syscall used by <code>fork()</code>. with some parameters, it creates a new process, with others, it creates a thread. the difference between them is just which data structures (memory space, processor state, stack, PID, open files, etc) are shared or not.</p></li> </ul>
{ "question_id": 4856255, "question_date": "2011-01-31T21:21:19.677Z", "question_score": 239, "tags": "linux|process|fork|exec|clone", "answer_id": 4856460, "answer_date": "2011-01-31T21:42:05.767Z", "answer_score": 186 }
Please answer the following Stack Overflow question: Title: Android Studio 3.0 Flavor Dimension Issue <p>Upgraded to Studio Canary build. My previous project of Telegram Messenger is giving following error.</p> <blockquote> <p>Error:All flavors must now belong to a named flavor dimension. The flavor 'armv7' is not assigned to a flavor dimension. Learn more at <a href="https://d.android.com/r/tools/flavorDimensions-missing-error-message.html" rel="noreferrer">https://d.android.com/r/tools/flavorDimensions-missing-error-message.html</a></p> </blockquote> <p>What should I do? I have already seen that link but couldn't understand what to do. I have 3 build variants now, release,debug and foss.</p>
<p>If you don't really need the mechanism, just specify a random flavor dimension in your <code>build.gradle</code>:</p> <pre><code>android { ... flavorDimensions "default" ... } </code></pre> <p>For more information, check the <a href="https://developer.android.com/studio/build/gradle-plugin-3-0-0-migration.html#flavor_dimensions" rel="noreferrer">migration guide</a> </p>
{ "question_id": 44105127, "question_date": "2017-05-22T05:19:32.040Z", "question_score": 239, "tags": "android|android-studio|gradle|armv7", "answer_id": 44105198, "answer_date": "2017-05-22T05:25:17.817Z", "answer_score": 566 }
Please answer the following Stack Overflow question: Title: What is the difference between MacVim and regular Vim? <p>I'm reasonably new to OS X, but I'm familiar with Vim from using it in various *nix systems. I've seen many people recommend running MacVim over Vim in the terminal. Can anyone tell me what differences there are between MacVim and regular Vim?</p>
<p><a href="http://code.google.com/p/macvim/" rel="noreferrer">MacVim</a> is just Vim. Anything you are used to do in Vim will work exactly the same way in MacVim.</p> <p>MacVim is more integrated in the whole OS than Vim in the Terminal or even GVim in Linux, it follows a lot of Mac OS X's conventions.</p> <p>If you work mainly with GUI apps (<a href="http://www.yummysoftware.com/" rel="noreferrer">YummyFTP</a> + <a href="https://github.com/brotherbard/gitx" rel="noreferrer">GitX</a> + <a href="http://www.charlesproxy.com/" rel="noreferrer">Charles</a>, for example) you may prefer MacVim. </p> <p>If you work mainly with CLI apps (ssh + svn + tcpdump, for example) you may prefer vim in the terminal.</p> <p>Entering and leaving one realm (CLI) for the other (GUI) and vice-versa can be "expensive".</p> <p>I use both MacVim and Vim depending on the task and the context: if I'm in CLI-land I'll just type <code>vim filename</code> and if I'm in GUI-land I'll just invoke Quicksilver and launch MacVim.</p> <p>When I switched from TextMate I kind of liked the fact that MacVim supported almost all of the regular shortcuts Mac users are accustomed to. I added some of my own, mimiking TextMate but, since I was working in multiple environments I forced my self to learn the vim way. Now I use both MacVim and Vim almost exactly the same way. Using one or the other is just a question of context for me.</p> <p>Also, like El Isra said, the default vim (CLI) in OS X is slightly outdated. You may install an up-to-date version via <a href="http://www.macports.org/" rel="noreferrer">MacPorts</a> or you can install MacVim and add an alias to your <code>.profile</code>:</p> <pre><code>alias vim='/path/to/MacVim.app/Contents/MacOS/Vim' </code></pre> <p>to have the same vim in MacVim and Terminal.app.</p> <p>Another difference is that many great colorschemes out there work out of the box in MacVim but look terrible in the Terminal.app which only supports 8 colors (+ highlights) but you can use <a href="http://code.google.com/p/iterm2/" rel="noreferrer">iTerm</a> — which can be set up to support 256 colors — instead of Terminal.</p> <p>So… basically my advice is to just use both.</p> <p><strong>EDIT:</strong> I didn't try it but the latest version of Terminal.app (in 10.7) is supposed to support 256 colors. I'm still on 10.6.x at work so I'll still use iTerm2 for a while.</p> <p><strong>EDIT:</strong> An even better way to use MacVim's CLI executable in your shell is to move the <code>mvim</code> script bundled with MacVim somewhere in your <code>$PATH</code> and use this command:</p> <pre><code>$ mvim -v </code></pre> <p><strong>EDIT:</strong> Yes, Terminal.app now supports 256 colors. So if you don't <em>need</em> iTerm2's advanced features you can safely use the default terminal emulator.</p>
{ "question_id": 5892547, "question_date": "2011-05-05T04:02:56.053Z", "question_score": 239, "tags": "macos|vim|text-editor|macvim", "answer_id": 5894021, "answer_date": "2011-05-05T07:19:03.440Z", "answer_score": 241 }
Please answer the following Stack Overflow question: Title: What's NSLocalizedString equivalent in Swift? <p>Is there an Swift equivalent of <code>NSLocalizedString(...)</code>? In <code>Objective-C</code>, we usually use:</p> <pre><code>NSString *string = NSLocalizedString(@"key", @"comment"); </code></pre> <p>How can I achieve the same in Swift? I found a function:</p> <pre><code>func NSLocalizedString( key: String, tableName: String? = default, bundle: NSBundle = default, value: String = default, #comment: String) -&gt; String </code></pre> <p>However, it is very long and not convenient at all.</p>
<p>The <code>NSLocalizedString</code> exists also in the Swift's world.</p> <pre><code>func NSLocalizedString( key: String, tableName: String? = default, bundle: NSBundle = default, value: String = default, #comment: String) -&gt; String </code></pre> <p>The <code>tableName</code>, <code>bundle</code>, and <code>value</code> parameters are marked with a <strong><code>default</code></strong> keyword which means we can omit these parameters while calling the function. In this case, their default values will be used.</p> <p>This leads to a conclusion that the method call can be simplified to:</p> <pre><code>NSLocalizedString("key", comment: "comment") </code></pre> <p><strong>Swift 5</strong> - no change, still works like that.</p>
{ "question_id": 25081757, "question_date": "2014-08-01T13:48:47.663Z", "question_score": 239, "tags": "ios|swift|localization|nslocalizedstring", "answer_id": 25081758, "answer_date": "2014-08-01T13:48:47.663Z", "answer_score": 291 }
Please answer the following Stack Overflow question: Title: Relatively position an element without it taking up space in document flow <p>How can I relatively position an element, and have it not take up space in the document flow?</p>
<p>What you're trying to do sounds like absolute positioning. On the other hand, you can, however, make a pseudo-relative element, by creating a zero-width, zero-height, relatively positioned element, essentially solely for the purpose of creating a reference point for position, and an absolutely positioned element within that:</p> <pre><code>&lt;div style="position: relative; width: 0; height: 0"&gt; &lt;div style="position: absolute; left: 100px; top: 100px"&gt; Hi there, I'm 100px offset from where I ought to be, from the top and left. &lt;/div&gt; &lt;/div&gt; </code></pre>
{ "question_id": 6040005, "question_date": "2011-05-18T04:49:41.417Z", "question_score": 239, "tags": "html|css|positioning|css-position", "answer_id": 6040258, "answer_date": "2011-05-18T05:30:02.130Z", "answer_score": 335 }
Please answer the following Stack Overflow question: Title: What's the difference between EscapeUriString and EscapeDataString? <p>If only deal with url encoding, I should use <a href="https://msdn.microsoft.com/en-us/library/system.uri.escapeuristring(v=vs.110).aspx">EscapeUriString</a>?</p>
<p>Use <code>EscapeDataString</code> always (for more info about why, see <a href="https://stackoverflow.com/a/34189188/68972">Livven's answer</a> below)</p> <p><strong>Edit</strong>: removed dead link to how the two differ on encoding</p>
{ "question_id": 4396598, "question_date": "2010-12-09T09:23:52.040Z", "question_score": 239, "tags": ".net|urlencode", "answer_id": 4396654, "answer_date": "2010-12-09T09:29:49.013Z", "answer_score": 128 }
Please answer the following Stack Overflow question: Title: Advantages to Using Private Static Methods <p>When creating a class that has internal private methods, usually to reduce code duplication, that don't require the use of any instance fields, are there performance or memory advantages to declaring the method as static?</p> <p>Example:</p> <pre><code>foreach (XmlElement element in xmlDoc.DocumentElement.SelectNodes("sample")) { string first = GetInnerXml(element, ".//first"); string second = GetInnerXml(element, ".//second"); string third = GetInnerXml(element, ".//third"); } </code></pre> <p>...</p> <pre><code>private static string GetInnerXml(XmlElement element, string nodeName) { return GetInnerXml(element, nodeName, null); } private static string GetInnerXml(XmlElement element, string nodeName, string defaultValue) { XmlNode node = element.SelectSingleNode(nodeName); return node == null ? defaultValue : node.InnerXml; } </code></pre> <p>Is there any advantage to declaring the GetInnerXml() methods as static? No opinion responses please, I have an opinion.</p>
<p>From the <a href="http://msdn.microsoft.com/en-us/library/ms245046.aspx" rel="noreferrer">FxCop rule page</a> on this:</p> <blockquote> <p>After you mark the methods as static, the compiler will emit non-virtual call sites to these members. Emitting non-virtual call sites will prevent a check at runtime for each call that ensures that the current object pointer is non-null. This can result in a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue.</p> </blockquote>
{ "question_id": 135020, "question_date": "2008-09-25T18:20:54.267Z", "question_score": 239, "tags": "c#|performance", "answer_id": 135038, "answer_date": "2008-09-25T18:24:24.523Z", "answer_score": 249 }
Please answer the following Stack Overflow question: Title: font-style: italic vs oblique in CSS <p>What is the difference between these two:</p> <pre><code>font-style:italic font-style:oblique </code></pre> <p>I tried using the <a href="http://www.w3schools.com/css/tryit.asp?filename=trycss_font-style" rel="noreferrer">W3Schools editor</a> but was unable to tell the difference.</p> <p>What am I missing?</p>
<p>In the purest (type designer) sense, an oblique is a roman font that has been skewed a certain number of degrees (8-12 degrees, usually). An italic is created by the type designer with specific characters (notably lowercase a) drawn differently to create a more calligraphic, as well as slanted version.</p> <p>Some type foundries have arbitrarily created obliques that aren't necessarily approved by the designers themselves... some fonts were meant not to be italicized or obliqued... but people did anyway. And as you may know, some operating systems will, upon clicking the 'italic' icon, skew the font and create an oblique on the fly. Not a pleasant sight.</p> <p>It's best to specify an italic only when you're sure that font has been designed with one.</p>
{ "question_id": 1680624, "question_date": "2009-11-05T13:34:12.790Z", "question_score": 239, "tags": "css|fonts", "answer_id": 1680673, "answer_date": "2009-11-05T13:42:41.917Z", "answer_score": 303 }
Please answer the following Stack Overflow question: Title: What's the correct way to sort Python `import x` and `from x import y` statements? <p>The <a href="http://www.python.org/dev/peps/pep-0008/#imports">python style guide</a> suggests to group imports like this:</p> <blockquote> <p>Imports should be grouped in the following order:</p> <ol> <li>standard library imports</li> <li>related third party imports</li> <li>local application/library specific imports</li> </ol> </blockquote> <p>However, it does not mention anything how the two different ways of imports should be laid out:</p> <pre><code>from foo import bar import foo </code></pre> <p>There are multiple ways to sort them (let's assume all those import belong to the same group):</p> <ul> <li><p>first <code>from..import</code>, then <code>import</code></p> <pre><code>from g import gg from x import xx import abc import def import x </code></pre></li> <li><p>first <code>import</code>, then <code>from..import</code></p> <pre><code>import abc import def import x from g import gg from x import xx </code></pre></li> <li><p>alphabetic order by module name, ignoring the kind of import</p> <pre><code>import abc import def from g import gg import x from xx import xx </code></pre></li> </ul> <p>PEP8 does not mention the preferred order for this and the "cleanup imports" features some IDEs have probably just do whatever the developer of that feature preferred.</p> <p><strong>I'm looking for another PEP clarifying this or a relevant comment/email from the <a href="http://en.wikipedia.org/wiki/Guido_van_Rossum">BDFL</a></strong> (or another Python core developer). <em>Please don't post subjective answers stating your own preference.</em></p>
<p>Imports are generally sorted alphabetically and described in various places besides PEP 8.</p> <p><strong>Alphabetically sorted modules are quicker to read and searchable</strong>. After all, Python is all about readability. Also, it is easier to verify that something is imported, and avoids duplicate imports.</p> <p>There is nothing available in PEP 8 regarding sorting. So it's all about choosing what you use.</p> <p>According to few references from reputable sites and repositories, also popularity, Alphabetical ordering is the way.</p> <p>for e.g. like this:</p> <pre><code>import httplib import logging import random import StringIO import time import unittest from nova.api import openstack from nova.auth import users from nova.endpoint import cloud </code></pre> <p>OR</p> <pre><code>import a_standard import b_standard import a_third_party import b_third_party from a_soc import f from a_soc import g from b_soc import d </code></pre> <p>Reddit official repository also states that In general PEP-8 import ordering should be used. However, there are a few additions which are that for each imported group the order of imports should be:</p> <pre><code>import &lt;package&gt;.&lt;module&gt; style lines in alphabetical order from &lt;package&gt;.&lt;module&gt; import &lt;symbol&gt; style in alphabetical order </code></pre> <p>References:</p> <ul> <li><a href="https://code.google.com/p/soc/wiki/PythonStyleGuide" rel="noreferrer">https://code.google.com/p/soc/wiki/PythonStyleGuide</a></li> <li><a href="https://github.com/reddit/reddit/wiki/PythonImportGuidelines" rel="noreferrer">https://github.com/reddit/reddit/wiki/PythonImportGuidelines</a></li> <li><a href="http://docs.openstack.org/developer/hacking/" rel="noreferrer">http://docs.openstack.org/developer/hacking/</a></li> <li><a href="http://developer.plone.org/reference_manuals/external/plone.api/contribute/conventions.html#grouping-and-sorting" rel="noreferrer">http://developer.plone.org/reference_manuals/external/plone.api/contribute/conventions.html#grouping-and-sorting</a></li> </ul> <p>PS: the <a href="https://pypi.python.org/pypi/isort/" rel="noreferrer">isort utility</a> automatically sorts your imports.</p>
{ "question_id": 20762662, "question_date": "2013-12-24T14:37:57.050Z", "question_score": 239, "tags": "python|coding-style|python-import|pep8", "answer_id": 20763446, "answer_date": "2013-12-24T15:48:50.043Z", "answer_score": 165 }
Please answer the following Stack Overflow question: Title: How to disable or hide scrollbar/minimap? <p>I can't find any option, setting, or keyboard shortcut that disables or hides that annoying scrollbar. I just don't find it useful and it's distracting.</p> <p>Can't just edit the editor's CSS like Atom, either.</p>
<h1>Remove Minimap</h1> <p>Add the following to your <code>settings.json</code> file</p> <pre><code>"editor.minimap.enabled": false </code></pre> <p><em>Note that, as pointed out in another answer, this process has now been simplified to:</em></p> <pre><code>View-&gt;Show Minimap </code></pre> <h1>Remove the Overview Ruler</h1> <p>Add the following to your <code>settings.json</code> file</p> <pre><code>"editor.hideCursorInOverviewRuler": true </code></pre> <p>This will keep the scrollbar, but will result in it only appearing when the cursor is within the editor, as seen in the image below:</p> <p><a href="https://i.stack.imgur.com/BNLOL.png" rel="noreferrer"><img src="https://i.stack.imgur.com/BNLOL.png" alt="enter image description here"></a></p> <p><H1>Completely remove scrollbars (requires restart)</H1></p> <p>If you would like to completely remove the scrollbars, add the following to your <code>settings.json</code> file (note the editor will say "Unknown configuration setting" - ignore this. It will still work):</p> <pre><code>"editor.scrollbar.horizontal": "hidden", "editor.scrollbar.vertical": "hidden" </code></pre> <p>This will result in the scrollbars not being visible even when the cursor is in the editor, as seen in the image below:</p> <p><a href="https://i.stack.imgur.com/PMjAE.png" rel="noreferrer"><img src="https://i.stack.imgur.com/PMjAE.png" alt="enter image description here"></a></p>
{ "question_id": 40891692, "question_date": "2016-11-30T15:06:32.833Z", "question_score": 239, "tags": "visual-studio-code|vscode-settings", "answer_id": 41481346, "answer_date": "2017-01-05T09:28:41.600Z", "answer_score": 332 }
Please answer the following Stack Overflow question: Title: How to check if there's nothing to be committed in the current branch? <p>The goal is to get an unambiguous status that can be evaluated in a shell command.</p> <p>I tried <code>git status</code> but it always returns 0, even if there are items to commit.</p> <pre class="lang-bash prettyprint-override"><code>git status echo $? #this is always 0 </code></pre> <p>I have an idea but I think it is rather a bad idea.</p> <pre class="lang-bash prettyprint-override"><code>if [ git status | grep -i -c &quot;[a-z]&quot;&gt; 2 ]; then code for change... else code for nothing change... fi </code></pre> <p>any other way?</p> <hr /> <p><strong>update with following solve, see Mark Longair's post</strong></p> <p>I tried this but it causes a problem.</p> <pre class="lang-bash prettyprint-override"><code>if [ -z $(git status --porcelain) ]; then echo &quot;IT IS CLEAN&quot; else echo &quot;PLEASE COMMIT YOUR CHANGE FIRST!!!&quot; echo git status fi </code></pre> <p>I get the following error <code>[: ??: binary operator expected</code></p> <p>now, I am looking at the man and try the git diff.</p> <p>===================code for my hope, and hope better answer======================</p> <pre class="lang-bash prettyprint-override"><code>#if [ `git status | grep -i -c &quot;$&quot;` -lt 3 ]; # change to below code,although the above code is simple, but I think it is not strict logical if [ `git diff --cached --exit-code HEAD^ &gt; /dev/null &amp;&amp; (git ls-files --other --exclude-standard --directory | grep -c -v '/$')` ]; then echo &quot;PLEASE COMMIT YOUR CHANGE FIRST!!!&quot; exit 1 else exit 0 fi </code></pre>
<p>An alternative to testing whether the output of <code>git status --porcelain</code> is empty is to test each condition you care about separately. One might not always care, for example, if there are untracked files in the output of <code>git status</code>.</p> <p>For example, to see if there are any local unstaged changes, you can look at the return code of:</p> <pre><code>git diff --exit-code </code></pre> <p>To check if there are any changes that are staged but not committed, you can use the return code of:</p> <pre><code>git diff --cached --exit-code </code></pre> <p>Finally, if you want to know about whether there are any untracked files in your working tree that aren't ignored, you can test whether the output of the following command is empty:</p> <pre><code>git ls-files --other --exclude-standard --directory </code></pre> <p><em>Update:</em> You ask below whether you can change that command to exclude the directories in the output. You can exclude empty directories by adding <code>--no-empty-directory</code>, but to exclude all directories in that output I think you'll have to filter the output, such as with:</p> <pre><code>git ls-files --other --exclude-standard --directory | egrep -v '/$' </code></pre> <p>The <code>-v</code> to <code>egrep</code> means to only output lines that don't match the pattern, and the pattern matches any line that ends with a <code>/</code>.</p>
{ "question_id": 5139290, "question_date": "2011-02-28T07:34:59.747Z", "question_score": 239, "tags": "git|git-status", "answer_id": 5139672, "answer_date": "2011-02-28T08:31:14.540Z", "answer_score": 292 }
Please answer the following Stack Overflow question: Title: Cannot install Lxml on Mac OS X 10.9 <p>I want to install Lxml so I can then install Scrapy.</p> <p>When I updated my Mac today it wouldn't let me reinstall lxml, I get the following error:</p> <pre><code>In file included from src/lxml/lxml.etree.c:314: /private/tmp/pip_build_root/lxml/src/lxml/includes/etree_defs.h:9:10: fatal error: 'libxml/xmlversion.h' file not found #include &quot;libxml/xmlversion.h&quot; ^ 1 error generated. error: command 'cc' failed with exit status 1 </code></pre> <p>I have tried using brew to install libxml2 and libxslt, both installed fine but I still cannot install lxml.</p> <p>Last time I was installing I needed to enable the developer tools on Xcode but since it's updated to Xcode 5 it doesn't give me that option anymore.</p> <p>Does anyone know what I need to do?</p>
<p>You should install or upgrade the commandline tool for Xcode. Try this in a terminal:</p> <pre><code>xcode-select --install </code></pre>
{ "question_id": 19548011, "question_date": "2013-10-23T17:07:32.370Z", "question_score": 239, "tags": "python|xcode|macos|scrapy|lxml", "answer_id": 19604913, "answer_date": "2013-10-26T09:10:16.523Z", "answer_score": 505 }
Please answer the following Stack Overflow question: Title: Xcode 'Build and Archive' menu item disabled <p>I have been using the new 'Build and Archive' feature of the latest Xcode 3.2.3. I like it.</p> <p>Now I noticed that it is always disabled for some reason. I can't seem to figure out what I changed to cause this.</p>
<p><img src="https://i.stack.imgur.com/uB65o.jpg" alt="iOS Device is selected and Archive is enabled"></p> <p>Build configiuration setting needs to be an "iOS Device" (or any specific device if connected) to activate "Product → Archive" menu item. For some strange reason when any kind of iOS Simulator is selected, Archive is greyed out.</p>
{ "question_id": 3087089, "question_date": "2010-06-21T17:51:44.543Z", "question_score": 239, "tags": "iphone|xcode", "answer_id": 3087101, "answer_date": "2010-06-21T17:53:16.703Z", "answer_score": 691 }
Please answer the following Stack Overflow question: Title: Explanation of [].slice.call in javascript? <p>I stumbled onto this neat shortcut for converting a DOM NodeList into a regular array, but I must admit, I don't completely understand how it works:</p> <pre><code>[].slice.call(document.querySelectorAll('a'), 0) </code></pre> <p>So it starts with an empty array <code>[]</code>, then <code>slice</code> is used to convert the result of <code>call</code> to a new array yeah?</p> <p>The bit I don't understand is the <code>call</code>. How does that convert <code>document.querySelectorAll('a')</code> from a NodeList to a regular array?</p>
<p>What's happening here is that you call <code>slice()</code> as if it was a function of <code>NodeList</code> using <code>call()</code>. What <code>slice()</code> does in this case is create an empty array, then iterate through the object it's running on (originally an array, now a <code>NodeList</code>) and keep appending the elements of that object to the empty array it created, which is eventually returned. Here's an <a href="http://shifteleven.com/articles/2007/06/28/array-like-objects-in-javascript" rel="noreferrer">article on this</a>.</p> <p><strong>EDIT:</strong></p> <blockquote> <p>So it starts with an empty array [], then slice is used to convert the result of call to a new array yeah?</p> </blockquote> <p>That's not right. <code>[].slice</code> returns a function object. A function object has a function <code>call()</code> which calls the function assigning the first parameter of the <code>call()</code> to <code>this</code>; in other words, making the function think that it's being called from the parameter (the <code>NodeList</code> returned by <code>document.querySelectorAll('a')</code>) rather than from an array.</p>
{ "question_id": 2125714, "question_date": "2010-01-24T02:48:55.680Z", "question_score": 239, "tags": "javascript|arrays|call|slice", "answer_id": 2125746, "answer_date": "2010-01-24T03:00:46.730Z", "answer_score": 178 }
Please answer the following Stack Overflow question: Title: Is there a limit to the length of HTML attributes? <p>How long is too long for an attribute value in HTML?</p> <p>I'm using HTML5 style data attributes (<code>data-foo="bar"</code>) in a new application, and in one place it would be really handy to store a fair whack of data (upwards of 100 characters). While I suspect that this amount is fine, it raises the question of how much is too much?</p>
<h2>HTML 4</h2> <p>From an HTML 4 perspective, attributes are an SGML construct. Their limits are defined in the <a href="http://www.w3.org/TR/html401/sgml/sgmldecl.html" rel="noreferrer">SGML Declaration of HTML 4</a>:</p> <pre> QUANTITY SGMLREF ATTCNT 60 -- increased -- ATTSPLEN 65536 -- These are the largest values -- LITLEN 65536 -- permitted in the declaration -- NAMELEN 65536 -- Avoid fixed limits in actual -- PILEN 65536 -- implementations of HTML UA's -- TAGLVL 100 TAGLEN 65536 GRPGTCNT 150 GRPCNT 64 </pre> <p>The value in question here is &quot;ATTSPLEN&quot; which would be the limit on an element's attribute specification list (which should be the total size of all attributes for that element). The note above mentions that fixed limits should be avoided, however, so it's likely that there is no real limit other than available memory in most implementations.</p> <h2>HTML 5</h2> <p>It would seem that <strong>HTML 5 has no limits</strong> on the length of attribute values.</p> <p>As <a href="http://dev.w3.org/html5/spec/Overview.html" rel="noreferrer">the spec</a> says, &quot;This version of HTML thus returns to a non-SGML basis.&quot;</p> <p>Later on, when describing how to parse HTML 5, the following passage appears (<strong>emphasis</strong> added):</p> <blockquote> <p>The algorithm described below places <strong>no limit</strong> on the depth of the DOM tree generated, or <strong>on the length of</strong> tag names, attribute names, <strong>attribute values</strong>, text nodes, etc. While implementors are encouraged to avoid arbitrary limits, it is recognized that practical concerns will likely force user agents to impose nesting depth constraints.</p> </blockquote> <p>Therefore, (theoretically) <em>there is no limit to the length/size of HTML 5 attributes</em>.</p>
{ "question_id": 1496096, "question_date": "2009-09-30T04:19:00.217Z", "question_score": 239, "tags": "html|custom-data-attribute", "answer_id": 1496165, "answer_date": "2009-09-30T04:54:12.417Z", "answer_score": 303 }
Please answer the following Stack Overflow question: Title: Orchestrating microservices <p>What is the standard pattern of orchestrating microservices?</p> <p>If a microservice only knows about its own domain, but there is a flow of data that requires that multiple services interact in some manner, what's the way to go about it?</p> <p>Let's say we have something like this:</p> <ul> <li>Invoicing</li> <li>Shipment</li> </ul> <p>And for the sake of the argument, let's say that once an order has been shipped, the invoice should be created. </p> <p>Somewhere, someone presses a button in a <code>GUI</code>, "I'm done, let's do this!" In a classic monolith service architecture, I'd say that there is either an <code>ESB</code> handling this, or the Shipment service has knowledge of the invoice service and just calls that.</p> <p>But what is the way people deal with this in this brave new world of microservices?</p> <p>I do get that this could be considered highly opinion-based. but there is a concrete side to it, as microservices are not supposed to do the above. So there has to be a "what should it by definition do instead", which is not opinion-based.</p> <p>Shoot.</p>
<p>The Book <a href="https://rads.stackoverflow.com/amzn/click/com/1491950358" rel="noreferrer" rel="nofollow noreferrer">Building Microservices</a> describes in detail the styles mentioned by @RogerAlsing in his answer.</p> <p>On page 43 under Orchestration vs Choreography the book says:</p> <blockquote> <p>As we start to model more and more complex logic, we have to deal with the problem of managing business processes that stretch across the boundary of individual services. And with microservices, we’ll hit this limit sooner than usual. [...] When it comes to actually implementing this flow, there are two styles of architecture we could follow. With orchestration, we rely on a central brain to guide and drive the process, much like the conductor in an orchestra. With choreography, we inform each part of the system of its job and let it work out the details, like dancers all find‐ ing their way and reacting to others around them in a ballet.</p> </blockquote> <p>The book then proceeds to explain the two styles. The orchestration style corresponds more to the SOA idea of <a href="http://serviceorientation.com/soamethodology/task_services" rel="noreferrer">orchestration/task services</a>, whereas the choreography style corresponds to the <a href="http://martinfowler.com/articles/microservices.html#SmartEndpointsAndDumbPipes" rel="noreferrer">dumb pipes and smart endpoints</a> mentioned in Martin Fowler's article.</p> <p><strong>Orchestration Style</strong></p> <p>Under this style, the book above mentions:</p> <blockquote> <p>Let’s think about what an orchestration solution would look like for this flow. Here, probably the simplest thing to do would be to have our customer service act as the central brain. On creation, it talks to the loyalty points bank, email service, and postal service [...], through a series of request/response calls. The customer service itself can then track where a customer is in this process. It can check to see if the customer’s account has been set up, or the email sent, or the post delivered. We get to take the flowchart [...] and model it directly into code. We could even use tooling that implements this for us, perhaps using an appropriate rules engine. Commercial tools exist for this very purpose in the form of business process modeling software. Assuming we use synchronous request/response, we could even know if each stage has worked [...] The downside to this orchestration approach is that the customer service can become too much of a central governing authority. It can become the hub in the middle of a web and a central point where logic starts to live. I have seen this approach result in a small number of smart “god” services telling anemic CRUD-based services what to do.</p> </blockquote> <p>Note: I suppose that when the author mentions tooling he's referring to something like <a href="http://en.wikipedia.org/wiki/Business_process_modeling" rel="noreferrer">BPM</a> (e.g. <a href="http://activiti.org/" rel="noreferrer">Activity</a>, <a href="http://ode.apache.org" rel="noreferrer">Apache ODE</a>, <a href="http://camunda.com" rel="noreferrer">Camunda</a>). As a matter of fact, the <a href="http://workflowpatterns.com" rel="noreferrer">Workflow Patterns Website</a> has an awesome set of patterns to do this kind of orchestration and it also offers evaluation details of different vendor tools that help to implement it this way. I don't think the author implies one is required to use one of these tools to implement this style of integration though, other lightweight orchestration frameworks could be used e.g. <a href="https://projects.spring.io/spring-integration/" rel="noreferrer">Spring Integration</a>, <a href="http://camel.apache.org" rel="noreferrer">Apache Camel</a> or <a href="https://www.mulesoft.com/platform/soa/mule-esb-open-source-esb" rel="noreferrer">Mule ESB</a></p> <p>However, <a href="http://www.oreilly.com/programming/free/software-architecture-patterns.csp" rel="noreferrer">other books</a> I've read on the topic of Microservices and in general the majority of articles I've found in the web seem to <a href="https://www.thoughtworks.com/insights/blog/scaling-microservices-event-stream" rel="noreferrer">disfavor this approach</a> of orchestration and instead suggest using the next one.</p> <p><strong>Choreography Style</strong></p> <p>Under choreography style the author says:</p> <blockquote> <p>With a choreographed approach, we could instead just have the customer service emit an event in an asynchronous manner, saying Customer created. The email service, postal service, and loyalty points bank then just subscribe to these events and react accordingly [...] This approach is significantly more decoupled. If some other service needed to reach to the creation of a customer, it just needs to subscribe to the events and do its job when needed. The downside is that the explicit view of the business process we see in [the workflow] is now only implicitly reflected in our system [...] This means additional work is needed to ensure that you can monitor and track that the right things have happened. For example, would you know if the loyalty points bank had a bug and for some reason didn’t set up the correct account? One approach I like for dealing with this is to build a monitoring system that explicitly matches the view of the business process in [the workflow], but then tracks what each of the services do as independent entities, letting you see odd exceptions mapped onto the more explicit process flow. The [flowchart] [...] isn’t the driving force, but just one lens through which we can see how the system is behaving. In general, I have found that systems that tend more toward the choreographed approach are more loosely coupled, and are more flexible and amenable to change. You do need to do extra work to monitor and track the processes across system boundaries, however. I have found most heavily orchestrated implementations to be extremely brittle, with a higher cost of change. With that in mind, I strongly prefer aiming for a choreographed system, where each service is smart enough to understand its role in the whole dance.</p> </blockquote> <p>Note: To this day I'm still not sure if choreography is just another name for <a href="http://radar.oreilly.com/2015/02/variations-in-event-driven-architecture.html" rel="noreferrer">event-driven architecture</a> (EDA), but if EDA is just one way to do it, what are the other ways? (Also see <a href="https://martinfowler.com/articles/201701-event-driven.html" rel="noreferrer">What do you mean by "Event-Driven"?</a> and <a href="https://www.youtube.com/watch?v=STKCRSUsyP0" rel="noreferrer">The Meanings of Event-Driven Architecture</a>). Also, it seems that things like CQRS and EventSourcing resonate a lot with this architectural style, right?</p> <p>Now, after this comes the fun. The Microservices book does not assume microservices are going to be implemented with REST. As a matter of fact in the next section in the book, they proceed to consider RPC and SOA-based solutions and finally REST. An important point here is that Microservices does not imply REST.</p> <p><strong>So, What About HATEOAS?</strong> <em>(Hypermedia as the Engine of Application State)</em></p> <p>Now, if we want to follow the RESTful approach we cannot ignore HATEOAS or Roy Fielding will be very much pleased to say in his blog that our solution is not truly REST. See his blog post on <a href="http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven" rel="noreferrer">REST API Must be Hypertext Driven</a>:</p> <blockquote> <p>I am getting frustrated by the number of people calling any HTTP-based interface a REST API. What needs to be done to make the REST architectural style clear on the notion that hypertext is a constraint? In other words, if the engine of application state (and hence the API) is not being driven by hypertext, then it cannot be RESTful and cannot be a REST API. Period. Is there some broken manual somewhere that needs to be fixed?</p> </blockquote> <p>So, as you can see, Fielding thinks that without HATEOAS you are not truly building RESTful applications. For Fielding, HATEOAS is the way to go when it comes to orchestrating services. I am just learning all this, but to me, HATEOAS does not clearly define who or what is the driving force behind actually following the links. In a UI that could be the user, but in computer-to-computer interactions, I suppose that needs to be done by a higher level service.</p> <p>According to HATEOAS, the only link the API consumer truly needs to know is the one that initiates the communication with the server (e.g. POST /order). From this point on, REST is going to conduct the flow, because, in the response of this endpoint, the resource returned will contain the links to the next possible states. The API consumer then decides what link to follow and move the application to the next state.</p> <p>Despite how cool that sounds, the client still needs to know if the link must be POSTed, PUTed, GETed, PATCHed, etc. And the client still needs to decide what payload to pass. The client still needs to be aware of what to do if that fails (retry, compensate, cancel, etc.).</p> <p>I am fairly new to all this, but for me, from HATEOAs perspective, this client, or API consumer is a high order service. If we think it from the perspective of a human, you can imagine an end-user on a web page, deciding what links to follow, but still, the programmer of the web page had to decide what method to use to invoke the links, and what payload to pass. So, to my point, in a computer-to-computer interaction, the computer takes the role of the end-user. Once more this is what we call an orchestrations service.</p> <p>I suppose we can use HATEOAS with either orchestration or choreography. </p> <p><strong>The API Gateway Pattern</strong></p> <p>Another interesting pattern is suggested by Chris Richardson who also proposed what he called an <a href="http://www.infoq.com/articles/microservices-intro" rel="noreferrer">API Gateway Pattern</a>.</p> <blockquote> <p>In a monolithic architecture, clients of the application, such as web browsers and native applications, make HTTP requests via a load balancer to one of N identical instances of the application. But in a microservice architecture, the monolith has been replaced by a collection of services. Consequently, a key question we need to answer is what do the clients interact with?</p> <p>An application client, such as a native mobile application, could make RESTful HTTP requests to the individual services [...] On the surface this might seem attractive. However, there is likely to be a significant mismatch in granularity between the APIs of the individual services and data required by the clients. For example, displaying one web page could potentially require calls to large numbers of services. Amazon.com, for example, <a href="http://highscalability.com/amazon-architecture" rel="noreferrer">describes</a> how some pages require calls to 100+ services. Making that many requests, even over a high-speed internet connection, let alone a lower-bandwidth, higher-latency mobile network, would be very inefficient and result in a poor user experience.</p> <p>A much better approach is for clients to make a small number of requests per-page, perhaps as few as one, over the Internet to a front-end server known as an API gateway.</p> <p>The API gateway sits between the application’s clients and the microservices. It provides APIs that are tailored to the client. The API gateway provides a coarse-grained API to mobile clients and a finer-grained API to desktop clients that use a high-performance network. In this example, the desktop clients make multiple requests to retrieve information about a product, whereas a mobile client makes a single request.</p> <p>The API gateway handles incoming requests by making requests to some number of microservices over the high-performance LAN. Netflix, for example, <a href="http://techblog.netflix.com/2013/01/optimizing-netflix-api.html" rel="noreferrer">describes</a> how each request fans out to on average six backend services. In this example, fine-grained requests from a desktop client are simply proxied to the corresponding service, whereas each coarse-grained request from a mobile client is handled by aggregating the results of calling multiple services.</p> <p>Not only does the API gateway optimize communication between clients and the application, but it also encapsulates the details of the microservices. This enables the microservices to evolve without impacting the clients. For example, two microservices might be merged. Another microservice might be partitioned into two or more services. Only the API gateway needs to be updated to reflect these changes. The clients are unaffected.</p> <p>Now that we have looked at how the API gateway mediates between the application and its clients, let’s now look at how to implement communication between microservices.</p> </blockquote> <p>This sounds pretty similar to the orchestration style mentioned above, just with a slightly different intent, in this case, it seems to be all about performance and simplification of interactions.</p>
{ "question_id": 29117570, "question_date": "2015-03-18T08:52:56.987Z", "question_score": 239, "tags": "http|orchestration|hypermedia|microservices", "answer_id": 30441546, "answer_date": "2015-05-25T15:27:12.350Z", "answer_score": 359 }
Please answer the following Stack Overflow question: Title: In Unix, can I run 'make' in a directory without cd'ing to that directory first? <p>In Unix, can I run <code>make</code> in a directory without <code>cd</code>'ing to that directory first?</p>
<p><code>make -C /path/to/dir</code></p>
{ "question_id": 453447, "question_date": "2009-01-17T15:31:29.840Z", "question_score": 239, "tags": "linux|unix|makefile", "answer_id": 453450, "answer_date": "2009-01-17T15:33:52.877Z", "answer_score": 384 }
Please answer the following Stack Overflow question: Title: Logging uncaught exceptions in Python <p>How do you cause uncaught exceptions to output via the <code>logging</code> module rather than to <code>stderr</code>?</p> <p>I realize the best way to do this would be:</p> <pre><code>try: raise Exception, 'Throwing a boring exception' except Exception, e: logging.exception(e) </code></pre> <p>But my situation is such that it would be <em>really nice</em> if <code>logging.exception(...)</code> were invoked automatically whenever an exception isn't caught.</p>
<p>As Ned pointed out, <code>sys.excepthook</code> is invoked every time an exception is raised and uncaught. The practical implication of this is that in your code you can override the default behavior of <code>sys.excepthook</code> to do whatever you want (including using <code>logging.exception</code>).</p> <p>As a straw man example:</p> <pre><code>import sys def foo(exctype, value, tb): print('My Error Information') print('Type:', exctype) print('Value:', value) print('Traceback:', tb) </code></pre> <p>Override <code>sys.excepthook</code>:</p> <pre><code>&gt;&gt;&gt; sys.excepthook = foo </code></pre> <p>Commit obvious syntax error (leave out the colon) and get back custom error information:</p> <pre><code>&gt;&gt;&gt; def bar(a, b) My Error Information Type: &lt;type 'exceptions.SyntaxError'&gt; Value: invalid syntax (&lt;stdin&gt;, line 1) Traceback: None </code></pre> <p>For more information about <code>sys.excepthook</code>, read <a href="http://docs.python.org/library/sys.html#sys.excepthook" rel="noreferrer">the docs</a>.</p>
{ "question_id": 6234405, "question_date": "2011-06-04T02:53:22.397Z", "question_score": 239, "tags": "python|logging|exception-handling", "answer_id": 6234491, "answer_date": "2011-06-04T03:26:14.740Z", "answer_score": 167 }
Please answer the following Stack Overflow question: Title: Why is Linux called a monolithic kernel? <p>I read that Linux is a monolithic kernel. Does monolithic kernel mean compiling and linking the complete kernel code into an executable?</p> <p>If Linux is able to support modules, why not break all the subsystems into modules and load them when necessary? In that case, the kernel doesn't have to load all modules initially and could maintain an index of the functions in the module and load them when necessary.</p>
<p>A monolithic kernel is a kernel where all services (file system, VFS, device drivers, etc) as well as core functionality (scheduling, memory allocation, etc.) are a tight knit group sharing the same space. This directly opposes a <em>microkernel</em>.</p> <p>A microkernel prefers an approach where core functionality is isolated from system services and device drivers (which are basically just system services). For instance, VFS (virtual file system) and block device file systems (i.e. minixfs) are separate processes that run outside of the kernel's space, using IPC to communicate with the kernel, other services and user processes. In short, if it's a <em>module</em> in Linux, it's a <em>service</em> in a microkernel, indicating an isolated process.</p> <p>Do not confuse the term <em>modular</em> kernel to be anything but monolithic. Some monolithic kernels can be compiled to be modular (e.g Linux), what matters is that the module is inserted to and runs from the same space that handles core functionality (kernel space).</p> <p>The advantage to a microkernel is that any failed service can be easily restarted, for instance, there is no kernel halt if the root file system throws an abort. This can also be seen as a disadvantage, though, because it can hide pretty critical bugs (or make them seem not-so-critical, because the problem seems to continuously fix itself). It's seen as a big advantage in scenarios where you simply can't conveniently fix something once it has been deployed. </p> <p>The disadvantage to a microkernel is that asynchronous IPC messaging can become very difficult to debug, especially if <a href="http://lwn.net/Articles/219954/" rel="noreferrer">fibrils</a> are implemented. Additionally, just tracking down a FS/write issue means examining the user space process, the block device service, VFS service, file system service and (possibly) the PCI service. If you get a blank on that, its time to look at the IPC service. This is often easier in a monolithic kernel. <a href="http://www.gnu.org/software/hurd/" rel="noreferrer">GNU Hurd</a> suffers from these debugging problems (<a href="http://www.gnu.org/software/hurd/open_issues/bash.html" rel="noreferrer">reference</a>). I'm not even going to go into checkpointing when dealing with complex message queues. Microkernels are not for the faint of heart.</p> <p>The shortest path to a working, stable kernel is the monolithic approach. Either approach can offer a POSIX interface, where the design of the kernel becomes of little interest to someone simply wanting to write code to run on any given design.</p> <p>I use Linux (monolithic) in production. However, most of my learning, hacking or tinkering with kernel development goes into a microkernel, specifically <a href="http://helenos.org" rel="noreferrer">HelenOS</a>.</p> <p><strong>Edit</strong></p> <p>If you got this far through my very long-winded answer, you will probably have some fun reading the '<a href="http://oreilly.com/catalog/opensources/book/appa.html" rel="noreferrer">Great Torvalds-Tanenbaum debate on kernel design</a>'. It's even funnier to read in 2013, more than 20 years after it transpired. The funniest part was Linus' signature in one of the last messages:</p> <pre><code>Linus "my first, and hopefully last flamefest" Torvalds </code></pre> <p>Obviously, that did not come true any more than Tanenbaum's prediction that x86 would soon be obsolete.</p> <p><strong>NB:</strong></p> <p>When I say "Minix", I do not imply Minix 3. Additionally, when I mention The HURD, I am referencing (mostly) the Mach microkernel. It is not my intent to disparage the recent work of others. </p>
{ "question_id": 1806585, "question_date": "2009-11-27T03:16:22.377Z", "question_score": 239, "tags": "architecture|operating-system|linux-kernel", "answer_id": 1806597, "answer_date": "2009-11-27T03:21:35.267Z", "answer_score": 320 }
Please answer the following Stack Overflow question: Title: What does this Google Play APK publish error message mean? <p>I'm trying to publish a new version of my Android app to Google Play and get the following error? </p> <blockquote> <p>This configuration cannot be published for the following reason(s): Version 1 is not served to any device configuration: all devices that might receive version 1 would receive version 4</p> </blockquote> <p>I don't understand it. What does it mean? </p> <p><img src="https://i.stack.imgur.com/1Ma2n.png" alt="enter image description here"></p>
<p>This happened to me when I published two APKs (versions 3 and then 4) in a short space of time. Clicking "Deactivate" on the dropdown next to version 3 appeared to fix it.</p> <p>My guess is that this is a very-poorly-worded error message meaning something like "your original APK hasn't been published to all the update servers yet, so some of them may miss that version entirely". But it's a bit of a guess.</p>
{ "question_id": 16060655, "question_date": "2013-04-17T12:56:17.797Z", "question_score": 239, "tags": "android|google-play", "answer_id": 17935218, "answer_date": "2013-07-29T22:21:16.507Z", "answer_score": 304 }
Please answer the following Stack Overflow question: Title: Libraries do not get added to APK anymore after upgrade to ADT 22 <p>I have a rather big Android App project that is referencing several library projects. Everything was fine until i upgraded the eclipse ADT plugin to the newest version (v22). I also upgraded the SDK of course. I do not see any compile errors in eclipse, but when i run the project on the phone i get a NoClassDefFoundError.</p> <pre><code>java.lang.NoClassDefFoundError: org.acra.ACRA .... </code></pre> <p>The arca library is included in one of the referenced library project (in the libs folder) and i can see it in the "Android Private Libraries" in the package explorer, also as i said, no compile errors. The project runs fine on everyone else's computer that did not upgrade ADT.</p> <p>I have already tried a whole bunch of stuff including but not limited to:</p> <ul> <li>re-install the android SDK</li> <li>download a fresh ADT bundle</li> <li>delete all my code an get it again from git</li> <li>copy the library in question to the app project</li> <li>comment out the code that uses this library - i just get the same error for the next library</li> </ul> <p>all without any success, so i'm getting really desperate here.</p> <p>I would be really happy if anyone could give me a hint on how to solve that problem.</p>
<p>Quoting Streets of Boston from <a href="https://groups.google.com/group/adt-dev/msg/ffe750835576b445" rel="noreferrer">his adt-dev post</a>:</p> <blockquote> <p>When upgrading, the 'Order and Export' of the new 'Android Private Libraries' is not always checked. And the android-support-v4.jar is now in this 'Android Private Libraries' section. </p> <p>To fix this, go to 'Order and Export' and check 'Android Private Libraries'. Then refresh/clean/rebuild. </p> <p>After you done this 'fix' for a library project, you may need to just close and re-open any depending project, because they may not see this 'fix' immediately. </p> </blockquote> <p>Give this a shot and with luck it will solve your problem.</p> <p><img src="https://i.stack.imgur.com/SbEWS.png" alt="enter image description here"></p>
{ "question_id": 16596969, "question_date": "2013-05-16T20:34:17.247Z", "question_score": 239, "tags": "android|eclipse|adt", "answer_id": 16596990, "answer_date": "2013-05-16T20:35:38.300Z", "answer_score": 337 }
Please answer the following Stack Overflow question: Title: Optimise PostgreSQL for fast testing <p>I am switching to PostgreSQL from SQLite for a typical Rails application.</p> <p>The problem is that running specs became slow with PG.<br> On SQLite it took ~34 seconds, on PG it's ~76 seconds which is <strong>more than 2x slower</strong>.</p> <p>So now I want to apply some techniques to <strong>bring the performance of the specs on par with SQLite</strong> with no code modifications (ideally just by setting the connection options, which is probably not possible).</p> <p>Couple of obvious things from top of my head are:</p> <ul> <li>RAM Disk (good setup with RSpec on OSX would be good to see)</li> <li>Unlogged tables (can it be applied on the whole database so I don't have change all the scripts?)</li> </ul> <p>As you may have understood I don't care about reliability and the rest (the DB is just a throwaway thingy here).<br> I need to get the most out of the PG and make it <strong>as fast as it can possibly be</strong>.</p> <p><strong>Best answer</strong> would ideally describe the <em>tricks</em> for doing just that, setup and the drawbacks of those tricks.</p> <p><strong>UPDATE:</strong> <code>fsync = off</code> + <code>full_page_writes = off</code> only decreased time to ~65 seconds (~-16 secs). Good start, but far from the target of 34.</p> <p><strong>UPDATE 2:</strong> I <a href="https://gist.github.com/1573414" rel="noreferrer">tried to use RAM disk</a> but the performance gain was within an error margin. So doesn't seem to be worth it.</p> <p><strong>UPDATE 3:*</strong> I found the biggest bottleneck and now my specs run as fast as the SQLite ones.</p> <p>The issue was the database cleanup that did the <strong>truncation</strong>. Apparently SQLite is way too fast there.</p> <p>To "fix" it I open a <strong>transaction</strong> before each test and roll it back at the end.</p> <p>Some numbers for ~700 tests.</p> <ul> <li>Truncation: SQLite - 34s, PG - 76s.</li> <li>Transaction: SQLite - 17s, PG - 18s.</li> </ul> <p>2x speed increase for SQLite. 4x speed increase for PG.</p>
<p>First, always use the latest version of PostgreSQL. Performance improvements are always coming, so you're probably wasting your time if you're tuning an old version. For example, <a href="https://stackoverflow.com/questions/11419536/postgresql-truncation-speed/11423886#11423886">PostgreSQL 9.2 significantly improves the speed of <code>TRUNCATE</code></a> and of course adds index-only scans. Even minor releases should always be followed; see the <a href="http://www.postgresql.org/support/versioning/" rel="noreferrer">version policy</a>.</p> <h2>Don'ts</h2> <p><a href="http://www.postgresql.org/docs/devel/static/manage-ag-tablespaces.html" rel="noreferrer">Do <em>NOT</em> put a tablespace on a RAMdisk or other non-durable storage</a>.</p> <p>If you lose a tablespace the whole database may be damaged and hard to use without significant work. There's very little advantage to this compared to just using <code>UNLOGGED</code> tables and having lots of RAM for cache anyway.</p> <p>If you truly want a ramdisk based system, <code>initdb</code> a whole new cluster on the ramdisk by <code>initdb</code>ing a new PostgreSQL instance on the ramdisk, so you have a completely disposable PostgreSQL instance.</p> <h2>PostgreSQL server configuration</h2> <p>When testing, you can configure your server for <a href="http://www.postgresql.org/docs/current/static/non-durability.html" rel="noreferrer">non-durable but faster operation</a>.</p> <p>This is one of the only acceptable uses for the <a href="http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-FSYNC" rel="noreferrer"><code>fsync=off</code></a> setting in PostgreSQL. This setting pretty much tells PostgreSQL not to bother with ordered writes or any of that other nasty data-integrity-protection and crash-safety stuff, giving it permission to totally trash your data if you lose power or have an OS crash.</p> <p>Needless to say, you should never enable <code>fsync=off</code> in production unless you're using Pg as a temporary database for data you can re-generate from elsewhere. If and only if you're doing to turn fsync off can also turn <a href="http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-FULL-PAGE-WRITES" rel="noreferrer"><code>full_page_writes</code></a> off, as it no longer does any good then. Beware that <code>fsync=off</code> and <code>full_page_writes</code> apply at the <em>cluster</em> level, so they affect <em>all</em> databases in your PostgreSQL instance.</p> <p>For production use you can possibly use <code>synchronous_commit=off</code> and set a <code>commit_delay</code>, as you'll get many of the same benefits as <code>fsync=off</code> without the giant data corruption risk. You do have a small window of loss of recent data if you enable async commit - but that's it.</p> <p>If you have the option of slightly altering the DDL, you can also use <code>UNLOGGED</code> tables in Pg 9.1+ to completely avoid WAL logging and gain a real speed boost at the cost of the tables getting erased if the server crashes. There is no configuration option to make all tables unlogged, it must be set during <code>CREATE TABLE</code>. In addition to being good for testing this is handy if you have tables full of generated or unimportant data in a database that otherwise contains stuff you need to be safe.</p> <p>Check your logs and see if you're getting warnings about too many checkpoints. If you are, you should increase your <a href="http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-CHECKPOINT-SEGMENTS" rel="noreferrer">checkpoint_segments</a>. You may also want to tune your checkpoint_completion_target to smooth writes out.</p> <p>Tune <code>shared_buffers</code> to fit your workload. This is OS-dependent, depends on what else is going on with your machine, and requires some trial and error. The defaults are extremely conservative. You may need to increase the OS's maximum shared memory limit if you increase <code>shared_buffers</code> on PostgreSQL 9.2 and below; 9.3 and above changed how they use shared memory to avoid that.</p> <p>If you're using a just a couple of connections that do lots of work, increase <code>work_mem</code> to give them more RAM to play with for sorts etc. Beware that too high a <code>work_mem</code> setting can cause out-of-memory problems because it's per-sort not per-connection so one query can have many nested sorts. You only <em>really</em> have to increase <code>work_mem</code> if you can see sorts spilling to disk in <code>EXPLAIN</code> or logged with the <a href="http://www.postgresql.org/docs/current/static/runtime-config-logging.html#GUC-LOG-TEMP-FILES" rel="noreferrer"><code>log_temp_files</code> setting</a> (recommended), but a higher value may also let Pg pick smarter plans.</p> <p>As said by another poster here it's wise to put the xlog and the main tables/indexes on separate HDDs if possible. Separate partitions is pretty pointless, you really want separate drives. This separation has much less benefit if you're running with <code>fsync=off</code> and almost none if you're using <code>UNLOGGED</code> tables.</p> <p>Finally, tune your queries. Make sure that your <code>random_page_cost</code> and <code>seq_page_cost</code> reflect your system's performance, ensure your <code>effective_cache_size</code> is correct, etc. Use <code>EXPLAIN (BUFFERS, ANALYZE)</code> to examine individual query plans, and turn the <code>auto_explain</code> module on to report all slow queries. You can often improve query performance dramatically just by creating an appropriate index or tweaking the cost parameters.</p> <p>AFAIK there's no way to set an entire database or cluster as <code>UNLOGGED</code>. It'd be interesting to be able to do so. Consider asking on the PostgreSQL mailing list.</p> <h2>Host OS tuning</h2> <p>There's some tuning you can do at the operating system level, too. The main thing you might want to do is convince the operating system not to flush writes to disk aggressively, since you really don't care when/if they make it to disk.</p> <p>In Linux you can control this with the <a href="http://www.kernel.org/doc/Documentation/sysctl/vm.txt" rel="noreferrer">virtual memory subsystem</a>'s <code>dirty_*</code> settings, like <code>dirty_writeback_centisecs</code>.</p> <p>The only issue with tuning writeback settings to be too slack is that a flush by some other program may cause all PostgreSQL's accumulated buffers to be flushed too, causing big stalls while everything blocks on writes. You may be able to alleviate this by running PostgreSQL on a different file system, but some flushes may be device-level or whole-host-level not filesystem-level, so you can't rely on that.</p> <p>This tuning really requires playing around with the settings to see what works best for your workload.</p> <p>On newer kernels, you may wish to ensure that <code>vm.zone_reclaim_mode</code> is set to zero, as it can cause severe performance issues with NUMA systems (most systems these days) due to interactions with how PostgreSQL manages <code>shared_buffers</code>.</p> <h2>Query and workload tuning</h2> <p>These are things that DO require code changes; they may not suit you. Some are things you might be able to apply.</p> <p>If you're not batching work into larger transactions, start. Lots of small transactions are expensive, so you should batch stuff whenever it's possible and practical to do so. If you're using async commit this is less important, but still highly recommended.</p> <p>Whenever possible use temporary tables. They don't generate WAL traffic, so they're lots faster for inserts and updates. Sometimes it's worth slurping a bunch of data into a temp table, manipulating it however you need to, then doing an <code>INSERT INTO ... SELECT ...</code> to copy it to the final table. Note that temporary tables are per-session; if your session ends or you lose your connection then the temp table goes away, and no other connection can see the contents of a session's temp table(s).</p> <p>If you're using PostgreSQL 9.1 or newer you can use <a href="http://www.postgresql.org/docs/9.1/static/sql-createtable.html#AEN67422" rel="noreferrer"><code>UNLOGGED</code></a> tables for data you can afford to lose, like session state. These are visible across different sessions and preserved between connections. They get truncated if the server shuts down uncleanly so they can't be used for anything you can't re-create, but they're great for caches, materialized views, state tables, etc.</p> <p>In general, don't <code>DELETE FROM blah;</code>. Use <code>TRUNCATE TABLE blah;</code> instead; it's a lot quicker when you're dumping all rows in a table. Truncate many tables in one <code>TRUNCATE</code> call if you can. There's a caveat if you're doing lots of <code>TRUNCATES</code> of small tables over and over again, though; see: <a href="https://stackoverflow.com/questions/11419536/postgresql-truncation-speed/11423886#11423886">Postgresql Truncation speed</a></p> <p>If you don't have indexes on foreign keys, <code>DELETE</code>s involving the primary keys referenced by those foreign keys will be horribly slow. Make sure to create such indexes if you ever expect to <code>DELETE</code> from the referenced table(s). Indexes are not required for <code>TRUNCATE</code>.</p> <p>Don't create indexes you don't need. Each index has a maintenance cost. Try to use a minimal set of indexes and let bitmap index scans combine them rather than maintaining too many huge, expensive multi-column indexes. Where indexes are required, try to populate the table first, then create indexes at the end.</p> <h2>Hardware</h2> <p>Having enough RAM to hold the entire database is a huge win if you can manage it.</p> <p>If you don't have enough RAM, the faster storage you can get the better. Even a cheap SSD makes a massive difference over spinning rust. Don't trust cheap SSDs for production though, they're often not crashsafe and might eat your data.</p> <h2>Learning</h2> <p>Greg Smith's book, <a href="http://www.packtpub.com/postgresql-90-high-performance/book" rel="noreferrer">PostgreSQL 9.0 High Performance</a> remains relevant despite referring to a somewhat older version. It should be a useful reference.</p> <p>Join the PostgreSQL general mailing list and follow it.</p> <h2>Reading:</h2> <ul> <li><a href="http://wiki.postgresql.org/wiki/Tuning_Your_PostgreSQL_Server" rel="noreferrer">Tuning your PostgreSQL server - PostgreSQL wiki</a></li> <li><a href="http://wiki.postgresql.org/wiki/Number_Of_Database_Connections" rel="noreferrer">Number of database connections - PostgreSQL wiki</a></li> </ul>
{ "question_id": 9407442, "question_date": "2012-02-23T04:59:33.033Z", "question_score": 239, "tags": "sql|database|performance|postgresql|database-tuning", "answer_id": 9407940, "answer_date": "2012-02-23T05:57:55.443Z", "answer_score": 318 }
Please answer the following Stack Overflow question: Title: Difference between DateTime and Time in Ruby <p>What's the difference between <code>DateTime</code> and <code>Time</code> classes in Ruby and what factors would cause me to choose one or the other?</p>
<p>Newer versions of Ruby (2.0+) do not really have significant differences between the two classes. Some libraries will use one or the other for historical reasons, but new code does not necessarily need to be concerned. Picking one for consistency is probably best, so try and mesh with what your libraries expect. For example, ActiveRecord prefers DateTime.</p> <p>In versions prior to Ruby 1.9 and on many systems Time is represented as a 32-bit signed value describing the number of seconds since January 1, 1970 UTC, a thin wrapper around a POSIX-standard <code>time_t</code> value, and is bounded:</p> <pre><code>Time.at(0x7FFFFFFF) # =&gt; Mon Jan 18 22:14:07 -0500 2038 Time.at(-0x7FFFFFFF) # =&gt; Fri Dec 13 15:45:53 -0500 1901 </code></pre> <p>Newer versions of Ruby are able to handle larger values without producing errors.</p> <p>DateTime is a calendar-based approach where the year, month, day, hour, minute and second are stored individually. This is a Ruby on Rails construct that serves as a wrapper around SQL-standard DATETIME fields. These contain arbitrary dates and can represent nearly any point in time as the range of expression is typically very large.</p> <pre><code>DateTime.new # =&gt; Mon, 01 Jan -4712 00:00:00 +0000 </code></pre> <p>So it's reassuring that DateTime can handle blog posts from Aristotle.</p> <p>When choosing one, the differences are somewhat subjective now. Historically DateTime has provided better options for manipulating it in a calendar fashion, but many of these methods have been ported over to Time as well, at least within the Rails environment.</p>
{ "question_id": 1261329, "question_date": "2009-08-11T15:59:51.010Z", "question_score": 239, "tags": "ruby|datetime|time", "answer_id": 1261435, "answer_date": "2009-08-11T16:16:45.187Z", "answer_score": 186 }
Please answer the following Stack Overflow question: Title: std::vector performance regression when enabling C++11 <p>I have found an interesting performance regression in a small C++ snippet, when I enable C++11:</p> <pre><code>#include &lt;vector&gt; struct Item { int a; int b; }; int main() { const std::size_t num_items = 10000000; std::vector&lt;Item&gt; container; container.reserve(num_items); for (std::size_t i = 0; i &lt; num_items; ++i) { container.push_back(Item()); } return 0; } </code></pre> <p>With g++ (GCC) 4.8.2 20131219 (prerelease) and C++03 I get:</p> <pre><code>milian:/tmp$ g++ -O3 main.cpp &amp;&amp; perf stat -r 10 ./a.out Performance counter stats for './a.out' (10 runs): 35.206824 task-clock # 0.988 CPUs utilized ( +- 1.23% ) 4 context-switches # 0.116 K/sec ( +- 4.38% ) 0 cpu-migrations # 0.006 K/sec ( +- 66.67% ) 849 page-faults # 0.024 M/sec ( +- 6.02% ) 95,693,808 cycles # 2.718 GHz ( +- 1.14% ) [49.72%] &lt;not supported&gt; stalled-cycles-frontend &lt;not supported&gt; stalled-cycles-backend 95,282,359 instructions # 1.00 insns per cycle ( +- 0.65% ) [75.27%] 30,104,021 branches # 855.062 M/sec ( +- 0.87% ) [77.46%] 6,038 branch-misses # 0.02% of all branches ( +- 25.73% ) [75.53%] 0.035648729 seconds time elapsed ( +- 1.22% ) </code></pre> <p>With C++11 enabled on the other hand, the performance degrades significantly:</p> <pre><code>milian:/tmp$ g++ -std=c++11 -O3 main.cpp &amp;&amp; perf stat -r 10 ./a.out Performance counter stats for './a.out' (10 runs): 86.485313 task-clock # 0.994 CPUs utilized ( +- 0.50% ) 9 context-switches # 0.104 K/sec ( +- 1.66% ) 2 cpu-migrations # 0.017 K/sec ( +- 26.76% ) 798 page-faults # 0.009 M/sec ( +- 8.54% ) 237,982,690 cycles # 2.752 GHz ( +- 0.41% ) [51.32%] &lt;not supported&gt; stalled-cycles-frontend &lt;not supported&gt; stalled-cycles-backend 135,730,319 instructions # 0.57 insns per cycle ( +- 0.32% ) [75.77%] 30,880,156 branches # 357.057 M/sec ( +- 0.25% ) [75.76%] 4,188 branch-misses # 0.01% of all branches ( +- 7.59% ) [74.08%] 0.087016724 seconds time elapsed ( +- 0.50% ) </code></pre> <p>Can someone explain this? So far my experience was that the STL gets faster by enabling C++11, esp. thanks to move semantics.</p> <p><strong>EDIT:</strong> As suggested, using <code>container.emplace_back();</code> instead the performance gets on par with the C++03 version. How can the C++03 version achieve the same for <code>push_back</code>?</p> <pre><code>milian:/tmp$ g++ -std=c++11 -O3 main.cpp &amp;&amp; perf stat -r 10 ./a.out Performance counter stats for './a.out' (10 runs): 36.229348 task-clock # 0.988 CPUs utilized ( +- 0.81% ) 4 context-switches # 0.116 K/sec ( +- 3.17% ) 1 cpu-migrations # 0.017 K/sec ( +- 36.85% ) 798 page-faults # 0.022 M/sec ( +- 8.54% ) 94,488,818 cycles # 2.608 GHz ( +- 1.11% ) [50.44%] &lt;not supported&gt; stalled-cycles-frontend &lt;not supported&gt; stalled-cycles-backend 94,851,411 instructions # 1.00 insns per cycle ( +- 0.98% ) [75.22%] 30,468,562 branches # 840.991 M/sec ( +- 1.07% ) [76.71%] 2,723 branch-misses # 0.01% of all branches ( +- 9.84% ) [74.81%] 0.036678068 seconds time elapsed ( +- 0.80% ) </code></pre>
<p>I can reproduce your results on my machine with those options you write in your post. </p> <p><strong>However, if I also enable <a href="http://gcc.gnu.org/wiki/LinkTimeOptimization">link time optimization</a> (I also pass the <code>-flto</code> flag to gcc 4.7.2), the results are identical:</strong></p> <p>(I am compiling your original code, with <code>container.push_back(Item());</code>)</p> <pre><code>$ g++ -std=c++11 -O3 -flto regr.cpp &amp;&amp; perf stat -r 10 ./a.out Performance counter stats for './a.out' (10 runs): 35.426793 task-clock # 0.986 CPUs utilized ( +- 1.75% ) 4 context-switches # 0.116 K/sec ( +- 5.69% ) 0 CPU-migrations # 0.006 K/sec ( +- 66.67% ) 19,801 page-faults # 0.559 M/sec 99,028,466 cycles # 2.795 GHz ( +- 1.89% ) [77.53%] 50,721,061 stalled-cycles-frontend # 51.22% frontend cycles idle ( +- 3.74% ) [79.47%] 25,585,331 stalled-cycles-backend # 25.84% backend cycles idle ( +- 4.90% ) [73.07%] 141,947,224 instructions # 1.43 insns per cycle # 0.36 stalled cycles per insn ( +- 0.52% ) [88.72%] 37,697,368 branches # 1064.092 M/sec ( +- 0.52% ) [88.75%] 26,700 branch-misses # 0.07% of all branches ( +- 3.91% ) [83.64%] 0.035943226 seconds time elapsed ( +- 1.79% ) $ g++ -std=c++98 -O3 -flto regr.cpp &amp;&amp; perf stat -r 10 ./a.out Performance counter stats for './a.out' (10 runs): 35.510495 task-clock # 0.988 CPUs utilized ( +- 2.54% ) 4 context-switches # 0.101 K/sec ( +- 7.41% ) 0 CPU-migrations # 0.003 K/sec ( +-100.00% ) 19,801 page-faults # 0.558 M/sec ( +- 0.00% ) 98,463,570 cycles # 2.773 GHz ( +- 1.09% ) [77.71%] 50,079,978 stalled-cycles-frontend # 50.86% frontend cycles idle ( +- 2.20% ) [79.41%] 26,270,699 stalled-cycles-backend # 26.68% backend cycles idle ( +- 8.91% ) [74.43%] 141,427,211 instructions # 1.44 insns per cycle # 0.35 stalled cycles per insn ( +- 0.23% ) [87.66%] 37,366,375 branches # 1052.263 M/sec ( +- 0.48% ) [88.61%] 26,621 branch-misses # 0.07% of all branches ( +- 5.28% ) [83.26%] 0.035953916 seconds time elapsed </code></pre> <p>As for the reasons, one needs to look at the generated assembly code (<code>g++ -std=c++11 -O3 -S regr.cpp</code>). <strong>In C++11 mode the generated code is significantly more cluttered</strong> than for C++98 mode and <strong>inlining the function</strong><br> <code>void std::vector&lt;Item,std::allocator&lt;Item&gt;&gt;::_M_emplace_back_aux&lt;Item&gt;(Item&amp;&amp;)</code><br> <strong>fails</strong> in C++11 mode with the default <code>inline-limit</code>. </p> <p><strong>This failed inline has a domino effect.</strong> Not because this function is being called (it is not even called!) but because we have to be prepared: <em>If</em> it is called, the function argments (<code>Item.a</code> and <code>Item.b</code>) must already be at the right place. This leads to a pretty messy code.</p> <p>Here is the relevant part of the generated code for the case where <strong>inlining succeeds</strong>:</p> <pre><code>.L42: testq %rbx, %rbx # container$D13376$_M_impl$_M_finish je .L3 #, movl $0, (%rbx) #, container$D13376$_M_impl$_M_finish_136-&gt;a movl $0, 4(%rbx) #, container$D13376$_M_impl$_M_finish_136-&gt;b .L3: addq $8, %rbx #, container$D13376$_M_impl$_M_finish subq $1, %rbp #, ivtmp.106 je .L41 #, .L14: cmpq %rbx, %rdx # container$D13376$_M_impl$_M_finish, container$D13376$_M_impl$_M_end_of_storage jne .L42 #, </code></pre> <p>This is a nice and compact for loop. Now, let's compare this to that of the <strong>failed inline</strong> case:</p> <pre><code>.L49: testq %rax, %rax # D.15772 je .L26 #, movq 16(%rsp), %rdx # D.13379, D.13379 movq %rdx, (%rax) # D.13379, *D.15772_60 .L26: addq $8, %rax #, tmp75 subq $1, %rbx #, ivtmp.117 movq %rax, 40(%rsp) # tmp75, container.D.13376._M_impl._M_finish je .L48 #, .L28: movq 40(%rsp), %rax # container.D.13376._M_impl._M_finish, D.15772 cmpq 48(%rsp), %rax # container.D.13376._M_impl._M_end_of_storage, D.15772 movl $0, 16(%rsp) #, D.13379.a movl $0, 20(%rsp) #, D.13379.b jne .L49 #, leaq 16(%rsp), %rsi #, leaq 32(%rsp), %rdi #, call _ZNSt6vectorI4ItemSaIS0_EE19_M_emplace_back_auxIIS0_EEEvDpOT_ # </code></pre> <p>This code is cluttered and there is a lot more going on in the loop than in the previous case. Before the function <code>call</code> (last line shown), the arguments must be placed appropriately:</p> <pre><code>leaq 16(%rsp), %rsi #, leaq 32(%rsp), %rdi #, call _ZNSt6vectorI4ItemSaIS0_EE19_M_emplace_back_auxIIS0_EEEvDpOT_ # </code></pre> <p>Even though this is never actually executed, the loop arranges the things before:</p> <pre><code>movl $0, 16(%rsp) #, D.13379.a movl $0, 20(%rsp) #, D.13379.b </code></pre> <p><strong>This leads to the messy code.</strong> If there is no function <code>call</code> because inlining succeeds, we have only 2 move instructions in the loop and there is no messing going with the <code>%rsp</code> (stack pointer). However, if the inlining fails, we get 6 moves and we mess a lot with the <code>%rsp</code>.</p> <p>Just to substantiate my theory (note the <code>-finline-limit</code>), both in C++11 mode:</p> <pre><code> $ g++ -std=c++11 -O3 -finline-limit=105 regr.cpp &amp;&amp; perf stat -r 10 ./a.out Performance counter stats for './a.out' (10 runs): 84.739057 task-clock # 0.993 CPUs utilized ( +- 1.34% ) 8 context-switches # 0.096 K/sec ( +- 2.22% ) 1 CPU-migrations # 0.009 K/sec ( +- 64.01% ) 19,801 page-faults # 0.234 M/sec 266,809,312 cycles # 3.149 GHz ( +- 0.58% ) [81.20%] 206,804,948 stalled-cycles-frontend # 77.51% frontend cycles idle ( +- 0.91% ) [81.25%] 129,078,683 stalled-cycles-backend # 48.38% backend cycles idle ( +- 1.37% ) [69.49%] 183,130,306 instructions # 0.69 insns per cycle # 1.13 stalled cycles per insn ( +- 0.85% ) [85.35%] 38,759,720 branches # 457.401 M/sec ( +- 0.29% ) [85.43%] 24,527 branch-misses # 0.06% of all branches ( +- 2.66% ) [83.52%] 0.085359326 seconds time elapsed ( +- 1.31% ) $ g++ -std=c++11 -O3 -finline-limit=106 regr.cpp &amp;&amp; perf stat -r 10 ./a.out Performance counter stats for './a.out' (10 runs): 37.790325 task-clock # 0.990 CPUs utilized ( +- 2.06% ) 4 context-switches # 0.098 K/sec ( +- 5.77% ) 0 CPU-migrations # 0.011 K/sec ( +- 55.28% ) 19,801 page-faults # 0.524 M/sec 104,699,973 cycles # 2.771 GHz ( +- 2.04% ) [78.91%] 58,023,151 stalled-cycles-frontend # 55.42% frontend cycles idle ( +- 4.03% ) [78.88%] 30,572,036 stalled-cycles-backend # 29.20% backend cycles idle ( +- 5.31% ) [71.40%] 140,669,773 instructions # 1.34 insns per cycle # 0.41 stalled cycles per insn ( +- 1.40% ) [88.14%] 38,117,067 branches # 1008.646 M/sec ( +- 0.65% ) [89.38%] 27,519 branch-misses # 0.07% of all branches ( +- 4.01% ) [86.16%] 0.038187580 seconds time elapsed ( +- 2.05% ) </code></pre> <p><strong>Indeed, if we ask the compiler to try just a little bit harder to inline that function, the difference in performance goes away.</strong></p> <hr> <p>So what is the take away from this story? That failed inlines can cost you a lot and you should make full use of the compiler capabilities: <strong>I can only recommend link time optimization.</strong> It gave a significant performance boost to my programs (up to 2.5x) and all I needed to do is to pass the <code>-flto</code> flag. That's a pretty good deal! ;)</p> <p>However, I do not recommend trashing your code with the inline keyword; let the compiler decide what to do. (The optimizer is allowed to treat the inline keyword as white space anyway.)</p> <hr> <p>Great question, +1!</p>
{ "question_id": 20977741, "question_date": "2014-01-07T17:13:05.107Z", "question_score": 239, "tags": "c++|performance|gcc|c++11|vector", "answer_id": 20983175, "answer_date": "2014-01-07T22:20:37.847Z", "answer_score": 252 }
Please answer the following Stack Overflow question: Title: Regex to validate date formats dd/mm/YYYY, dd-mm-YYYY, dd.mm.YYYY, dd mmm YYYY, dd-mmm-YYYY, dd/mmm/YYYY, dd.mmm.YYYY with Leap Year Support <p>I need to validate a date string for the format <code>dd/mm/yyyy</code> with a regular expresssion.</p> <p>This regex validates <code>dd/mm/yyyy</code>, but not the invalid dates like <code>31/02/4500</code>:</p> <pre><code>^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$ </code></pre> <p>What is a valid regex to validate <code>dd/mm/yyyy</code> format with leap year support?</p>
<p>The regex you pasted does not validate leap years correctly, but there is one that does <a href="https://stackoverflow.com/a/8768241/1537042">in the same post</a>. I modified it to take <code>dd/mm/yyyy</code>, <code>dd-mm-yyyy</code> or <code>dd.mm.yyyy</code>.</p> <p><code>^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[13-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$</code></p> <p>I tested it a bit in the link Arun provided in his answer and also <a href="http://regexr.com?346hf" rel="noreferrer">here</a> and it seems to work.</p> <p>Edit February 14th 2019: I've removed a comma that was in the regex which allowed dates like <code>29-0,-11</code></p>
{ "question_id": 15491894, "question_date": "2013-03-19T05:11:08.383Z", "question_score": 238, "tags": "regex", "answer_id": 15504877, "answer_date": "2013-03-19T16:19:55.663Z", "answer_score": 415 }
Please answer the following Stack Overflow question: Title: Cannot delete or update a parent row: a foreign key constraint fails <p>When doing:</p> <pre><code>DELETE FROM `jobs` WHERE `job_id` =1 LIMIT 1 </code></pre> <p>It errors:</p> <pre><code>#1451 - Cannot delete or update a parent row: a foreign key constraint fails (paymesomething.advertisers, CONSTRAINT advertisers_ibfk_1 FOREIGN KEY (advertiser_id) REFERENCES jobs (advertiser_id)) </code></pre> <p>Here are my tables:</p> <pre><code>CREATE TABLE IF NOT EXISTS `advertisers` ( `advertiser_id` int(11) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `password` char(32) NOT NULL, `email` varchar(128) NOT NULL, `address` varchar(255) NOT NULL, `phone` varchar(255) NOT NULL, `fax` varchar(255) NOT NULL, `session_token` char(30) NOT NULL, PRIMARY KEY (`advertiser_id`), UNIQUE KEY `email` (`email`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ; INSERT INTO `advertisers` (`advertiser_id`, `name`, `password`, `email`, `address`, `phone`, `fax`, `session_token`) VALUES (1, 'TEST COMPANY', '', '', '', '', '', ''); CREATE TABLE IF NOT EXISTS `jobs` ( `job_id` int(11) unsigned NOT NULL AUTO_INCREMENT, `advertiser_id` int(11) unsigned NOT NULL, `name` varchar(255) NOT NULL, `shortdesc` varchar(255) NOT NULL, `longdesc` text NOT NULL, `address` varchar(255) NOT NULL, `time_added` int(11) NOT NULL, `active` tinyint(1) NOT NULL, `moderated` tinyint(1) NOT NULL, PRIMARY KEY (`job_id`), KEY `advertiser_id` (`advertiser_id`,`active`,`moderated`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ; INSERT INTO `jobs` (`job_id`, `advertiser_id`, `name`, `shortdesc`, `longdesc`, `address`, `active`, `moderated`) VALUES (1, 1, 'TEST', 'TESTTEST', 'TESTTESTES', '', 0, 0); ALTER TABLE `advertisers` ADD CONSTRAINT `advertisers_ibfk_1` FOREIGN KEY (`advertiser_id`) REFERENCES `jobs` (`advertiser_id`); </code></pre>
<p>As is, you must delete the row out of the advertisers table before you can delete the row in the jobs table that it references. This:</p> <pre><code>ALTER TABLE `advertisers` ADD CONSTRAINT `advertisers_ibfk_1` FOREIGN KEY (`advertiser_id`) REFERENCES `jobs` (`advertiser_id`); </code></pre> <p>...is actually the opposite to what it should be. As it is, it means that you'd have to have a record in the jobs table before the advertisers. So you need to use:</p> <pre><code>ALTER TABLE `jobs` ADD CONSTRAINT `advertisers_ibfk_1` FOREIGN KEY (`advertiser_id`) REFERENCES `advertisers` (`advertiser_id`); </code></pre> <p>Once you correct the foreign key relationship, your delete statement will work.</p>
{ "question_id": 1905470, "question_date": "2009-12-15T06:09:52.940Z", "question_score": 238, "tags": "mysql|sql", "answer_id": 1905498, "answer_date": "2009-12-15T06:15:27.993Z", "answer_score": 145 }
Please answer the following Stack Overflow question: Title: How to get the key of a key/value JavaScript object <p>If I have a JS object like:</p> <pre><code>var foo = { 'bar' : 'baz' } </code></pre> <p>If I know that <code>foo</code> has that basic key/value structure, but don't know the name of the key, How can I get it? <code>for ... in</code>? <code>$.each()</code>?</p>
<p>If you want to get all keys, <a href="http://ecma262-5.com/ELS5_HTML.htm#Section_15.2.3.14" rel="noreferrer">ECMAScript 5 introduced <code>Object.keys</code></a>. This is only supported by newer browsers but the <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys" rel="noreferrer">MDC documentation</a> provides an alternative implementation (which also uses <code>for...in</code> btw):</p> <pre><code>if(!Object.keys) Object.keys = function(o){ if (o !== Object(o)) throw new TypeError('Object.keys called on non-object'); var ret=[],p; for(p in o) if(Object.prototype.hasOwnProperty.call(o,p)) ret.push(p); return ret; } </code></pre> <p>Of course if you want both, key and value, then <code>for...in</code> is the only reasonable solution.</p>
{ "question_id": 6268679, "question_date": "2011-06-07T16:45:10.030Z", "question_score": 238, "tags": "javascript|jquery", "answer_id": 6268840, "answer_date": "2011-06-07T16:56:09.730Z", "answer_score": 98 }
Please answer the following Stack Overflow question: Title: How to split a comma-separated string? <p>I have a String with an unknown length that looks something like this</p> <pre><code>"dog, cat, bear, elephant, ..., giraffe" </code></pre> <p>What would be the optimal way to divide this string at the commas so each word could become an element of an ArrayList?</p> <p>For example</p> <pre><code>List&lt;String&gt; strings = new ArrayList&lt;Strings&gt;(); // Add the data here so strings.get(0) would be equal to "dog", // strings.get(1) would be equal to "cat" and so forth. </code></pre>
<p>You could do this:</p> <pre><code>String str = "..."; List&lt;String&gt; elephantList = Arrays.asList(str.split(",")); </code></pre> <p>Basically the <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split%28java.lang.String%29" rel="noreferrer"><code>.split()</code></a> method will split the string according to (in this case) delimiter you are passing and will return an array of strings. </p> <p>However, you seem to be after a List of Strings rather than an array, so the array must be turned into a list by using the <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#asList%28T...%29" rel="noreferrer"><code>Arrays.asList()</code></a> utility. Just as an FYI you could also do something like so:</p> <pre><code>String str = "..."; ArrayList&lt;String&gt; elephantList = new ArrayList&lt;&gt;(Arrays.asList(str.split(",")); </code></pre> <p>But it is usually better practice to program to an interface rather than to an actual concrete implementation, so I would recommend the 1st option.</p>
{ "question_id": 10631715, "question_date": "2012-05-17T07:43:41.970Z", "question_score": 238, "tags": "java|string|split", "answer_id": 10631738, "answer_date": "2012-05-17T07:45:12.960Z", "answer_score": 393 }
Please answer the following Stack Overflow question: Title: Why does this iterative list-growing code give IndexError: list assignment index out of range? How can I repeatedly add elements to a list? <p>I tried writing some code like:</p> <pre><code>i = [1, 2, 3, 5, 8, 13] j = [] k = 0 for l in i: j[k] = l k += 1 </code></pre> <p>But I get an error message that says <code>IndexError: list assignment index out of range</code>, referring to the <code>j[k] = l</code> line of code. Why does this occur? How can I fix it?</p>
<p><code>j</code> is an empty list, but you're attempting to write to element <code>[0]</code> in the first iteration, which doesn't exist yet.</p> <p>Try the following instead, to add a new element to the end of the list:</p> <pre><code>for l in i: j.append(l) </code></pre> <p>Of course, you'd never do this in practice if all you wanted to do was to copy an existing list. You'd just do:</p> <pre><code>j = list(i) </code></pre> <p>Alternatively, if you wanted to use the Python list like an array in other languages, then you could pre-create a list with its elements set to a null value (<code>None</code> in the example below), and later, overwrite the values in specific positions:</p> <pre><code>i = [1, 2, 3, 5, 8, 13] j = [None] * len(i) #j == [None, None, None, None, None, None] k = 0 for l in i: j[k] = l k += 1 </code></pre> <p>The thing to realise is that a <code>list</code> object will not allow you to assign a value to an index that doesn't exist.</p>
{ "question_id": 5653533, "question_date": "2011-04-13T18:01:35.987Z", "question_score": 238, "tags": "python|list|exception", "answer_id": 5653549, "answer_date": "2011-04-13T18:03:47.390Z", "answer_score": 382 }
Please answer the following Stack Overflow question: Title: How to increase maximum execution time in php <p>I want to increase <em>maximum execution time</em> in php , not by changing <code>php.ini</code> file. </p> <p>I want to Increase it from my php file.</p> <p>Is this possible?</p>
<pre><code>ini_set('max_execution_time', '300'); //300 seconds = 5 minutes ini_set('max_execution_time', '0'); // for infinite time of execution </code></pre> <p>Place this at the top of your PHP script and let your script loose!</p> <p>Taken from <a href="http://davidwalsh.name/increase-php-script-execution-time-limit-ini_set" rel="noreferrer">Increase PHP Script Execution Time Limit Using ini_set()</a></p>
{ "question_id": 16171132, "question_date": "2013-04-23T13:51:58.053Z", "question_score": 238, "tags": "php|ini|execution-time", "answer_id": 16171228, "answer_date": "2013-04-23T13:55:30.533Z", "answer_score": 526 }
Please answer the following Stack Overflow question: Title: Laravel: Get base URL <p>Simple question, but the answer seems quite hard to come by. In Codeigniter, I could load the URL helper and then simply do</p> <pre><code>echo base_url(); </code></pre> <p>to get my site's URL. Is there an equivalent in Laravel?</p>
<p>You can use the URL facade which lets you do calls to the <a href="http://laravel.com/api/4.1/Illuminate/Routing/UrlGenerator.html">URL generator</a></p> <p>So you can do:</p> <pre><code>URL::to('/'); </code></pre> <p>You can also use the application container:</p> <pre><code>$app-&gt;make('url')-&gt;to('/'); $app['url']-&gt;to('/'); App::make('url')-&gt;to('/'); </code></pre> <p>Or inject the UrlGenerator:</p> <pre><code>&lt;?php namespace Vendor\Your\Class\Namespace; use Illuminate\Routing\UrlGenerator; class Classname { protected $url; public function __construct(UrlGenerator $url) { $this-&gt;url = $url; } public function methodName() { $this-&gt;url-&gt;to('/'); } } </code></pre>
{ "question_id": 23059918, "question_date": "2014-04-14T12:19:23.940Z", "question_score": 238, "tags": "php|laravel|base-url", "answer_id": 23060363, "answer_date": "2014-04-14T12:41:29.960Z", "answer_score": 339 }
Please answer the following Stack Overflow question: Title: Print string and variable contents on the same line in R <p>Is there a way to print text and variable contents on the same line? For example,</p> <pre><code>wd &lt;- getwd() print("Current working dir: ", wd) </code></pre> <p>I couldn't find anything about the syntax that would allow me to do this.</p>
<p>You can use <code>paste</code> with <code>print</code></p> <pre><code>print(paste0("Current working dir: ", wd)) </code></pre> <p>or <code>cat</code></p> <pre><code>cat("Current working dir: ", wd) </code></pre>
{ "question_id": 15589601, "question_date": "2013-03-23T17:07:06.747Z", "question_score": 238, "tags": "r|printing", "answer_id": 15589629, "answer_date": "2013-03-23T17:08:41.047Z", "answer_score": 364 }
Please answer the following Stack Overflow question: Title: React.createElement: type is invalid -- expected a string <p>Trying to get react-router (v4.0.0) and react-hot-loader (3.0.0-beta.6) to play nicely, but getting the following error in the browser console:</p> <pre><code>Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in. </code></pre> <p><strong>index.js:</strong></p> <pre class="lang-js prettyprint-override"><code>import React from 'react'; import ReactDom from 'react-dom'; import routes from './routes.js'; require('jquery'); import 'bootstrap/dist/css/bootstrap.min.css'; import 'bootstrap/dist/js/bootstrap.min.js'; import './css/main.css'; const renderApp = (appRoutes) =&gt; { ReactDom.render(appRoutes, document.getElementById('root')); }; renderApp( routes() ); </code></pre> <p><strong>routes.js:</strong></p> <pre class="lang-js prettyprint-override"><code>import React from 'react'; import { AppContainer } from 'react-hot-loader'; import { Router, Route, browserHistory, IndexRoute } from 'react-router'; import store from './store/store.js'; import { Provider } from 'react-redux'; import App from './containers/App.jsx'; import Products from './containers/shop/Products.jsx'; import Basket from './containers/shop/Basket.jsx'; const routes = () =&gt; ( &lt;AppContainer&gt; &lt;Provider store={store}&gt; &lt;Router history={browserHistory}&gt; &lt;Route path=&quot;/&quot; component={App}&gt; &lt;IndexRoute component={Products} /&gt; &lt;Route path=&quot;/basket&quot; component={Basket} /&gt; &lt;/Route&gt; &lt;/Router&gt; &lt;/Provider&gt; &lt;/AppContainer&gt; ); export default routes; </code></pre>
<p>Most of the time this is due to an incorrect export/import.<br></p> <p>Common error:</p> <pre><code>// File: LeComponent.js export class LeComponent extends React.Component { ... } // File: App.js import LeComponent from './LeComponent'; </code></pre> <p>Possible option:</p> <pre><code>// File: LeComponent.js export default class LeComponent extends React.Component { ... } // File: App.js import LeComponent from './LeComponent'; </code></pre> <p>There are a few ways it could be wrong, but that error is because of an import/export mismatch 60% of the time, everytime. <br></p> <p><strong>Edit</strong></p> <p>Typically you <em>should</em> get a stacktrace that indicates an approximate location of where the failure occurs. This generally follows straight after the message you have in your original question. </p> <p>If it doesn't show, it might be worth investigating why (it might be a build setting that you're missing). Regardless, if it doesn't show, the only course of action is narrowing down <em>where</em> the export/import is failing. </p> <p>Sadly, the only way to do it, without a stacktrace is to manually remove each module/submodule until you don't get the error anymore, then work your way back up the stack. </p> <p><strong>Edit 2</strong></p> <p>Via comments, it was indeed an import issue, specifically importing a module that didn't exist</p>
{ "question_id": 42813342, "question_date": "2017-03-15T14:57:12.373Z", "question_score": 238, "tags": "reactjs|react-router|react-hot-loader", "answer_id": 42814137, "answer_date": "2017-03-15T15:29:37.177Z", "answer_score": 258 }
Please answer the following Stack Overflow question: Title: jQuery add required to input fields <p>I have been searching ways to have jQuery automatically write required using html5 validation to my all of my input fields but I am having trouble telling it where to write it.</p> <p>I want to take this</p> <pre><code> &lt;input type="text" name="first_name" value="" id="freeform_first_name" maxlength="150"&gt; </code></pre> <p>and have it automatically add <strong>required</strong> before the closing tag</p> <pre><code> &lt;input type="text" name="first_name" value="" id="freeform_first_name" maxlength="150" required&gt; </code></pre> <p>I thought I could do someting along the lines of </p> <pre><code>$("input").attr("required", "true"); </code></pre> <p>But it doesn't work. Any help is greatly appreciated. </p>
<pre><code>$("input").prop('required',true); </code></pre> <p><kbd><strong><a href="http://jsfiddle.net/LEZ4r/1/" rel="noreferrer">DEMO FIDDLE</a></strong></kbd></p>
{ "question_id": 19166685, "question_date": "2013-10-03T18:38:18.660Z", "question_score": 238, "tags": "javascript|jquery|validation", "answer_id": 19166712, "answer_date": "2013-10-03T18:39:25.697Z", "answer_score": 536 }
Please answer the following Stack Overflow question: Title: How to access the value of a promise? <p>I'm looking at this example from Angular's docs for <code>$q</code> but I think this probably applies to promises in general. The example below is copied verbatim from their docs with their comment included:</p> <pre><code>promiseB = promiseA.then(function(result) { return result + 1; }); // promiseB will be resolved immediately after promiseA is resolved and its value // will be the result of promiseA incremented by 1 </code></pre> <p>I'm not clear how this works. If I can call <code>.then()</code> on the result of the first <code>.then()</code>, chaining them, which I know I can, then <code>promiseB</code> is a promise object, of type <code>Object</code>. It is not a <code>Number</code>. So what do they mean by "its value will be the result of promiseA incremented by 1"? </p> <p>Am I supposed to access that as <code>promiseB.value</code> or something like that? How can the success callback return a promise AND return "result + 1"? I'm missing something.</p>
<p><code>promiseA</code>'s <code>then</code> function returns a new promise (<code>promiseB</code>) that is immediately resolved after <code>promiseA</code> is resolved, its value is the value of the what is returned from the success function within <code>promiseA</code>.</p> <p>In this case <code>promiseA</code> is resolved with a value - <code>result</code> and then immediately resolves <code>promiseB</code> with the value of <code>result + 1</code>.</p> <p>Accessing the value of <code>promiseB</code> is done in the same way we accessed the result of <code>promiseA</code>.</p> <pre><code>promiseB.then(function(result) { // here you can use the result of promiseB }); </code></pre> <hr /> <p><em>Edit December 2019</em>: <code>async</code>/<code>await</code> is now standard in JS, which allows an alternative syntax to the approach described above. You can now write:</p> <pre><code>let result = await functionThatReturnsPromiseA(); result = result + 1; </code></pre> <p>Now there is no promiseB, because we've unwrapped the result from promiseA using <code>await</code>, and you can work with it directly.</p> <p>However, <code>await</code> can only be used inside an <code>async</code> function. So to zoom out slightly, the above would have to be contained like so:</p> <pre><code>async function doSomething() { let result = await functionThatReturnsPromiseA(); return result + 1; } </code></pre> <p>And, for clarity, the return value of the function <code>doSomething</code> in this example is still a promise - because async functions return promises. So if you wanted to access that return value, you would have to do <code>result = await doSomething()</code>, which you can only do inside another async function. Basically, only in a parent async context can you directly access the value produced from a child async context.</p>
{ "question_id": 29516390, "question_date": "2015-04-08T13:42:53.510Z", "question_score": 238, "tags": "javascript|angularjs|promise|angular-promise", "answer_id": 29516570, "answer_date": "2015-04-08T13:49:06.597Z", "answer_score": 227 }
Please answer the following Stack Overflow question: Title: How to Get Element By Class in JavaScript? <p>I want to replace the contents within a html element so I'm using the following function for that:</p> <pre><code>function ReplaceContentInContainer(id,content) { var container = document.getElementById(id); container.innerHTML = content; } ReplaceContentInContainer('box','This is the replacement text'); &lt;div id='box'&gt;&lt;/div&gt; </code></pre> <p>The above works great but the problem is I have more than one html element on a page that I want to replace the contents of. So I can't use ids but classes instead. I have been told that javascript does not support any type of inbuilt get element by class function. So how can the above code be revised to make it work with classes instead of ids? </p> <p>P.S. I don't want to use jQuery for this.</p>
<p>This code should work in all browsers.</p> <pre><code>function replaceContentInContainer(matchClass, content) { var elems = document.getElementsByTagName('*'), i; for (i in elems) { if((' ' + elems[i].className + ' ').indexOf(' ' + matchClass + ' ') &gt; -1) { elems[i].innerHTML = content; } } } </code></pre> <p>The way it works is by looping through all of the elements in the document, and searching their class list for <code>matchClass</code>. If a match is found, the contents is replaced.</p> <p><a href="http://jsfiddle.net/AXdtH/2/" rel="noreferrer">jsFiddle Example, using Vanilla JS (i.e. no framework)</a></p>
{ "question_id": 3808808, "question_date": "2010-09-28T00:13:15.393Z", "question_score": 238, "tags": "javascript", "answer_id": 3808886, "answer_date": "2010-09-28T00:35:21.877Z", "answer_score": 201 }
Please answer the following Stack Overflow question: Title: How to create hyperlink to call phone number on mobile devices? <p>What is the proper, universal format for creating a clickable hyperlink for users on mobile devices to call a phone number?</p> <p>Area code with dashes</p> <pre><code>&lt;a href="tel:555-555-1212"&gt;555-555-1212&lt;/a&gt; </code></pre> <p>Area code with no dashes</p> <pre><code>&lt;a href="tel:5555551212"&gt;555-555-1212&lt;/a&gt; </code></pre> <p>Area code with dashes and 1</p> <pre><code>&lt;a href="tel:1-555-555-1212"&gt;555-555-1212&lt;/a&gt; </code></pre> <p>Area code with no dashes and 1</p> <pre><code>&lt;a href="tel:15555551212"&gt;555-555-1212&lt;/a&gt; </code></pre> <p>Area code with dashes, 1 and + sign</p> <pre><code>&lt;a href="tel:+1-555-555-1212"&gt;555-555-1212&lt;/a&gt; </code></pre> <p>Area code with no dashes, 1 and + sign</p> <pre><code>&lt;a href="tel:+15555551212"&gt;555-555-1212&lt;/a&gt; </code></pre>
<p>Dashes (<code>-</code>) have no significance other than making the number more readable, so you might as well include them.</p> <p>Since we never know where our website visitors are coming from, we need to make phone numbers callable from anywhere in the world. For this reason the <code>+</code> sign is <strong>always necessary</strong>. The <code>+</code> sign is automatically converted by your mobile carrier to your <a href="https://en.wikipedia.org/wiki/List_of_international_call_prefixes" rel="noreferrer">international dialing prefix</a>, also known as "<strong>exit code</strong>". This code varies by region, country, and sometimes a single country can use multiple codes, depending on the carrier. Fortunately, when it is a local call, dialing it with the international format will still work.</p> <p>Using your example number, when calling from China, people would need to dial:</p> <pre><code>00-1-555-555-1212 </code></pre> <p>And from Russia, they would dial</p> <pre><code>810-1-555-555-1212 </code></pre> <p>The <code>+</code> sign solves this issue by allowing you to omit the international dialing prefix.</p> <p>After the international dialing prefix comes the <a href="https://www.itu.int/dms_pub/itu-t/opb/sp/T-SP-E.164D-2016-PDF-E.pdf" rel="noreferrer">country code</a><sup>(pdf)</sup>, followed by the geographic code (area code), finally the local phone number.</p> <p>Therefore either of the last two of your examples would work, but my recommendation is to use this format for readability:</p> <pre><code>&lt;a href="tel:+1-555-555-1212"&gt;+1-555-555-1212&lt;/a&gt; </code></pre> <p><strong>Note:</strong> For numbers that contain a <a href="https://en.wikipedia.org/wiki/Trunk_prefix" rel="noreferrer">trunk prefix</a> different from the country code (e.g. if you write it locally with brackets around a <code>0</code>), you need to omit it because the number must be in international format.</p>
{ "question_id": 13662175, "question_date": "2012-12-01T18:04:32.240Z", "question_score": 238, "tags": "android|html|mobile|hyperlink", "answer_id": 13662220, "answer_date": "2012-12-01T18:09:49.227Z", "answer_score": 207 }
Please answer the following Stack Overflow question: Title: How to delete an item from state array? <p>The story is, I should be able to put Bob, Sally and Jack into a box. I can also remove either from the box. When removed, no slot is left.</p> <pre><code>people = ["Bob", "Sally", "Jack"] </code></pre> <p>I now need to remove, say, "Bob". The new array would be:</p> <pre><code>["Sally", "Jack"] </code></pre> <p>Here is my react component:</p> <pre><code>... getInitialState: function() { return{ people: [], } }, selectPeople(e){ this.setState({people: this.state.people.concat([e.target.value])}) }, removePeople(e){ var array = this.state.people; var index = array.indexOf(e.target.value); // Let's say it's Bob. delete array[index]; }, ... </code></pre> <p>Here I show you a minimal code as there is more to it (onClick etc). The key part is to delete, remove, destroy "Bob" from the array but <code>removePeople()</code> is not working when called. Any ideas? I was <a href="https://stackoverflow.com/questions/5767325/remove-a-particular-element-from-an-array-in-javascript">looking at this</a> but I might be doing something wrong since I'm using React.</p>
<p>To remove an element from an array, just do:</p> <pre><code>array.splice(index, 1); </code></pre> <p>In your case:</p> <pre><code>removePeople(e) { var array = [...this.state.people]; // make a separate copy of the array var index = array.indexOf(e.target.value) if (index !== -1) { array.splice(index, 1); this.setState({people: array}); } }, </code></pre>
{ "question_id": 36326612, "question_date": "2016-03-31T07:17:36.523Z", "question_score": 238, "tags": "javascript|arrays|reactjs", "answer_id": 36326779, "answer_date": "2016-03-31T07:25:00.693Z", "answer_score": 283 }
Please answer the following Stack Overflow question: Title: Keep CMD open after BAT file executes <p>I have a bat file like this:</p> <pre><code>ipconfig </code></pre> <p>That will print out the IP info to the screen, but before the user can read that info CMD closes itself.</p> <p>I believe that CMD assumes the script has finished, so it closes.</p> <p>How do I keep CMD open after the script is finished?</p>
<p>Depending on how you are running the command, you can put <code>/k</code> after <code>cmd</code> to keep the window open.</p> <pre><code>cmd /k my_script.bat </code></pre> <p>Simply adding <code>cmd /k</code> to the end of your batch file will work too. Credit to <a href="https://stackoverflow.com/users/4141943/luigi-damico">Luigi D'Amico</a> who posted about this in the comments below.</p>
{ "question_id": 17957076, "question_date": "2013-07-30T20:48:27.557Z", "question_score": 238, "tags": "file|batch-file|cmd", "answer_id": 17957220, "answer_date": "2013-07-30T20:55:10.167Z", "answer_score": 219 }
Please answer the following Stack Overflow question: Title: Change Bootstrap input focus blue glow <p>Does anyone know the how to change Bootstrap's <code>input:focus</code>? The blue glow that shows up when you click on an <code>input</code> field?</p>
<p>In the end I changed the following css entry in bootstrap.css</p> <pre><code>textarea:focus, input[type="text"]:focus, input[type="password"]:focus, input[type="datetime"]:focus, input[type="datetime-local"]:focus, input[type="date"]:focus, input[type="month"]:focus, input[type="time"]:focus, input[type="week"]:focus, input[type="number"]:focus, input[type="email"]:focus, input[type="url"]:focus, input[type="search"]:focus, input[type="tel"]:focus, input[type="color"]:focus, .uneditable-input:focus { border-color: rgba(126, 239, 104, 0.8); box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075) inset, 0 0 8px rgba(126, 239, 104, 0.6); outline: 0 none; } </code></pre>
{ "question_id": 14820952, "question_date": "2013-02-11T21:13:23.250Z", "question_score": 238, "tags": "html|css|twitter-bootstrap", "answer_id": 14822905, "answer_date": "2013-02-11T23:30:22.817Z", "answer_score": 263 }
Please answer the following Stack Overflow question: Title: How to set gradle home while importing existing project in Android studio <p>How to set gradle home while importing existing project in Android studio. While trying to import I need to set up this path. <img src="https://i.stack.imgur.com/e2k3g.png" alt="enter image description here"></p>
<p>The gradle plugin (which contains a bundled version of gradle) should be already installed in <em>where/you/installed/android-studio</em>/plugins/gradle so you shouldn't need to manually download it. Depending on the version of Android Studio, that last directory may be <em>where/you/installed/android-studio</em>/gradle/gradle-x.y.z (x.y.z is the version, so check your filesystem for the exact path).</p> <p>If you intend on doing gradle development outside Android Studio or want a different version, you can download it separately and point it at that path, but if you only want to get Android Studio working with the bundled version, this path should do it.</p>
{ "question_id": 21646252, "question_date": "2014-02-08T12:57:06.447Z", "question_score": 238, "tags": "android-studio|gradle|intellij-idea|android-gradle-plugin", "answer_id": 22753291, "answer_date": "2014-03-31T03:43:07.143Z", "answer_score": 237 }
Please answer the following Stack Overflow question: Title: How do I remove duplicates from a C# array? <p>I have been working with a <code>string[]</code> array in C# that gets returned from a function call. I could possibly cast to a <code>Generic</code> collection, but I was wondering if there was a better way to do it, possibly by using a temp array.</p> <p><strong>What is the best way to remove duplicates from a C# array?</strong></p>
<p>You could possibly use a LINQ query to do this:</p> <pre><code>int[] s = { 1, 2, 3, 3, 4}; int[] q = s.Distinct().ToArray(); </code></pre>
{ "question_id": 9673, "question_date": "2008-08-13T11:48:44.360Z", "question_score": 238, "tags": "c#|arrays|duplicates", "answer_id": 9685, "answer_date": "2008-08-13T12:03:05.940Z", "answer_score": 484 }
Please answer the following Stack Overflow question: Title: Difference between "\n" and Environment.NewLine <p>What is the difference between two, if any (with respect to .Net)?</p>
<p>Depends on the platform. On Windows it is actually "\r\n".</p> <p>From MSDN:</p> <blockquote> <p>A string containing "\r\n" for non-Unix platforms, or a string containing "\n" for Unix platforms.</p> </blockquote>
{ "question_id": 1015766, "question_date": "2009-06-18T23:45:18.400Z", "question_score": 238, "tags": "c#|.net|cross-platform", "answer_id": 1015771, "answer_date": "2009-06-18T23:46:48.397Z", "answer_score": 227 }
Please answer the following Stack Overflow question: Title: Is it possible to set a number to NaN or infinity? <p>Is it possible to set an element of an array to <code>NaN</code> in Python?</p> <p>Additionally, is it possible to set a variable to +/- infinity? If so, is there any function to check whether a number is infinity or not?</p>
<p>Cast from string using <code>float()</code>:</p> <pre><code>&gt;&gt;&gt; float('NaN') nan &gt;&gt;&gt; float('Inf') inf &gt;&gt;&gt; -float('Inf') -inf &gt;&gt;&gt; float('Inf') == float('Inf') True &gt;&gt;&gt; float('Inf') == 1 False </code></pre>
{ "question_id": 5438745, "question_date": "2011-03-25T22:24:07.630Z", "question_score": 238, "tags": "python|numeric|nan|infinite", "answer_id": 5438756, "answer_date": "2011-03-25T22:25:46.467Z", "answer_score": 300 }
Please answer the following Stack Overflow question: Title: How can I select the last element with a specific class, not last child inside of parent? <pre><code>&lt;div class="commentList"&gt; &lt;article class="comment " id="com21"&gt;&lt;/article&gt; &lt;article class="comment " id="com20"&gt;&lt;/article&gt; &lt;article class="comment " id="com19"&gt;&lt;/article&gt; &lt;div class="something"&gt; hello &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I want to select <code>#com19</code> ?</p> <pre><code>.comment { width:470px; border-bottom:1px dotted #f0f0f0; margin-bottom:10px; } .comment:last-child { border-bottom:none; margin-bottom:0; } </code></pre> <p>That does not work as long as I do have another <code>div.something</code> as actual last child in the commentList. Is it possible to use the last-child selector in this case to select the last appearance of <code>article.comment</code>?</p> <p><a href="http://jsfiddle.net/C23g6/2/" rel="noreferrer">jsFiddle</a></p>
<p><code>:last-child</code> only works when the element in question is the last child of the container, not the last of a specific type of element. For that, you want <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/:last-of-type" rel="noreferrer"><code>:last-of-type</code></a></p> <p><a href="http://jsfiddle.net/C23g6/3/" rel="noreferrer">http://jsfiddle.net/C23g6/3/</a></p> <p>As per @BoltClock's comment, this is only checking for the last <code>article</code> element, not the last element with the class of <code>.comment</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>body { background: black; } .comment { width: 470px; border-bottom: 1px dotted #f0f0f0; margin-bottom: 10px; } .comment:last-of-type { border-bottom: none; margin-bottom: 0; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="commentList"&gt; &lt;article class="comment " id="com21"&gt;&lt;/article&gt; &lt;article class="comment " id="com20"&gt;&lt;/article&gt; &lt;article class="comment " id="com19"&gt;&lt;/article&gt; &lt;div class="something"&gt; hello &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
{ "question_id": 7298057, "question_date": "2011-09-04T08:15:34.087Z", "question_score": 238, "tags": "html|css|css-selectors", "answer_id": 7298062, "answer_date": "2011-09-04T08:17:03.463Z", "answer_score": 282 }
Please answer the following Stack Overflow question: Title: How to concatenate multiple lines of output to one line? <p>If I run the command <code>cat file | grep pattern</code>, I get many lines of output. How do you concatenate all lines into one line, effectively replacing each <code>"\n"</code> with <code>"\" "</code> (end with <code>"</code> followed by space)?</p> <p><code>cat file | grep pattern | xargs sed s/\n/ /g</code> isn't working for me.</p>
<p>Use <code>tr '\n' ' '</code> to translate all newline characters to spaces:</p> <pre><code>$ grep pattern file | tr '\n' ' ' </code></pre> <p>Note: <code>grep</code> reads files, <code>cat</code> concatenates files. Don't <code>cat file | grep</code>!</p> <p><strong>Edit:</strong></p> <p><code>tr</code> can only handle single character translations. You could use <code>awk</code> to change the output record separator like:</p> <pre><code>$ grep pattern file | awk '{print}' ORS='" ' </code></pre> <p>This would transform:</p> <pre><code>one two three </code></pre> <p>to:</p> <pre><code>one" two" three" </code></pre>
{ "question_id": 15580144, "question_date": "2013-03-22T21:27:51.810Z", "question_score": 238, "tags": "linux|bash|unix|grep|tr", "answer_id": 15580184, "answer_date": "2013-03-22T21:31:18.233Z", "answer_score": 349 }
Please answer the following Stack Overflow question: Title: jQuery 'input' event <p>I've never heard of an event in jQuery called <code>input</code> till I saw this <a href="http://jsfiddle.net/philfreo/MqM76/">jsfiddle</a>.</p> <p>Do you know why it's working? Is it an alias for <code>keyup</code> or something?</p> <pre><code>$(document).on('input', 'input:text', function() {}); </code></pre>
<blockquote> <p>Occurs when the text content of an element is changed through the user interface.</p> </blockquote> <p>It's not quite an alias for <code>keyup</code> because <code>keyup</code> will fire even if the key does nothing (for example: pressing and then releasing the Control key will trigger a <code>keyup</code> event).</p> <p>A good way to think about it is like this: it's an event that triggers whenever the input changes. This includes -- but is not limited to -- pressing keys which modify the input (so, for example, <code>Ctrl</code> by itself will not trigger the event, but <code>Ctrl-V</code> to paste some text will), selecting an auto-completion option, Linux-style middle-click paste, drag-and-drop, and lots of other things.</p> <p>See <a href="http://help.dottoro.com/ljhxklln.php">this</a> page and the comments on this answer for more details.</p>
{ "question_id": 17384218, "question_date": "2013-06-29T20:05:55.227Z", "question_score": 238, "tags": "jquery|events|input", "answer_id": 17384264, "answer_date": "2013-06-29T20:11:27.970Z", "answer_score": 227 }
Please answer the following Stack Overflow question: Title: Create component & add it to a specific module with Angular-CLI <p>I'm starting to use angular-cli and I've already read a lot to find an answer about what I want to do...no success, so I came here.</p> <p>Is there a way to create a component to a new module? </p> <p>e.g.: <code>ng g module newModule</code></p> <p><code>ng g component newComponent</code> (how to add this component to newModule??)</p> <p>because the angular-cli default behavior is to put all new components inside <code>app.module</code>. I would like to choose where my component will be, so that I can create separated modules and won't have all my components inside <code>app.module</code> . It is possible to do that using angular-cli or do I have to do this manually?</p>
<p>To create a component as part of a module you should</p> <ol> <li><code>ng g module newModule</code> to generate a module,</li> <li><code>cd newModule</code> to change directory into the <code>newModule</code> folder</li> <li><code>ng g component newComponent</code> to create a component as a child of the module.</li> </ol> <p>UPDATE: Angular 9</p> <p>Now it doesn't matter what folder you are in when generating the component.</p> <ol> <li><code>ng g module NewModule</code> to generate a module.</li> <li><code>ng g component new-module/new-component</code> to create NewComponent.</li> </ol> <p>Note: When the Angular CLI sees new-module/new-component, it understands and translates the case to match <code>new-module -&gt; NewModule</code> and <code>new-component -&gt; NewComponent</code>. It can get confusing in the beginning, so easy way is to match the names in #2 with the folder names for the module and component.</p>
{ "question_id": 40649799, "question_date": "2016-11-17T08:20:23.213Z", "question_score": 238, "tags": "angular|typescript|angular-cli", "answer_id": 40649834, "answer_date": "2016-11-17T08:22:52.837Z", "answer_score": 314 }