input_text
stringlengths 115
13.8k
| output_text
stringlengths 24
15k
| metadata
dict |
---|---|---|
Please answer the following Stack Overflow question:
Title: How to amend a commit without changing commit message (reusing the previous one)?
<p>Is there a way to amend a commit without <code>vi</code> (or your <code>$EDITOR</code>) popping up with the option to modify your commit message, but simply reusing the previous message?</p> | <p>Since Git <code>1.7.9</code> you can also use <code>git commit --amend --no-edit</code> to get your result.</p>
<p>Note that this will not include metadata from the other commit such as the timestamp or tag, which may or may not be important to you.</p> | {
"question_id": 10237071,
"question_date": "2012-04-19T21:28:45.240Z",
"question_score": 877,
"tags": "git|commit|git-commit|git-amend",
"answer_id": 10365442,
"answer_date": "2012-04-28T16:33:42.043Z",
"answer_score": 1364
} |
Please answer the following Stack Overflow question:
Title: How to pass an object from one activity to another on Android
<p>I am trying to work on sending an object of my <em>customer</em> class from one <code>Activity</code> and displaying it in another <code>Activity</code>.</p>
<p>The code for the customer class:</p>
<pre><code>public class Customer {
private String firstName, lastName, address;
int age;
public Customer(String fname, String lname, int age, String address) {
firstName = fname;
lastName = lname;
age = age;
address = address;
}
public String printValues() {
String data = null;
data = "First Name :" + firstName + " Last Name :" + lastName
+ " Age : " + age + " Address : " + address;
return data;
}
}
</code></pre>
<p>I want to send its object from one <code>Activity</code> to another and then display the data on the other <code>Activity</code>.</p>
<p>How can I achieve that?</p> | <p>One option could be letting your custom class implement the <code>Serializable</code> interface and then you can pass object instances in the intent extra using the <code>putExtra(Serializable..)</code> variant of the <code>Intent#putExtra()</code> method.</p>
<p><strong>Actual Code</strong>:</p>
<p>In Your Custom Model/Object Class:</p>
<pre><code>public class YourClass implements Serializable {
</code></pre>
<p>At other class where using the Custom Model/Class:</p>
<pre><code>//To pass:
intent.putExtra("KEY_NAME", myObject);
</code></pre>
<p>myObject is of type "YourClass".
Then to retrieve from another activity, use getSerializableExtra
get the object using same Key name. And typecast to YourClass is needed:</p>
<pre><code>// To retrieve object in second Activity
myObject = (YourClass) getIntent().getSerializableExtra("KEY_NAME");
</code></pre>
<p>Note: Make sure each nested class of your main custom class has implemented Serializable interface to avoid any serialization exceptions. For example:</p>
<pre><code>class MainClass implements Serializable {
public MainClass() {}
public static class ChildClass implements Serializable {
public ChildClass() {}
}
}
</code></pre> | {
"question_id": 2736389,
"question_date": "2010-04-29T10:06:52.730Z",
"question_score": 876,
"tags": "java|android|object|android-intent|android-activity",
"answer_id": 2736612,
"answer_date": "2010-04-29T10:39:05.523Z",
"answer_score": 962
} |
Please answer the following Stack Overflow question:
Title: Limit file format when using <input type="file">?
<p>I'd like to restrict the type of file that can be chosen from the native OS file chooser when the user clicks the Browse button in the <code><input type="file"></code> element in HTML. I have a feeling it's impossible, but I'd like to know if there <em>is</em> a solution. I'd like to keep solely to HTML and JavaScript; no Flash please.</p> | <p>Strictly speaking, the answer is <strong>no</strong>. A developer <em>cannot</em> prevent a user from uploading files of any type or extension.<br/><br/>But still, the <strong><a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/accept" rel="noreferrer">accept</a></strong> attribute of <code><input type = "file"></code> can help to provide a filter in the file select dialog box provided by the user's browser/OS. For example,</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- (IE 10+, Edge (EdgeHTML), Edge (Chromium), Chrome, Firefox 42+) -->
<input type="file" accept=".xls,.xlsx" /></code></pre>
</div>
</div>
</p>
<p>should provide a way to filter out files other than .xls or .xlsx. Although the <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input" rel="noreferrer">MDN</a> page for <code>input</code> element always said that it supports this, to my surprise, this didn't work for me in Firefox until version 42. This works in IE 10+, Edge, and Chrome.</p>
<p>So, for supporting Firefox older than 42 along with IE 10+, Edge, Chrome, and Opera, I guess it's better to use comma-separated list of MIME-types:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- (IE 10+, Edge (EdgeHTML), Edge (Chromium), Chrome, Firefox) -->
<input type="file"
accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel" /> </code></pre>
</div>
</div>
</p>
<p>[<strong>Edge</strong> (EdgeHTML) behavior: The file type filter dropdown shows the file types mentioned here, but is not the default in the dropdown. The default filter is <code>All files (*)</code>.]<br /></p>
<p>You can also use asterisks in MIME-types. For example:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="file" accept="image/*" /> <!-- all image types -->
<input type="file" accept="audio/*" /> <!-- all audio types -->
<input type="file" accept="video/*" /> <!-- all video types --> </code></pre>
</div>
</div>
</p>
<p>W3C <strong><a href="https://html.spec.whatwg.org/multipage/input.html#attr-input-accept" rel="noreferrer">recommends</a></strong> authors to specify both MIME-types and their corresponding extensions in the <code>accept</code> attribute. So, the <strong>best</strong> approach is:<br /></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Right approach: Use both file extensions and their corresponding MIME-types. -->
<!-- (IE 10+, Edge (EdgeHTML), Edge (Chromium), Chrome, Firefox) -->
<input type="file"
accept=".xls,.xlsx, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel" /> </code></pre>
</div>
</div>
</p>
<p>JSFiddle of the same: <a href="http://jsfiddle.net/sachinjoseph/BkcKQ/" rel="noreferrer">here</a>.<br /></p>
<p><strong>Reference:</strong> <a href="http://www.iana.org/assignments/media-types/media-types.xhtml" rel="noreferrer">List of MIME-types</a><br /><br />
<strong>IMPORTANT:</strong> Using the <code>accept</code> attribute only provides a way of filtering in the files of types that are of interest. Browsers still allow users to choose files of any type. Additional (client-side) checks should be done (using JavaScript, one way would be <a href="https://stackoverflow.com/a/4329103/1724702">this</a>), and definitely file types <em><strong>MUST be verified on the server</strong></em>, using a combination of MIME-type using both the file extension and its binary signature (<a href="https://stackoverflow.com/questions/58510/using-net-how-can-you-find-the-mime-type-of-a-file-based-on-the-file-signature">ASP.NET</a>, <a href="https://stackoverflow.com/questions/310714/how-to-check-file-types-of-uploaded-files-in-php">PHP</a>, <a href="https://stackoverflow.com/questions/4600679/detect-mime-type-of-uploaded-file-in-ruby">Ruby</a>, <a href="https://stackoverflow.com/questions/8666445/check-file-type-after-upload">Java</a>). You might also want to refer to <a href="http://en.wikipedia.org/wiki/List_of_file_signatures" rel="noreferrer">these</a> <a href="http://www.garykessler.net/library/file_sigs.html" rel="noreferrer">tables</a> for file types and their <a href="http://en.wikipedia.org/wiki/Magic_number_%28programming%29" rel="noreferrer">magic numbers</a>, to perform a more robust server-side verification.<br /><br />
Here are <a href="https://stackoverflow.com/questions/3597082/how-is-a-website-hacked-by-a-maliciously-encoded-image-that-contained-a-php-scr">three</a> <a href="http://www.acunetix.com/websitesecurity/upload-forms-threat/" rel="noreferrer">good</a> <a href="http://www.hanselman.com/blog/BackToBasicsWhenAllowingUserUploadsDontAllowUploadsToExecuteCode.aspx" rel="noreferrer">reads</a> on file-uploads and security.</p>
<p><strong>EDIT:</strong> Maybe file type verification using its binary signature can also be done on client side using JavaScript (rather than just by looking at the extension) using HTML5 File API, but still, the file must be verified on the server, because a malicious user will still be able to upload files by making a custom HTTP request.</p> | {
"question_id": 4328947,
"question_date": "2010-12-01T20:44:40.973Z",
"question_score": 876,
"tags": "html|file|types",
"answer_id": 23706177,
"answer_date": "2014-05-16T23:54:20.527Z",
"answer_score": 1478
} |
Please answer the following Stack Overflow question:
Title: Remove trailing spaces automatically or with a shortcut
<p>Is there a way to remove trailing spaces in Visual Studio Code (automatically or with a shortcut)?</p>
<p>I've been looking for this in the command palette and in the editor settings, but I cannot find what I am looking for.</p> | <p>You can enable whitespace trimming at <strong><em>file save time</em></strong> from settings:</p>
<ol>
<li>Open Visual Studio Code User Settings (menu <em>File</em> → <em>Preferences</em> → <em>Settings</em> → <em>User Settings</em> tab).</li>
<li>Click the <a href="https://i.stack.imgur.com/Q8BKi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Q8BKi.png" alt="enter image description here"></a> icon in the top-right part of the window. This will open a document.</li>
<li>Add a new <code>"files.trimTrailingWhitespace": true</code> setting to the User Settings document if it's not already there. This is so you aren't editing the Default Setting directly, but instead adding to it.</li>
<li>Save the User Settings file.</li>
</ol>
<p>We also added a new command to trigger this manually (<em>Trim Trailing Whitespace</em> from the command palette).</p> | {
"question_id": 30884131,
"question_date": "2015-06-17T06:46:21.973Z",
"question_score": 876,
"tags": "visual-studio-code|vscode-settings",
"answer_id": 30884298,
"answer_date": "2015-06-17T06:55:01.310Z",
"answer_score": 1504
} |
Please answer the following Stack Overflow question:
Title: ASP.NET Web Site or ASP.NET Web Application?
<p>When I start a new ASP.NET project in Visual Studio, I can create an ASP.NET Web Application or I can create an ASP.NET Web Site.</p>
<p>What is the difference between ASP.NET Web Application and ASP.NET Web Site? Why would I choose one over other?</p>
<p>Is the answer different based on which version of Visual Studio I am using?</p> | <h3>Website:</h3>
<p>The <em>Web Site</em> project is compiled on the fly. You end up with a lot more DLL files, which can be a pain. It also gives problems when you have pages or controls in one directory that need to reference pages and controls in another directory since the other directory may not be compiled into the code yet. Another problem can be in publishing.</p>
<p>If Visual Studio isn't told to re-use the same names constantly, it will come up with new names for the DLL files generated by pages all the time. That can lead to having several close copies of DLL files containing the same class name,
which will generate plenty of errors. The Web Site project was introduced with Visual Studio 2005, but it has turned out not to be popular.</p>
<h3>Web Application:</h3>
<p>The <em>Web Application</em> Project was created as an add-in and now exists as part
of SP 1 for Visual Studio 2005. The main differences are the Web Application Project
was designed to work similarly to the Web projects that shipped with Visual Studio 2003. It will compile the application into a single DLL file at build
time. To update the project, it must be recompiled and the DLL file
published for changes to occur.</p>
<p>Another nice feature of the Web Application
project is it's much easier to exclude files from the project view. In the
Web Site project, each file that you exclude is renamed with an excluded
keyword in the filename. In the Web Application Project, the project just
keeps track of which files to include/exclude from the project view without
renaming them, making things much tidier.</p>
<p><em><a href="https://web.archive.org/web/20081211085108/http://www.megasolutions.net/AspNet/difference-between-Web-Site-and-Web-Application-Project-27210.aspx" rel="noreferrer">Reference</a></em></p>
<p>The article <em><a href="http://maordavid.blogspot.com/2007/06/aspnet-20-web-site-vs-web-application.html" rel="noreferrer">ASP.NET 2.0 - Web Site vs Web Application project</a></em> also gives reasons on why to use one and not the other. Here is an excerpt of it:</p>
<blockquote>
<ul>
<li>You need to migrate large Visual Studio .NET 2003 applications to VS
2005? <strong>use the Web Application project.</strong></li>
<li>You want to open and edit any directory as a Web project without
creating a project file? <strong>use Web Site
project.</strong></li>
<li>You need to add pre-build and post-build steps during compilation?
<strong>use Web Application project.</strong></li>
<li>You need to build a Web application using multiple Web
projects? <strong>use the Web Application project.</strong></li>
<li>You want to generate one assembly for each page? <strong>use the Web Site project.</strong></li>
<li>You prefer dynamic compilation and working on pages without building
entire site on each page view? <strong>use Web
Site project.</strong></li>
<li>You prefer single-page code model to code-behind model? <strong>use Web Site
project.</strong></li>
</ul>
</blockquote>
<p><em><a href="http://msdn.microsoft.com/en-us/library/dd547590.aspx" rel="noreferrer">Web Application Projects versus Web Site Projects</a></em> (MSDN) explains the differences between the web site and web application projects. Also, it discusses the configuration to be made in Visual Studio.</p> | {
"question_id": 398037,
"question_date": "2008-12-29T16:24:13.090Z",
"question_score": 876,
"tags": "asp.net|.net|visual-studio|projects-and-solutions",
"answer_id": 398049,
"answer_date": "2008-12-29T16:28:58.167Z",
"answer_score": 565
} |
Please answer the following Stack Overflow question:
Title: Parsing a string to a date in JavaScript
<p>How can I convert a string to a Date object in JavaScript?</p>
<pre class="lang-js prettyprint-override"><code>var st = "date in some format"
var dt = new Date();
var dt_st = // st in Date format, same as dt.
</code></pre> | <p>The best string format for string parsing is the date ISO format together with the JavaScript Date object constructor. </p>
<p>Examples of ISO format: <code>YYYY-MM-DD</code> or <code>YYYY-MM-DDTHH:MM:SS</code>.</p>
<p><strong>But wait!</strong> Just using the "ISO format" doesn't work reliably by itself. String are sometimes parsed as UTC and sometimes as localtime (based on browser vendor and version). The best practice should always be to store dates as UTC and make computations as UTC.</p>
<p>To parse a date as UTC, append a <strong>Z</strong> - e.g.: <code>new Date('2011-04-11T10:20:30Z')</code>.</p>
<p>To display a date in UTC, use <code>.toUTCString()</code>,<br>
to display a date in user's local time, use <code>.toString()</code>.</p>
<p>More info on <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date" rel="noreferrer">MDN | Date</a> and <a href="https://stackoverflow.com/a/40768745/584192">this answer</a>.</p>
<p>For old Internet Explorer compatibility (IE versions less than 9 do not support ISO format in Date constructor), you should split datetime string representation to it's parts and then you can use constructor using datetime parts, e.g.: <code>new Date('2011', '04' - 1, '11', '11', '51', '00')</code>. Note that the number of the month must be 1 less.</p>
<hr>
<p><strong>Alternate method - use an appropriate library:</strong></p>
<p>You can also take advantage of the library <a href="http://momentjs.com" rel="noreferrer">Moment.js</a> that allows parsing date with the specified time zone.</p> | {
"question_id": 5619202,
"question_date": "2011-04-11T09:21:18.607Z",
"question_score": 875,
"tags": "javascript|date|date-parsing",
"answer_id": 5619588,
"answer_date": "2011-04-11T09:53:38.570Z",
"answer_score": 1016
} |
Please answer the following Stack Overflow question:
Title: How can I make git accept a self signed certificate?
<p>Using Git, is there a way to tell it to accept a self signed certificate?</p>
<p>I am using an https server to host a git server but for now the certificate is self signed.</p>
<p>When I try to create the repo there for the first time:</p>
<pre><code>git push origin master -f
</code></pre>
<p>I get the error:</p>
<pre><code>error: Cannot access URL
https://the server/git.aspx/PocketReferences/, return code 22
fatal: git-http-push failed
</code></pre> | <h3>To permanently accept a specific certificate</h3>
<p>Try <code>http.sslCAPath</code> or <code>http.sslCAInfo</code>. <a href="https://stackoverflow.com/a/26785963/877115">Adam Spiers's answer</a> gives some great examples. This is the most secure solution to the question.</p>
<h3>To disable TLS/SSL verification for a single git command</h3>
<p>try passing <code>-c</code> to <code>git</code> with the proper config variable, or use <a href="https://stackoverflow.com/a/19363404/194894">Flow's answer</a>:</p>
<pre><code>git -c http.sslVerify=false clone https://example.com/path/to/git
</code></pre>
<h3>To disable SSL verification for all repositories</h3>
<p>It is possible to globally deactivate ssl verification. It is <strong>highly recommended to NOT do this</strong> but it is mentioned for completeness:</p>
<pre><code>git config --global http.sslVerify false # Do NOT do this!
</code></pre>
<hr />
<p>There are quite a few SSL configuration options in <code>git</code>. From the man page of <code>git config</code>:</p>
<pre><code>http.sslVerify
Whether to verify the SSL certificate when fetching or pushing over HTTPS.
Can be overridden by the GIT_SSL_NO_VERIFY environment variable.
http.sslCAInfo
File containing the certificates to verify the peer with when fetching or pushing
over HTTPS. Can be overridden by the GIT_SSL_CAINFO environment variable.
http.sslCAPath
Path containing files with the CA certificates to verify the peer with when
fetching or pushing over HTTPS.
Can be overridden by the GIT_SSL_CAPATH environment variable.
</code></pre>
<p>A few other useful SSL configuration options:</p>
<pre><code>http.sslCert
File containing the SSL certificate when fetching or pushing over HTTPS.
Can be overridden by the GIT_SSL_CERT environment variable.
http.sslKey
File containing the SSL private key when fetching or pushing over HTTPS.
Can be overridden by the GIT_SSL_KEY environment variable.
http.sslCertPasswordProtected
Enable git's password prompt for the SSL certificate. Otherwise OpenSSL will
prompt the user, possibly many times, if the certificate or private key is encrypted.
Can be overridden by the GIT_SSL_CERT_PASSWORD_PROTECTED environment variable.
</code></pre> | {
"question_id": 11621768,
"question_date": "2012-07-23T23:00:06.777Z",
"question_score": 875,
"tags": "git|version-control|https|self-signed",
"answer_id": 11622001,
"answer_date": "2012-07-23T23:28:17.183Z",
"answer_score": 1586
} |
Please answer the following Stack Overflow question:
Title: URL encoding the space character: + or %20?
<p>When is a space in a URL encoded to <code>+</code>, and when is it encoded to <code>%20</code>?</p> | <p>From <a href="http://en.wikipedia.org/wiki/URL_encoding" rel="noreferrer">Wikipedia</a> (emphasis and link added):</p>
<blockquote>
<p>When data that has been entered into HTML forms is submitted, the form field names and values are encoded and sent to the server in an HTTP request message using method GET or POST, or, historically, via email. <strong>The encoding used by default is based on a very early version of the general URI percent-encoding rules, with a <a href="http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1" rel="noreferrer">number of modifications</a> such as newline normalization and replacing spaces with "+" instead of "%20".</strong> The MIME type of data encoded this way is application/x-www-form-urlencoded, and it is currently defined (still in a very outdated manner) in the HTML and XForms specifications.</p>
</blockquote>
<p>So, the <em>real</em> percent encoding uses <code>%20</code> while form data in URLs is in a modified form that uses <code>+</code>. So you're most likely to only see <code>+</code> in URLs in the query string after an <code>?</code>.</p> | {
"question_id": 1634271,
"question_date": "2009-10-27T23:23:23.770Z",
"question_score": 875,
"tags": "url|url-encoding",
"answer_id": 1634293,
"answer_date": "2009-10-27T23:26:24.420Z",
"answer_score": 496
} |
Please answer the following Stack Overflow question:
Title: How to set focus on an input field after rendering?
<p>What's the react way of setting focus on a particular text field after the component is rendered?</p>
<p>Documentation seems to suggest using refs, e.g:</p>
<p>Set <code>ref="nameInput"</code> on my input field in the render function, and then call:</p>
<pre><code>this.refs.nameInput.getInputDOMNode().focus();
</code></pre>
<p>But where should I call this? I've tried a few places but I cannot get it to work.</p> | <p>You should do it in <code>componentDidMount</code> and <a href="https://facebook.github.io/react/docs/refs-and-the-dom.html" rel="noreferrer"><code>refs callback</code></a> instead. Something like this</p>
<pre><code>componentDidMount(){
this.nameInput.focus();
}
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class App extends React.Component{
componentDidMount(){
this.nameInput.focus();
}
render() {
return(
<div>
<input
defaultValue="Won't focus"
/>
<input
ref={(input) => { this.nameInput = input; }}
defaultValue="will focus"
/>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('app'));</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-dom.js"></script>
<div id="app"></div></code></pre>
</div>
</div>
</p> | {
"question_id": 28889826,
"question_date": "2015-03-05T23:28:22.933Z",
"question_score": 875,
"tags": "javascript|reactjs",
"answer_id": 28890330,
"answer_date": "2015-03-06T00:19:47.780Z",
"answer_score": 776
} |
Please answer the following Stack Overflow question:
Title: How to create a new object instance from a Type
<p>One may not always know the <code>Type</code> of an object at compile-time, but may need to create an instance of the <code>Type</code>. </p>
<p>How do you get a new object instance from a <code>Type</code>?</p> | <p>The <code>Activator</code> class within the root <code>System</code> namespace is pretty powerful.</p>
<p>There are a lot of overloads for passing parameters to the constructor and such. Check out the documentation at: </p>
<blockquote>
<p><a href="http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx</a></p>
</blockquote>
<p>or (new path)</p>
<blockquote>
<p><a href="https://docs.microsoft.com/en-us/dotnet/api/system.activator.createinstance" rel="noreferrer">https://docs.microsoft.com/en-us/dotnet/api/system.activator.createinstance</a></p>
</blockquote>
<p>Here are some simple examples:</p>
<pre><code>ObjectType instance = (ObjectType)Activator.CreateInstance(objectType);
ObjectType instance = (ObjectType)Activator.CreateInstance("MyAssembly","MyNamespace.ObjectType");
</code></pre> | {
"question_id": 752,
"question_date": "2008-08-03T16:29:03.607Z",
"question_score": 875,
"tags": "c#|.net|performance|reflection|types",
"answer_id": 755,
"answer_date": "2008-08-03T16:35:34.233Z",
"answer_score": 1016
} |
Please answer the following Stack Overflow question:
Title: How to import the class within the same directory or sub directory?
<p>I have a directory that stores all the <strong>.py</strong> files.</p>
<pre><code>bin/
main.py
user.py # where class User resides
dir.py # where class Dir resides
</code></pre>
<p>I want to use classes from <strong>user.py</strong> and <strong>dir.py</strong> in <strong>main.py</strong>.<br>
How can I import these Python classes into <strong>main.py</strong>?<br>
Furthermore, how can I import class <code>User</code> if <strong>user.py</strong> is in a sub directory?</p>
<pre><code>bin/
dir.py
main.py
usr/
user.py
</code></pre> | <h1>Python 2</h1>
<p>Make an empty file called <code>__init__.py</code> in the same directory as the files. That will signify to Python that it's "ok to import from this directory".</p>
<p>Then just do...</p>
<pre><code>from user import User
from dir import Dir
</code></pre>
<p>The same holds true if the files are in a subdirectory - put an <code>__init__.py</code> in the subdirectory as well, and then use regular import statements, with dot notation. For each level of directory, you need to add to the import path. </p>
<pre><code>bin/
main.py
classes/
user.py
dir.py
</code></pre>
<p>So if the directory was named "classes", then you'd do this:</p>
<pre><code>from classes.user import User
from classes.dir import Dir
</code></pre>
<h1>Python 3</h1>
<p>Same as previous, but prefix the module name with a <code>.</code> if not using a subdirectory:</p>
<pre><code>from .user import User
from .dir import Dir
</code></pre> | {
"question_id": 4142151,
"question_date": "2010-11-10T07:32:23.797Z",
"question_score": 874,
"tags": "python|python-import",
"answer_id": 4142178,
"answer_date": "2010-11-10T07:36:10.503Z",
"answer_score": 1194
} |
Please answer the following Stack Overflow question:
Title: How to force maven update?
<p>I imported my already working project on another computer and it started to download dependencies. </p>
<p>Apparently my internet connection crashed and now I get the following:</p>
<pre><code> >Build errors for comics; org.apache.maven.lifecycle.LifecycleExecutionException:
Failed to execute goal on project comicsTest: Could not resolve dependencies for project comicsTest:comicsTest:war:0.0.1-SNAPSHOT:
The following artifacts could not be resolved:
org.springframework:spring-context:jar:3.0.5.RELEASE,
org.hibernate:hibernate-entitymanager:jar:3.6.0.Final,
org.hibernate:hibernate-core:jar:3.6.0.Final,
org.hibernate:hibernate-commons-annotations:jar:3.2.0.Final,
org.aspectj:aspectjweaver:jar:1.6.8,
commons-lang:commons-lang:jar:2.5,
>mysql:mysql-connector-java:jar:5.1.13: Failure to transfer org.springframework:spring-context:jar:3.0.5.RELEASE from http://repo1.maven.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced.
>Original error: Could not transfer artifact org.springframework:spring-context:jar:3.0.5.RELEASE from central (http://repo1.maven.org/maven2): No response received after 60000
</code></pre>
<p>How do I force maven to update?</p> | <pre><code>mvn clean install -U
</code></pre>
<p><code>-U</code> means force update of <em>snapshot</em> dependencies.</p>
<p>Release dependencies will be updated this way if they have never been previously successfully downloaded. ref: <a href="https://stackoverflow.com/a/29020990/32453">https://stackoverflow.com/a/29020990/32453</a></p> | {
"question_id": 4701532,
"question_date": "2011-01-15T19:01:41.137Z",
"question_score": 874,
"tags": "maven",
"answer_id": 9697970,
"answer_date": "2012-03-14T08:06:29.447Z",
"answer_score": 1838
} |
Please answer the following Stack Overflow question:
Title: How do I tell Maven to use the latest version of a dependency?
<p>In Maven, dependencies are usually set up like this:</p>
<pre class="lang-xml prettyprint-override"><code><dependency>
<groupId>wonderful-inc</groupId>
<artifactId>dream-library</artifactId>
<version>1.2.3</version>
</dependency>
</code></pre>
<p>Now, if you are working with libraries that have frequent releases, constantly updating the <version> tag can be somewhat annoying. Is there any way to tell Maven to always use the latest available version (from the repository)? </p> | <p><em><strong>NOTE:</strong></em></p>
<p><em>The mentioned <code>LATEST</code> and <code>RELEASE</code> metaversions <a href="https://cwiki.apache.org/confluence/display/MAVEN/Maven+3.x+Compatibility+Notes#Maven3.xCompatibilityNotes-PluginMetaversionResolution" rel="noreferrer">have been dropped <strong>for plugin dependencies</strong> in Maven 3 "for the sake of reproducible builds"</a>, over 6 years ago.
(They still work perfectly fine for regular dependencies.)
For plugin dependencies please refer to this <strong><a href="https://stackoverflow.com/a/1172805/363573">Maven 3 compliant solution</a></strong></em>.</p>
<hr />
<p>If you always want to use the newest version, Maven has two keywords you can use as an alternative to version ranges. You should use these options with care as you are no longer in control of the plugins/dependencies you are using.</p>
<blockquote>
<p>When you depend on a plugin or a dependency, you can use the a version value of LATEST or RELEASE. LATEST refers to the latest released or snapshot version of a particular artifact, the most recently deployed artifact in a particular repository. RELEASE refers to the last non-snapshot release in the repository. In general, it is not a best practice to design software which depends on a non-specific version of an artifact. If you are developing software, you might want to use RELEASE or LATEST as a convenience so that you don't have to update version numbers when a new release of a third-party library is released. When you release software, you should always make sure that your project depends on specific versions to reduce the chances of your build or your project being affected by a software release not under your control. Use LATEST and RELEASE with caution, if at all.</p>
</blockquote>
<p>See the <a href="http://www.sonatype.com/books/maven-book/reference/pom-relationships-sect-pom-syntax.html#pom-relationships-sect-latest-release" rel="noreferrer">POM Syntax section of the Maven book</a> for more details. Or see this doc on <a href="http://www.mojohaus.org/versions-maven-plugin/examples/resolve-ranges.html" rel="noreferrer">Dependency Version Ranges</a>, where:</p>
<ul>
<li>A square bracket ( <code>[</code> & <code>]</code> ) means "closed" (inclusive).</li>
<li>A parenthesis ( <code>(</code> & <code>)</code> ) means "open" (exclusive).</li>
</ul>
<p>Here's an example illustrating the various options. In the Maven repository, com.foo:my-foo has the following metadata:</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?><metadata>
<groupId>com.foo</groupId>
<artifactId>my-foo</artifactId>
<version>2.0.0</version>
<versioning>
<release>1.1.1</release>
<versions>
<version>1.0</version>
<version>1.0.1</version>
<version>1.1</version>
<version>1.1.1</version>
<version>2.0.0</version>
</versions>
<lastUpdated>20090722140000</lastUpdated>
</versioning>
</metadata>
</code></pre>
<p>If a dependency on that artifact is required, you have the following options (other <a href="https://cwiki.apache.org/confluence/display/MAVENOLD/Dependency+Mediation+and+Conflict+Resolution#DependencyMediationandConflictResolution-DependencyVersionRanges" rel="noreferrer">version ranges</a> can be specified of course, just showing the relevant ones here):</p>
<p>Declare an exact version (will always resolve to 1.0.1):</p>
<pre class="lang-xml prettyprint-override"><code><version>[1.0.1]</version>
</code></pre>
<p>Declare an explicit version (will always resolve to 1.0.1 unless a collision occurs, when Maven will select a matching version):</p>
<pre class="lang-xml prettyprint-override"><code><version>1.0.1</version>
</code></pre>
<p>Declare a version range for all 1.x (will currently resolve to 1.1.1):</p>
<pre class="lang-xml prettyprint-override"><code><version>[1.0.0,2.0.0)</version>
</code></pre>
<p>Declare an open-ended version range (will resolve to 2.0.0):</p>
<pre class="lang-xml prettyprint-override"><code><version>[1.0.0,)</version>
</code></pre>
<p>Declare the version as LATEST (will resolve to 2.0.0) (removed from maven 3.x)</p>
<pre class="lang-xml prettyprint-override"><code><version>LATEST</version>
</code></pre>
<p>Declare the version as RELEASE (will resolve to 1.1.1) (removed from maven 3.x):</p>
<pre class="lang-xml prettyprint-override"><code><version>RELEASE</version>
</code></pre>
<p>Note that by default your own deployments will update the "latest" entry in the Maven metadata, but to update the "release" entry, you need to activate the "release-profile" from the <a href="http://maven.apache.org/guides/introduction/introduction-to-the-pom.html" rel="noreferrer">Maven super POM</a>. You can do this with either "-Prelease-profile" or "-DperformRelease=true"</p>
<hr />
<p>It's worth emphasising that any approach that allows Maven to pick the dependency versions (LATEST, RELEASE, and version ranges) can leave you open to build time issues, as later versions can have different behaviour (for example the dependency plugin has previously switched a default value from true to false, with confusing results).</p>
<p>It is therefore generally a good idea to define exact versions in releases. As <a href="https://stackoverflow.com/questions/30571/how-do-i-tell-maven-to-use-the-latest-version-of-a-dependency/1172805#1172805">Tim's answer</a> points out, the <a href="http://www.mojohaus.org/versions-maven-plugin/" rel="noreferrer">maven-versions-plugin</a> is a handy tool for updating dependency versions, particularly the <a href="http://www.mojohaus.org/versions-maven-plugin/use-latest-versions-mojo.html" rel="noreferrer">versions:use-latest-versions</a> and <a href="http://www.mojohaus.org/versions-maven-plugin/use-latest-releases-mojo.html" rel="noreferrer">versions:use-latest-releases</a> goals.</p> | {
"question_id": 30571,
"question_date": "2008-08-27T16:17:02.633Z",
"question_score": 874,
"tags": "java|maven|dependencies|maven-2|maven-metadata",
"answer_id": 1172371,
"answer_date": "2009-07-23T14:58:06.890Z",
"answer_score": 819
} |
Please answer the following Stack Overflow question:
Title: How to move the cursor word by word in the OS X Terminal
<p>I know the combination <kbd>Ctrl</kbd>+<kbd>A</kbd> to jump to the beginning of the current command, and <kbd>Ctrl</kbd>+<kbd>E</kbd> to jump to the end. </p>
<p>But is there any way to jump word by word, like <kbd>Alt</kbd>+<kbd>←</kbd>/<kbd>→</kbd> in Cocoa applications does?</p> | <p>Out of the box you can use the quite bizarre <kbd>Esc</kbd>+<kbd>F</kbd> to move to the beginning of the next word and <kbd>Esc</kbd>+<kbd>B</kbd> to move to the beginning of the current word.</p> | {
"question_id": 81272,
"question_date": "2008-09-17T08:57:17.040Z",
"question_score": 874,
"tags": "macos|terminal|keyboard-shortcuts",
"answer_id": 81309,
"answer_date": "2008-09-17T09:04:01.687Z",
"answer_score": 637
} |
Please answer the following Stack Overflow question:
Title: What is __future__ in Python used for and how/when to use it, and how it works
<p><code>__future__</code> frequently appears in Python modules. I do not understand what <code>__future__</code> is for and how/when to use it even after reading <a href="http://docs.python.org/library/__future__.html" rel="noreferrer">the Python's <code>__future__</code> doc</a>. </p>
<p>Can anyone explain with examples?</p>
<p>A few answers regarding the basic usage of <code>__future__</code> I've received seemed correct. </p>
<p>However, I need to understand one more thing regarding how <code>__future__</code> works:</p>
<p>The most confusing concept for me is how a current python release includes features for future releases, and how a program using a feature from a future release can be be compiled successfully in the current version of Python.</p>
<p>I am guessing that the current release is packaged with potential features for the future. However, the features are available only by using <code>__future__</code> because they are not the current standard. Let me know if I am right.</p> | <p>With <code>__future__</code> module's inclusion, you can slowly be accustomed to incompatible changes or to such ones introducing new keywords.</p>
<p>E.g., for using context managers, you had to do <code>from __future__ import with_statement</code> in 2.5, as the <code>with</code> keyword was new and shouldn't be used as variable names any longer. In order to use <code>with</code> as a Python keyword in Python 2.5 or older, you will need to use the import from above.</p>
<p>Another example is</p>
<pre><code>from __future__ import division
print 8/7 # prints 1.1428571428571428
print 8//7 # prints 1
</code></pre>
<p>Without the <code>__future__</code> stuff, both <code>print</code> statements would print <code>1</code>.</p>
<p>The internal difference is that without that import, <code>/</code> is mapped to the <code>__div__()</code> method, while with it, <code>__truediv__()</code> is used. (In any case, <code>//</code> calls <code>__floordiv__()</code>.)</p>
<p>Apropos <code>print</code>: <code>print</code> becomes a function in 3.x, losing its special property as a keyword. So it is the other way round.</p>
<pre><code>>>> print
>>> from __future__ import print_function
>>> print
<built-in function print>
>>>
</code></pre> | {
"question_id": 7075082,
"question_date": "2011-08-16T07:52:30.613Z",
"question_score": 874,
"tags": "python|python-2.x",
"answer_id": 7075121,
"answer_date": "2011-08-16T07:56:46.957Z",
"answer_score": 491
} |
Please answer the following Stack Overflow question:
Title: Is the Scala 2.8 collections library a case of "the longest suicide note in history"?
<p>I have just started to look at the <a href="http://lampsvn.epfl.ch/trac/scala/browser/scala/trunk/src/library/scala/collection" rel="noreferrer">Scala collections library re-implementation</a> which is coming in the imminent <strong>2.8</strong> release. Those familiar with the library from 2.7 will notice that the library, from a usage perspective, has changed little. For example...</p>
<pre><code>> List("Paris", "London").map(_.length)
res0: List[Int] List(5, 6)
</code></pre>
<p>...would work in either versions. <strong>The library is eminently useable</strong>: in fact it's fantastic. However, those previously unfamiliar with Scala and <em>poking around to get a feel for the language</em> now have to make sense of method signatures like:</p>
<pre><code>def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That
</code></pre>
<p>For such simple functionality, this is a daunting signature and one which I find myself struggling to understand. <strong>Not that I think Scala was ever likely to be the next Java</strong> (or /C/C++/C#) - I don't believe its creators were aiming it at that market - but I think it is/was certainly feasible for Scala to become the next Ruby or Python (i.e. to gain a significant commercial user-base)</p>
<ul>
<li>Is this going to put people off coming to Scala?</li>
<li>Is this going to give Scala a bad name in the commercial world as an <em>academic plaything</em> that only dedicated PhD students can understand? Are <a href="http://en.wikipedia.org/wiki/Chief_technical_officer" rel="noreferrer">CTO</a>s and heads of software going to get scared off?</li>
<li>Was the library re-design a sensible idea?</li>
<li>If you're using Scala commercially, are you worried about this? Are you planning to adopt 2.8 immediately or wait to see what happens?</li>
</ul>
<p><a href="http://en.wikipedia.org/wiki/Steve_Yegge" rel="noreferrer">Steve Yegge</a> <a href="http://steve-yegge.blogspot.com/2008/06/rhinos-and-tigers.html" rel="noreferrer">once attacked Scala</a> (mistakenly in my opinion) for what he saw as its overcomplicated type-system. I worry that someone is going to have a field day spreading <a href="http://en.wikipedia.org/wiki/Fear,_uncertainty_and_doubt" rel="noreferrer">FUD</a> with this API (similarly to how Josh Bloch scared the <a href="http://en.wikipedia.org/wiki/Java_Community_Process" rel="noreferrer">JCP</a> out of adding closures to Java).</p>
<p><strong>Note</strong> - <em>I should be clear that, whilst I believe that <a href="https://en.wikipedia.org/wiki/Joshua_Bloch" rel="noreferrer">Joshua Bloch</a> was influential in the rejection of the BGGA closures proposal, I don't ascribe this to anything other than his honestly-held beliefs that the proposal represented a mistake.</em></p>
<hr/>
<p>Despite whatever my wife and coworkers keep telling me, I don't think I'm an idiot: I have a good degree in mathematics from the <a href="http://www.ox.ac.uk/" rel="noreferrer">University of Oxford</a>, and I've been programming commercially for almost 12 years and in <a href="http://en.wikipedia.org/wiki/Scala_%28programming_language%29" rel="noreferrer">Scala</a> for about a year (also commercially).</p>
<p><em>Note the inflammatory subject title is a <a href="http://en.wikipedia.org/wiki/The_longest_suicide_note_in_history" rel="noreferrer">quotation made about the manifesto of a UK political party</a> in the early 1980s</em>. This question is subjective but it is a genuine question, I've made it CW and I'd like some opinions on the matter.</p> | <p>I hope it's not a "suicide note", but I can see your point. You hit on what is at the same time both a strength and a problem of Scala: its <strong>extensibility</strong>. This lets us implement most major functionality in libraries. In some other languages, sequences with something like <code>map</code> or <code>collect</code> would be built in, and nobody has to see all the hoops the compiler has to go through to make them work smoothly. In Scala, it's all in a library, and therefore out in the open.</p>
<p>In fact the functionality of <code>map</code> that's supported by its complicated type is pretty advanced. Consider this:</p>
<pre><code>scala> import collection.immutable.BitSet
import collection.immutable.BitSet
scala> val bits = BitSet(1, 2, 3)
bits: scala.collection.immutable.BitSet = BitSet(1, 2, 3)
scala> val shifted = bits map { _ + 1 }
shifted: scala.collection.immutable.BitSet = BitSet(2, 3, 4)
scala> val displayed = bits map { _.toString + "!" }
displayed: scala.collection.immutable.Set[java.lang.String] = Set(1!, 2!, 3!)
</code></pre>
<p>See how you always get the best possible type? If you map <code>Int</code>s to <code>Int</code>s you get again a <code>BitSet</code>, but if you map <code>Int</code>s to <code>String</code>s, you get a general <code>Set</code>. Both the static type and the runtime representation of map's result depend on the result type of the function that's passed to it. And this works even if the set is empty, so the function is never applied! As far as I know there is no other collection framework with an equivalent functionality. Yet from a user perspective this is how things are <em>supposed</em> to work.</p>
<p>The problem we have is that all the clever technology that makes this happen leaks into the type signatures which become large and scary. But maybe a user should not be shown by default the full type signature of <code>map</code>? How about if she looked up <code>map</code> in <code>BitSet</code> she got:</p>
<pre><code>map(f: Int => Int): BitSet (click here for more general type)
</code></pre>
<p>The docs would not lie in that case, because from a user perspective indeed map has the type <code>(Int => Int) => BitSet</code>. But <code>map</code> also has a more general type which can be inspected by clicking on another link.</p>
<p>We have not yet implemented functionality like this in our tools. But I believe we need to do this, to avoid scaring people off and to give more useful info. With tools like that, hopefully smart frameworks and libraries will not become suicide notes. </p> | {
"question_id": 1722726,
"question_date": "2009-11-12T14:49:57.267Z",
"question_score": 874,
"tags": "scala|scala-2.8|scala-collections",
"answer_id": 1728140,
"answer_date": "2009-11-13T09:28:46.170Z",
"answer_score": 890
} |
Please answer the following Stack Overflow question:
Title: SQL SELECT WHERE field contains words
<p>I need a select which would return results like this:</p>
<pre><code>SELECT * FROM MyTable WHERE Column1 CONTAINS 'word1 word2 word3'
</code></pre>
<p>And I need all results, i.e. this includes strings with 'word2 word3 word1' or 'word1 word3 word2' or any other combination of the three.</p>
<p>All words need to be in the result.</p> | <p>Rather slow, but working method to include <strong>any</strong> of words:</p>
<pre><code>SELECT * FROM mytable
WHERE column1 LIKE '%word1%'
OR column1 LIKE '%word2%'
OR column1 LIKE '%word3%'
</code></pre>
<p>If you need <strong>all</strong> words to be present, use this:</p>
<pre><code>SELECT * FROM mytable
WHERE column1 LIKE '%word1%'
AND column1 LIKE '%word2%'
AND column1 LIKE '%word3%'
</code></pre>
<p>If you want something faster, you need to look into full text search, and this is very specific for each database type.</p> | {
"question_id": 14290857,
"question_date": "2013-01-12T06:19:50.197Z",
"question_score": 873,
"tags": "sql|select",
"answer_id": 14290878,
"answer_date": "2013-01-12T06:21:46.640Z",
"answer_score": 1300
} |
Please answer the following Stack Overflow question:
Title: How do I comment out a block of tags in XML?
<p>How do I comment out a block of tags in XML?</p>
<p>I.e. How can I comment out <code><staticText></code> and everything inside it, in the code below?</p>
<pre><code> <detail>
<band height="20">
<staticText>
<reportElement x="180" y="0" width="200" height="20"/>
<text><![CDATA[Hello World!]]></text>
</staticText>
</band>
</detail>
</code></pre>
<p>I could use <code><!-- staticText--></code> but that's just for single tags (as what I know), like <code>//</code> in Java and C. I would like something more like how <code>/** comment **/</code> can be used in Java and C, so I can comment out longer blocks of XML code.</p> | <p>You can use that style of comment across multiple lines (which exists also in HTML)</p>
<pre><code><detail>
<band height="20">
<!--
Hello,
I am a multi-line XML comment
<staticText>
<reportElement x="180" y="0" width="200" height="20"/>
<text><![CDATA[Hello World!]]></text>
</staticText>
-->
</band>
</detail>
</code></pre> | {
"question_id": 2757396,
"question_date": "2010-05-03T10:31:24.907Z",
"question_score": 873,
"tags": "xml|comments",
"answer_id": 2757401,
"answer_date": "2010-05-03T10:33:03.223Z",
"answer_score": 1244
} |
Please answer the following Stack Overflow question:
Title: Adding options to a <select> using jQuery?
<p>What's the easiest way to add an <code>option</code> to a dropdown using jQuery? </p>
<p>Will this work?</p>
<pre><code>$("#mySelect").append('<option value=1>My option</option>');
</code></pre> | <p>This did NOT work in IE8 (yet did in FF):</p>
<pre><code>$("#selectList").append(new Option("option text", "value"));
</code></pre>
<p>This DID work:</p>
<pre><code>var o = new Option("option text", "value");
/// jquerify the DOM object 'o' so we can use the html method
$(o).html("option text");
$("#selectList").append(o);
</code></pre> | {
"question_id": 740195,
"question_date": "2009-04-11T14:34:04.563Z",
"question_score": 873,
"tags": "javascript|jquery|html-select",
"answer_id": 2162574,
"answer_date": "2010-01-29T14:37:36.943Z",
"answer_score": 373
} |
Please answer the following Stack Overflow question:
Title: How to cancel a local git commit?
<p>My issue is I have changed a file e.g.: README, added a new line '<em>this for my testing line</em>' and saved the file, then I issued the following commands:</p>
<pre><code>git status
# On branch master
# Changed but not updated:
# (use "git add <file>..." to update what will be committed)
# (use "git checkout -- <file>..." to discard changes in working directory)
#
# modified: README
#
no changes added to commit (use "git add" and/or "git commit -a")
git add README
git commit -a -m 'To add new line to readme'
</code></pre>
<p>I didn't push the code to GitHub. Now I want to cancel this commit.</p>
<p>For this, I used</p>
<pre><code>git reset --hard HEAD~1
</code></pre>
<p>But I lost the newly added line '<em>this for my testing line</em>' from the README file.
This should not happen. I need the content to be there. <strong>Is there a way to retain the content and cancel my local commit?</strong></p> | <p>Just use <code>git reset</code> without the <code>--hard</code> flag:</p>
<pre><code>git reset HEAD~1
</code></pre>
<p>PS: On Unix based systems you can use <code>HEAD^</code> which is equal to <code>HEAD~1</code>. On Windows <code>HEAD^</code> will not work because <code>^</code> signals a line continuation. So your command prompt will just ask you <code>More?</code>.</p> | {
"question_id": 4850717,
"question_date": "2011-01-31T12:14:48.060Z",
"question_score": 873,
"tags": "git|git-reset|git-commit",
"answer_id": 4850743,
"answer_date": "2011-01-31T12:17:08.753Z",
"answer_score": 1628
} |
Please answer the following Stack Overflow question:
Title: Rename master branch for both local and remote Git repositories
<p>I have the branch <code>master</code> which tracks the remote branch <code>origin/master</code>.</p>
<p>I want to rename them to <code>master-old</code> both locally and on the remote. Is this possible? </p>
<p>For other users who tracked <code>origin/master</code> (and who always updated their local <code>master</code> branch via <code>git pull</code>), what would happen after I renamed the remote branch?<br>
Would their <code>git pull</code> still work or would it throw an error that it couldn't find <code>origin/master</code> anymore?</p>
<p>Then, further on, I want to create a new <code>master</code> branch (both locally and remote). Again, after I did this, what would happen now if the other users do <code>git pull</code>?</p>
<p>I guess all this would result in a lot of trouble. Is there a clean way to get what I want? Or should I just leave <code>master</code> as it is and create a new branch <code>master-new</code> and just work there further on?</p> | <p>The closest thing to renaming is deleting and then recreating on the remote. For example:</p>
<pre class="lang-bash prettyprint-override"><code>git branch -m master master-old
git push remote :master # Delete master
git push remote master-old # Create master-old on remote
git checkout -b master some-ref # Create a new local master
git push remote master # Create master on remote
</code></pre>
<p>However, this has a lot of caveats. First, no existing checkouts will know about the rename - Git does <em>not</em> attempt to track branch renames. If the new <code>master</code> doesn't exist yet, <em>git pull</em> will error out. If the new <code>master</code> has been created. the pull will attempt to merge <code>master</code> and <code>master-old</code>. So it's generally a bad idea unless you have the cooperation of everyone who has checked out the repository previously.</p>
<p>Note: Newer versions of Git will not allow you to delete the master branch remotely by default. You can override this by setting the <code>receive.denyDeleteCurrent</code> configuration value to <code>warn</code> or <code>ignore</code> on the <em>remote</em> repository. Otherwise, if you're ready to create a new master right away, skip the <code>git push remote :master</code> step, and pass <code>--force</code> to the <code>git push remote master</code> step. Note that if you're not able to change the remote's configuration, you won't be able to completely delete the master branch!</p>
<p>This caveat only applies to the current branch (usually the <code>master</code> branch); any other branch can be deleted and recreated as above.</p> | {
"question_id": 1526794,
"question_date": "2009-10-06T16:51:57.323Z",
"question_score": 873,
"tags": "git|git-branch|git-pull",
"answer_id": 1527004,
"answer_date": "2009-10-06T17:35:11.310Z",
"answer_score": 643
} |
Please answer the following Stack Overflow question:
Title: How to initialize HashSet values by construction?
<p>I need to create a <code>Set</code> with initial values.</p>
<pre><code>Set<String> h = new HashSet<String>();
h.add("a");
h.add("b");
</code></pre>
<p>Is there a way to do this in one line of code? For instance, it's useful for a final static field.</p> | <p>There is a shorthand that I use that is not very time efficient, but fits on a single line:</p>
<pre><code>Set<String> h = new HashSet<>(Arrays.asList("a", "b"));
</code></pre>
<p>Again, this is not time efficient since you are constructing an array, converting to a list and using that list to create a set.</p>
<p>When initializing static final sets I usually write it like this:</p>
<pre><code>public static final String[] SET_VALUES = new String[] { "a", "b" };
public static final Set<String> MY_SET = new HashSet<>(Arrays.asList(SET_VALUES));
</code></pre>
<p>Slightly less ugly and efficiency does not matter for the static initialization.</p> | {
"question_id": 2041778,
"question_date": "2010-01-11T12:31:50.687Z",
"question_score": 872,
"tags": "java|collections|constructor|initialization|hashset",
"answer_id": 2041810,
"answer_date": "2010-01-11T12:38:01.390Z",
"answer_score": 1102
} |
Please answer the following Stack Overflow question:
Title: Getting the client's time zone (and offset) in JavaScript
<p>How can I gather the visitor's time zone information?</p>
<p>I need both:</p>
<ol>
<li>the time zone (for example, Europe/London)</li>
<li>and the offset from UTC or GMT (for example, UTC+01)</li>
</ol> | <h1>Using <code>getTimezoneOffset()</code></h1>
<p>You can get the time zone <em>offset</em> in minutes like this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var offset = new Date().getTimezoneOffset();
console.log(offset);
// if offset equals -60 then the time zone offset is UTC+01</code></pre>
</div>
</div>
</p>
<blockquote>
<p>The time-zone offset is the difference, in minutes, between UTC and local time. Note that this means that the offset is positive if the local timezone is behind UTC and negative if it is ahead. For example, if your time zone is UTC+10 (Australian Eastern Standard Time), -600 will be returned. Daylight savings time prevents this value from being a constant even for a given locale</p>
</blockquote>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset" rel="noreferrer">Mozilla Date Object reference</a></li>
</ul>
<p>Note that not all timezones are offset by whole hours: for example, Newfoundland is UTC minus 3h 30m (leaving Daylight Saving Time out of the equation).</p>
<p>Please also note that this only gives you the time zone offset (eg: UTC+01), it does not give you the time zone (eg: Europe/London).</p> | {
"question_id": 1091372,
"question_date": "2009-07-07T09:48:16.783Z",
"question_score": 872,
"tags": "javascript|timezone",
"answer_id": 1091399,
"answer_date": "2009-07-07T09:53:56.087Z",
"answer_score": 730
} |
Please answer the following Stack Overflow question:
Title: How to fix docker: Got permission denied issue
<p>I installed Docker in my machine where I have Ubuntu OS.<br />
When I run:</p>
<pre><code>sudo docker run hello-world
</code></pre>
<p>All is ok, but I want to hide the <code>sudo</code> command to make the command shorter.<br />
If I write the command without <code>sudo</code></p>
<pre><code>docker run hello-world
</code></pre>
<p>That displays the following:</p>
<pre><code>docker: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Post http://%2Fvar%2Frun%2Fdocker.sock/v1.35/containers/create: dial unix /var/run/docker.sock: connect: permission denied. See 'docker run --help'.
</code></pre>
<p>The same happens when I try to run:</p>
<pre><code>docker-compose up
</code></pre>
<p>How can I resolve this?</p> | <p>If you want to run docker as non-root user then you need to add it to the docker group.</p>
<ol>
<li>Create the docker group if it does not exist</li>
</ol>
<pre class="lang-sh prettyprint-override"><code>$ sudo groupadd docker
</code></pre>
<ol start="2">
<li>Add your user to the docker group.</li>
</ol>
<pre class="lang-sh prettyprint-override"><code>$ sudo usermod -aG docker $USER
</code></pre>
<ol start="3">
<li>Run the following command or Logout and login again and run (that doesn't work you may need to reboot your machine first)</li>
</ol>
<pre class="lang-sh prettyprint-override"><code>$ newgrp docker
</code></pre>
<ol start="4">
<li>Check if docker can be run without root</li>
</ol>
<pre class="lang-sh prettyprint-override"><code>$ docker run hello-world
</code></pre>
<p>Reboot if still got error</p>
<pre class="lang-sh prettyprint-override"><code>$ reboot
</code></pre>
<p><strong>Warning</strong></p>
<blockquote>
<p>The docker group grants privileges equivalent to the root user. For details on how this impacts security in your system, see <a href="https://docs.docker.com/engine/security/#docker-daemon-attack-surface" rel="noreferrer">Docker Daemon Attack Surface.</a>.</p>
</blockquote>
<p>Taken from the docker official documentation:
<a href="https://docs.docker.com/install/linux/linux-postinstall/#manage-docker-as-a-non-root-user" rel="noreferrer">manage-docker-as-a-non-root-user</a></p> | {
"question_id": 48957195,
"question_date": "2018-02-23T22:38:58.363Z",
"question_score": 872,
"tags": "docker|docker-compose",
"answer_id": 48957722,
"answer_date": "2018-02-23T23:40:15.617Z",
"answer_score": 1625
} |
Please answer the following Stack Overflow question:
Title: Automatically create requirements.txt
<p>Sometimes I download the python source code from <code>github</code> and don't know how to install all the dependencies. If there is no <code>requirements.txt</code> file I have to create it by hands.<br />
The question is:<br />
Given the python source code directory is it possible to create <code>requirements.txt</code> automatically from the import section?</p> | <p>Use <a href="https://packaging.python.org/tutorials/managing-dependencies/#managing-dependencies" rel="noreferrer">Pipenv</a> or other tools is recommended for improving your development flow.</p>
<pre><code>pip3 freeze > requirements.txt # Python3
pip freeze > requirements.txt # Python2
</code></pre>
<p>If you do not use a virtual environment, <a href="https://github.com/Damnever/pigar" rel="noreferrer">pigar</a> will be a good choice for you.</p> | {
"question_id": 31684375,
"question_date": "2015-07-28T18:29:03.303Z",
"question_score": 871,
"tags": "python|dependencies|python-import|requirements.txt",
"answer_id": 33468993,
"answer_date": "2015-11-02T00:39:32.483Z",
"answer_score": 933
} |
Please answer the following Stack Overflow question:
Title: SQL JOIN - WHERE clause vs. ON clause
<p>After reading it, this is <em>not</em> a duplicate of <a href="https://stackoverflow.com/questions/44917/explicit-vs-implicit-sql-joins">Explicit vs Implicit SQL Joins</a>.
The answer may be related (or even the same) but the <strong>question</strong> is different.</p>
<hr>
<p>What is the difference and what should go in each?</p>
<p>If I understand the theory correctly, the query optimizer should be able to use both interchangeably.</p> | <p>They are not the same thing.</p>
<p>Consider these queries:</p>
<pre><code>SELECT *
FROM Orders
LEFT JOIN OrderLines ON OrderLines.OrderID=Orders.ID
WHERE Orders.ID = 12345
</code></pre>
<p>and</p>
<pre><code>SELECT *
FROM Orders
LEFT JOIN OrderLines ON OrderLines.OrderID=Orders.ID
AND Orders.ID = 12345
</code></pre>
<p>The first will return an order and its lines, if any, for order number <code>12345</code>. The second will return all orders, but only order <code>12345</code> will have any lines associated with it.</p>
<p>With an <code>INNER JOIN</code>, the clauses are <em>effectively</em> equivalent. However, just because they are functionally the same, in that they produce the same results, does not mean the two kinds of clauses have the same semantic meaning.</p> | {
"question_id": 354070,
"question_date": "2008-12-09T20:14:52.187Z",
"question_score": 871,
"tags": "sql|join|where-clause|on-clause",
"answer_id": 354094,
"answer_date": "2008-12-09T20:21:10.613Z",
"answer_score": 1078
} |
Please answer the following Stack Overflow question:
Title: How to display HTML in TextView?
<p>I have simple <strong>HTML</strong>:</p>
<pre><code><h2>Title</h2><br>
<p>description here</p>
</code></pre>
<p>I want to display HTML styled text it in <code>TextView</code>. How to do this?</p> | <p>You need to use <a href="http://developer.android.com/reference/android/text/Html.html#fromHtml%28java.lang.String%29" rel="noreferrer"><code>Html.fromHtml()</code></a> to use HTML in your XML Strings. Simply referencing a String with HTML in your layout XML will not work.</p>
<p>This is what you should do in Java</p>
<pre><code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
textView.setText(Html.fromHtml("<h2>Title</h2><br><p>Description here</p>", Html.FROM_HTML_MODE_COMPACT));
} else {
textView.setText(Html.fromHtml("<h2>Title</h2><br><p>Description here</p>"));
}
</code></pre>
<p>And in Kotlin:</p>
<pre><code>textView.text = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(html, Html.FROM_HTML_MODE_COMPACT)
} else {
Html.fromHtml(html)
}
</code></pre> | {
"question_id": 2116162,
"question_date": "2010-01-22T09:14:22.173Z",
"question_score": 871,
"tags": "android|html|xml-parsing|textview",
"answer_id": 2116191,
"answer_date": "2010-01-22T09:20:22.643Z",
"answer_score": 1546
} |
Please answer the following Stack Overflow question:
Title: How does one remove a Docker image?
<p>I'm running Docker under Vagrant under OS X 10.8.4 (Mountain Lion), and whenever I try to delete a saved image, I get an error:</p>
<pre><code>$ docker rmi some-image-id
2013/07/15 hh:mm:ss unexpected JSON input
</code></pre>
<p>According to the <code>rmi</code> help, the proper syntax is <code>docker rmi IMAGE [IMAGE...]</code>, and I'm not sure what to make of that.</p>
<p>How can I delete an image?</p>
<pre><code>$ docker version
Client version: 0.4.8
Server version: 0.4.8
Go version: go1.1
</code></pre>
<p> </p>
<pre><code>$docker info
Containers: 1
Images: 3
</code></pre>
<p>Interestingly, when I run <code>docker ps</code>, no containers show up at all. Running <code>docker images</code> shows four (4) <code>base</code> images and one (1) <code>node</code> image.</p> | <p>Try <code>docker rmi node</code>. That should work. </p>
<p>Seeing all created containers is as simple as <code>docker ps -a</code>. </p>
<p>To remove all existing containers (not images!) run <code>docker rm $(docker ps -aq)</code></p> | {
"question_id": 17665283,
"question_date": "2013-07-15T22:56:02.127Z",
"question_score": 871,
"tags": "docker",
"answer_id": 17870293,
"answer_date": "2013-07-25T23:09:09.553Z",
"answer_score": 1031
} |
Please answer the following Stack Overflow question:
Title: Code formatting shortcuts in Android Studio for Operation Systems
<p>I have started developing with <a href="http://developer.android.com/sdk/installing/studio.html" rel="noreferrer">Android Studio</a>. In Eclipse I was using <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>F</kbd>, but in Android Studio it does not work. It will be different.</p>
<p>How can I jump to any method in a <code>.java</code> file? I was using <kbd>Ctrl</kbd> + <kbd>O</kbd> in Eclipse.</p>
<p>Is it available? What is the shortcut for code formatting?</p> | <p>Windows: <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>L</kbd></p>
<p>Linux: <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Alt</kbd> + <kbd>L</kbd></p>
<p>macOS: <kbd>Option</kbd> + <kbd>Command</kbd> + <kbd>L</kbd></p>
<p>Reference: <a href="https://developer.android.com/sdk/installing/studio-tips.html#KeyCommands" rel="noreferrer">Key Commands</a> and here are all of the commands for <a href="https://www.jetbrains.com/idea/docs/IntelliJIDEA_ReferenceCard.pdf" rel="noreferrer">Windows/ Linux users</a> and for <a href="http://www.jetbrains.com/idea/docs/IntelliJIDEA_ReferenceCard_Mac.pdf" rel="noreferrer">Mac users</a>.</p>
<hr />
<p>As Rohit faced a problem in Ubuntu with the format code shortcut, this is due to the <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>L</kbd> key being used to lock the screen in Ubuntu.</p>
<p>I found that Ubuntu handles this keyboard shortcut first. So you should bind the <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>L</kbd> keyboard shortcut to something else so that it doesn't conflict with Ubuntu.</p>
<h2>Steps</h2>
<ol>
<li><p>Go to <em>System Tools</em> → <em>System Settings</em> → <em>Keyboard</em> → <em>Shortcuts</em> tab → <em>System</em> → <em>Lock Screen</em>.</p>
</li>
<li><p>Select the row <em>New Accelerator...</em>, then press any special key with the Alpha key (e.g. <kbd>Shift</kbd> + <kbd>L</kbd>). You should've successfully changed the keyboard shortcut.</p>
</li>
<li><p>Check if the keyboard shortcut now works in Android Studio.</p>
</li>
</ol>
<h2>Alternative method</h2>
<blockquote>
<p><kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>Shift</kbd> + <kbd>L</kbd> (to show a dialog)</p>
</blockquote>
<hr />
<p>You can also use Eclipse shortcuts.</p>
<ul>
<li>Windows and Linux: Go to menu <em>File</em> → <em>Settings</em> → <em>Keymap</em></li>
<li>macOS: Go to menu <em>Preferences</em> → <em>Keymap</em> and choose Eclipse from the drop-down menu.</li>
</ul>
<h3>Using MenuBar</h3>
<ul>
<li><p>Select code which you want to reformat</p>
</li>
<li><p>Click on <strong>Code</strong> in the menu bar and select <em>Reformat Code</em> as shown in the image below:</p>
<p><a href="https://i.stack.imgur.com/xVAIu.png" rel="noreferrer"><img src="https://i.stack.imgur.com/xVAIu.png" alt="Enter image description here" /></a></p>
</li>
</ul>
<p>In Android studio 3.5, there is problem with rearranging the xml code, it also rearrange the views as well, so need to use these settings first.</p>
<p>Settings -> Editor -> Code Style -> XML-> Set From -> Predefined Style > Android.</p>
<h1>Update for Android Studio 4+</h1>
<p>Since Android Studio 4+, you might face issue shortcuts on mac. <a href="https://stackoverflow.com/questions/62305912/shortcuts-not-working-after-updating-to-android-studio-4-in-mac">Shortcuts not working after updating to Android studio 4, in Mac?</a> have an answer for that.</p> | {
"question_id": 16580171,
"question_date": "2013-05-16T06:10:42.120Z",
"question_score": 871,
"tags": "android-studio|code-formatting",
"answer_id": 16580200,
"answer_date": "2013-05-16T06:13:05.240Z",
"answer_score": 1864
} |
Please answer the following Stack Overflow question:
Title: What's the simplest way to list conflicted files in Git?
<p>I just need a plain list of <em>conflicted</em> files.</p>
<p>Is there anything simpler than:</p>
<pre><code>git ls-files -u | cut -f 2 | sort -u
</code></pre>
<p>or:</p>
<pre><code>git ls-files -u | awk '{print $4}' | sort | uniq
</code></pre>
<p>I guess I could set up a handy <code>alias</code> for that, however was wondering how pros do it. I'd use it to write shell loops e.g. to auto-resolve conflict, etc. Maybe replace that loop by plugging into <code>mergetool.cmd</code>?</p> | <p>Use git diff, with <a href="https://git-scm.com/docs/git-diff#Documentation/git-diff.txt---name-only" rel="noreferrer">name-only</a> to show only the names, and <a href="https://git-scm.com/docs/git-diff#Documentation/git-diff.txt---diff-filterACDMRTUXB82308203" rel="noreferrer">diff-filter=U</a> to only include 'Unmerged' files (optionally, <a href="https://git-scm.com/docs/git-diff#Documentation/git-diff.txt---relativeltpathgt" rel="noreferrer">relative</a> to show paths relative to current working directory) .</p>
<pre><code>git diff --name-only --diff-filter=U --relative
</code></pre> | {
"question_id": 3065650,
"question_date": "2010-06-17T21:08:52.290Z",
"question_score": 871,
"tags": "git|git-merge|git-merge-conflict",
"answer_id": 10874862,
"answer_date": "2012-06-03T23:43:59.907Z",
"answer_score": 1509
} |
Please answer the following Stack Overflow question:
Title: Check if an element contains a class in JavaScript?
<p>Using plain JavaScript (not jQuery), Is there any way to check if an element <em>contains</em> a class?</p>
<p>Currently, I'm doing this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var test = document.getElementById("test");
var testClass = test.className;
switch (testClass) {
case "class1":
test.innerHTML = "I have class1";
break;
case "class2":
test.innerHTML = "I have class2";
break;
case "class3":
test.innerHTML = "I have class3";
break;
case "class4":
test.innerHTML = "I have class4";
break;
default:
test.innerHTML = "";
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="test" class="class1"></div></code></pre>
</div>
</div>
</p>
<p>The issue is that if I change the HTML to this...</p>
<pre><code><div id="test" class="class1 class5"></div>
</code></pre>
<p>...there's no longer an exact match, so I get the default output of nothing (<code>""</code>). But I still want the output to be <code>I have class1</code> because the <code><div></code> still <em>contains</em> the <code>.class1</code> class.</p> | <p>Use <a href="https://developer.mozilla.org/en-US/docs/DOM/element.classList" rel="noreferrer"><code>element.classList</code></a> <code>.contains</code> method:</p>
<pre><code>element.classList.contains(class);
</code></pre>
<p>This works on all current browsers and there are polyfills to support older browsers too.</p>
<hr />
<p><strong>Alternatively</strong>, if you work with older browsers and don't want to use polyfills to fix them, using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf" rel="noreferrer"><code>indexOf</code></a> is correct, but you have to tweak it a little:</p>
<pre><code>function hasClass(element, className) {
return (' ' + element.className + ' ').indexOf(' ' + className+ ' ') > -1;
}
</code></pre>
<p>Otherwise you will also get <code>true</code> if the class you are looking for is part of another class name.</p>
<p><a href="http://jsfiddle.net/fkling/zBKCC/" rel="noreferrer"><strong>DEMO</strong></a></p>
<p>jQuery uses a similar (if not the same) method.</p>
<hr />
<p><strong>Applied to the example:</strong></p>
<p>As this does not work together with the switch statement, you could achieve the same effect with this code:</p>
<pre><code>var test = document.getElementById("test"),
classes = ['class1', 'class2', 'class3', 'class4'];
test.innerHTML = "";
for(var i = 0, j = classes.length; i < j; i++) {
if(hasClass(test, classes[i])) {
test.innerHTML = "I have " + classes[i];
break;
}
}
</code></pre>
<p>It's also less redundant ;)</p> | {
"question_id": 5898656,
"question_date": "2011-05-05T13:40:19.623Z",
"question_score": 870,
"tags": "javascript|html|css|dom",
"answer_id": 5898748,
"answer_date": "2011-05-05T13:46:49.143Z",
"answer_score": 1527
} |
Please answer the following Stack Overflow question:
Title: Difference between text and varchar (character varying)
<p>What's the difference between the <code>text</code> data type and the <code>character varying</code> (<code>varchar</code>) data types?</p>
<p>According to <a href="http://www.postgresql.org/docs/8.0/interactive/datatype-character.html" rel="noreferrer">the documentation</a></p>
<blockquote>
<p>If character varying is used without length specifier, the type accepts strings of any size. The latter is a PostgreSQL extension.</p>
</blockquote>
<p>and</p>
<blockquote>
<p>In addition, PostgreSQL provides the text type, which stores strings of any length. Although the type text is not in the SQL standard, several other SQL database management systems have it as well.</p>
</blockquote>
<p>So what's the difference?</p> | <p>There is no difference, under the hood it's all <code>varlena</code> (<a href="http://www.varlena.com/varlena.php" rel="noreferrer">variable length array</a>).</p>
<p>Check this article from Depesz: <a href="http://www.depesz.com/index.php/2010/03/02/charx-vs-varcharx-vs-varchar-vs-text/" rel="noreferrer">http://www.depesz.com/index.php/2010/03/02/charx-vs-varcharx-vs-varchar-vs-text/</a></p>
<p>A couple of highlights:</p>
<blockquote>
<p>To sum it all up:</p>
<ul>
<li>char(n) – takes too much space when dealing with values shorter than <code>n</code> (pads them to <code>n</code>), and can lead to subtle errors because of adding trailing
spaces, plus it is problematic to change the limit</li>
<li>varchar(n) – it's problematic to change the limit in live environment (requires exclusive lock while altering table)</li>
<li>varchar – just like text</li>
<li><strong>text – for me a winner</strong> – over (n) data types because it lacks their problems, and over varchar – because it has distinct name</li>
</ul>
</blockquote>
<p>The article does detailed testing to show that the performance of inserts and selects for all 4 data types are similar. It also takes a detailed look at alternate ways on constraining the length when needed. Function based constraints or domains provide the advantage of instant increase of the length constraint, and on the basis that decreasing a string length constraint is rare, depesz concludes that one of them is usually the best choice for a length limit.</p> | {
"question_id": 4848964,
"question_date": "2011-01-31T08:44:34.020Z",
"question_score": 870,
"tags": "string|postgresql|text|types|varchar",
"answer_id": 4849030,
"answer_date": "2011-01-31T08:55:19.273Z",
"answer_score": 1042
} |
Please answer the following Stack Overflow question:
Title: git error: failed to push some refs to remote
<p>I can't push now, though I could do it yesterday.</p>
<p>When I use <code>git push origin master</code>, I get an error:</p>
<pre><code>$ git remote -v
origin https://github.com/REDACTED.git (fetch)
origin https://github.com/REDACTED.git (push)
$ git push origin master
Username for 'https://github.com': REDACTED
Password for 'https://[email protected]':
To https://github.com/REDACTED.git
! [rejected] master -> master (non-fast-forward)
error: failed to push some refs to 'https://github.com/REDACTED.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
</code></pre>
<p>What my working directory and remote repository looks like:</p>
<p><img src="https://i.stack.imgur.com/Sz17u.png" alt="Screenshot of Windows file folder with these directories: .git, css, js. And these files: index.php, readme, setsu.php. The word "local" with an arrow points to the css-folder. Below, screenshot with heading "github", and a css-folder and index.php-file" /></p> | <p>(Note: <a href="https://github.blog/changelog/2020-08-26-set-the-default-branch-for-newly-created-repositories/" rel="noreferrer">starting Oct. 2020</a>, any new repository is created with the default branch <code>main</code>, not <code>master</code>. And you can <a href="https://github.com/github/renaming" rel="noreferrer">rename existing repository default branch from <code>master</code> to <code>main</code></a>.<br />
The rest of this 2014 answer has been updated to use "<code>main</code>")</p>
<p>(The following assumes <code>github.com</code> itself is <em>not</em> down, as <a href="https://stackoverflow.com/users/965638/eri0o">eri0o</a> points out in <a href="https://stackoverflow.com/questions/24114676/git-error-failed-to-push-some-refs-to-remote/24114760#comment121465079_24114676">the comments</a>: see <a href="https://www.githubstatus.com/" rel="noreferrer"><code>www.githubstatus.com</code></a> to be sure)</p>
<p>If the GitHub repo has seen new commits pushed to it, while you were working locally, I would advise using:</p>
<pre><code>git pull --rebase
git push
</code></pre>
<p>The full syntax is:</p>
<pre><code>git pull --rebase origin main
git push origin main
</code></pre>
<p><a href="https://stackoverflow.com/a/30209750/6309">With Git 2.6+</a> (Sept. 2015), after having done (once)</p>
<pre><code>git config --global pull.rebase true
git config --global rebase.autoStash true
</code></pre>
<p>A simple <code>git pull</code> would be enough.<br />
(Note: with <a href="https://stackoverflow.com/a/61562652/6309">Git 2.27 Q2 2020</a>, a <code>merge.autostash</code> is also available for your regular pull, without rebase)</p>
<p>That way, you would replay (the <code>--rebase</code> part) your local commits on top of the newly updated <code>origin/main</code> (or <code>origin/yourBranch</code>: <code>git pull origin yourBranch</code>).</p>
<p>See a more complete example in the <a href="http://chimera.labs.oreilly.com/books/1230000000561/ch06.html#pull-rebase" rel="noreferrer">chapter 6 Pull with rebase</a> of the <a href="http://chimera.labs.oreilly.com/books/1230000000561" rel="noreferrer">Git Pocket Book</a>.</p>
<p>I would recommend a:</p>
<pre><code># add and commit first
#
git push -u origin main
# Or git 2.37 Q2 2022+
git config --global push.autoSetupRemote true
git push
</code></pre>
<p>That would establish a tracking relationship between your local main branch and its upstream branch.<br />
After that, any future push for that branch can be done with a simple:</p>
<pre><code>git push
</code></pre>
<p>Again, with <a href="https://stackoverflow.com/a/72401899/6309">Git 2.37+ and its global option <code>push.autoSetupRemote</code></a>, a simple <code>git push</code> even for the first one would do the same (I.e: establishing a tracking relationship between your local <code>main</code> branch and its upstream branch <code>origin/main</code>).</p>
<p>See "<a href="https://stackoverflow.com/a/17096880/6309">Why do I need to explicitly push a new branch?</a>".</p>
<hr />
<p>Since the OP already <a href="https://stackoverflow.com/a/18589043/6309">reset and redone its commit</a> on top of <code>origin/main</code>:</p>
<pre><code>git reset --mixed origin/main
git add .
git commit -m "This is a new commit for what I originally planned to be amended"
git push origin main
</code></pre>
<p>There is no need to <code>pull --rebase</code>.</p>
<p>Note: <code>git reset --mixed origin/main</code> can also be written <code>git reset origin/main</code>, since the <code>--mixed</code> option is the default one when using <a href="http://git-scm.com/docs/git-reset" rel="noreferrer"><code>git reset</code></a>.</p> | {
"question_id": 24114676,
"question_date": "2014-06-09T06:21:26.680Z",
"question_score": 869,
"tags": "git|github",
"answer_id": 24114760,
"answer_date": "2014-06-09T06:28:17.683Z",
"answer_score": 1097
} |
Please answer the following Stack Overflow question:
Title: Moment.js transform to date object
<p>Using Moment.js I can't transform a correct moment object to a date object with timezones. I can't get the correct date.</p>
<p><strong>Example:</strong></p>
<pre><code>var oldDate = new Date(),
momentObj = moment(oldDate).tz("MST7MDT"),
newDate = momentObj.toDate();
console.log("start date " + oldDate)
console.log("Format from moment with offset " + momentObj.format())
console.log("Format from moment without offset " + momentObj.utc().format())
console.log("(Date object) Time with offset " + newDate)
console.log("(Date object) Time without offset "+ moment.utc(newDate).toDate())
</code></pre> | <p>Use this to transform a moment object into a date object:</p>
<p>From <a href="http://momentjs.com/docs/#/displaying/as-javascript-date/">http://momentjs.com/docs/#/displaying/as-javascript-date/</a></p>
<pre><code>moment().toDate();
</code></pre>
<p>Yields:</p>
<pre><code>Tue Nov 04 2014 14:04:01 GMT-0600 (CST)
</code></pre> | {
"question_id": 17987647,
"question_date": "2013-08-01T07:25:25.843Z",
"question_score": 869,
"tags": "javascript|momentjs",
"answer_id": 26744045,
"answer_date": "2014-11-04T20:06:33.373Z",
"answer_score": 1550
} |
Please answer the following Stack Overflow question:
Title: In a Bash script, how can I exit the entire script if a certain condition occurs?
<p>I'm writing a script in Bash to test some code. However, it seems silly to run the tests if compiling the code fails in the first place, in which case I'll just abort the tests.</p>
<p>Is there a way I can do this without wrapping the entire script inside of a while loop and using breaks? Something like a <strong>dun dun dun</strong> goto?</p> | <p>Try this statement:</p>
<pre><code>exit 1
</code></pre>
<p>Replace <code>1</code> with appropriate error codes. See also <a href="http://www.tldp.org/LDP/abs/html/exitcodes.html" rel="noreferrer">Exit Codes With Special Meanings</a>.</p> | {
"question_id": 1378274,
"question_date": "2009-09-04T09:51:52.710Z",
"question_score": 869,
"tags": "bash|scripting|exit|exit-code",
"answer_id": 1378284,
"answer_date": "2009-09-04T09:53:53.160Z",
"answer_score": 1019
} |
Please answer the following Stack Overflow question:
Title: Clearing localStorage in javascript?
<p>Is there any way to reset/clear browser's localStorage in javascript?</p> | <p>Use this to clear localStorage:</p>
<pre><code>localStorage.clear();
</code></pre> | {
"question_id": 7667958,
"question_date": "2011-10-05T21:26:53.873Z",
"question_score": 869,
"tags": "javascript|local-storage",
"answer_id": 7667973,
"answer_date": "2011-10-05T21:28:26.593Z",
"answer_score": 1576
} |
Please answer the following Stack Overflow question:
Title: CSS 100% height with padding/margin
<p>With HTML/CSS, how can I make an element that has a width and/or height that is 100% of it's parent element and still has proper padding or margins?</p>
<p>By "proper" I mean that if my parent element is <code>200px</code> tall and I specify <code>height = 100%</code> with <code>padding = 5px</code> I would expect that I should get a <code>190px</code> high element with <code>border = 5px</code> on all sides, nicely centered in the parent element.</p>
<p>Now, I know that that's not how the standard box model specifies it should work (although I'd like to know why, exactly...), so the obvious answer doesn't work:</p>
<pre class="lang-css prettyprint-override"><code>#myDiv {
width: 100%
height: 100%;
padding: 5px;
}
</code></pre>
<p>But it would seem to me that there must be SOME way of reliably producing this effect for a parent of arbitrary size. Does anyone know of a way of accomplishing this (seemingly simple) task?</p>
<p>Oh, and for the record I'm not terribly interested in IE compatibility so that should (hopefully) make things a bit easier. </p>
<p><strong>EDIT:</strong> Since an example was asked for, here's the simplest one I can think of:</p>
<pre class="lang-html prettyprint-override"><code><html style="height: 100%">
<body style="height: 100%">
<div style="background-color: black; height: 100%; padding: 25px"></div>
</body>
</html>
</code></pre>
<p>The challenge is then to get the black box to show up with a 25 pixel padding on all edges without the page growing big enough to require scrollbars.</p> | <p>I learned how to do these sort of things reading "<a href="http://cssdesignpatterns.com/" rel="noreferrer">PRO HTML and CSS Design Patterns</a>". The <code>display:block</code> is the default display value for the <code>div</code>, but I like to make it explicit. The container has to be the right type; <code>position</code> attribute is <code>fixed</code>, <code>relative</code>, or <code>absolute</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>.stretchedToMargin {
display: block;
position:absolute;
height:auto;
bottom:0;
top:0;
left:0;
right:0;
margin-top:20px;
margin-bottom:20px;
margin-right:80px;
margin-left:80px;
background-color: green;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="stretchedToMargin">
Hello, world
</div></code></pre>
</div>
</div>
</p>
<p><a href="http://jsfiddle.net/Rpdr9/" rel="noreferrer">Fiddle</a> by Nooshu's <a href="https://stackoverflow.com/questions/485827/css-100-height-with-padding-margin#comment2356498_485887">comment</a></p> | {
"question_id": 485827,
"question_date": "2009-01-27T23:28:18.187Z",
"question_score": 869,
"tags": "css",
"answer_id": 485887,
"answer_date": "2009-01-27T23:53:17.637Z",
"answer_score": 784
} |
Please answer the following Stack Overflow question:
Title: Why does "npm install" rewrite package-lock.json?
<p>I just recently upgraded to <em>npm@5</em>. I now have a <em>package-lock.json</em> file with everything from <em>package.json</em>. I would expect that, when I run <code>npm install</code> that the dependency versions would be pulled from the lock file to determine what should be installed in my <em>node_modules</em> directory. What's strange is that it actually ends up modifying and rewriting my <em>package-lock.json</em> file.</p>
<p>For example, the lock file had typescript specified to be at version <em>2.1.6</em>. Then, after the <code>npm install</code> command, the version was changed to <em>2.4.1</em>. That seems to defeat the whole purpose of a lock file.</p>
<p>What am I missing? How do I get npm to actually respect my lock file?</p> | <p><strong>Update 3:</strong> As other answers point out as well, the <code>npm ci</code> command got introduced in npm 5.7.0 as additional way to achieve fast and reproducible builds in the CI context. See the <a href="https://docs.npmjs.com/cli/ci.html" rel="nofollow noreferrer">documentation</a> and <a href="https://blog.npmjs.org/post/171556855892/introducing-npm-ci-for-faster-more-reliable" rel="nofollow noreferrer">npm blog</a> for further information.</p>
<hr />
<p><strong>Update 2:</strong> The issue to update and clarify the documentation is <a href="https://github.com/npm/npm/issues/18103" rel="nofollow noreferrer">GitHub issue #18103</a>.</p>
<hr />
<p><strong>Update 1:</strong> The behaviour that was described below got fixed in npm 5.4.2: the currently intended behaviour is outlined in <a href="https://github.com/npm/npm/issues/17979#issuecomment-332701215" rel="nofollow noreferrer">GitHub issue #17979</a>.</p>
<hr />
<p><strong>Original answer (pre-5.4.2):</strong> The behaviour of <code>package-lock.json</code> was changed in <a href="https://github.com/npm/npm/releases/tag/v5.1.0" rel="nofollow noreferrer">npm 5.1.0</a> as discussed in <a href="https://github.com/npm/npm/issues/16866" rel="nofollow noreferrer">issue #16866</a>. The behaviour that you observe is apparently intended by npm as of version 5.1.0.</p>
<p>That means that <code>package.json</code> can override <code>package-lock.json</code> whenever a newer version is found for a dependency in <code>package.json</code>. If you want to pin your dependencies effectively, you now must specify the versions without a prefix, e.g., you need to write them as <code>1.2.0</code> instead of <code>~1.2.0</code> or <code>^1.2.0</code>. Then the combination of <code>package.json</code> and <code>package-lock.json</code> will yield reproducible builds. To be clear: <code>package-lock.json</code> alone no longer locks the root level dependencies!</p>
<p>Whether this design decision was good or not is arguable, there is an ongoing discussion resulting from this confusion on GitHub in <a href="https://github.com/npm/npm/issues/17979" rel="nofollow noreferrer">issue #17979</a>. (In my eyes it is a questionable decision; at least the name <code>lock</code> doesn't hold true any longer.)</p>
<p>One more side note: there is also a restriction for registries that don’t support immutable packages, such as when you pull packages directly from GitHub instead of npmjs.org. See <a href="https://docs.npmjs.com/files/package-locks" rel="nofollow noreferrer">this documentation of package locks</a> for further explanation.</p> | {
"question_id": 45022048,
"question_date": "2017-07-10T21:38:49.340Z",
"question_score": 869,
"tags": "node.js|npm|npm-install|package-lock.json",
"answer_id": 45566871,
"answer_date": "2017-08-08T11:16:35.910Z",
"answer_score": 585
} |
Please answer the following Stack Overflow question:
Title: Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?
<p>I'm a bit confused about how Java generics handle inheritance / polymorphism.</p>
<p>Assume the following hierarchy -</p>
<p><strong>Animal</strong> (Parent)</p>
<p><strong>Dog</strong> - <strong>Cat</strong> (Children)</p>
<p>So suppose I have a method <code>doSomething(List<Animal> animals)</code>. By all the rules of inheritance and polymorphism, I would assume that a <code>List<Dog></code> <em>is</em> a <code>List<Animal></code> and a <code>List<Cat></code> <em>is</em> a <code>List<Animal></code> - and so either one could be passed to this method. Not so. If I want to achieve this behavior, I have to explicitly tell the method to accept a list of any subclass of Animal by saying <code>doSomething(List<? extends Animal> animals)</code>. </p>
<p>I understand that this is Java's behavior. My question is <em>why</em>? Why is polymorphism generally implicit, but when it comes to generics it must be specified?</p> | <p>No, a <code>List<Dog></code> is <em>not</em> a <code>List<Animal></code>. Consider what you can do with a <code>List<Animal></code> - you can add <em>any</em> animal to it... including a cat. Now, can you logically add a cat to a litter of puppies? Absolutely not.</p>
<pre><code>// Illegal code - because otherwise life would be Bad
List<Dog> dogs = new ArrayList<Dog>(); // ArrayList implements List
List<Animal> animals = dogs; // Awooga awooga
animals.add(new Cat());
Dog dog = dogs.get(0); // This should be safe, right?
</code></pre>
<p>Suddenly you have a <em>very</em> confused cat.</p>
<p>Now, you <em>can't</em> add a <code>Cat</code> to a <code>List<? extends Animal></code> because you don't know it's a <code>List<Cat></code>. You can retrieve a value and know that it will be an <code>Animal</code>, but you can't add arbitrary animals. The reverse is true for <code>List<? super Animal></code> - in that case you can add an <code>Animal</code> to it safely, but you don't know anything about what might be retrieved from it, because it could be a <code>List<Object></code>.</p> | {
"question_id": 2745265,
"question_date": "2010-04-30T14:39:39.237Z",
"question_score": 869,
"tags": "java|generics|inheritance|polymorphism",
"answer_id": 2745301,
"answer_date": "2010-04-30T14:44:06.167Z",
"answer_score": 1022
} |
Please answer the following Stack Overflow question:
Title: What is Vim recording and how can it be disabled?
<p>I keep seeing the <code>recording</code> message at the bottom of my gVim 7.2 window.</p>
<p>What is it and how do I turn it off?</p> | <p>You start recording by <kbd>q</kbd><kbd><letter></kbd>
and you can end it by typing <kbd>q</kbd> again.</p>
<p>Recording is a really useful feature of Vim.</p>
<p>It records everything you type. You can then replay it simply by typing <kbd>@</kbd><kbd><letter></kbd>.
Record search, movement, replacement...</p>
<p>One of the best feature of Vim IMHO.</p> | {
"question_id": 1527784,
"question_date": "2009-10-06T20:03:12.273Z",
"question_score": 868,
"tags": "vim",
"answer_id": 1527824,
"answer_date": "2009-10-06T20:08:29.333Z",
"answer_score": 1224
} |
Please answer the following Stack Overflow question:
Title: What is the Java equivalent for LINQ?
<p>What is Java equivalent for LINQ?</p> | <p>There is nothing like LINQ for Java.</p>
<p>...</p>
<p><strong>Edit</strong></p>
<p>Now with Java 8 we are introduced to the <a href="http://www.oracle.com/technetwork/articles/java/ma14-java-se-8-streams-2177646.html" rel="noreferrer">Stream API</a>, this is a similar kind of thing when dealing with collections, but it is not quite the same as Linq.</p>
<p>If it is an ORM you are looking for, like Entity Framework, then you can try <a href="http://hibernate.org/orm/" rel="noreferrer">Hibernate</a></p>
<p>:-)</p> | {
"question_id": 1217228,
"question_date": "2009-08-01T18:53:26.813Z",
"question_score": 868,
"tags": "java|linq",
"answer_id": 1217229,
"answer_date": "2009-08-01T18:55:49.507Z",
"answer_score": 841
} |
Please answer the following Stack Overflow question:
Title: How to link a folder with an existing Heroku app
<p>I have an existing Rails app on GitHub and deployed on Heroku. I'm trying to set up a new development machine and have cloned the project from my GitHub repository. However, I'm confused as to how to link this folder up to Heroku. Originally, I used the <code>heroku create</code> command, but obviously I don't want to do that this time since it will create another Heroku instance.</p> | <p><a href="http://www.heroku.com" rel="noreferrer">Heroku</a> links your projects based on the <code>heroku</code> git remote (and a few other options, see the update below). To add your Heroku remote as a remote in your current repository, use the following command:</p>
<pre><code>git remote add heroku [email protected]:project.git
</code></pre>
<p>where <code>project</code> is the name of your Heroku project (the same as the <code>project.heroku.com</code> subdomain). Once you've done so, you can use the <code>heroku xxxx</code> commands (assuming you have the <a href="https://toolbelt.heroku.com/" rel="noreferrer">Heroku Toolbelt</a> installed), and can push to Heroku as usual via <code>git push heroku master</code>. As a shortcut, if you're using the command line tool, you can type:</p>
<pre><code>heroku git:remote -a project
</code></pre>
<p>where, again, <code>project</code> is the name of your Heroku project (thanks, <a href="https://stackoverflow.com/a/12115798/62082">Colonel Panic</a>). You can name the Git remote anything you want by passing <code>-r remote_name</code>.</p>
<p><strong>[Update]</strong></p>
<p>As mentioned by Ben in the comments, the remote doesn't need to be named <code>heroku</code> for the gem commands to work. I checked <a href="https://github.com/heroku/heroku/blob/master/lib/heroku/command/base.rb" rel="noreferrer">the source</a>, and it appears it works like this:</p>
<ol>
<li>If you specify an app name via the <code>--app</code> option (e.g. <code>heroku info --app myapp</code>), it will use that app.</li>
<li>If you specify a Git <em>remote</em> name via the <code>--remote</code> option (e.g. <code>heroku info --remote production</code>), it will use the app associated with that Git remote.</li>
<li>If you specify no option and you have <code>heroku.remote</code> set in your Git config file, it will use the app associated with that remote (for example, to set the default remote to "production" use <code>git config heroku.remote production</code> in your repository, and Heroku will run <code>git config heroku.remote</code> to read the value of this setting)</li>
<li>If you specify no option, the gem finds no configuration in your <code>.git/config</code> file, and the gem only finds one remote in your Git remotes that has "heroku.com" in the URL, it will use that remote.</li>
<li>If none of these work, it raises an error instructing you to pass <code>--app</code> to your command.</li>
</ol> | {
"question_id": 5129598,
"question_date": "2011-02-26T20:39:34.793Z",
"question_score": 868,
"tags": "git|heroku",
"answer_id": 5129733,
"answer_date": "2011-02-26T21:03:05.793Z",
"answer_score": 1323
} |
Please answer the following Stack Overflow question:
Title: Why do we need middleware for async flow in Redux?
<p>According to the docs, <a href="http://redux.js.org/docs/advanced/AsyncFlow.html" rel="noreferrer">"Without middleware, Redux store only supports synchronous data flow"</a>. I don't understand why this is the case. Why can't the container component call the async API, and then <code>dispatch</code> the actions? </p>
<p>For example, imagine a simple UI: a field and a button. When user pushes the button, the field gets populated with data from a remote server.</p>
<p><a href="https://i.stack.imgur.com/GBI59.png" rel="noreferrer"><img src="https://i.stack.imgur.com/GBI59.png" alt="A field and a button"></a></p>
<pre><code>import * as React from 'react';
import * as Redux from 'redux';
import { Provider, connect } from 'react-redux';
const ActionTypes = {
STARTED_UPDATING: 'STARTED_UPDATING',
UPDATED: 'UPDATED'
};
class AsyncApi {
static getFieldValue() {
const promise = new Promise((resolve) => {
setTimeout(() => {
resolve(Math.floor(Math.random() * 100));
}, 1000);
});
return promise;
}
}
class App extends React.Component {
render() {
return (
<div>
<input value={this.props.field}/>
<button disabled={this.props.isWaiting} onClick={this.props.update}>Fetch</button>
{this.props.isWaiting && <div>Waiting...</div>}
</div>
);
}
}
App.propTypes = {
dispatch: React.PropTypes.func,
field: React.PropTypes.any,
isWaiting: React.PropTypes.bool
};
const reducer = (state = { field: 'No data', isWaiting: false }, action) => {
switch (action.type) {
case ActionTypes.STARTED_UPDATING:
return { ...state, isWaiting: true };
case ActionTypes.UPDATED:
return { ...state, isWaiting: false, field: action.payload };
default:
return state;
}
};
const store = Redux.createStore(reducer);
const ConnectedApp = connect(
(state) => {
return { ...state };
},
(dispatch) => {
return {
update: () => {
dispatch({
type: ActionTypes.STARTED_UPDATING
});
AsyncApi.getFieldValue()
.then(result => dispatch({
type: ActionTypes.UPDATED,
payload: result
}));
}
};
})(App);
export default class extends React.Component {
render() {
return <Provider store={store}><ConnectedApp/></Provider>;
}
}
</code></pre>
<p>When the exported component is rendered, I can click the button and the input is updated correctly. </p>
<p>Note the <code>update</code> function in the <code>connect</code> call. It dispatches an action that tells the App that it is updating, and then performs an async call. After the call finishes, the provided value is dispatched as a payload of another action.</p>
<p>What is wrong with this approach? Why would I want to use Redux Thunk or Redux Promise, as the documentation suggests?</p>
<p><strong>EDIT:</strong> I searched the Redux repo for clues, and found that Action Creators were required to be pure functions in the past. For example, <a href="https://github.com/reactjs/redux/issues/533" rel="noreferrer">here's a user trying to provide a better explanation for async data flow:</a></p>
<blockquote>
<p>The action creator itself is still a pure function, but the thunk function it returns doesn't need to be, and it can do our async calls</p>
</blockquote>
<p><a href="https://github.com/reactjs/redux/issues/1088" rel="noreferrer">Action creators are no longer required to be pure.</a> So, thunk/promise middleware was definitely required in the past, but it seems that this is no longer the case?</p> | <blockquote>
<p>What is wrong with this approach? Why would I want to use Redux Thunk or Redux Promise, as the documentation suggests?</p>
</blockquote>
<p>There is nothing wrong with this approach. It’s just inconvenient in a large application because you’ll have different components performing the same actions, you might want to debounce some actions, or keep some local state like auto-incrementing IDs close to action creators, etc. So it is just easier from the maintenance point of view to extract action creators into separate functions.</p>
<p><strong>You can read <a href="https://stackoverflow.com/questions/35411423/how-to-dispatch-a-redux-action-with-a-timeout/35415559#35415559">my answer to “How to dispatch a Redux action with a timeout”</a> for a more detailed walkthrough.</strong></p>
<p>Middleware like Redux Thunk or Redux Promise just gives you “syntax sugar” for dispatching thunks or promises, but you don’t <em>have to</em> use it.</p>
<p>So, without any middleware, your action creator might look like</p>
<pre><code>// action creator
function loadData(dispatch, userId) { // needs to dispatch, so it is first argument
return fetch(`http://data.com/${userId}`)
.then(res => res.json())
.then(
data => dispatch({ type: 'LOAD_DATA_SUCCESS', data }),
err => dispatch({ type: 'LOAD_DATA_FAILURE', err })
);
}
// component
componentWillMount() {
loadData(this.props.dispatch, this.props.userId); // don't forget to pass dispatch
}
</code></pre>
<p>But with Thunk Middleware you can write it like this:</p>
<pre><code>// action creator
function loadData(userId) {
return dispatch => fetch(`http://data.com/${userId}`) // Redux Thunk handles these
.then(res => res.json())
.then(
data => dispatch({ type: 'LOAD_DATA_SUCCESS', data }),
err => dispatch({ type: 'LOAD_DATA_FAILURE', err })
);
}
// component
componentWillMount() {
this.props.dispatch(loadData(this.props.userId)); // dispatch like you usually do
}
</code></pre>
<p>So there is no huge difference. One thing I like about the latter approach is that the component doesn’t care that the action creator is async. It just calls <code>dispatch</code> normally, it can also use <code>mapDispatchToProps</code> to bind such action creator with a short syntax, etc. The components don’t know how action creators are implemented, and you can switch between different async approaches (Redux Thunk, Redux Promise, Redux Saga) without changing the components. On the other hand, with the former, explicit approach, your components know <em>exactly</em> that a specific call is async, and needs <code>dispatch</code> to be passed by some convention (for example, as a sync parameter).</p>
<p>Also think about how this code will change. Say we want to have a second data loading function, and to combine them in a single action creator.</p>
<p>With the first approach we need to be mindful of what kind of action creator we are calling:</p>
<pre><code>// action creators
function loadSomeData(dispatch, userId) {
return fetch(`http://data.com/${userId}`)
.then(res => res.json())
.then(
data => dispatch({ type: 'LOAD_SOME_DATA_SUCCESS', data }),
err => dispatch({ type: 'LOAD_SOME_DATA_FAILURE', err })
);
}
function loadOtherData(dispatch, userId) {
return fetch(`http://data.com/${userId}`)
.then(res => res.json())
.then(
data => dispatch({ type: 'LOAD_OTHER_DATA_SUCCESS', data }),
err => dispatch({ type: 'LOAD_OTHER_DATA_FAILURE', err })
);
}
function loadAllData(dispatch, userId) {
return Promise.all(
loadSomeData(dispatch, userId), // pass dispatch first: it's async
loadOtherData(dispatch, userId) // pass dispatch first: it's async
);
}
// component
componentWillMount() {
loadAllData(this.props.dispatch, this.props.userId); // pass dispatch first
}
</code></pre>
<p>With Redux Thunk action creators can <code>dispatch</code> the result of other action creators and not even think whether those are synchronous or asynchronous:</p>
<pre><code>// action creators
function loadSomeData(userId) {
return dispatch => fetch(`http://data.com/${userId}`)
.then(res => res.json())
.then(
data => dispatch({ type: 'LOAD_SOME_DATA_SUCCESS', data }),
err => dispatch({ type: 'LOAD_SOME_DATA_FAILURE', err })
);
}
function loadOtherData(userId) {
return dispatch => fetch(`http://data.com/${userId}`)
.then(res => res.json())
.then(
data => dispatch({ type: 'LOAD_OTHER_DATA_SUCCESS', data }),
err => dispatch({ type: 'LOAD_OTHER_DATA_FAILURE', err })
);
}
function loadAllData(userId) {
return dispatch => Promise.all(
dispatch(loadSomeData(userId)), // just dispatch normally!
dispatch(loadOtherData(userId)) // just dispatch normally!
);
}
// component
componentWillMount() {
this.props.dispatch(loadAllData(this.props.userId)); // just dispatch normally!
}
</code></pre>
<p>With this approach, if you later want your action creators to look into current Redux state, you can just use the second <code>getState</code> argument passed to the thunks without modifying the calling code at all:</p>
<pre><code>function loadSomeData(userId) {
// Thanks to Redux Thunk I can use getState() here without changing callers
return (dispatch, getState) => {
if (getState().data[userId].isLoaded) {
return Promise.resolve();
}
fetch(`http://data.com/${userId}`)
.then(res => res.json())
.then(
data => dispatch({ type: 'LOAD_SOME_DATA_SUCCESS', data }),
err => dispatch({ type: 'LOAD_SOME_DATA_FAILURE', err })
);
}
}
</code></pre>
<p>If you need to change it to be synchronous, you can also do this without changing any calling code:</p>
<pre><code>// I can change it to be a regular action creator without touching callers
function loadSomeData(userId) {
return {
type: 'LOAD_SOME_DATA_SUCCESS',
data: localStorage.getItem('my-data')
}
}
</code></pre>
<p>So the benefit of using middleware like Redux Thunk or Redux Promise is that components aren’t aware of how action creators are implemented, and whether they care about Redux state, whether they are synchronous or asynchronous, and whether or not they call other action creators. The downside is a little bit of indirection, but we believe it’s worth it in real applications.</p>
<p>Finally, Redux Thunk and friends is just one possible approach to asynchronous requests in Redux apps. Another interesting approach is <a href="https://github.com/yelouafi/redux-saga" rel="noreferrer">Redux Saga</a> which lets you define long-running daemons (“sagas”) that take actions as they come, and transform or perform requests before outputting actions. This moves the logic from action creators into sagas. You might want to check it out, and later pick what suits you the most.</p>
<blockquote>
<p>I searched the Redux repo for clues, and found that Action Creators were required to be pure functions in the past. </p>
</blockquote>
<p>This is incorrect. The docs said this, but the docs were wrong.<br>
Action creators were never required to be pure functions.<br>
We fixed the docs to reflect that.</p> | {
"question_id": 34570758,
"question_date": "2016-01-02T21:09:48.110Z",
"question_score": 868,
"tags": "javascript|asynchronous|reactjs|redux|redux-thunk",
"answer_id": 34599594,
"answer_date": "2016-01-04T20:50:12.887Z",
"answer_score": 883
} |
Please answer the following Stack Overflow question:
Title: Split array into chunks
<p>Let's say that I have an Javascript array looking as following: </p>
<pre><code>["Element 1","Element 2","Element 3",...]; // with close to a hundred elements.
</code></pre>
<p>What approach would be appropriate to chunk (split) the array into many smaller arrays with, lets say, 10 elements at its most?</p> | <p>The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice" rel="noreferrer"><code>array.slice()</code></a> method can extract a slice from the beginning, middle, or end of an array for whatever purposes you require, without changing the original array.</p>
<pre><code>const chunkSize = 10;
for (let i = 0; i < array.length; i += chunkSize) {
const chunk = array.slice(i, i + chunkSize);
// do whatever
}
</code></pre>
<p>The last <code>chunk</code> may be smaller than <code>chunkSize</code>. For example when given an <code>array</code> of 12 elements the first chunk will have 10 elements, the second chunk only has 2.</p>
<p>Note that a <code>chunkSize</code> of <code>0</code> will cause an infinite loop.</p> | {
"question_id": 8495687,
"question_date": "2011-12-13T20:24:42.420Z",
"question_score": 867,
"tags": "javascript|arrays|split",
"answer_id": 8495740,
"answer_date": "2011-12-13T20:28:18.040Z",
"answer_score": 1068
} |
Please answer the following Stack Overflow question:
Title: Setting Windows PowerShell environment variables
<p>I have found out that setting the PATH environment variable affects only the old command prompt. PowerShell seems to have different environment settings. How do I change the environment variables for PowerShell (v1)?</p>
<p>Note:</p>
<p>I want to make my changes permanent, so I don't have to set it every time I run PowerShell. Does PowerShell have a profile file? Something like Bash profile on Unix?</p> | <p>Changing the actual environment variables can be done by
using the <code>env: namespace / drive</code> information. For example, this
code will update the path environment variable:</p>
<pre><code>$env:Path = "SomeRandomPath"; (replaces existing path)
$env:Path += ";SomeRandomPath" (appends to existing path)
</code></pre>
<h2>Making change permanent</h2>
<p>There are ways to make environment settings permanent, but
if you are only using them from PowerShell, it's probably
a lot better to use <a href="https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_profiles" rel="noreferrer">Powershell <em>profiles</em></a> script.</p>
<p>Everytime a new instance of Powershell starts, it look for specific script files (named <em>profile</em> files) and execute them if they do exist. You can edit one of these profile to customize your enviroment.</p>
<p>To know where those <em>profile</em> scripts are located in your computer type:</p>
<pre><code>$profile
$profile.AllUsersAllHosts
$profile.AllUsersCurrentHost
$profile.CurrentUserAllHosts
$profile.CurrentUserCurrentHost
</code></pre>
<p>You can edit one of them, for example, by typing:</p>
<pre><code>notepad $profile
</code></pre> | {
"question_id": 714877,
"question_date": "2009-04-03T17:19:35.087Z",
"question_score": 867,
"tags": "windows|powershell",
"answer_id": 714918,
"answer_date": "2009-04-03T17:35:44.890Z",
"answer_score": 717
} |
Please answer the following Stack Overflow question:
Title: Query for documents where array size is greater than 1
<p>I have a MongoDB collection with documents in the following format:</p>
<pre><code>{
"_id" : ObjectId("4e8ae86d08101908e1000001"),
"name" : ["Name"],
"zipcode" : ["2223"]
}
{
"_id" : ObjectId("4e8ae86d08101908e1000002"),
"name" : ["Another ", "Name"],
"zipcode" : ["2224"]
}
</code></pre>
<p>I can currently get documents that match a specific array size: </p>
<pre><code>db.accommodations.find({ name : { $size : 2 }})
</code></pre>
<p>This correctly returns the documents with 2 elements in the <code>name</code> array. However, I can't do a <code>$gt</code> command to return all documents where the <code>name</code> field has an array size of greater than 2:</p>
<pre><code>db.accommodations.find({ name : { $size: { $gt : 1 } }})
</code></pre>
<p>How can I select all documents with a <code>name</code> array of a size greater than one (preferably without having to modify the current data structure)?</p> | <p><strong>Update:</strong></p>
<p><em>For mongodb versions <strong>2.2+</strong> more efficient way to do this described by <strong>@JohnnyHK</strong> in another <a href="https://stackoverflow.com/a/15224544/508601">answer</a>.</em></p>
<hr />
<ol>
<li><p>Using <a href="http://docs.mongodb.org/manual/reference/operator/query/where/#op._S_where" rel="noreferrer">$where</a></p>
<p>db.accommodations.find( { $where: "this.name.length > 1" } );</p>
</li>
</ol>
<p>But...</p>
<blockquote>
<p>Javascript executes more slowly than the native operators listed on
this page, but is very flexible. See the server-side processing page
for more information.</p>
</blockquote>
<ol start="2">
<li><p>Create <strong>extra</strong> field <code>NamesArrayLength</code>, update it with names array length and then use in queries:</p>
<p>db.accommodations.find({"NamesArrayLength": {$gt: 1} });</p>
</li>
</ol>
<p>It will be better solution, and will work much faster (you can create index on it).</p> | {
"question_id": 7811163,
"question_date": "2011-10-18T17:18:15.450Z",
"question_score": 867,
"tags": "mongodb|mongodb-query",
"answer_id": 7811259,
"answer_date": "2011-10-18T17:27:17.710Z",
"answer_score": 592
} |
Please answer the following Stack Overflow question:
Title: How do you declare an interface in C++?
<p>How do I setup a class that represents an interface? Is this just an abstract base class?</p> | <p>To expand on the answer by <a href="https://stackoverflow.com/questions/318064/how-do-you-declare-an-interface-in-c#318084">bradtgmurray</a>, you may want to make one exception to the pure virtual method list of your interface by adding a virtual destructor. This allows you to pass pointer ownership to another party without exposing the concrete derived class. The destructor doesn't have to do anything, because the interface doesn't have any concrete members. It might seem contradictory to define a function as both virtual and inline, but trust me - it isn't.</p>
<pre><code>class IDemo
{
public:
virtual ~IDemo() {}
virtual void OverrideMe() = 0;
};
class Parent
{
public:
virtual ~Parent();
};
class Child : public Parent, public IDemo
{
public:
virtual void OverrideMe()
{
//do stuff
}
};
</code></pre>
<p>You don't have to include a body for the virtual destructor - it turns out some compilers have trouble optimizing an empty destructor and you're better off using the default. </p> | {
"question_id": 318064,
"question_date": "2008-11-25T16:48:47.303Z",
"question_score": 867,
"tags": "c++|inheritance|interface|abstract-class|pure-virtual",
"answer_id": 318137,
"answer_date": "2008-11-25T17:11:33.763Z",
"answer_score": 728
} |
Please answer the following Stack Overflow question:
Title: What's the difference between identifying and non-identifying relationships?
<p>I haven't been able to fully grasp the differences. Can you describe both concepts and use real world examples?</p> | <ul>
<li><p>An <strong>identifying relationship</strong> is when the existence of a row in a child table depends on a row in a parent table. This may be confusing because it's common practice these days to create a pseudokey for a child table, but <em>not</em> make the foreign key to the parent part of the child's primary key. Formally, the "right" way to do this is to make the foreign key part of the child's primary key. But the logical relationship is that the child cannot exist without the parent.</p>
<p>Example: A <code>Person</code> has one or more phone numbers. If they had just one phone number, we could simply store it in a column of <code>Person</code>. Since we want to support multiple phone numbers, we make a second table <code>PhoneNumbers</code>, whose primary key includes the <code>person_id</code> referencing the <code>Person</code> table. </p>
<p>We may think of the phone number(s) as belonging to a person, even though they are modeled as attributes of a separate table. This is a strong clue that this is an identifying relationship (even if we don't literally include <code>person_id</code> in the primary key of <code>PhoneNumbers</code>).</p></li>
<li><p>A <strong>non-identifying relationship</strong> is when the primary key attributes of the parent <em>must not</em> become primary key attributes of the child. A good example of this is a lookup table, such as a foreign key on <code>Person.state</code> referencing the primary key of <code>States.state</code>. <code>Person</code> is a child table with respect to <code>States</code>. But a row in <code>Person</code> is not identified by its <code>state</code> attribute. I.e. <code>state</code> is not part of the primary key of <code>Person</code>.</p>
<p>A non-identifying relationship can be <strong>optional</strong> or <strong>mandatory</strong>, which means the foreign key column allows NULL or disallows NULL, respectively.</p></li>
</ul>
<hr>
<p>See also my answer to <a href="https://stackoverflow.com/questions/2814469/still-confused-about-identifying-vs-non-identifying-relationships/2814663#2814663">Still Confused About Identifying vs. Non-Identifying Relationships</a></p> | {
"question_id": 762937,
"question_date": "2009-04-18T05:04:55.070Z",
"question_score": 867,
"tags": "database|database-design|data-modeling|identifying-relationship",
"answer_id": 762994,
"answer_date": "2009-04-18T05:59:30.870Z",
"answer_score": 1133
} |
Please answer the following Stack Overflow question:
Title: Skip Git commit hooks
<p>I'm looking at a Git hook which looks for print statements in Python code. If a print statement is found, it prevents the Git commit.</p>
<p>I want to override this hook and I was told that there is a command to do so. I haven't been able to find it. Any thoughts?</p> | <p>Maybe (from <a href="https://git-scm.com/docs/git-commit" rel="noreferrer"><code>git commit</code> man page</a>):</p>
<pre><code>git commit --no-verify -m "commit message"
^^^^^^^^^^^
-n
--no-verify
</code></pre>
<blockquote>
<p>This option bypasses the pre-commit and commit-msg hooks. See also <a href="http://git-scm.com/docs/githooks" rel="noreferrer">githooks(5)</a>.</p>
</blockquote>
<p>As commented by <a href="https://stackoverflow.com/users/451480/blaise">Blaise</a>, <code>-n</code> can have a different role for certain commands.<br />
For instance, <a href="http://git-scm.com/docs/git-push" rel="noreferrer"><code>git push -n</code></a> is actually a dry-run push.<br />
Only <code>git push --no-verify</code> would skip the hook.</p>
<hr />
<p>Note: Git 2.14.x/2.15 improves the <code>--no-verify</code> behavior:</p>
<p>See <a href="https://github.com/git/git/commit/680ee550d72150f27cdb3235462eee355a20038b" rel="noreferrer">commit 680ee55</a> (14 Aug 2017) by <a href="https://github.com/" rel="noreferrer">Kevin Willford (``)</a>.<br />
<sup>(Merged by <a href="https://github.com/gitster" rel="noreferrer">Junio C Hamano -- <code>gitster</code> --</a> in <a href="https://github.com/git/git/commit/c3e034f0f0753126494285d1098e1084ec05d2c4" rel="noreferrer">commit c3e034f</a>, 23 Aug 2017)</sup></p>
<blockquote>
<h2><code>commit</code>: skip discarding the index if there is no <code>pre-commit</code> hook</h2>
</blockquote>
<blockquote>
<p>"<code>git commit</code>" used to discard the index and re-read from the filesystem
just in case the <code>pre-commit</code> hook has updated it in the middle; this
has been optimized out when we know we do not run the <code>pre-commit</code> hook.</p>
</blockquote>
<hr />
<p><a href="https://stackoverflow.com/users/462849/davi-lima">Davi Lima</a> points out <a href="https://stackoverflow.com/questions/7230820/skip-git-commit-hooks/7230886?noredirect=1#comment101929781_7230886">in the comments</a> the <a href="https://git-scm.com/docs/git-cherry-pick" rel="noreferrer"><code>git cherry-pick</code></a> does <em>not</em> support --no-verify.<br />
So if a cherry-pick triggers a pre-commit hook, you might, as in <a href="http://web-dev.wirt.us/info/git-drupal/git-continue-vs-no-verify" rel="noreferrer">this blog post</a>, have to comment/disable somehow that hook in order for your git cherry-pick to proceed.</p>
<p>The same process would be necessary in case of a <code>git rebase --continue</code>, after a merge conflict resolution.</p>
<hr />
<p>With Git 2.36 (Q2 2022), the callers of <code>run_commit_hook()</code> to learn if it got "success" because the hook succeeded or because there wasn't any hook.</p>
<p>See <a href="https://github.com/git/git/commit/a8cc594333848713b8e772cccf8159196ea85ede" rel="noreferrer">commit a8cc594</a> (fixed with <a href="https://github.com/git/git/commit/4369e3a1a39895ab51c2bef2985255ad05957a20" rel="noreferrer">commit 4369e3a1</a>), <a href="https://github.com/git/git/commit/9f6e63b966e9876ca6f990819fabafc473a3c9b0" rel="noreferrer">commit 9f6e63b</a> (07 Mar 2022) by <a href="https://github.com/avar" rel="noreferrer">Ævar Arnfjörð Bjarmason (<code>avar</code>)</a>.<br />
<sup>(Merged by <a href="https://github.com/gitster" rel="noreferrer">Junio C Hamano -- <code>gitster</code> --</a> in <a href="https://github.com/git/git/commit/7431379a9c5ed4006603114b1991c6c6e98d5dca" rel="noreferrer">commit 7431379</a>, 16 Mar 2022)</sup></p>
<blockquote>
<h2><a href="https://github.com/git/git/commit/a8cc594333848713b8e772cccf8159196ea85ede" rel="noreferrer"><code>hooks</code></a>: fix an obscure <strong><a href="https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use" rel="noreferrer">TOCTOU</a></strong> "did we just run a hook?" race</h2>
<p><sup>Signed-off-by: Ævar Arnfjörð Bjarmason</sup></p>
</blockquote>
<blockquote>
<p>Fix a <a href="https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use" rel="noreferrer"><strong>Time-of-check to time-of-use</strong> (<strong>TOCTOU</strong>)</a> race in code added in <a href="https://github.com/git/git/commit/680ee550d72150f27cdb3235462eee355a20038b" rel="noreferrer">680ee55</a> ("<code>commit</code>: skip discarding the index if there is no pre-commit hook", 2017-08-14, Git v2.15.0-rc0 -- <a href="https://github.com/git/git/commit/c3e034f0f0753126494285d1098e1084ec05d2c4" rel="noreferrer">merge</a> listed in <a href="https://github.com/git/git/commit/ab86f93d680618f62ad6e3c2f37db76029cfce5e" rel="noreferrer">batch #3</a>).</p>
<p>This obscure race condition can occur if we e.g. ran the "<code>pre-commit</code>" hook and it modified the index, but <code>hook_exists()</code> returns false later on (e.g., because the hook itself went away, the directory became unreadable, etc.).<br />
Then we won't call <code>discard_cache()</code> when we should have.</p>
<p>The race condition itself probably doesn't matter, and users would have been unlikely to run into it in practice.<br />
This problem has been noted on-list when <a href="https://github.com/git/git/commit/680ee550d72150f27cdb3235462eee355a20038b" rel="noreferrer">680ee55</a> <a href="https://lore.kernel.org/git/[email protected]/" rel="noreferrer">was discussed</a>, but had not been fixed.</p>
<p>Let's also change this for the push-to-checkout hook.<br />
Now instead of checking if the hook exists and either doing a push to checkout or a push to deploy we'll always attempt a push to checkout.<br />
If the hook doesn't exist we'll fall back on push to deploy.<br />
The same behavior as before, without the TOCTOU race.<br />
See <a href="https://github.com/git/git/commit/0855331941b723b227e93b33955bbe0b45025659" rel="noreferrer">0855331</a> ("<code>receive-pack</code>: support push-to-checkout hook", 2014-12-01, Git v2.4.0-rc0 -- <a href="https://github.com/git/git/commit/cba07bb6ff58da5aa4538c4a2bbf70b717b172b3" rel="noreferrer">merge</a>) for the introduction of the previous behavior.</p>
<p>This leaves uses of <code>hook_exists()</code> in two places that matter.<br />
The "reference-transaction" check in <a href="https://github.com/git/git/blob/a8cc594333848713b8e772cccf8159196ea85ede/refs.c" rel="noreferrer"><code>refs.c</code></a>, see <a href="https://github.com/git/git/commit/675415976704459edaf8fb39a176be2be0f403d8" rel="noreferrer">6754159</a> ("<code>refs</code>: implement reference transaction hook", 2020-06-19, Git v2.28.0-rc0 -- <a href="https://github.com/git/git/commit/33a22c1a88d8e8cddd41ea0aa264ee213ce9c1d7" rel="noreferrer">merge</a> listed in <a href="https://github.com/git/git/commit/4a0fcf9f760c9774be77f51e1e88a7499b53d2e2" rel="noreferrer">batch #7</a>), and the "prepare-commit-msg" hook, see <a href="https://github.com/git/git/commit/66618a50f9c9f008d7aef751418f12ba9bfc6b85" rel="noreferrer">66618a5</a> ("<code>sequencer</code>: run 'prepare-commit-msg' hook", 2018-01-24, Git v2.17.0-rc0 -- <a href="https://github.com/git/git/commit/1772ad1125a6f8a5473d73bbd17162bb20ebd825" rel="noreferrer">merge</a> listed in <a href="https://github.com/git/git/commit/b2e45c695d09f6a31ce09347ae0a5d2cdfe9dd4e" rel="noreferrer">batch #2</a>).</p>
<p>In both of those cases we're saving ourselves CPU time by not preparing data for the hook that we'll then do nothing with if we don't have the hook.<br />
So using this <code>"invoked_hook"</code> pattern doesn't make sense in those cases.</p>
<p>The "<code>reference-transaction</code>" and "<code>prepare-commit-msg</code>" hook also aren't racy.<br />
In those cases we'll skip the hook runs if we race with a new hook being added, whereas in the TOCTOU races being fixed here we were incorrectly skipping the required post-hook logic.</p>
</blockquote> | {
"question_id": 7230820,
"question_date": "2011-08-29T13:31:59.837Z",
"question_score": 867,
"tags": "git|githooks|git-commit",
"answer_id": 7230886,
"answer_date": "2011-08-29T13:36:30.647Z",
"answer_score": 1447
} |
Please answer the following Stack Overflow question:
Title: open() in Python does not create a file if it doesn't exist
<p>What is the best way to open a file as read/write if it exists, or if it does not, then create it and open it as read/write? From what I read, <code>file = open('myfile.dat', 'rw')</code> should do this, right?</p>
<p>It is not working for me (Python 2.6.2) and I'm wondering if it is a version problem, or not supposed to work like that or what.</p>
<p>The bottom line is, I just need a solution for the problem. I am curious about the other stuff, but all I need is a nice way to do the opening part.</p>
<p>The enclosing directory was writeable by user and group, not other (I'm on a Linux system... so permissions 775 in other words), and the exact error was:</p>
<blockquote>
<p>IOError: no such file or directory.</p>
</blockquote> | <p>You should use <code>open</code> with the <code>w+</code> mode:</p>
<pre><code>file = open('myfile.dat', 'w+')
</code></pre> | {
"question_id": 2967194,
"question_date": "2010-06-03T15:05:54.200Z",
"question_score": 866,
"tags": "python|linux|file-io|file-permissions",
"answer_id": 2967249,
"answer_date": "2010-06-03T15:12:39.770Z",
"answer_score": 1021
} |
Please answer the following Stack Overflow question:
Title: Should I use != or <> for not equal in T-SQL?
<p>I have seen <code>SQL</code> that uses both <code>!=</code> and <code><></code> for <strong><em>not equal</em></strong>. What is the preferred syntax and why?</p>
<p>I like <code>!=</code>, because <code><></code> reminds me of <code>Visual Basic</code>.</p> | <p>Technically they function the same if you’re using SQL Server AKA T-SQL. If you're using it in stored procedures there is no performance reason to use one over the other. It then comes down to personal preference. I prefer to use <> as it is ANSI compliant.</p>
<p>You can find links to the various ANSI standards at...</p>
<p><a href="http://en.wikipedia.org/wiki/SQL" rel="noreferrer">http://en.wikipedia.org/wiki/SQL</a></p> | {
"question_id": 723195,
"question_date": "2009-04-06T20:56:15.100Z",
"question_score": 866,
"tags": "sql|sql-server|tsql",
"answer_id": 723317,
"answer_date": "2009-04-06T21:29:28.330Z",
"answer_score": 581
} |
Please answer the following Stack Overflow question:
Title: React js onClick can't pass value to method
<p>I want to read the onClick event value properties. But when I click on it, I see something like this on the console: </p>
<pre><code>SyntheticMouseEvent {dispatchConfig: Object, dispatchMarker: ".1.1.0.2.0.0:1", nativeEvent: MouseEvent, type: "click", target
</code></pre>
<p>My code is working correctly. When I run I can see <code>{column}</code> but can't get it in the onClick event.</p>
<p>My Code:</p>
<pre><code>var HeaderRows = React.createClass({
handleSort: function(value) {
console.log(value);
},
render: function () {
var that = this;
return(
<tr>
{this.props.defaultColumns.map(function (column) {
return (
<th value={column} onClick={that.handleSort} >{column}</th>
);
})}
{this.props.externalColumns.map(function (column) {
// Multi dimension array - 0 is column name
var externalColumnName = column[0];
return ( <th>{externalColumnName}</th>);
})}
</tr>
);
}
});
</code></pre>
<p>How can I pass a value to the <code>onClick</code> event in React js?</p> | <h2>Easy Way</h2>
<p>Use an arrow function:</p>
<pre><code>return (
<th value={column} onClick={() => this.handleSort(column)}>{column}</th>
);
</code></pre>
<p>This will create a new function that calls <code>handleSort</code> with the right params.</p>
<h2>Better Way</h2>
<p><a href="https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-bind.md#protips" rel="noreferrer">Extract it into a sub-component.</a>
The problem with using an arrow function in the render call is it will create a new function every time, which ends up causing unneeded re-renders.</p>
<p>If you create a sub-component, you can pass handler and use props as the arguments, which will then re-render only when the props change (because the handler reference now never changes):</p>
<p><em>Sub-component</em></p>
<pre><code>class TableHeader extends Component {
handleClick = () => {
this.props.onHeaderClick(this.props.value);
}
render() {
return (
<th onClick={this.handleClick}>
{this.props.column}
</th>
);
}
}
</code></pre>
<p><em>Main component</em></p>
<pre><code>{this.props.defaultColumns.map((column) => (
<TableHeader
value={column}
onHeaderClick={this.handleSort}
/>
))}
</code></pre>
<hr>
<p><strong>Old Easy Way (ES5)</strong></p>
<p>Use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind" rel="noreferrer"><code>.bind</code></a> to pass the parameter you want, this way you are binding the function with the Component context :</p>
<pre><code>return (
<th value={column} onClick={this.handleSort.bind(this, column)}>{column}</th>
);
</code></pre> | {
"question_id": 29810914,
"question_date": "2015-04-22T23:40:14.340Z",
"question_score": 866,
"tags": "javascript|reactjs",
"answer_id": 29810951,
"answer_date": "2015-04-22T23:43:29.100Z",
"answer_score": 1604
} |
Please answer the following Stack Overflow question:
Title: What is the difference between JSF, Servlet and JSP?
<p>I have some questions. These are :</p>
<ol>
<li>How are JSP and Servlet related to each other?</li>
<li>Is JSP some kind of Servlet? </li>
<li>How are JSP and JSF related to each other? </li>
<li>Is JSF some kind of <strong>Pre-Build UI based JSP</strong> like ASP.NET-MVC?</li>
</ol> | <h3><a href="https://stackoverflow.com/tags/jsp/info">JSP (JavaServer Pages)</a></h3>
<p>JSP is a <strong>Java view technology</strong> running on the server machine which allows you to write template text in client side languages (like HTML, CSS, JavaScript, ect.). JSP supports <a href="http://docs.oracle.com/javaee/5/tutorial/doc/bnann.html" rel="noreferrer">taglibs</a>, which are backed by pieces of Java code that let you control the page flow or output dynamically. A well-known taglib is <a href="https://stackoverflow.com/tags/jstl/info">JSTL</a>. JSP also supports <a href="https://stackoverflow.com/tags/el/info">Expression Language</a>, which can be used to access backend data (via attributes available in the page, request, session and application scopes), mostly in combination with taglibs.</p>
<p>When a JSP is requested for the first time or when the web app starts up, the servlet container will compile it into a class extending <a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServlet.html" rel="noreferrer"><code>HttpServlet</code></a> and use it during the web app's lifetime. You can find the generated source code in the server's work directory. In for example <a href="http://tomcat.apache.org" rel="noreferrer">Tomcat</a>, it's the <code>/work</code> directory. On a JSP request, the servlet container will execute the compiled JSP class and send the generated output (usually just HTML/CSS/JS) through the web server over a network to the client side, which in turn displays it in the web browser.</p>
<h3><a href="https://stackoverflow.com/tags/servlets/info">Servlets</a></h3>
<p>Servlet is a <strong>Java application programming interface (API)</strong> running on the server machine, which intercepts requests made by the client and generates/sends a response. A well-known example is the <code>HttpServlet</code> which provides methods to hook on <a href="http://www.w3.org/Protocols/rfc2616/rfc2616.html" rel="noreferrer">HTTP</a> requests using the popular <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html" rel="noreferrer">HTTP methods</a> such as <code>GET</code> and <code>POST</code>. You can configure <code>HttpServlet</code>s to listen to a certain HTTP URL pattern, which is configurable in <code>web.xml</code>, or more recently with <a href="http://docs.oracle.com/javaee/6/tutorial/doc/bnafd.html" rel="noreferrer">Java EE 6</a>, with <code>@WebServlet</code> annotation.</p>
<p>When a Servlet is first requested or during web app startup, the servlet container will create an instance of it and keep it in memory during the web app's lifetime. The same instance will be reused for every incoming request whose URL matches the servlet's URL pattern. You can access the request data by <a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html" rel="noreferrer"><code>HttpServletRequest</code></a> and handle the response by <a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletResponse.html" rel="noreferrer"><code>HttpServletResponse</code></a>. Both objects are available as method arguments inside any of the overridden methods of <code>HttpServlet</code>, such as <code>doGet()</code> and <code>doPost()</code>.</p>
<h3><a href="https://stackoverflow.com/tags/jsf/info">JSF (JavaServer Faces)</a></h3>
<p>JSF is a <strong>component based MVC framework</strong> which is built on top of the Servlet API and provides <a href="http://docs.oracle.com/javaee/6/tutorial/doc/bnarf.html" rel="noreferrer">components</a> via taglibs which can be used in JSP or any other Java based view technology such as <a href="http://docs.oracle.com/javaee/6/tutorial/doc/giepx.html" rel="noreferrer">Facelets</a>. Facelets is much more suited to JSF than JSP. It namely provides great <a href="http://docs.oracle.com/javaee/6/tutorial/doc/giqxp.html" rel="noreferrer">templating capabilities</a> such as <a href="http://docs.oracle.com/javaee/6/tutorial/doc/giqzr.html" rel="noreferrer">composite components</a>, while JSP basically only offers the <a href="http://java.sun.com/products/jsp/syntax/2.0/syntaxref2020.html#8828" rel="noreferrer"><code><jsp:include></code></a> for templating in JSF, so that you're forced to create custom components with raw Java code (which is a bit opaque and a lot of tedious work) when you want to replace a repeated group of components with a single component. Since JSF 2.0, JSP has been deprecated as view technology in favor of Facelets.</p>
<p><strong>Note</strong>: JSP itself is NOT deprecated, just the combination of JSF with JSP is deprecated.</p>
<p><strong>Note</strong>: JSP has great templating abilities by means of Taglibs, especially the (<a href="http://docs.oracle.com/javaee/5/tutorial/doc/bnann.html" rel="noreferrer">Tag File</a>) variant. JSP templating in combination with JSF is what is lacking.</p>
<p>As being a MVC (<a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller" rel="noreferrer">Model-View-Controller</a>) framework, JSF provides the <a href="http://docs.oracle.com/javaee/6/api/javax/faces/webapp/FacesServlet.html" rel="noreferrer"><code>FacesServlet</code></a> as the sole request-response <em>Controller</em>. It takes all the standard and tedious HTTP request/response work from your hands, such as gathering user input, validating/converting them, putting them in model objects, invoking actions and rendering the response. This way you end up with basically a JSP or Facelets (XHTML) page for <em>View</em> and a JavaBean class as <em>Model</em>. The JSF components are used to bind the view with the model (such as your ASP.NET web control does) and the <code>FacesServlet</code> uses the <em>JSF component tree</em> to do all the work.</p>
<h3>Related questions</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/2556553/what-is-the-main-stream-java-alternative-to-asp-net-php">What is the main-stream Java alternative to ASP.NET / PHP?</a></li>
<li><a href="https://stackoverflow.com/questions/1958808/java-web-development-what-skills-do-i-need">Java EE web development, what skills do I need?</a></li>
<li><a href="https://stackoverflow.com/questions/3106452/java-servlet-instantiation-and-session-variables">How do servlets work? Instantiation, session variables and multithreading</a></li>
<li><a href="https://stackoverflow.com/questions/1727603/places-where-java-beans-used">What is a Javabean and where are they used?</a></li>
<li><a href="https://stackoverflow.com/questions/3177733/howto-avoid-java-code-in-jsp-files">How to avoid Java code in JSP files?</a></li>
<li><a href="https://stackoverflow.com/questions/5104094/what-components-are-mvc-in-jsf-mvc-framework">What components are MVC in JSF MVC framework?</a></li>
<li><a href="https://stackoverflow.com/questions/4421839/what-is-the-need-of-jsf-when-ui-can-be-achieved-from-css-html-javascript-jquery/">What is the need of JSF, when UI can be achieved with JavaScript libraries such as jQuery and AngularJS</a></li>
</ul> | {
"question_id": 2095397,
"question_date": "2010-01-19T17:15:41.960Z",
"question_score": 866,
"tags": "java|jsp|jsf|servlets|jakarta-ee",
"answer_id": 2097732,
"answer_date": "2010-01-19T22:39:14.557Z",
"answer_score": 1273
} |
Please answer the following Stack Overflow question:
Title: File Upload ASP.NET MVC 3.0
<p>(Preface: this question is about ASP.NET MVC 3.0 which <a href="https://stackoverflow.com/questions/51390971/im-lost-what-happened-to-asp-net-mvc-5/51391202#51391202">was released in 2011</a>, it is not about <strong>ASP.NET Core 3.0</strong> which was released in 2019)</p>
<p>I want to upload file in asp.net mvc. How can I upload the file using html <code>input file</code> control?</p> | <p>You don't use a file input control. Server side controls are not used in ASP.NET MVC. Checkout the <a href="http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx" rel="noreferrer">following blog post</a> which illustrates how to achieve this in ASP.NET MVC.</p>
<p>So you would start by creating an HTML form which would contain a file input:</p>
<pre><code>@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="submit" value="OK" />
}
</code></pre>
<p>and then you would have a controller to handle the upload:</p>
<pre><code>public class HomeController : Controller
{
// This action renders the form
public ActionResult Index()
{
return View();
}
// This action handles the form POST and the upload
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
// extract only the filename
var fileName = Path.GetFileName(file.FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
// redirect back to the index action to show the form once again
return RedirectToAction("Index");
}
}
</code></pre> | {
"question_id": 5193842,
"question_date": "2011-03-04T12:42:08.117Z",
"question_score": 866,
"tags": "c#|asp.net-mvc|asp.net-mvc-3",
"answer_id": 5193851,
"answer_date": "2011-03-04T12:42:55.093Z",
"answer_score": 1173
} |
Please answer the following Stack Overflow question:
Title: Kill detached screen session
<p>I learned from somewhere a detached screen can be killed by</p>
<pre><code>screen -X -S [session # you want to kill] kill
</code></pre>
<p>where [session # you want to kill] can be gotten from</p>
<pre><code>screen -ls
</code></pre>
<p>But this doesn't work. Anything wrong? What's the correct way?</p> | <p>"kill" will only kill one screen window. To "kill" the complete session, use <code>quit</code>.</p>
<h3>Example</h3>
<pre><code>$ screen -X -S [session # you want to kill] quit
</code></pre>
<p>For dead sessions use:
$ screen -wipe</p> | {
"question_id": 1509677,
"question_date": "2009-10-02T13:58:13.630Z",
"question_score": 865,
"tags": "linux|kill|gnu-screen",
"answer_id": 1509764,
"answer_date": "2009-10-02T14:10:50.500Z",
"answer_score": 1267
} |
Please answer the following Stack Overflow question:
Title: Entity Framework vs LINQ to SQL
<p>Now that .NET v3.5 SP1 has been released (along with VS2008 SP1), we now have access to the .NET entity framework.</p>
<p>My question is this. When trying to decide between using the Entity Framework and LINQ to SQL as an ORM, what's the difference?</p>
<p>The way I understand it, the Entity Framework (when used with LINQ to Entities) is a 'big brother' to LINQ to SQL? If this is the case - what advantages does it have? What can it do that LINQ to SQL can't do on its own?</p> | <p>LINQ to SQL only supports 1 to 1 mapping of database tables, views, sprocs and functions available in Microsoft SQL Server. It's a great API to use for quick data access construction to relatively well designed SQL Server databases. LINQ2SQL was first released with C# 3.0 and .Net Framework 3.5.</p>
<p>LINQ to Entities (ADO.Net Entity Framework) is an ORM (Object Relational Mapper) API which allows for a broad definition of object domain models and their relationships to many different ADO.Net data providers. As such, you can mix and match a number of different database vendors, application servers or protocols to design an aggregated mash-up of objects which are constructed from a variety of tables, sources, services, etc. ADO.Net Framework was released with the .Net Framework 3.5 SP1.</p>
<p>This is a good introductory article on MSDN:
<a href="http://msdn.microsoft.com/en-us/library/cc161164.aspx" rel="noreferrer">Introducing LINQ to Relational Data</a></p> | {
"question_id": 8676,
"question_date": "2008-08-12T11:04:11.677Z",
"question_score": 865,
"tags": ".net|entity-framework|linq-to-sql",
"answer_id": 110153,
"answer_date": "2008-09-21T03:22:59.403Z",
"answer_score": 496
} |
Please answer the following Stack Overflow question:
Title: not None test in Python
<p>Out of these not None tests.</p>
<pre><code>if val != None:
if not (val is None):
if val is not None:
</code></pre>
<p>Which one is preferable, and why?</p> | <pre><code>if val is not None:
# ...
</code></pre>
<p>is the Pythonic idiom for testing that a variable is not set to <code>None</code>. This idiom has particular uses in the case of <a href="http://effbot.org/zone/default-values.htm" rel="noreferrer">declaring keyword functions with default parameters</a>. <code>is</code> tests identity in Python. Because there is one and only one instance of <code>None</code> present in a running Python script/program, <code>is</code> is the optimal test for this. As <a href="https://stackoverflow.com/questions/3965104/not-none-test-in-python/3965165#3965165">Johnsyweb points out</a>, this is discussed in <a href="http://www.python.org/dev/peps/pep-0008/" rel="noreferrer">PEP 8</a> under "Programming Recommendations".</p>
<p>As for why this is preferred to </p>
<pre><code>if not (val is None):
# ...
</code></pre>
<p>this is simply part of the <a href="http://www.python.org/dev/peps/pep-0020/" rel="noreferrer">Zen of Python</a>: "Readability counts." Good Python is often close to good <a href="http://en.wikipedia.org/wiki/Pseudocode" rel="noreferrer">pseudocode</a>.</p> | {
"question_id": 3965104,
"question_date": "2010-10-19T03:20:18.543Z",
"question_score": 864,
"tags": "python|nonetype",
"answer_id": 3965129,
"answer_date": "2010-10-19T03:24:31.670Z",
"answer_score": 1254
} |
Please answer the following Stack Overflow question:
Title: Cleaning up old remote git branches
<p>I work from two different computers (A and B) and store a common git remote in the dropbox directory.</p>
<p>Let's say I have two branches, master and devel. Both are tracking their remote counterparts origin/master and origin/devel.</p>
<p>Now while on computer A, I delete branch devel, on local and remote.</p>
<pre><code>git push origin :heads/devel
git branch -d devel
</code></pre>
<p>Running <code>git branch -a</code> on computer A, I get the following list of branches.</p>
<ul>
<li>master</li>
<li>origin/HEAD</li>
<li>origin/master</li>
</ul>
<p>Running <code>git fetch</code> on computer B, I can remove the local devel branch with <code>git branch -d devel</code>, but I can't remove the remote devel branch.</p>
<p><code>git push origin :heads/devel</code> returns the following error messages.</p>
<blockquote>
<p>error: unable to push to unqualified destination: heads/proxy3d<br>
The destination refspec neither matches an existing ref on the remote nor begins with refs/, and we are unable to guess a prefix based on the source ref.<br>
fatal: The remote end hung up unexpectedly</p>
</blockquote>
<p><code>git branch -a</code> still lists origin/devel in the remote branches.</p>
<p>How can I clean up the remote branches from computer B?</p> | <p>First, what is the result of <code>git branch -a</code> on machine B?</p>
<p>Second, you have already deleted <code>heads/devel</code> on <code>origin</code>, so that's why you can't delete it from machine B.</p>
<p>Try</p>
<pre><code>git branch -r -d origin/devel
</code></pre>
<p>or</p>
<pre><code>git remote prune origin
</code></pre>
<p>or</p>
<pre><code>git fetch origin --prune
</code></pre>
<p>and feel free to add <code>--dry-run</code> to the end of your <code>git</code> statement to see the result of running it without actually running it.</p>
<p>Docs for <a href="https://git-scm.com/docs/git-remote#Documentation/git-remote.txt-empruneem" rel="noreferrer"><code>git remote prune</code></a> and <a href="https://git-scm.com/docs/git-branch" rel="noreferrer"><code>git branch</code></a>.</p> | {
"question_id": 3184555,
"question_date": "2010-07-06T08:14:50.793Z",
"question_score": 864,
"tags": "git|git-branch",
"answer_id": 3184742,
"answer_date": "2010-07-06T08:45:46.127Z",
"answer_score": 1502
} |
Please answer the following Stack Overflow question:
Title: A monad is just a monoid in the category of endofunctors, what's the problem?
<p>Who first said the following?</p>
<blockquote>
<p>A monad is just a monoid in the
category of endofunctors, what's the
problem?</p>
</blockquote>
<p>And on a less important note, is this true and if so could you give an explanation (hopefully one that can be understood by someone who doesn't have much Haskell experience)?</p> | <p>That particular phrasing is by James Iry, from his highly entertaining <em><a href="http://james-iry.blogspot.com/2009/05/brief-incomplete-and-mostly-wrong.html" rel="noreferrer">Brief, Incomplete and Mostly Wrong History of Programming Languages</a></em>, in which he fictionally attributes it to Philip Wadler.</p>
<p>The original quote is from Saunders Mac Lane in <em>Categories for the Working Mathematician</em>, one of the foundational texts of Category Theory. <a href="http://books.google.com/books?id=MXboNPdTv7QC&pg=PA138&lpg=PA138&dq=%22monoid+in+the+category+of+endofunctors%22+mac+lane&source=bl&ots=feQWTkH2Uw&sig=tv-1JwaMOygKGmFE2vM2FhJVS9o&hl=en&ei=5iWsTJCkBIPSsAPQwJ36Aw&sa=X&oi=book_result&ct=result&resnum=1&ved=0CBIQ6AEwAA#v=onepage&q&f=false" rel="noreferrer">Here it is in context</a>, which is probably the best place to learn exactly what it means.</p>
<p>But, I'll take a stab. The original sentence is this:</p>
<blockquote>
<p>All told, a monad in X is just a monoid in the category of endofunctors of X, with product × replaced by composition of endofunctors and unit set by the identity endofunctor.</p>
</blockquote>
<p><em>X</em> here is a category. Endofunctors are functors from a category to itself (which is usually <em>all</em> <code>Functor</code>s as far as functional programmers are concerned, since they're mostly dealing with just one category; the category of types - but I digress). But you could imagine another category which is the category of "endofunctors on <em>X</em>". This is a category in which the objects are endofunctors and the morphisms are natural transformations.</p>
<p>And of those endofunctors, some of them might be monads. Which ones are monads? Exactly the ones which are <em>monoidal</em> in a particular sense. Instead of spelling out the exact mapping from monads to monoids (since Mac Lane does that far better than I could hope to), I'll just put their respective definitions side by side and let you compare:</p>
<h2>A monoid is...</h2>
<ul>
<li>A set, <em><strong>S</strong></em></li>
<li>An operation, <em><strong>• : S × S → S</strong></em></li>
<li>An element of <em>S</em>, <em><strong>e : 1 → S</strong></em></li>
</ul>
<h3>...satisfying these laws:</h3>
<ul>
<li><em>(a • b) • c = a • (b • c)</em>, for all <em>a</em>, <em>b</em> and <em>c</em> in <em>S</em></li>
<li><em>e • a = a • e = a</em>, for all <em>a</em> in <em>S</em></li>
</ul>
<h2>A monad is...</h2>
<ul>
<li>An endofunctor, <em><strong>T : X → X</strong></em> (in Haskell, a type constructor of kind <code>* -> *</code> with a <code>Functor</code> instance)</li>
<li>A natural transformation, <em><strong>μ : T × T → T</strong></em>, where <em>×</em> means functor composition (<em>μ</em> is known as <em><a href="http://hackage.haskell.org/package/base/docs/Control-Monad.html#v:join" rel="noreferrer"><code>join</code></a></em> in Haskell)</li>
<li>A natural transformation, <em><strong>η : I → T</strong></em>, where <em>I</em> is the identity endofunctor on <em>X</em> (<em>η</em> is known as <em><a href="http://hackage.haskell.org/package/base/docs/Control-Monad.html#v:return" rel="noreferrer"><code>return</code></a></em> in Haskell)</li>
</ul>
<h3>...satisfying these laws:</h3>
<ul>
<li><em>μ ∘ Tμ = μ ∘ μT</em></li>
<li><em>μ ∘ Tη = μ ∘ ηT = 1</em> (the identity natural transformation)</li>
</ul>
<p>With a bit of squinting you might be able to see that both of these definitions are instances of the same <a href="https://en.wikipedia.org/wiki/Monoid_(category_theory)" rel="noreferrer">abstract concept</a>.</p> | {
"question_id": 3870088,
"question_date": "2010-10-06T06:55:24.847Z",
"question_score": 864,
"tags": "haskell|monads|category-theory|monoids",
"answer_id": 3870310,
"answer_date": "2010-10-06T07:35:28.823Z",
"answer_score": 930
} |
Please answer the following Stack Overflow question:
Title: Why does parseInt(1/0, 19) return 18?
<p>I have an annoying problem in <strong>JavaScript</strong>.</p>
<pre><code>> parseInt(1 / 0, 19)
> 18
</code></pre>
<p>Why does the <code>parseInt</code> function return <code>18</code>?</p> | <p>The result of <code>1/0</code> is <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Infinity" rel="noreferrer"><code>Infinity</code></a>.</p>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt" rel="noreferrer"><code>parseInt</code></a> treats its first argument as a string which means first of all <code>Infinity.toString()</code> is called, producing the string <code>"Infinity"</code>. So it works the same as if you asked it to convert <code>"Infinity"</code> in base 19 to decimal.</p>
<p>Here are the digits in base 19 along with their decimal values:</p>
<pre class="lang-none prettyprint-override"><code>Base 19 Base 10 (decimal)
---------------------------
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
a 10
b 11
c 12
d 13
e 14
f 15
g 16
h 17
i 18
</code></pre>
<p>What happens next is that <code>parseInt</code> scans the input <code>"Infinity"</code> to find which part of it can be parsed and stops after accepting the first <code>I</code> (because <code>n</code> is not a valid digit in base 19).</p>
<p>Therefore it behaves as if you called <code>parseInt("I", 19)</code>, which converts to decimal 18 by the table above.</p> | {
"question_id": 11340673,
"question_date": "2012-07-05T08:37:52.827Z",
"question_score": 864,
"tags": "javascript|parseint",
"answer_id": 11340718,
"answer_date": "2012-07-05T08:41:49.153Z",
"answer_score": 1307
} |
Please answer the following Stack Overflow question:
Title: How to define a two-dimensional array?
<p>I want to define a two-dimensional array without an initialized length like this:</p>
<pre><code>Matrix = [][]
</code></pre>
<p>But this gives an error:</p>
<blockquote>
<p>IndexError: list index out of range</p>
</blockquote> | <p>You're technically trying to index an uninitialized array. You have to first initialize the outer list with lists before adding items; Python calls this
"list comprehension".</p>
<pre><code># Creates a list containing 5 lists, each of 8 items, all set to 0
w, h = 8, 5
Matrix = [[0 for x in range(w)] for y in range(h)]
</code></pre>
<p>#You can now add items to the list:</p>
<pre><code>Matrix[0][0] = 1
Matrix[6][0] = 3 # error! range...
Matrix[0][6] = 3 # valid
</code></pre>
<p>Note that the matrix is "y" address major, in other words, the "y index" comes before the "x index".</p>
<pre><code>print Matrix[0][0] # prints 1
x, y = 0, 6
print Matrix[x][y] # prints 3; be careful with indexing!
</code></pre>
<p>Although you can name them as you wish, I look at it this way to avoid some confusion that could arise with the indexing, if you use "x" for both the inner and outer lists, and want a non-square Matrix.</p> | {
"question_id": 6667201,
"question_date": "2011-07-12T15:54:38.027Z",
"question_score": 863,
"tags": "python|list|multidimensional-array",
"answer_id": 6667288,
"answer_date": "2011-07-12T15:59:36.860Z",
"answer_score": 1189
} |
Please answer the following Stack Overflow question:
Title: The located assembly's manifest definition does not match the assembly reference
<p>I am trying to run some unit tests in a C# Windows Forms application (Visual Studio 2005), and I get the following error:</p>
<blockquote>
<p>System.IO.FileLoadException: Could not load file or assembly 'Utility, Version=1.2.0.200, Culture=neutral, PublicKeyToken=764d581291d764f7' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)**</p>
<p>at x.Foo.FooGO()</p>
<p>at x.Foo.Foo2(String groupName_) in Foo.cs:line 123</p>
<p>at x.Foo.UnitTests.FooTests.TestFoo() in FooTests.cs:line 98**</p>
<p>System.IO.FileLoadException: Could not load file or assembly 'Utility, Version=1.2.0.203, Culture=neutral, PublicKeyToken=764d581291d764f7' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)</p>
</blockquote>
<p>I look in my references, and I only have a reference to <code>Utility version 1.2.0.203</code> (the other one is old).</p>
<p>Any suggestions on how I figure out what is trying to reference this old version of this DLL file?</p>
<p>Besides, I don't think I even have this old assembly on my hard drive.
Is there any tool to search for this old versioned assembly?</p> | <p>The .NET Assembly loader:</p>
<ul>
<li>is unable to find 1.2.0.203</li>
<li>but did find a 1.2.0.200</li>
</ul>
<p>This assembly does not match what was requested and therefore you get this error.</p>
<p>In simple words, it can't find the assembly that was referenced. Make sure it can find the right assembly by putting it in the GAC or in the application path.</p>
<p>run below command to add the assembly dll file to GAC:</p>
<pre class="lang-bash prettyprint-override"><code>gacutil /i "path/to/my.dll"
</code></pre>
<p>Also see <a href="https://docs.microsoft.com/archive/blogs/junfeng/the-located-assemblys-manifest-definition-with-name-xxx-dll-does-not-match-the-assembly-reference" rel="nofollow noreferrer">https://docs.microsoft.com/archive/blogs/junfeng/the-located-assemblys-manifest-definition-with-name-xxx-dll-does-not-match-the-assembly-reference</a>.</p> | {
"question_id": 215026,
"question_date": "2008-10-18T13:16:26.373Z",
"question_score": 863,
"tags": "c#|reference|compiler-errors|dependencies|version",
"answer_id": 215054,
"answer_date": "2008-10-18T13:39:12.460Z",
"answer_score": 493
} |
Please answer the following Stack Overflow question:
Title: C++ Singleton design pattern
<p>Recently I've bumped into a realization/implementation of the Singleton design pattern for C++. It has looked like this (I have adopted it from the real-life example):</p>
<pre><code>// a lot of methods are omitted here
class Singleton
{
public:
static Singleton* getInstance( );
~Singleton( );
private:
Singleton( );
static Singleton* instance;
};
</code></pre>
<p>From this declaration, I can deduce that the instance field is initiated on the heap. That means there is a memory allocation. What is completely unclear for me is when exactly the memory is going to be deallocated? Or is there a bug and memory leak? It seems like there is a problem with the implementation.</p>
<p>My main question is, how do I implement it in the right way?</p> | <p>In 2008 I provided a C++98 implementation of the Singleton design pattern that is lazy-evaluated, guaranteed-destruction, not-technically-thread-safe:<br />
<a href="https://stackoverflow.com/a/271104/364696">Can any one provide me a sample of Singleton in c++?</a></p>
<p>Here is an updated C++11 implementation of the Singleton design pattern that is lazy-evaluated, correctly-destroyed, and <a href="https://stackoverflow.com/a/449823/52074">thread-safe</a>.</p>
<pre><code>class S
{
public:
static S& getInstance()
{
static S instance; // Guaranteed to be destroyed.
// Instantiated on first use.
return instance;
}
private:
S() {} // Constructor? (the {} brackets) are needed here.
// C++ 03
// ========
// Don't forget to declare these two. You want to make sure they
// are inaccessible(especially from outside), otherwise, you may accidentally get copies of
// your singleton appearing.
S(S const&); // Don't Implement
void operator=(S const&); // Don't implement
// C++ 11
// =======
// We can use the better technique of deleting the methods
// we don't want.
public:
S(S const&) = delete;
void operator=(S const&) = delete;
// Note: Scott Meyers mentions in his Effective Modern
// C++ book, that deleted functions should generally
// be public as it results in better error messages
// due to the compilers behavior to check accessibility
// before deleted status
};
</code></pre>
<p>See this article about when to use a singleton: (not often)<br />
<a href="https://stackoverflow.com/questions/86582/singleton-how-should-it-be-used">Singleton: How should it be used</a></p>
<p>See this two article about initialization order and how to cope:<br />
<a href="https://stackoverflow.com/questions/211237/c-static-variables-initialisation-order/211307#211307">Static variables initialisation order</a><br />
<a href="https://stackoverflow.com/questions/335369/finding-c-static-initialization-order-problems/335746#335746">Finding C++ static initialization order problems</a></p>
<p>See this article describing lifetimes:<br />
<a href="https://stackoverflow.com/questions/246564/what-is-the-lifetime-of-a-static-variable-in-a-c-function">What is the lifetime of a static variable in a C++ function?</a></p>
<p>See this article that discusses some threading implications to singletons:<br />
<a href="https://stackoverflow.com/questions/449436/singleton-instance-declared-as-static-variable-of-getinstance-method/449823#449823">Singleton instance declared as static variable of GetInstance method, is it thread-safe?</a></p>
<p>See this article that explains why double checked locking will not work on C++:<br />
<a href="https://stackoverflow.com/questions/367633/what-are-all-the-common-undefined-behaviour-that-c-programmer-should-know-about/367690#367690">What are all the common undefined behaviours that a C++ programmer should know about?</a><br />
<a href="http://www.drdobbs.com/cpp/c-and-the-perils-of-double-checked-locki/184405726" rel="noreferrer">Dr Dobbs: C++ and The Perils of Double-Checked Locking: Part I</a></p> | {
"question_id": 1008019,
"question_date": "2009-06-17T16:02:22.563Z",
"question_score": 863,
"tags": "c++|design-patterns|singleton",
"answer_id": 1008289,
"answer_date": "2009-06-17T16:49:58.803Z",
"answer_score": 1326
} |
Please answer the following Stack Overflow question:
Title: Include jQuery in the JavaScript Console
<p>Is there an easy way to include jQuery in the Chrome JavaScript console for sites that do not use it? For example, on a website I would like to get the number of rows in a table. I know this is really easy with jQuery.</p>
<pre><code>$('element').length;
</code></pre>
<p>The site does not use jQuery. Can I add it in from the command line?</p> | <p>Run this in your browser's JavaScript console, then jQuery should be available...</p>
<pre class="lang-js prettyprint-override"><code>var jq = document.createElement('script');
jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);
// ... give time for script to load, then type (or see below for non wait option)
jQuery.noConflict();
</code></pre>
<p><strong>NOTE:</strong> if the site has scripts that conflict with jQuery (other libs, etc.) you could still run into problems.</p>
<h3>Update:</h3>
<p>Making the best better, creating a Bookmark makes it really convenient, let's do it, and a little feedback is great too:</p>
<ol>
<li>Right click the Bookmarks Bar, and click <strong>Add Page</strong></li>
<li>Name it as you like, e.g. Inject jQuery, and use the following line for URL:</li>
</ol>
<blockquote>
<p>javascript:(function(e,s){e.src=s;e.onload=function(){jQuery.noConflict();console.log('jQuery injected')};document.head.appendChild(e);})(document.createElement('script'),'//code.jquery.com/jquery-latest.min.js')</p>
</blockquote>
<p>Below is the formatted code:</p>
<pre class="lang-js prettyprint-override"><code>javascript: (function(e, s) {
e.src = s;
e.onload = function() {
jQuery.noConflict();
console.log('jQuery injected');
};
document.head.appendChild(e);
})(document.createElement('script'), '//code.jquery.com/jquery-latest.min.js')
</code></pre>
<p>Here the official jQuery CDN URL is used, feel free to use your own CDN/version.</p> | {
"question_id": 7474354,
"question_date": "2011-09-19T16:42:34.913Z",
"question_score": 863,
"tags": "javascript|jquery",
"answer_id": 7474386,
"answer_date": "2011-09-19T16:44:57.963Z",
"answer_score": 1547
} |
Please answer the following Stack Overflow question:
Title: AngularJS : Prevent error $digest already in progress when calling $scope.$apply()
<p>I'm finding that I need to update my page to my scope manually more and more since building an application in angular.</p>
<p>The only way I know of to do this is to call <code>$apply()</code> from the scope of my controllers and directives. The problem with this is that it keeps throwing an error to the console that reads :</p>
<blockquote>
<p>Error: $digest already in progress</p>
</blockquote>
<p>Does anyone know how to avoid this error or achieve the same thing but in a different way?</p> | <blockquote>
<p><strong>Don't use this pattern</strong> - This will end up causing more errors than it solves. Even though you think it fixed something, it didn't. </p>
</blockquote>
<p>You can check if a <code>$digest</code> is already in progress by checking <code>$scope.$$phase</code>. </p>
<pre><code>if(!$scope.$$phase) {
//$digest or $apply
}
</code></pre>
<p><code>$scope.$$phase</code> will return <code>"$digest"</code> or <code>"$apply"</code> if a <code>$digest</code> or <code>$apply</code> is in progress. I believe the difference between these states is that <code>$digest</code> will process the watches of the current scope and its children, and <code>$apply</code> will process the watchers of all scopes.</p>
<p>To @dnc253's point, if you find yourself calling <code>$digest</code> or <code>$apply</code> frequently, you may be doing it wrong. I generally find I need to digest when I need to update the scope's state as a result of a DOM event firing outside the reach of Angular. For example, when a twitter bootstrap modal becomes hidden. Sometimes the DOM event fires when a <code>$digest</code> is in progress, sometimes not. That's why I use this check. </p>
<p>I would love to know a better way if anyone knows one.</p>
<hr>
<p>From comments:
by @anddoutoi</p>
<p><a href="https://github.com/angular/angular.js/wiki/Dev-Guide%3A-Anti-Patterns" rel="noreferrer">angular.js Anti Patterns</a></p>
<blockquote>
<ol start="2">
<li>Don't do <code>if (!$scope.$$phase) $scope.$apply()</code>, it means your <code>$scope.$apply()</code> isn't high enough in the call stack.</li>
</ol>
</blockquote> | {
"question_id": 12729122,
"question_date": "2012-10-04T14:07:32.103Z",
"question_score": 863,
"tags": "angularjs|angularjs-scope|angularjs-digest",
"answer_id": 12859093,
"answer_date": "2012-10-12T12:28:54.100Z",
"answer_score": 672
} |
Please answer the following Stack Overflow question:
Title: Error - Unable to access the IIS metabase
<p>After installing <strong>Visual Studio 2012</strong> and opening my solution I get a series of errors in this form:</p>
<blockquote>
<p>The Web Application Project Foo is configured to use <strong>IIS</strong>.<br>
Unable to access the <strong>IIS Metabase</strong>. You do not have sufficient privilege to access <strong>IIS</strong> web sites on your machine.</p>
</blockquote>
<p>I get this for each of our web applications. </p>
<hr>
<p>Things I have tried:</p>
<ol>
<li>Running Visual Studio as Administrator </li>
<li>Running aspnet_regiis.exe -ga MyUserName </li>
<li>Running aspnet_regiis.exe -i</li>
</ol>
<p>These seem to be common solutions for this problem but I have not had any success with them. </p>
<blockquote>
<p>Is there anything else I can try to do? </p>
</blockquote> | <p><strong>Thank you to everyone that answered.</strong> Since this was closed for a long time I couldn't provide much feedback, but I did eventually fix my problem. I tried many of these other solutions and they didn't fix my issue, but I'm sure they help when the root cause is different.</p>
<p><strong>My Solution</strong></p>
<p>I solved this problem by turning off the IIS and .Net Framework features within Windows 7 and then turning them back on. It seems like this re-installation is what fixed my issue. I still don't know what caused the problem, but at least one other developer on my team had the same issue.</p> | {
"question_id": 12859891,
"question_date": "2012-10-12T13:15:03.270Z",
"question_score": 863,
"tags": "c#|.net|iis|iis-metabase",
"answer_id": 14715377,
"answer_date": "2013-02-05T19:30:23.007Z",
"answer_score": 17
} |
Please answer the following Stack Overflow question:
Title: How do I convert a string to a number in PHP?
<p>I want to convert these types of values, <code>'3'</code>, <code>'2.34'</code>, <code>'0.234343'</code>, etc. to a number. In JavaScript we can use <code>Number()</code>, but is there any similar method available in PHP?</p>
<pre><code>Input Output
'2' 2
'2.34' 2.34
'0.3454545' 0.3454545
</code></pre> | <p>You don't typically need to do this, since PHP will coerce the type for you in most circumstances. For situations where you do want to explicitly convert the type, <a href="http://www.php.net/manual/en/language.types.type-juggling.php#language.types.typecasting"><em>cast</em></a> it:</p>
<pre><code>$num = "3.14";
$int = (int)$num;
$float = (float)$num;
</code></pre> | {
"question_id": 8529656,
"question_date": "2011-12-16T04:08:14.207Z",
"question_score": 862,
"tags": "php|casting|type-conversion",
"answer_id": 8529687,
"answer_date": "2011-12-16T04:13:32.693Z",
"answer_score": 1321
} |
Please answer the following Stack Overflow question:
Title: Using Python 3 in virtualenv
<p>Using <a href="https://virtualenv.pypa.io/en/latest/">virtualenv</a>, I run my projects with the default version of Python (2.7). On one project, I need to use Python 3.4. </p>
<p>I used <code>brew install python3</code> to install it on my Mac. Now, how do I create a virtualenv that uses the new version?</p>
<p>e.g. sudo virtualenv envPython3</p>
<p>If I try:</p>
<pre><code>virtualenv -p python3 test
</code></pre>
<p>I get:</p>
<pre><code>Running virtualenv with interpreter /usr/local/bin/python3
Using base prefix '/usr/local/Cellar/python3/3.4.0_1/Frameworks/Python.framework/Versions/3.4'
New python executable in test/bin/python3.4
Also creating executable in test/bin/python
Failed to import the site module
Traceback (most recent call last):
File "/Users/user/Documents/workspace/test/test/bin/../lib/python3.4/site.py", line 67, in <module>
import os
File "/Users/user/Documents/workspace/test/test/bin/../lib/python3.4/os.py", line 634, in <module>
from _collections_abc import MutableMapping
ImportError: No module named '_collections_abc'
ERROR: The executable test/bin/python3.4 is not functioning
ERROR: It thinks sys.prefix is '/Users/user/Documents/workspace/test' (should be '/Users/user/Documents/workspace/test/test')
ERROR: virtualenv is not compatible with this system or executable
</code></pre> | <p>simply run</p>
<pre><code>virtualenv -p python3 envname
</code></pre>
<p>Update after OP's edit:</p>
<p>There was a bug in the OP's version of virtualenv, as described <a href="https://github.com/pypa/virtualenv/issues/463" rel="noreferrer">here</a>. The problem was fixed by running:</p>
<pre><code>pip install --upgrade virtualenv
</code></pre> | {
"question_id": 23842713,
"question_date": "2014-05-24T08:05:53.040Z",
"question_score": 862,
"tags": "python|python-3.x|virtualenv",
"answer_id": 23842752,
"answer_date": "2014-05-24T08:11:01.997Z",
"answer_score": 1485
} |
Please answer the following Stack Overflow question:
Title: Is there any standard for JSON API response format?
<p>Do standards or best practices exist for structuring JSON responses from an API? Obviously, every application's data is different, so that much I'm not concerned with, but rather the "response boilerplate", if you will. An example of what I mean:</p>
<p><strong>Successful request:</strong></p>
<pre><code>{
"success": true,
"payload": {
/* Application-specific data would go here. */
}
}
</code></pre>
<p><strong>Failed request:</strong></p>
<pre><code>{
"success": false,
"payload": {
/* Application-specific data would go here. */
},
"error": {
"code": 123,
"message": "An error occurred!"
}
}
</code></pre> | <p>Yes there are a couple of standards (albeit some liberties on the definition of standard) that have emerged:</p>
<ol>
<li><a href="http://jsonapi.org" rel="noreferrer">JSON API</a> - JSON API covers creating and updating resources as well, not just responses.</li>
<li><a href="https://github.com/omniti-labs/jsend" rel="noreferrer">JSend</a> - Simple and probably what you are already doing.</li>
<li><a href="http://docs.oasis-open.org/odata/odata-json-format/v4.0/errata02/os/odata-json-format-v4.0-errata02-os-complete.html#_Toc403940655" rel="noreferrer">OData JSON Protocol</a> - Very complicated.</li>
<li><a href="http://stateless.co/hal_specification.html" rel="noreferrer">HAL</a> - Like OData but aiming to be <a href="http://en.wikipedia.org/wiki/HATEOAS" rel="noreferrer">HATEOAS</a> like.</li>
</ol>
<p>There are also JSON API description formats:</p>
<ul>
<li><a href="https://github.com/wordnik/swagger-core/wiki" rel="noreferrer">Swagger</a>
<ul>
<li><a href="http://json-schema.org/" rel="noreferrer">JSON Schema</a> (used by swagger but you could use it stand alone)</li>
</ul></li>
<li>WADL in JSON</li>
<li><a href="http://raml.org" rel="noreferrer">RAML</a></li>
<li>HAL because <a href="http://en.wikipedia.org/wiki/HATEOAS" rel="noreferrer">HATEOAS</a> in theory is self describing.</li>
</ul> | {
"question_id": 12806386,
"question_date": "2012-10-09T18:43:36.350Z",
"question_score": 862,
"tags": "json",
"answer_id": 14538774,
"answer_date": "2013-01-26T16:12:33.243Z",
"answer_score": 792
} |
Please answer the following Stack Overflow question:
Title: Unfortunately MyApp has stopped. How can I solve this?
<p>I am developing an application, and everytime I run it, I get the message:</p>
<blockquote>
<p>Unfortunately, MyApp has stopped.</p>
</blockquote>
<p>What can I do to solve this?</p>
<hr/>
<p><em>About this question - obviously inspired by <a href="https://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors">What is a stack trace, and how can I use it to debug my application errors?</a>, there are lots of questions stating that their application has crashed, without any further detail. This question aims to instruct novice Android programmers on how to try and fix their problems themselves, or ask the right questions.</em></p> | <p><em>This answer describes the process of retrieving the stack trace. Already have the stack trace? Read up on stack traces in "<a href="https://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors">What is a stack trace, and how can I use it to debug my application errors?</a>"</em></p>
<h1>The Problem</h1>
<p>Your application quit because an uncaught <code>RuntimeException</code> was thrown.<br>
The most common of these is the <a href="https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it"><code>NullPointerException</code></a>.</p>
<h1>How to solve it?</h1>
<p>Every time an Android application crashes (or any Java application for that matter), a <code>Stack trace</code> is written to the console (in this case, logcat). This stack trace contains vital information for solving your problem.</p>
<h2>Android Studio</h2>
<p><img src="https://i.stack.imgur.com/ZL3Y8.png" alt="Finding the stack trace in Android Studio"></p>
<p>In the bottom bar of the window, click on the <code>Logcat</code> button. Alternatively, you can press <kbd>alt</kbd>+<kbd>6</kbd>. Make sure your emulator or device is selected in the <code>Devices</code> panel. Next, try to find the stack trace, which is shown in red. There may be a lot of stuff logged into logcat, so you may need to scroll a bit. An easy way to find the stack trace is to clear the logcat (using the recycle bin on the right), and let the app crash again.</p>
<h1>I have found the stack trace, now what?</h1>
<p>Yay! You're halfway to solving your problem.<br>
You only need to find out what exactly made your application crash, by analyzing the stack trace.</p>
<p>Read up on stack traces in "<a href="https://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors">What is a stack trace, and how can I use it to debug my application errors?</a>"</p>
<h1>I still can't solve my problem!</h1>
<p>If you've found your <code>Exception</code> and the line where it occurred, and still cannot figure out how to fix it, don't hesitate to ask a question on StackOverflow. </p>
<p>Try to be as concise as possible: post the stack trace, and the <em>relevant</em> code (e.g. a few lines up to the line which threw the <code>Exception</code>).</p> | {
"question_id": 23353173,
"question_date": "2014-04-28T23:55:14.227Z",
"question_score": 862,
"tags": "java|android|debugging|kotlin",
"answer_id": 23353174,
"answer_date": "2014-04-28T23:55:14.227Z",
"answer_score": 767
} |
Please answer the following Stack Overflow question:
Title: How to identify on which OS Python is running on?
<p>What do I need to look at to see whether I'm on Windows or Unix, etc?</p> | <pre><code>>>> import os
>>> os.name
'posix'
>>> import platform
>>> platform.system()
'Linux'
>>> platform.release()
'2.6.22-15-generic'
</code></pre>
<p>The output of <a href="https://docs.python.org/library/platform.html#platform.system" rel="noreferrer"><code>platform.system()</code></a> is as follows:</p>
<ul>
<li>Linux: <code>Linux</code></li>
<li>Mac: <code>Darwin</code></li>
<li>Windows: <code>Windows</code></li>
</ul>
<p>See: <a href="https://docs.python.org/library/platform.html" rel="noreferrer"><code>platform</code> — Access to underlying platform’s identifying data</a></p> | {
"question_id": 1854,
"question_date": "2008-08-05T03:23:18.917Z",
"question_score": 862,
"tags": "python|operating-system|cross-platform|platform-agnostic",
"answer_id": 1857,
"answer_date": "2008-08-05T03:27:03.760Z",
"answer_score": 1145
} |
Please answer the following Stack Overflow question:
Title: How do I access my SSH public key?
<p>I've just generated my RSA key pair, and I wanted to add that key to GitHub.</p>
<p>I tried <code>cd id_rsa.pub</code> and <code>id_rsa.pub</code>, but no luck. How can I access my SSH public key?</p> | <p><code>cat ~/.ssh/id_rsa.pub</code> or <code>cat ~/.ssh/id_dsa.pub</code></p>
<p>You can list all the public keys you have by doing:</p>
<p><code>$ ls ~/.ssh/*.pub</code></p> | {
"question_id": 3828164,
"question_date": "2010-09-30T06:03:56.423Z",
"question_score": 860,
"tags": "git|ssh|rsa",
"answer_id": 3828169,
"answer_date": "2010-09-30T06:05:16.860Z",
"answer_score": 1444
} |
Please answer the following Stack Overflow question:
Title: How to split a string into an array in Bash?
<p>In a Bash script, I would like to split a line into pieces and store them in an array.</p>
<p>For example, given the line:</p>
<pre><code>Paris, France, Europe
</code></pre>
<p>I would like to have the resulting array to look like so:</p>
<pre><code>array[0] = Paris
array[1] = France
array[2] = Europe
</code></pre>
<p>A simple implementation is preferable; speed does not matter. How can I do it?</p> | <pre><code>IFS=', ' read -r -a array <<< "$string"
</code></pre>
<p>Note that the characters in <code>$IFS</code> are treated individually as separators so that in this case fields may be separated by <em>either</em> a comma or a space rather than the sequence of the two characters. Interestingly though, empty fields aren't created when comma-space appears in the input because the space is treated specially.</p>
<p>To access an individual element:</p>
<pre><code>echo "${array[0]}"
</code></pre>
<p>To iterate over the elements:</p>
<pre><code>for element in "${array[@]}"
do
echo "$element"
done
</code></pre>
<p>To get both the index and the value:</p>
<pre><code>for index in "${!array[@]}"
do
echo "$index ${array[index]}"
done
</code></pre>
<p>The last example is useful because Bash arrays are sparse. In other words, you can delete an element or add an element and then the indices are not contiguous.</p>
<pre><code>unset "array[1]"
array[42]=Earth
</code></pre>
<p>To get the number of elements in an array:</p>
<pre><code>echo "${#array[@]}"
</code></pre>
<p>As mentioned above, arrays can be sparse so you shouldn't use the length to get the last element. Here's how you can in Bash 4.2 and later:</p>
<pre><code>echo "${array[-1]}"
</code></pre>
<p>in any version of Bash (from somewhere after 2.05b):</p>
<pre><code>echo "${array[@]: -1:1}"
</code></pre>
<p>Larger negative offsets select farther from the end of the array. Note the space before the minus sign in the older form. It is required.</p> | {
"question_id": 10586153,
"question_date": "2012-05-14T15:15:58.363Z",
"question_score": 860,
"tags": "arrays|bash|split",
"answer_id": 10586169,
"answer_date": "2012-05-14T15:16:48.597Z",
"answer_score": 1402
} |
Please answer the following Stack Overflow question:
Title: What's the difference between struct and class in .NET?
<p>What's the difference between struct and class in .NET?</p> | <p>In .NET, there are two categories of types, <em>reference types</em> and <em>value types</em>.</p>
<p>Structs are <em>value types</em> and classes are <em>reference types</em>.</p>
<p>The general difference is that a <em>reference type</em> lives on the heap, and a <em>value type</em> lives inline, that is, wherever it is your variable or field is defined.</p>
<p>A variable containing a <em>value type</em> contains the entire <em>value type</em> value. For a struct, that means that the variable contains the entire struct, with all its fields.</p>
<p>A variable containing a <em>reference type</em> contains a pointer, or a <em>reference</em> to somewhere else in memory where the actual value resides.</p>
<p>This has one benefit, to begin with:</p>
<ul>
<li><em>value types</em> always contains a value</li>
<li><em>reference types</em> can contain a <em>null</em>-reference, meaning that they don't refer to anything at all at the moment</li>
</ul>
<p>Internally, <em>reference type</em>s are implemented as pointers, and knowing that, and knowing how variable assignment works, there are other behavioral patterns:</p>
<ul>
<li>copying the contents of a <em>value type</em> variable into another variable, copies the entire contents into the new variable, making the two distinct. In other words, after the copy, changes to one won't affect the other</li>
<li>copying the contents of a <em>reference type</em> variable into another variable, copies the reference, which means you now have two references to the same <em>somewhere else</em> storage of the actual data. In other words, after the copy, changing the data in one reference will appear to affect the other as well, but only because you're really just looking at the same data both places</li>
</ul>
<p>When you declare variables or fields, here's how the two types differ:</p>
<ul>
<li>variable: <em>value type</em> lives on the stack, <em>reference type</em> lives on the stack as a pointer to somewhere in heap memory where the actual memory lives (though note <a href="https://blogs.msdn.microsoft.com/ericlippert/2009/04/27/the-stack-is-an-implementation-detail-part-one/" rel="noreferrer">Eric Lipperts article series: The Stack Is An Implementation Detail</a>.)</li>
<li>class/struct-field: <em>value type</em> lives completely inside the type, <em>reference type</em> lives inside the type as a pointer to somewhere in heap memory where the actual memory lives.</li>
</ul> | {
"question_id": 13049,
"question_date": "2008-08-16T08:21:47.947Z",
"question_score": 860,
"tags": ".net|class|struct|value-type|reference-type",
"answer_id": 13275,
"answer_date": "2008-08-16T18:41:38.037Z",
"answer_score": 1222
} |
Please answer the following Stack Overflow question:
Title: What is PECS (Producer Extends Consumer Super)?
<p>I came across PECS (short for <em>Producer <code>extends</code> and Consumer <code>super</code></em>) while reading up on generics. </p>
<p>Can someone explain to me how to use PECS to resolve confusion between <code>extends</code> and <code>super</code>?</p> | <p><strong>tl;dr:</strong> "PECS" is from the collection's point of view. If you are <em>only</em> pulling items from a generic collection, it is a producer and you should use <code>extends</code>; if you are <em>only</em> stuffing items in, it is a consumer and you should use <code>super</code>. If you do both with the same collection, you shouldn't use either <code>extends</code> or <code>super</code>.</p>
<hr />
<p>Suppose you have a method that takes as its parameter a collection of things, but you want it to be more flexible than just accepting a <code>Collection<Thing></code>.</p>
<p><strong>Case 1: You want to go through the collection and do things with each item.</strong><br />
Then the list is a <strong>producer</strong>, so you should use a <code>Collection<? extends Thing></code>.</p>
<p>The reasoning is that a <code>Collection<? extends Thing></code> could hold any subtype of <code>Thing</code>, and thus each element will behave as a <code>Thing</code> when you perform your operation. (You actually cannot add anything (except null) to a <code>Collection<? extends Thing></code>, because you cannot know at runtime which <em>specific</em> subtype of <code>Thing</code> the collection holds.)</p>
<p><strong>Case 2: You want to add things to the collection.</strong><br />
Then the list is a <strong>consumer</strong>, so you should use a <code>Collection<? super Thing></code>.</p>
<p>The reasoning here is that unlike <code>Collection<? extends Thing></code>, <code>Collection<? super Thing></code> can always hold a <code>Thing</code> no matter what the actual parameterized type is. Here you don't care what is already in the list as long as it will allow a <code>Thing</code> to be added; this is what <code>? super Thing</code> guarantees.</p> | {
"question_id": 2723397,
"question_date": "2010-04-27T17:16:40.273Z",
"question_score": 860,
"tags": "java|generics|super|bounded-wildcard|pecs",
"answer_id": 2723538,
"answer_date": "2010-04-27T17:37:26.150Z",
"answer_score": 989
} |
Please answer the following Stack Overflow question:
Title: Redirect all output to file in Bash
<p>I know that in Linux, to redirect output from the screen to a file, I can either use the <code>></code> or <code>tee</code>. However, I'm not sure why part of the output is still output to the screen and not written to the file. </p>
<p>Is there a way to redirect all output to file?</p> | <p>That part is written to stderr, use <code>2></code> to redirect it. For example:</p>
<pre><code>foo > stdout.txt 2> stderr.txt
</code></pre>
<p>or if you want in same file:</p>
<pre><code>foo > allout.txt 2>&1
</code></pre>
<p>Note: this works in (ba)sh, check your shell for proper syntax</p> | {
"question_id": 6674327,
"question_date": "2011-07-13T05:06:49.710Z",
"question_score": 859,
"tags": "linux|bash|io-redirection",
"answer_id": 6674348,
"answer_date": "2011-07-13T05:10:01.043Z",
"answer_score": 1370
} |
Please answer the following Stack Overflow question:
Title: How can I list all collections in the MongoDB shell?
<p>In the MongoDB shell, how do I list all collections for the current database that I'm using?</p> | <p>You can do...</p>
<p>JavaScript (shell):</p>
<pre><code>db.getCollectionNames()
</code></pre>
<p>Node.js:</p>
<pre><code>db.listCollections()
</code></pre>
<p>Non-JavaScript (shell only):</p>
<pre><code>show collections
</code></pre>
<p>The reason I call that non-JavaScript is because:</p>
<pre><code>$ mongo prodmongo/app --eval "show collections"
MongoDB shell version: 3.2.10
connecting to: prodmongo/app
2016-10-26T19:34:34.886-0400 E QUERY [thread1] SyntaxError: missing ; before statement @(shell eval):1:5
$ mongo prodmongo/app --eval "db.getCollectionNames()"
MongoDB shell version: 3.2.10
connecting to: prodmongo/app
[
"Profiles",
"Unit_Info"
]
</code></pre>
<p>If you really want that sweet, sweet <code>show collections</code> output, you can:</p>
<pre><code>$ mongo prodmongo/app --eval "db.getCollectionNames().join('\n')"
MongoDB shell version: 3.2.10
connecting to: prodmongo/app
Profiles
Unit_Info
</code></pre> | {
"question_id": 8866041,
"question_date": "2012-01-14T22:52:03.327Z",
"question_score": 859,
"tags": "mongodb|mongo-shell",
"answer_id": 8866075,
"answer_date": "2012-01-14T22:57:47.127Z",
"answer_score": 1291
} |
Please answer the following Stack Overflow question:
Title: Getting a list of all subdirectories in the current directory
<p>Is there a way to return a list of all the subdirectories in the current directory in Python?</p>
<p>I know you can do this with files, but I need to get the list of directories instead.</p> | <p>Do you mean immediate subdirectories, or every directory right down the tree? </p>
<p>Either way, you could use <a href="http://docs.python.org/library/os.html#os.walk" rel="noreferrer"><code>os.walk</code></a> to do this:</p>
<pre><code>os.walk(directory)
</code></pre>
<p>will yield a tuple for each subdirectory. Ths first entry in the 3-tuple is a directory name, so</p>
<pre><code>[x[0] for x in os.walk(directory)]
</code></pre>
<p>should give you all of the subdirectories, recursively.</p>
<p>Note that the second entry in the tuple is the list of child directories of the entry in the first position, so you could use this instead, but it's not likely to save you much.</p>
<p>However, you could use it just to give you the immediate child directories:</p>
<pre><code>next(os.walk('.'))[1]
</code></pre>
<p>Or see the other solutions already posted, using <a href="http://docs.python.org/library/os.html#os.listdir" rel="noreferrer"><code>os.listdir</code></a> and <a href="http://docs.python.org/library/os.path.html#os.path.isdir" rel="noreferrer"><code>os.path.isdir</code></a>, including those at "<a href="https://stackoverflow.com/questions/800197/get-all-of-the-immediate-subdirectories-in-python">How to get all of the immediate subdirectories in Python</a>".</p> | {
"question_id": 973473,
"question_date": "2009-06-10T02:48:21.730Z",
"question_score": 858,
"tags": "python|directory|subdirectory",
"answer_id": 973488,
"answer_date": "2009-06-10T02:54:45.913Z",
"answer_score": 853
} |
Please answer the following Stack Overflow question:
Title: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details
<p>I am having this error when seeding my database with code first approach.</p>
<blockquote>
<p>Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.</p>
</blockquote>
<p>To be honest I don't know how to check the content of the validation errors. Visual Studio shows me that it's an array with 8 objects, so 8 validation errors.</p>
<p>This was working with my previous model, but I made a few changes that I explain below:</p>
<ul>
<li>I had an enum called Status, I changed it to a class called Status</li>
<li>I changed the class ApplicantsPositionHistory to have 2 foreign key to the same table</li>
</ul>
<p>Excuse me for the long code, but I have to paste it all. The exception is thrown in the last line of the following code.</p>
<pre><code>namespace Data.Model
{
public class Position
{
[DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.Identity)]
public int PositionID { get; set; }
[Required(ErrorMessage = "Position name is required.")]
[StringLength(20, MinimumLength = 3, ErrorMessage = "Name should not be longer than 20 characters.")]
[Display(Name = "Position name")]
public string name { get; set; }
[Required(ErrorMessage = "Number of years is required")]
[Display(Name = "Number of years")]
public int yearsExperienceRequired { get; set; }
public virtual ICollection<ApplicantPosition> applicantPosition { get; set; }
}
public class Applicant
{
[DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.Identity)]
public int ApplicantID { get; set; }
[Required(ErrorMessage = "Name is required")]
[StringLength(20, MinimumLength = 3, ErrorMessage="Name should not be longer than 20 characters.")]
[Display(Name = "First and LastName")]
public string name { get; set; }
[Required(ErrorMessage = "Telephone number is required")]
[StringLength(10, MinimumLength = 3, ErrorMessage = "Telephone should not be longer than 20 characters.")]
[Display(Name = "Telephone Number")]
public string telephone { get; set; }
[Required(ErrorMessage = "Skype username is required")]
[StringLength(10, MinimumLength = 3, ErrorMessage = "Skype user should not be longer than 20 characters.")]
[Display(Name = "Skype Username")]
public string skypeuser { get; set; }
public byte[] photo { get; set; }
public virtual ICollection<ApplicantPosition> applicantPosition { get; set; }
}
public class ApplicantPosition
{
[Key]
[Column("ApplicantID", Order = 0)]
public int ApplicantID { get; set; }
[Key]
[Column("PositionID", Order = 1)]
public int PositionID { get; set; }
public virtual Position Position { get; set; }
public virtual Applicant Applicant { get; set; }
[Required(ErrorMessage = "Applied date is required")]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
[Display(Name = "Date applied")]
public DateTime appliedDate { get; set; }
[Column("StatusID", Order = 0)]
public int StatusID { get; set; }
public Status CurrentStatus { get; set; }
//[NotMapped]
//public int numberOfApplicantsApplied
//{
// get
// {
// int query =
// (from ap in Position
// where ap.Status == (int)Status.Applied
// select ap
// ).Count();
// return query;
// }
//}
}
public class Address
{
[StringLength(20, MinimumLength = 3, ErrorMessage = "Country should not be longer than 20 characters.")]
public string Country { get; set; }
[StringLength(20, MinimumLength = 3, ErrorMessage = "City should not be longer than 20 characters.")]
public string City { get; set; }
[StringLength(50, MinimumLength = 3, ErrorMessage = "Address should not be longer than 50 characters.")]
[Display(Name = "Address Line 1")]
public string AddressLine1 { get; set; }
[Display(Name = "Address Line 2")]
public string AddressLine2 { get; set; }
}
public class ApplicationPositionHistory
{
[DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.Identity)]
public int ApplicationPositionHistoryID { get; set; }
public ApplicantPosition applicantPosition { get; set; }
[Column("oldStatusID")]
public int oldStatusID { get; set; }
[Column("newStatusID")]
public int newStatusID { get; set; }
public Status oldStatus { get; set; }
public Status newStatus { get; set; }
[StringLength(500, MinimumLength = 3, ErrorMessage = "Comments should not be longer than 500 characters.")]
[Display(Name = "Comments")]
public string comments { get; set; }
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
[Display(Name = "Date")]
public DateTime dateModified { get; set; }
}
public class Status
{
[DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.Identity)]
public int StatusID { get; set; }
[StringLength(20, MinimumLength = 3, ErrorMessage = "Status should not be longer than 20 characters.")]
[Display(Name = "Status")]
public string status { get; set; }
}
}
</code></pre>
<p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.IO;
namespace Data.Model
{
public class HRContextInitializer : DropCreateDatabaseAlways<HRContext>
{
protected override void Seed(HRContext context)
{
#region Status
Status applied = new Status() { status = "Applied" };
Status reviewedByHR = new Status() { status = "Reviewed By HR" };
Status approvedByHR = new Status() { status = "Approved by HR" };
Status rejectedByHR = new Status() { status = "Rejected by HR" };
Status assignedToTechnicalDepartment = new Status() { status = "Assigned to Technical Department" };
Status approvedByTechnicalDepartment = new Status() { status = "Approved by Technical Department" };
Status rejectedByTechnicalDepartment = new Status() { status = "Rejected by Technical Department" };
Status assignedToGeneralManager = new Status() { status = "Assigned to General Manager" };
Status approvedByGeneralManager = new Status() { status = "Approved by General Manager" };
Status rejectedByGeneralManager = new Status() { status = "Rejected by General Manager" };
context.Status.Add(applied);
context.Status.Add(reviewedByHR);
context.Status.Add(approvedByHR);
context.Status.Add(rejectedByHR);
context.Status.Add(assignedToTechnicalDepartment);
context.Status.Add(approvedByTechnicalDepartment);
context.Status.Add(rejectedByTechnicalDepartment);
context.Status.Add(assignedToGeneralManager);
context.Status.Add(approvedByGeneralManager);
context.Status.Add(rejectedByGeneralManager);
#endregion
#region Position
Position netdeveloper = new Position() { name = ".net developer", yearsExperienceRequired = 5 };
Position javadeveloper = new Position() { name = "java developer", yearsExperienceRequired = 5 };
context.Positions.Add(netdeveloper);
context.Positions.Add(javadeveloper);
#endregion
#region Applicants
Applicant luis = new Applicant()
{
name = "Luis",
skypeuser = "le.valencia",
telephone = "0491732825",
photo = File.ReadAllBytes(@"C:\Users\LUIS.SIMBIOS\Documents\Visual Studio 2010\Projects\SlnHR\HRRazorForms\Content\pictures\1.jpg")
};
Applicant john = new Applicant()
{
name = "John",
skypeuser = "jo.valencia",
telephone = "3435343543",
photo = File.ReadAllBytes(@"C:\Users\LUIS.SIMBIOS\Documents\Visual Studio 2010\Projects\SlnHR\HRRazorForms\Content\pictures\2.jpg")
};
context.Applicants.Add(luis);
context.Applicants.Add(john);
#endregion
#region ApplicantsPositions
ApplicantPosition appicantposition = new ApplicantPosition()
{
Applicant = luis,
Position = netdeveloper,
appliedDate = DateTime.Today,
StatusID = 1
};
ApplicantPosition appicantposition2 = new ApplicantPosition()
{
Applicant = john,
Position = javadeveloper,
appliedDate = DateTime.Today,
StatusID = 1
};
context.ApplicantsPositions.Add(appicantposition);
context.ApplicantsPositions.Add(appicantposition2);
#endregion
context.SaveChanges(); --->> Error here
}
}
}
</code></pre> | <blockquote>
<p>To be honest I don't know how to check the content of the validation errors. Visual Studio shows me that it's an array with 8 objects, so 8 validation errors.</p>
</blockquote>
<p>Actually you should see the errors if you drill into that array in Visual studio during debug. But you can also catch the exception and then write out the errors to some logging store or the console:</p>
<pre><code>try
{
// Your code...
// Could also be before try if you know the exception occurs in SaveChanges
context.SaveChanges();
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
</code></pre>
<p><code>EntityValidationErrors</code> is a collection which represents the entities which couldn't be validated successfully, and the inner collection <code>ValidationErrors</code> per entity is a list of errors on property level.</p>
<p>These validation messages are usually helpful enough to find the source of the problem. </p>
<p><strong>Edit</strong></p>
<p>A few slight improvements:</p>
<p>The <em>value</em> of the offending property can be included in the inner loop like so:</p>
<pre><code> foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Value: \"{1}\", Error: \"{2}\"",
ve.PropertyName,
eve.Entry.CurrentValues.GetValue<object>(ve.PropertyName),
ve.ErrorMessage);
}
</code></pre>
<p>While debugging <code>Debug.Write</code> might be preferable over <code>Console.WriteLine</code> as it works in all kind of applications, not only console applications (thanks to @Bart for his note in the comments below).</p>
<p>For web applications that are in production and that use <strong>Elmah</strong> for exception logging it turned out to be very useful for me to create a custom exception and overwrite <code>SaveChanges</code> in order to throw this new exception.</p>
<p>The custom exception type looks like this:</p>
<pre><code>public class FormattedDbEntityValidationException : Exception
{
public FormattedDbEntityValidationException(DbEntityValidationException innerException) :
base(null, innerException)
{
}
public override string Message
{
get
{
var innerException = InnerException as DbEntityValidationException;
if (innerException != null)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine();
sb.AppendLine();
foreach (var eve in innerException.EntityValidationErrors)
{
sb.AppendLine(string.Format("- Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().FullName, eve.Entry.State));
foreach (var ve in eve.ValidationErrors)
{
sb.AppendLine(string.Format("-- Property: \"{0}\", Value: \"{1}\", Error: \"{2}\"",
ve.PropertyName,
eve.Entry.CurrentValues.GetValue<object>(ve.PropertyName),
ve.ErrorMessage));
}
}
sb.AppendLine();
return sb.ToString();
}
return base.Message;
}
}
}
</code></pre>
<p>And <code>SaveChanges</code> can be overwritten the following way:</p>
<pre><code>public class MyContext : DbContext
{
// ...
public override int SaveChanges()
{
try
{
return base.SaveChanges();
}
catch (DbEntityValidationException e)
{
var newException = new FormattedDbEntityValidationException(e);
throw newException;
}
}
}
</code></pre>
<p>A few remarks:</p>
<ul>
<li><p>The yellow error screen that Elmah shows in the web interface or in the sent emails (if you have configured that) now displays the validation details directly at the top of the message.</p></li>
<li><p>Overwriting the <code>Message</code> property in the custom exception instead of overwriting <code>ToString()</code> has the benefit that the standard ASP.NET "Yellow screen of death (YSOD)" displays this message as well. In contrast to Elmah the YSOD apparently doesn't use <code>ToString()</code>, but both display the <code>Message</code> property.</p></li>
<li><p>Wrapping the original <code>DbEntityValidationException</code> as inner exception ensures that the original stack trace will still be available and is displayed in Elmah and the YSOD.</p></li>
<li><p>By setting a breakpoint on the line <code>throw newException;</code> you can simply inspect the <code>newException.Message</code> property as a text instead of drilling into the validation collections which is a bit awkward and doesn't seem to work easily for everyone (see comments below).</p></li>
</ul> | {
"question_id": 7795300,
"question_date": "2011-10-17T14:33:44.990Z",
"question_score": 858,
"tags": "c#|entity-framework|entity-framework-4|entity-framework-4.1",
"answer_id": 7798264,
"answer_date": "2011-10-17T19:03:47.580Z",
"answer_score": 1324
} |
Please answer the following Stack Overflow question:
Title: There is no tracking information for the current branch
<p>I've been using github from a relatively short period, and I've always used the client to perform commits and pulls. I decided to try it from the git bash yesterday, and I successfully created a new repo and committed files.</p>
<p>Today I did changes to the repository from another computer, I've committed the changes and now I'm back home and performed a <code>git pull</code> to update my local version and I get this:</p>
<pre><code>There is no tracking information for the current branch.
Please specify which branch you want to merge with.
See git-pull(1) for details
git pull <remote> <branch>
If you wish to set tracking information for this branch you can do so with:
git branch --set-upstream develop origin/<branch>
</code></pre>
<p>the only contributor to this repo is me and there are no branches (just a master). I'm on windows and I've performed the pull from git bash:</p>
<p><a href="https://i.stack.imgur.com/AeyH8.png" rel="noreferrer"><img src="https://i.stack.imgur.com/AeyH8.png" alt="enter image description here"></a></p>
<p>git status:</p>
<pre><code>$ git status
# On branch master
nothing to commit, working directory clean
</code></pre>
<p>git branch:</p>
<pre><code>$ git branch
* master
</code></pre>
<p>What am I doing wrong?</p> | <p>You could specify what branch you want to pull:</p>
<pre><code>git pull origin master
</code></pre>
<p>Or you could set it up so that your local master branch tracks github master branch as an upstream:</p>
<pre><code>git branch --set-upstream-to=origin/master master
git pull
</code></pre>
<p>This branch tracking is set up for you automatically when you clone a repository (for the default branch only), but if you add a remote to an existing repository you have to set up the tracking yourself. Thankfully, the advice given by git makes that pretty easy to remember how to do.</p> | {
"question_id": 32056324,
"question_date": "2015-08-17T17:27:05.540Z",
"question_score": 858,
"tags": "git|github|git-pull",
"answer_id": 32056416,
"answer_date": "2015-08-17T17:33:51.010Z",
"answer_score": 1326
} |
Please answer the following Stack Overflow question:
Title: How are iloc and loc different?
<p>Can someone explain how these two methods of slicing are different?<br />
I've seen <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html" rel="noreferrer">the docs</a>,
and I've seen <a href="https://stackoverflow.com/questions/28757389/loc-vs-iloc-vs-ix-vs-at-vs-iat">these</a> <a href="https://stackoverflow.com/questions/27667759/is-ix-always-better-than-loc-and-iloc-since-it-is-faster-and-supports-i">answers</a>, but I still find myself unable to understand how the three are different. To me, they seem interchangeable in large part, because they are at the lower levels of slicing.</p>
<p>For example, say we want to get the first five rows of a <code>DataFrame</code>. How is it that these two work?</p>
<pre><code>df.loc[:5]
df.iloc[:5]
</code></pre>
<p>Can someone present three cases where the distinction in uses are clearer?</p>
<hr />
<p>Once upon a time, I also wanted to know how these two functions differ from <code>df.ix[:5]</code> but <code>ix</code> has been removed from pandas 1.0, so I don't care anymore.</p> | <h2>Label <em>vs.</em> Location</h2>
<p>The main distinction between the two methods is:</p>
<ul>
<li><p><code>loc</code> gets rows (and/or columns) with particular <strong>labels</strong>.</p>
</li>
<li><p><code>iloc</code> gets rows (and/or columns) at integer <strong>locations</strong>.</p>
</li>
</ul>
<p>To demonstrate, consider a series <code>s</code> of characters with a non-monotonic integer index:</p>
<pre><code>>>> s = pd.Series(list("abcdef"), index=[49, 48, 47, 0, 1, 2])
49 a
48 b
47 c
0 d
1 e
2 f
>>> s.loc[0] # value at index label 0
'd'
>>> s.iloc[0] # value at index location 0
'a'
>>> s.loc[0:1] # rows at index labels between 0 and 1 (inclusive)
0 d
1 e
>>> s.iloc[0:1] # rows at index location between 0 and 1 (exclusive)
49 a
</code></pre>
<p>Here are some of the differences/similarities between <code>s.loc</code> and <code>s.iloc</code> when passed various objects:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th><object></th>
<th>description</th>
<th><code>s.loc[<object>]</code></th>
<th><code>s.iloc[<object>]</code></th>
</tr>
</thead>
<tbody>
<tr>
<td><code>0</code></td>
<td>single item</td>
<td>Value at index <em>label</em> <code>0</code> (the string <code>'d'</code>)</td>
<td>Value at index <em>location</em> 0 (the string <code>'a'</code>)</td>
</tr>
<tr>
<td><code>0:1</code></td>
<td>slice</td>
<td><strong>Two</strong> rows (labels <code>0</code> and <code>1</code>)</td>
<td><strong>One</strong> row (first row at location 0)</td>
</tr>
<tr>
<td><code>1:47</code></td>
<td>slice with out-of-bounds end</td>
<td><strong>Zero</strong> rows (empty Series)</td>
<td><strong>Five</strong> rows (location 1 onwards)</td>
</tr>
<tr>
<td><code>1:47:-1</code></td>
<td>slice with negative step</td>
<td><strong>three</strong> rows (labels <code>1</code> back to <code>47</code>)</td>
<td><strong>Zero</strong> rows (empty Series)</td>
</tr>
<tr>
<td><code>[2, 0]</code></td>
<td>integer list</td>
<td><strong>Two</strong> rows with given labels</td>
<td><strong>Two</strong> rows with given locations</td>
</tr>
<tr>
<td><code>s > 'e'</code></td>
<td>Bool series (indicating which values have the property)</td>
<td><strong>One</strong> row (containing <code>'f'</code>)</td>
<td><code>NotImplementedError</code></td>
</tr>
<tr>
<td><code>(s>'e').values</code></td>
<td>Bool array</td>
<td><strong>One</strong> row (containing <code>'f'</code>)</td>
<td>Same as <code>loc</code></td>
</tr>
<tr>
<td><code>999</code></td>
<td>int object not in index</td>
<td><code>KeyError</code></td>
<td><code>IndexError</code> (out of bounds)</td>
</tr>
<tr>
<td><code>-1</code></td>
<td>int object not in index</td>
<td><code>KeyError</code></td>
<td>Returns last value in <code>s</code></td>
</tr>
<tr>
<td><code>lambda x: x.index[3]</code></td>
<td>callable applied to series (here returning 3<sup>rd</sup> item in index)</td>
<td><code>s.loc[s.index[3]]</code></td>
<td><code>s.iloc[s.index[3]]</code></td>
</tr>
</tbody>
</table>
</div>
<p><code>loc</code>'s label-querying capabilities extend well-beyond integer indexes and it's worth highlighting a couple of additional examples.</p>
<p>Here's a Series where the index contains string objects:</p>
<pre><code>>>> s2 = pd.Series(s.index, index=s.values)
>>> s2
a 49
b 48
c 47
d 0
e 1
f 2
</code></pre>
<p>Since <code>loc</code> is label-based, it can fetch the first value in the Series using <code>s2.loc['a']</code>. It can also slice with non-integer objects:</p>
<pre><code>>>> s2.loc['c':'e'] # all rows lying between 'c' and 'e' (inclusive)
c 47
d 0
e 1
</code></pre>
<p>For DateTime indexes, we don't need to pass the exact date/time to fetch by label. For example:</p>
<pre><code>>>> s3 = pd.Series(list('abcde'), pd.date_range('now', periods=5, freq='M'))
>>> s3
2021-01-31 16:41:31.879768 a
2021-02-28 16:41:31.879768 b
2021-03-31 16:41:31.879768 c
2021-04-30 16:41:31.879768 d
2021-05-31 16:41:31.879768 e
</code></pre>
<p>Then to fetch the row(s) for March/April 2021 we only need:</p>
<pre><code>>>> s3.loc['2021-03':'2021-04']
2021-03-31 17:04:30.742316 c
2021-04-30 17:04:30.742316 d
</code></pre>
<h2>Rows and Columns</h2>
<p><code>loc</code> and <code>iloc</code> work the same way with DataFrames as they do with Series. It's useful to note that both methods can address columns and rows together.</p>
<p>When given a tuple, the first element is used to index the rows and, if it exists, the second element is used to index the columns.</p>
<p>Consider the DataFrame defined below:</p>
<pre><code>>>> import numpy as np
>>> df = pd.DataFrame(np.arange(25).reshape(5, 5),
index=list('abcde'),
columns=['x','y','z', 8, 9])
>>> df
x y z 8 9
a 0 1 2 3 4
b 5 6 7 8 9
c 10 11 12 13 14
d 15 16 17 18 19
e 20 21 22 23 24
</code></pre>
<p>Then for example:</p>
<pre><code>>>> df.loc['c': , :'z'] # rows 'c' and onwards AND columns up to 'z'
x y z
c 10 11 12
d 15 16 17
e 20 21 22
>>> df.iloc[:, 3] # all rows, but only the column at index location 3
a 3
b 8
c 13
d 18
e 23
</code></pre>
<p>Sometimes we want to mix label and positional indexing methods for the rows and columns, somehow combining the capabilities of <code>loc</code> and <code>iloc</code>.</p>
<p>For example, consider the following DataFrame. How best to slice the rows up to and including 'c' <em>and</em> take the first four columns?</p>
<pre><code>>>> import numpy as np
>>> df = pd.DataFrame(np.arange(25).reshape(5, 5),
index=list('abcde'),
columns=['x','y','z', 8, 9])
>>> df
x y z 8 9
a 0 1 2 3 4
b 5 6 7 8 9
c 10 11 12 13 14
d 15 16 17 18 19
e 20 21 22 23 24
</code></pre>
<p>We can achieve this result using <code>iloc</code> and the help of another method:</p>
<pre><code>>>> df.iloc[:df.index.get_loc('c') + 1, :4]
x y z 8
a 0 1 2 3
b 5 6 7 8
c 10 11 12 13
</code></pre>
<p><a href="http://pandas.pydata.org/pandas-docs/version/0.19.1/generated/pandas.Index.get_loc.html" rel="noreferrer"><code>get_loc()</code></a> is an index method meaning "get the position of the label in this index". Note that since slicing with <code>iloc</code> is exclusive of its endpoint, we must add 1 to this value if we want row 'c' as well.</p> | {
"question_id": 31593201,
"question_date": "2015-07-23T16:34:10.667Z",
"question_score": 858,
"tags": "python|pandas|dataframe|indexing|pandas-loc",
"answer_id": 31593712,
"answer_date": "2015-07-23T16:59:47.117Z",
"answer_score": 1381
} |
Please answer the following Stack Overflow question:
Title: Node.js: printing to console without a trailing newline?
<p>Is there a method for printing to the console without a trailing newline? The <code>console</code> object <a href="https://nodejs.org/docs/v0.4.8/api/stdio.html#console.log" rel="noreferrer">documentation</a> doesn't say anything regarding that:</p>
<blockquote>
<p><strong><code>console.log()</code></strong></p>
<p>Prints to stdout with newline. This function can take multiple arguments in a <code>printf()</code>-like way. Example:</p>
<pre><code>console.log('count: %d', count);
</code></pre>
<p>If formating elements are not found in the first string then <code>util.inspect</code> is used on each argument.</p>
</blockquote> | <p>You can use <code>process.stdout.write()</code>:</p>
<pre><code>process.stdout.write("hello: ");
</code></pre>
<p>See the <a href="http://nodejs.org/api/process.html#process_process_stdout">docs for details</a>.</p> | {
"question_id": 6157497,
"question_date": "2011-05-27T20:42:34.220Z",
"question_score": 858,
"tags": "node.js|console|console.log",
"answer_id": 6157569,
"answer_date": "2011-05-27T20:51:00.257Z",
"answer_score": 1312
} |
Please answer the following Stack Overflow question:
Title: How can I open multiple files using "with open" in Python?
<p>I want to change a couple of files at one time, <strong>iff</strong> I can write to all of them. I'm wondering if I somehow can combine the multiple open calls with the <code>with</code> statement:</p>
<pre><code>try:
with open('a', 'w') as a and open('b', 'w') as b:
do_something()
except IOError as e:
print 'Operation failed: %s' % e.strerror
</code></pre>
<p>If that's not possible, what would an elegant solution to this problem look like?</p> | <p>As of Python 2.7 (or 3.1 respectively) you can write</p>
<pre><code>with open('a', 'w') as a, open('b', 'w') as b:
do_something()
</code></pre>
<p>(<em>Historical note</em>: In earlier versions of Python, you can sometimes use
<a href="http://docs.python.org/library/contextlib.html#contextlib.nested" rel="noreferrer"><code>contextlib.nested()</code></a> to nest context managers. This won't work as expected for opening multiples files, though -- see the linked documentation for details.)</p>
<hr />
<p>In the rare case that you want to open a variable number of files all at the same time, you can use <a href="https://docs.python.org/3/library/contextlib.html#contextlib.ExitStack" rel="noreferrer"><code>contextlib.ExitStack</code></a>, starting from Python version 3.3:</p>
<pre><code>with ExitStack() as stack:
files = [stack.enter_context(open(fname)) for fname in filenames]
# Do something with "files"
</code></pre>
<p>Note that more commonly you want to process files sequentially rather than opening all of them at the same time, in particular if you have a variable number of files:</p>
<pre><code>for fname in filenames:
with open(fname) as f:
# Process f
</code></pre> | {
"question_id": 4617034,
"question_date": "2011-01-06T16:16:43.910Z",
"question_score": 858,
"tags": "python|file-io",
"answer_id": 4617069,
"answer_date": "2011-01-06T16:19:55.333Z",
"answer_score": 1318
} |
Please answer the following Stack Overflow question:
Title: Are Git forks actually Git clones?
<p>I keep hearing people say they're forking code in Git. Git "fork" sounds suspiciously like Git "clone" plus some (meaningless) psychological willingness to forgo future merges. There is no fork command in Git, right?</p>
<p>GitHub makes forks a little more real by stapling correspondence onto it. That is, you press the fork button and later, when you press the pull request button, the system is smart enough to email the owner. Hence, it's a little bit of a dance around repository ownership and permissions.</p>
<p>Yes/No? Any angst over GitHub extending Git in this direction? Or any rumors of Git absorbing the functionality?</p> | <p><strong><a href="https://help.github.com/articles/fork-a-repo" rel="noreferrer">Fork</a></strong>, in the GitHub context, doesn't extend Git. <br/>
It only allows clone on the server side.</p>
<p>When you clone a GitHub repository on your local workstation, you cannot contribute back to the upstream repository unless you are explicitly declared as "contributor". That's because your clone is a separate instance of that project. If you want to contribute to the project, you can use forking to do it, in the following way:</p>
<ul>
<li>clone that GitHub repository on your GitHub account (that is the <a href="https://help.github.com/articles/fork-a-repo" rel="noreferrer">"fork" part</a>, a clone on the server side)</li>
<li>contribute commits to that GitHub repository (it is in your own GitHub account, so you have every right to push to it)</li>
<li>signal any interesting contribution back to the original GitHub repository (that is the <strong><a href="https://help.github.com/articles/using-pull-requests" rel="noreferrer">"pull request" part</a></strong> by way of the changes you made on your own GitHub repository)</li>
</ul>
<p>Check also "<a href="http://www.eqqon.com/index.php/Collaborative_Github_Workflow" rel="noreferrer">Collaborative GitHub Workflow</a>".</p>
<p>If you want to keep a link with the original repository (also called upstream), you need to add a remote referring that original repository. <br/>
See "<a href="https://stackoverflow.com/questions/9257533/what-is-the-difference-between-origin-and-upstream-in-github/9257901#9257901">What is the difference between origin and upstream on GitHub?</a>"</p>
<p><img src="https://i.stack.imgur.com/cEJjT.png" alt="fork and upstream"></p>
<p>And with Git 2.20 (Q4 2018) and more, fetching from fork is more efficient, <a href="https://stackoverflow.com/a/52458712/6309">with <strong>delta islands</strong></a>.</p> | {
"question_id": 6286571,
"question_date": "2011-06-08T23:45:54.433Z",
"question_score": 858,
"tags": "git|github|git-clone|git-fork",
"answer_id": 6286877,
"answer_date": "2011-06-09T00:37:30.077Z",
"answer_score": 964
} |
Please answer the following Stack Overflow question:
Title: How to pass all arguments passed to my Bash script to a function of mine?
<p>Let's say I have a function <code>abc()</code> that will handle the logic related to analyzing the arguments passed to my script.</p>
<p>How can I pass all arguments my Bash script has received to <code>abc()</code>? The number of arguments is variable, so I can't just hard-code the arguments passed like this:</p>
<pre><code>abc $1 $2 $3 $4
</code></pre>
<p>Better yet, is there any way for my function to have access to the script arguments' variables?</p> | <p>The <code>$@</code> variable expands to all command-line parameters separated by spaces. Here is an example.</p>
<pre><code>abc "$@"
</code></pre>
<p>When using <code>$@</code>, you should (almost) always put it in double-quotes to avoid misparsing of arguments containing spaces or wildcards (see below). This works for multiple arguments. It is also portable to all POSIX-compliant shells.</p>
<p>It is also worth noting that <code>$0</code> (generally the script's name or path) is not in <code>$@</code>.</p>
<p>The <a href="https://www.gnu.org/software/bash/manual/bash.html#Special-Parameters" rel="noreferrer">Bash Reference Manual Special Parameters Section</a> says that <code>$@</code> expands to the positional parameters starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is <code>"$@"</code> is equivalent to <code>"$1" "$2" "$3"...</code>.</p>
<h1>Passing <em>some</em> arguments:</h1>
<p>If you want to pass <em>all but the first</em> arguments, you can first use <code>shift</code> to "consume" the first argument and then pass <code>"$@"</code> to pass the remaining arguments to another command. In Bash (and zsh and ksh, but not in plain POSIX shells like dash), you can do this without messing with the argument list using a variant of array slicing: <code>"${@:3}"</code> will get you the arguments starting with <code>"$3"</code>. <code>"${@:3:4}"</code> will get you up to four arguments starting at <code>"$3"</code> (i.e. <code>"$3" "$4" "$5" "$6"</code>), if that many arguments were passed.</p>
<h1>Things you probably don't want to do:</h1>
<p><code>"$*"</code> gives all of the arguments stuck together into a single string (separated by spaces, or whatever the first character of <code>$IFS</code> is). This looses the distinction between spaces <em>within</em> arguments and the spaces <em>between</em> arguments, so is generally a bad idea. Although it might be ok for printing the arguments, e.g. <code>echo "$*"</code>, provided you don't care about preserving the space within/between distinction.</p>
<p>Assigning the arguments to a regular variable (as in <code>args="$@"</code>) mashes all the arguments together like <code>"$*"</code> does. If you want to store the arguments in a variable, use an array with <code>args=("$@")</code> (the parentheses make it an array), and then reference them as e.g. <code>"${args[0]}"</code> etc. Note that in Bash and ksh, array indexes start at 0, so <code>$1</code> will be in <code>args[0]</code>, etc. zsh, on the other hand, starts array indexes at 1, so <code>$1</code> will be in <code>args[1]</code>. And more basic shells like dash don't have arrays at all.</p>
<p>Leaving off the double-quotes, with either <code>$@</code> or <code>$*</code>, will try to split each argument up into separate words (based on whitespace or whatever's in <code>$IFS</code>), and also try to expand anything that looks like a filename wildcard into a list of matching filenames. This can have really weird effects, and should almost always be avoided. (Except in zsh, where this expansion doesn't take place by default.)</p> | {
"question_id": 3811345,
"question_date": "2010-09-28T09:24:16.390Z",
"question_score": 857,
"tags": "bash|function|parameter-passing",
"answer_id": 3816747,
"answer_date": "2010-09-28T20:24:18.870Z",
"answer_score": 1413
} |
Please answer the following Stack Overflow question:
Title: Permission denied (publickey) when deploying heroku code. fatal: The remote end hung up unexpectedly
<p>I'm attempting to deploy my code to heroku with the following command line:</p>
<pre><code>git push heroku master
</code></pre>
<p>but get the following error:</p>
<pre><code>Permission denied (publickey).
fatal: The remote end hung up unexpectedly
</code></pre>
<p>I have already uploaded my public SSH key, but it still comes up with this error.</p> | <p>You have to upload your public key to Heroku:</p>
<pre><code>heroku keys:add ~/.ssh/id_rsa.pub
</code></pre>
<p>If you don't have a public key, Heroku will prompt you to add one automatically which works seamlessly. Just use: </p>
<pre><code>heroku keys:add
</code></pre>
<p>To clear all your previous keys do :</p>
<pre><code>heroku keys:clear
</code></pre>
<p>To display all your existing keys do :</p>
<pre><code>heroku keys
</code></pre>
<p>EDIT:</p>
<p>The above did not seem to work for me. I had messed around with the <code>HOME</code> environment variable and so SSH was searching for keys in the wrong directory.</p>
<p>To ensure that SSH checks for the key in the correct directory do :</p>
<pre><code>ssh -vT [email protected]
</code></pre>
<p>Which will display the following ( Sample ) lines</p>
<pre><code>OpenSSH_4.6p1, OpenSSL 0.9.8e 23 Feb 2007
debug1: Connecting to heroku.com [50.19.85.156] port 22.
debug1: Connection established.
debug1: identity file /c/Wrong/Directory/.ssh/identity type -1
debug1: identity file /c/Wrong/Directory/.ssh/id_rsa type -1
debug1: identity file /c/Wrong/Directory/.ssh/id_dsa type -1
debug1: Remote protocol version 2.0, remote software version Twisted
debug1: no match: Twisted
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_4.6
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-cbc hmac-md5 none
debug1: kex: client->server aes128-cbc hmac-md5 none
debug1: sending SSH2_MSG_KEXDH_INIT
debug1: expecting SSH2_MSG_KEXDH_REPLY
debug1: Host 'heroku.com' is known and matches the RSA host key.
debug1: Found key in /c/Wrong/Directory/.ssh/known_hosts:1
debug1: ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Trying private key: /c/Wrong/Directory/.ssh/identity
debug1: Trying private key: /c/Wrong/Directory/.ssh/id_rsa
debug1: Trying private key: /c/Wrong/Directory/.ssh/id_dsa
debug1: No more authentication methods to try.
</code></pre>
<p><strong><code>Permission denied (publickey).</code></strong></p>
<p>From the above you could observe that ssh looks for the keys in the <code>/c/Wrong/Directory/.ssh</code> directory which is not where we have the public keys that we just added to heroku ( using <code>heroku keys:add ~/.ssh/id_rsa.pub</code> ) ( <strong>Please note that in windows OS <code>~</code> refers to the <code>HOME</code> path which in win 7 / 8 is <code>C:\Users\UserName</code></strong> )</p>
<p>To view your current home directory do : <code>echo $HOME</code> or <code>echo %HOME%</code> ( Windows )</p>
<p>To set your <code>HOME</code> directory correctly ( by correctly I mean the parent directory of <code>.ssh</code> directory, so that ssh could look for keys in the correct directory ) refer these links :</p>
<ol>
<li><p><a href="https://unix.stackexchange.com/questions/21598/how-do-i-set-a-user-environment-variable-permanently-not-session">SO Answer on how to set Unix environment variable permanently</a></p></li>
<li><p><a href="https://stackoverflow.com/questions/2840871/ssh-is-looking-in-the-wrong-place-for-the-public-private-key-pair-on-windows">SO Question regarding ssh looking for keys in the wrong directory and a solution for the same.</a></p></li>
</ol> | {
"question_id": 4269922,
"question_date": "2010-11-24T17:51:13.963Z",
"question_score": 857,
"tags": "git|heroku|deployment|public-key",
"answer_id": 6059231,
"answer_date": "2011-05-19T13:15:00.223Z",
"answer_score": 1484
} |
Please answer the following Stack Overflow question:
Title: How can I convert a comma-separated string to an array?
<p>I have a comma-separated string that I want to convert into an array, so I can loop through it.</p>
<p>Is there anything built-in to do this?</p>
<p>For example, I have this string</p>
<pre><code>var str = "January,February,March,April,May,June,July,August,September,October,November,December";
</code></pre>
<p>Now I want to split this by the comma, and then store it in an array.</p> | <pre><code>var array = string.split(',');
</code></pre>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split" rel="noreferrer">MDN reference</a>, mostly helpful for the possibly unexpected behavior of the <code>limit</code> parameter. (Hint: <code>"a,b,c".split(",", 2)</code> comes out to <code>["a", "b"]</code>, not <code>["a", "b,c"]</code>.)</p> | {
"question_id": 2858121,
"question_date": "2010-05-18T14:23:47.677Z",
"question_score": 856,
"tags": "javascript|string|split",
"answer_id": 2858130,
"answer_date": "2010-05-18T14:24:41.680Z",
"answer_score": 1421
} |
Please answer the following Stack Overflow question:
Title: Pass Method as Parameter using C#
<p>I have several methods all with the same parameter types and return values but different names and blocks. I want to pass the name of the method to run to another method that will invoke the passed method.</p>
<pre><code>public int Method1(string)
{
// Do something
return myInt;
}
public int Method2(string)
{
// Do something different
return myInt;
}
public bool RunTheMethod([Method Name passed in here] myMethodName)
{
// Do stuff
int i = myMethodName("My String");
// Do more stuff
return true;
}
public bool Test()
{
return RunTheMethod(Method1);
}
</code></pre>
<p>This code does not work but this is what I am trying to do. What I don't understand is how to write the RunTheMethod code since I need to define the parameter.</p> | <p>You can use the Func delegate in .net 3.5 as the parameter in your RunTheMethod method. The Func delegate allows you to specify a method that takes a number of parameters of a specific type and returns a single argument of a specific type. Here is an example that should work:</p>
<pre><code>public class Class1
{
public int Method1(string input)
{
//... do something
return 0;
}
public int Method2(string input)
{
//... do something different
return 1;
}
public bool RunTheMethod(Func<string, int> myMethodName)
{
//... do stuff
int i = myMethodName("My String");
//... do more stuff
return true;
}
public bool Test()
{
return RunTheMethod(Method1);
}
}
</code></pre> | {
"question_id": 2082615,
"question_date": "2010-01-17T21:01:01.313Z",
"question_score": 856,
"tags": "c#|.net|methods|delegates",
"answer_id": 2082650,
"answer_date": "2010-01-17T21:08:10.990Z",
"answer_score": 1010
} |
Please answer the following Stack Overflow question:
Title: How can I use Python to get the system hostname?
<p>I'm writing a chat program for a local network. I would like be able to identify computers and get the user-set computer name with Python.</p> | <p>Use <a href="http://docs.python.org/library/socket.html" rel="noreferrer"><code>socket</code></a> and its <a href="http://docs.python.org/library/socket.html#socket.gethostname" rel="noreferrer"><code>gethostname()</code></a> functionality. This will get the <code>hostname</code> of the computer where the Python interpreter is running:</p>
<pre><code>import socket
print(socket.gethostname())
</code></pre> | {
"question_id": 4271740,
"question_date": "2010-11-24T21:33:23.920Z",
"question_score": 856,
"tags": "python|hostname",
"answer_id": 4271755,
"answer_date": "2010-11-24T21:36:29.377Z",
"answer_score": 1304
} |
Please answer the following Stack Overflow question:
Title: What does -> mean in Python function definitions?
<p>I've recently noticed something interesting when looking at <a href="http://docs.python.org/3.3/reference/grammar.html" rel="noreferrer">Python 3.3 grammar specification</a>:</p>
<pre><code>funcdef: 'def' NAME parameters ['->' test] ':' suite
</code></pre>
<p>The optional 'arrow' block was absent in Python 2 and I couldn't find any information regarding its meaning in Python 3. It turns out this is correct Python and it's accepted by the interpreter:</p>
<pre><code>def f(x) -> 123:
return x
</code></pre>
<p>I thought that this might be some kind of a precondition syntax, but:</p>
<ul>
<li>I cannot test <code>x</code> here, as it is still undefined,</li>
<li>No matter what I put after the arrow (e.g. <code>2 < 1</code>), it doesn't affect the function behavior.</li>
</ul>
<p>Could anyone familiar with this syntax style explain it?</p> | <p>It's a <a href="http://www.python.org/dev/peps/pep-3107/" rel="noreferrer">function annotation</a>.</p>
<p>In more detail, Python 2.x has docstrings, which allow you to attach a metadata string to various types of object. This is amazingly handy, so Python 3 extends the feature by allowing you to attach metadata to functions describing their parameters and return values.</p>
<p>There's no preconceived use case, but the PEP suggests several. One very handy one is to allow you to annotate parameters with their expected types; it would then be easy to write a decorator that verifies the annotations or coerces the arguments to the right type. Another is to allow parameter-specific documentation instead of encoding it into the docstring.</p> | {
"question_id": 14379753,
"question_date": "2013-01-17T13:03:35.930Z",
"question_score": 856,
"tags": "python|python-3.x|annotations|function-definition",
"answer_id": 14379780,
"answer_date": "2013-01-17T13:04:57.427Z",
"answer_score": 640
} |
Please answer the following Stack Overflow question:
Title: How to sort a list/tuple of lists/tuples by the element at a given index?
<p>I have some data either in a list of lists or a list of tuples, like this:</p>
<pre><code>data = [[1,2,3], [4,5,6], [7,8,9]]
data = [(1,2,3), (4,5,6), (7,8,9)]
</code></pre>
<p>And I want to sort by the 2nd element in the subset. Meaning, sorting by 2,5,8 where <code>2</code> is from <code>(1,2,3)</code>, <code>5</code> is from <code>(4,5,6)</code>. What is the common way to do this? Should I store tuples or lists in my list?</p> | <pre><code>sorted_by_second = sorted(data, key=lambda tup: tup[1])
</code></pre>
<p>or:</p>
<pre><code>data.sort(key=lambda tup: tup[1]) # sorts in place
</code></pre>
<p>The default sort mode is ascending. To sort in descending order use the option <a href="https://docs.python.org/3/howto/sorting.html#ascending-and-descending" rel="noreferrer"><code>reverse=True</code></a>:</p>
<pre><code>sorted_by_second = sorted(data, key=lambda tup: tup[1], reverse=True)
</code></pre>
<p>or:</p>
<pre><code>data.sort(key=lambda tup: tup[1], reverse=True) # sorts in place
</code></pre> | {
"question_id": 3121979,
"question_date": "2010-06-25T23:01:41.033Z",
"question_score": 855,
"tags": "python|list|sorting|tuples",
"answer_id": 3121985,
"answer_date": "2010-06-25T23:04:59.327Z",
"answer_score": 1430
} |
Please answer the following Stack Overflow question:
Title: Is there a better way to do optional function parameters in JavaScript?
<p>I've always handled optional parameters in JavaScript like this:</p>
<pre><code>function myFunc(requiredArg, optionalArg){
optionalArg = optionalArg || 'defaultValue';
// Do stuff
}
</code></pre>
<p>Is there a better way to do it?</p>
<p>Are there any cases where using <code>||</code> like that is going to fail?</p> | <p>Your logic fails if optionalArg is passed, but evaluates as false - try this as an alternative</p>
<pre><code>if (typeof optionalArg === 'undefined') { optionalArg = 'default'; }
</code></pre>
<p>Or an alternative idiom:</p>
<pre><code>optionalArg = (typeof optionalArg === 'undefined') ? 'default' : optionalArg;
</code></pre>
<p>Use whichever idiom communicates the intent best to you!</p> | {
"question_id": 148901,
"question_date": "2008-09-29T14:27:08.543Z",
"question_score": 855,
"tags": "javascript|function|arguments",
"answer_id": 148918,
"answer_date": "2008-09-29T14:30:34.013Z",
"answer_score": 1097
} |
Please answer the following Stack Overflow question:
Title: SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder"
<p>My application is to be deployed on both tcServer and WebSphere 6.1. This application uses ehCache and so requires slf4j as a dependency.
As a result I've added the slf4j-api.jar (1.6) jar to my war file bundle.</p>
<p>The application works fine in tcServer except for the following error:</p>
<pre><code>SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
</code></pre>
<p>However, when I deploy in WebSphere I get a <code>java.lang.NoClassDefFoundError: org.slf4j.impl.StaticLoggerBinder</code>.</p>
<p>Also accompanied by <code>Failed to load class "org.slf4j.impl.StaticMDCBinder"</code></p>
<p>I've checked the classpaths of both application servers and there is no other slf4j jar.</p>
<p>Does anyone have any ideas what may be happening here?</p> | <p>I had the same issue with WebSphere 6.1. As Ceki pointed out, there were tons of jars that WebSphere was using and one of them was pointing to an older version of slf4j.</p>
<p>The No-Op fallback happens only with slf4j -1.6+ so anything older than that will throw an exception and halts your deployment.</p>
<p>There is a documentation in <a href="http://www.slf4j.org/codes.html#StaticLoggerBinder" rel="noreferrer">SLf4J site</a> which resolves this. I followed that and added <code>slf4j-simple-1.6.1.jar</code> to my application along with <code>slf4j-api-1.6.1.jar</code> which I already had.</p>
<p>If you use Maven, add the following dependencies, with <code>${slf4j.version}</code> being <a href="https://mvnrepository.com/artifact/org.slf4j/slf4j-api" rel="noreferrer">the latest version of slf4j</a></p>
<pre><code><dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>${slf4j.version}</version>
</dependency>
</code></pre>
<p>This solved my issue.</p> | {
"question_id": 7421612,
"question_date": "2011-09-14T19:03:46.340Z",
"question_score": 854,
"tags": "java|websphere|slf4j",
"answer_id": 9919375,
"answer_date": "2012-03-29T05:07:33.450Z",
"answer_score": 784
} |
Please answer the following Stack Overflow question:
Title: Windows batch files: .bat vs .cmd?
<p>As I understand it, <code>.bat</code> is the old 16-bit naming convention, and <code>.cmd</code> is for 32-bit Windows, i.e., starting with NT. But I continue to see .bat files everywhere, and they seem to work exactly the same using either suffix. Assuming that my code will never need to run on anything older than NT, does it really matter which way I name my batch files, or is there some <strong>gotcha</strong> awaiting me by using the wrong suffix?</p> | <p>From <a href="https://groups.google.com/group/microsoft.public.win2000.cmdprompt.admin/msg/ad9066638815812c" rel="noreferrer">this news group posting</a> by <a href="http://en.wikipedia.org/wiki/Mark_Zbikowski" rel="noreferrer">Mark Zbikowski</a> himself:</p>
<blockquote>
<p>The differences between .CMD and .BAT as far as CMD.EXE is concerned
are: With extensions enabled, PATH/APPEND/PROMPT/SET/ASSOC in .CMD
files will set ERRORLEVEL regardless of error. .BAT sets ERRORLEVEL
only on errors.</p>
</blockquote>
<p>In other words, if ERRORLEVEL is set to non-0 and then you run one of those commands, the resulting ERRORLEVEL will be:</p>
<ul>
<li>left alone at its non-0 value in a .bat file </li>
<li>reset to 0 in a .cmd file. </li>
</ul> | {
"question_id": 148968,
"question_date": "2008-09-29T14:39:07.190Z",
"question_score": 854,
"tags": "windows|batch-file|cmd",
"answer_id": 148991,
"answer_date": "2008-09-29T14:41:55.700Z",
"answer_score": 524
} |
Please answer the following Stack Overflow question:
Title: Difference between id and name attributes in HTML
<p>What is the difference between the <code>id</code> and <code>name</code> attributes? They both seem to serve the same purpose of providing an identifier.</p>
<p>I would like to know (specifically with regards to HTML forms) whether or not using both is necessary or encouraged for any reasons.</p> | <p>The <code>name</code> attribute is used when sending data in a form submission. Different controls respond differently. For example, you may have several radio buttons with different <code>id</code> attributes, but the same <code>name</code>. When submitted, there is just the one value in the response - the radio button you selected.</p>
<p>Of course, there's more to it than that, but it will definitely get you thinking in the right direction.</p> | {
"question_id": 1397592,
"question_date": "2009-09-09T04:53:48.057Z",
"question_score": 854,
"tags": "html|attributes",
"answer_id": 1397613,
"answer_date": "2009-09-09T04:58:06.317Z",
"answer_score": 741
} |
Please answer the following Stack Overflow question:
Title: Could not find module "@angular-devkit/build-angular"
<p>After updating to Angular 6.0.1, I get the following error on <code>ng serve</code>:</p>
<pre><code>Could not find module "@angular-devkit/build-angular" from "/home/Projects/myProjectName".
Error: Could not find module "@angular-devkit/build-angular" from "/home/Projects/myProjectName".
at Object.resolve (/home/Projects/myProjectName/node_modules/@angular-devkit/core/node/resolve.js:141:11)
at Observable.rxjs_1.Observable [as _subscribe] (/home/Projects/myProjectName/node_modules/@angular-devkit/architect/src/architect.js:132:40)
</code></pre>
<p><code>ng update</code> says everything is in order. Deleting <code>node_modules</code> folder and a fresh <code>npm install</code> install did not help either. </p>
<p>My project is based on <a href="https://github.com/akveo/ngx-admin" rel="noreferrer">ng2-admin(Angular4 version)</a>. Here is my package.json dependecies:</p>
<pre><code> "dependencies": {
"@angular/animations": "^6.0.1",
"@angular/common": "^6.0.1",
"@angular/compiler": "^6.0.1",
"@angular/core": "^6.0.1",
"@angular/forms": "^6.0.1",
"@angular/http": "^6.0.1",
"@angular/platform-browser": "^6.0.1",
"@angular/platform-browser-dynamic": "^6.0.1",
"@angular/platform-server": "^6.0.1",
"@angular/router": "^6.0.1",
"@ng-bootstrap/ng-bootstrap": "1.0.0-alpha.26",
"@ngx-translate/core": "^10.0.1",
"@ngx-translate/http-loader": "^3.0.1",
"amcharts3": "github:amcharts/amcharts3",
"ammap3": "github:amcharts/ammap3",
"angular-table": "^1.0.4",
"angular2-csv": "^0.2.5",
"angular2-datatable": "0.6.0",
"animate.css": "3.5.2",
"bootstrap": "4.0.0-alpha.6",
"bower": "^1.8.4",
"chart.js": "1.1.1",
"chartist": "0.10.1",
"chroma-js": "1.3.3",
"ckeditor": "4.6.2",
"core-js": "2.4.1",
"easy-pie-chart": "2.1.7",
"font-awesome": "4.7.0",
"fullcalendar": "3.3.1",
"google-maps": "3.2.1",
"ionicons": "2.0.1",
"jquery": "3.2.1",
"jquery-slimscroll": "1.3.8",
"leaflet": "0.7.7",
"leaflet-map": "0.2.1",
"lodash": "4.17.4",
"ng2-ckeditor": "1.1.6",
"ng2-completer": "^1.6.3",
"ng2-handsontable": "^2.1.0-rc.3",
"ng2-slim-loading-bar": "^4.0.0",
"ng2-smart-table": "^1.0.3",
"ng2-tree": "2.0.0-alpha.5",
"ngx-uploader": "4.2.4",
"normalize.css": "6.0.0",
"roboto-fontface": "0.7.0",
"rxjs": "^6.1.0",
"rxjs-compat": "^6.1.0",
"zone.js": "0.8.26"
},
"devDependencies": {
"@angular/cli": "^6.0.1",
"@angular/compiler-cli": "^6.0.1",
"@types/fullcalendar": "2.7.40",
"@types/jasmine": "2.5.38",
"@types/jquery": "2.0.41",
"@types/jquery.slimscroll": "1.3.30",
"@types/lodash": "4.14.61",
"@types/node": "6.0.69",
"codelyzer": "3.0.1",
"gh-pages": "0.12.0",
"jasmine-core": "2.5.2",
"jasmine-spec-reporter": "3.2.0",
"karma": "1.4.1",
"karma-chrome-launcher": "2.0.0",
"karma-cli": "1.0.1",
"karma-coverage-istanbul-reporter": "0.2.0",
"karma-jasmine": "1.1.0",
"karma-jasmine-html-reporter": "0.2.2",
"npm-run-all": "4.0.2",
"protractor": "5.1.0",
"rimraf": "2.6.1",
"standard-changelog": "1.0.1",
"stylelint": "7.10.1",
"ts-node": "2.1.2",
"tslint": "5.2.0",
"tslint-eslint-rules": "4.0.0",
"tslint-language-service": "0.9.6",
"typescript": "^2.7.2",
"typogr": "0.6.6",
"underscore": "1.8.3",
"wintersmith": "2.2.5",
"wintersmith-sassy": "1.1.0"
}
</code></pre>
<p>and my angular.json:</p>
<pre><code>{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"ng2-admin": {
"root": "",
"sourceRoot": "src",
"projectType": "application",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist",
"index": "src/index.html",
"main": "src/main.ts",
"tsConfig": "src/tsconfig.app.json",
"polyfills": "src/polyfills.ts",
"assets": [
"src/assets",
"src/favicon.ico"
],
"styles": [
"node_modules/roboto-fontface/css/roboto/sass/roboto-fontface.scss",
"node_modules/normalize.css/normalize.css",
"node_modules/font-awesome/scss/font-awesome.scss",
"node_modules/ionicons/scss/ionicons.scss",
"node_modules/bootstrap/scss/bootstrap.scss",
"node_modules/leaflet/dist/leaflet.css",
"node_modules/chartist/dist/chartist.css",
"node_modules/fullcalendar/dist/fullcalendar.css",
"node_modules/handsontable/dist/handsontable.full.css",
"node_modules/ng2-slim-loading-bar/style.css",
"src/app/theme/theme.scss",
"src/styles.scss"
],
"scripts": [
"node_modules/jquery/dist/jquery.js",
"node_modules/easy-pie-chart/dist/jquery.easypiechart.js",
"node_modules/jquery-slimscroll/jquery.slimscroll.js",
"node_modules/tether/dist/js/tether.js",
"node_modules/bootstrap/dist/js/bootstrap.js",
"node_modules/handsontable/dist/handsontable.full.js",
"node_modules/chroma-js/chroma.js"
]
},
"configurations": {
"production": {
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"aot": true,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
]
}
}
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "ng2-admin:build"
},
"configurations": {
"production": {
"browserTarget": "ng2-admin:build:production"
}
}
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "ng2-admin:build"
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"karmaConfig": "./karma.conf.js",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.spec.json",
"scripts": [
"node_modules/jquery/dist/jquery.js",
"node_modules/easy-pie-chart/dist/jquery.easypiechart.js",
"node_modules/jquery-slimscroll/jquery.slimscroll.js",
"node_modules/tether/dist/js/tether.js",
"node_modules/bootstrap/dist/js/bootstrap.js",
"node_modules/handsontable/dist/handsontable.full.js",
"node_modules/chroma-js/chroma.js"
],
"styles": [
"node_modules/roboto-fontface/css/roboto/sass/roboto-fontface.scss",
"node_modules/normalize.css/normalize.css",
"node_modules/font-awesome/scss/font-awesome.scss",
"node_modules/ionicons/scss/ionicons.scss",
"node_modules/bootstrap/scss/bootstrap.scss",
"node_modules/leaflet/dist/leaflet.css",
"node_modules/chartist/dist/chartist.css",
"node_modules/fullcalendar/dist/fullcalendar.css",
"node_modules/handsontable/dist/handsontable.full.css",
"node_modules/ng2-slim-loading-bar/style.css",
"src/app/theme/theme.scss",
"src/styles.scss"
],
"assets": [
"src/assets",
"src/favicon.ico"
]
}
},
"lint": {
"builder": "@angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"src/tsconfig.app.json",
"src/tsconfig.spec.json"
],
"exclude": []
}
}
}
},
"ng2-admin-e2e": {
"root": "",
"sourceRoot": "",
"projectType": "application",
"architect": {
"e2e": {
"builder": "@angular-devkit/build-angular:protractor",
"options": {
"protractorConfig": "./protractor.conf.js",
"devServerTarget": "ng2-admin:serve"
}
},
"lint": {
"builder": "@angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"e2e/tsconfig.e2e.json"
],
"exclude": []
}
}
}
}
},
"defaultProject": "ng2-admin",
"schematics": {
"@schematics/angular:component": {
"prefix": "app",
"styleext": "scss"
},
"@schematics/angular:directive": {
"prefix": "app"
}
}
}
</code></pre> | <p>Install <code>@angular-devkit/build-angular</code> as dev dependency. This package is newly introduced in Angular 6.0</p>
<pre><code>npm install --save-dev @angular-devkit/build-angular
</code></pre>
<p>or,</p>
<pre><code>yarn add @angular-devkit/build-angular --dev
</code></pre> | {
"question_id": 50333003,
"question_date": "2018-05-14T14:38:46.117Z",
"question_score": 853,
"tags": "angular|angular-cli|angular6|angular-cli-v6",
"answer_id": 50333128,
"answer_date": "2018-05-14T14:44:57.863Z",
"answer_score": 1299
} |
Please answer the following Stack Overflow question:
Title: How to specify the download location with wget?
<p>I need files to be downloaded to /tmp/cron_test/. My wget code is</p>
<pre><code>wget --random-wait -r -p -nd -e robots=off -A".pdf" -U mozilla http://math.stanford.edu/undergrad/
</code></pre>
<p>So is there some parameter to specify the directory?</p> | <p>From the manual page:</p>
<pre><code>-P prefix
--directory-prefix=prefix
Set directory prefix to prefix. The directory prefix is the
directory where all other files and sub-directories will be
saved to, i.e. the top of the retrieval tree. The default
is . (the current directory).
</code></pre>
<p>So you need to add <code>-P /tmp/cron_test/</code> (short form) or <code>--directory-prefix=/tmp/cron_test/</code> (long form) to your command. Also note that if the directory does not exist it will get created.</p> | {
"question_id": 1078524,
"question_date": "2009-07-03T09:19:43.803Z",
"question_score": 853,
"tags": "wget",
"answer_id": 1078539,
"answer_date": "2009-07-03T09:23:23.373Z",
"answer_score": 1140
} |
Please answer the following Stack Overflow question:
Title: DateTime2 vs DateTime in SQL Server
<p>Which one: </p>
<ul>
<li><a href="https://msdn.microsoft.com/en-us/library/ms187819.aspx" rel="noreferrer"><code>datetime</code></a></li>
<li><a href="https://msdn.microsoft.com/en-us/library/bb677335.aspx" rel="noreferrer"><code>datetime2</code></a></li>
</ul>
<p>is <em>the</em> recommended way to store date and time in SQL Server 2008+?</p>
<p>I'm aware of differences in precision (and storage space probably), but ignoring those for now, is there a best practice document on when to use what, or maybe we should just use <code>datetime2</code> only?</p> | <p>The MSDN documentation for <a href="http://technet.microsoft.com/en-us/library/ms187819.aspx" rel="noreferrer">datetime</a> recommends using <a href="http://technet.microsoft.com/en-us/library/bb677335.aspx" rel="noreferrer">datetime2</a>. Here is their recommendation:</p>
<blockquote>
<p>Use the <code>time</code>, <code>date</code>, <code>datetime2</code> and
<code>datetimeoffset</code> data types for new
work. These types align with the SQL
Standard. They are more portable.
<code>time</code>, <code>datetime2</code> and <code>datetimeoffset</code>
provide more seconds precision.
<code>datetimeoffset</code> provides time zone
support for globally deployed
applications.</p>
</blockquote>
<p>datetime2 has larger date range, a larger default fractional precision, and optional user-specified precision. Also depending on the user-specified precision it may use less storage. </p> | {
"question_id": 1334143,
"question_date": "2009-08-26T11:45:10.697Z",
"question_score": 853,
"tags": "sql|sql-server|tsql|datetime|datetime2",
"answer_id": 1884088,
"answer_date": "2009-12-10T21:17:57.087Z",
"answer_score": 726
} |
Please answer the following Stack Overflow question:
Title: Can a CSS class inherit one or more other classes?
<p>Is it possible to make a CSS class that "inherits" from another CSS class (or more than one).</p>
<p>For example, say we had:</p>
<pre class="lang-css prettyprint-override"><code>.something { display:inline }
.else { background:red }
</code></pre>
<p>What I'd like to do is something like this:</p>
<pre class="lang-css prettyprint-override"><code>.composite
{
.something;
.else
}
</code></pre>
<p>where the ".composite" class would both display inline and have a red background</p> | <p>There are tools like <a href="http://lesscss.org/" rel="noreferrer">LESS</a>, which allow you to compose CSS at a higher level of abstraction similar to what you describe.</p>
<p>Less calls these "Mixins"</p>
<p>Instead of</p>
<pre><code>/* CSS */
</code></pre>
<pre class="lang-css prettyprint-override"><code>#header {
-moz-border-radius: 8px;
-webkit-border-radius: 8px;
border-radius: 8px;
}
#footer {
-moz-border-radius: 8px;
-webkit-border-radius: 8px;
border-radius: 8px;
}
</code></pre>
<p>You could say</p>
<pre><code>/* LESS */
</code></pre>
<pre class="lang-css prettyprint-override"><code>.rounded_corners {
-moz-border-radius: 8px;
-webkit-border-radius: 8px;
border-radius: 8px;
}
#header {
.rounded_corners;
}
#footer {
.rounded_corners;
}
</code></pre> | {
"question_id": 1065435,
"question_date": "2009-06-30T19:10:57.717Z",
"question_score": 852,
"tags": "css",
"answer_id": 1065476,
"answer_date": "2009-06-30T19:18:52.740Z",
"answer_score": 483
} |
Please answer the following Stack Overflow question:
Title: Cutting the videos based on start and end time using ffmpeg
<p>I tried to cut the video using the start and end time of the video by using the following command</p>
<pre><code>ffmpeg -ss 00:00:03 -t 00:00:08 -i movie.mp4 -acodec copy -vcodec copy -async 1 cut.mp4
</code></pre>
<p>By using the above command i want to cut the video from <code>00:00:03</code> to <code>00:00:08</code>. But it is not cutting the video between those times instead of that it is cutting the video with first 11 seconds. can anyone help me how resolve this?</p>
<p><strong>Edit 1:</strong></p>
<p>I have tried to cut by using the following command which is suggested by <a href="https://stackoverflow.com/users/112212/mark4o">mark4o</a></p>
<pre><code>ffmpeg -i movie.mp4 -ss 00:00:03 -t 00:00:08 -async 1 cut.mp4
</code></pre>
<p>But it was shown the following error.</p>
<p><em><strong>the encoder 'aac' is experimental but experimental codecs are not enabled</strong></em></p>
<p>so i added the <code>-strict -2</code> into the command i.e.,</p>
<pre><code>ffmpeg -i movie.mp4 -ss 00:00:03 -t 00:00:08 -async 1 -strict -2 cut.mp4
</code></pre>
<p>Now it is working fine.</p> | <p>You probably do not have a keyframe at the 3 second mark. Because non-keyframes encode differences from other frames, they require all of the data starting with the previous keyframe.</p>
<p>With the mp4 container it is possible to cut at a non-keyframe without re-encoding using an edit list. In other words, if the closest keyframe before 3s is at 0s then it will copy the video starting at 0s and use an edit list to tell the player to start playing 3 seconds in.</p>
<p>If you are using the <a href="http://ffmpeg.org/download.html">latest ffmpeg</a> from git master it will do this using an edit list when invoked using the command that you provided. If this is not working for you then you are probably either using an older version of ffmpeg, or your player does not support edit lists. Some players will ignore the edit list and always play all of the media in the file from beginning to end.</p>
<p>If you want to cut precisely starting at a non-keyframe and want it to play starting at the desired point on a player that does not support edit lists, or want to ensure that the cut portion is not actually in the output file (for example if it contains confidential information), then you can do that by re-encoding so that there will be a keyframe precisely at the desired start time. Re-encoding is the default if you do not specify <code>copy</code>. For example:</p>
<pre><code>ffmpeg -i movie.mp4 -ss 00:00:03 -t 00:00:08 -async 1 cut.mp4
</code></pre>
<p>When re-encoding you may also wish to include additional quality-related options or a particular AAC encoder. For details, see ffmpeg's <a href="https://trac.ffmpeg.org/wiki/Encode/H.264">x264 Encoding Guide</a> for video and <a href="https://trac.ffmpeg.org/wiki/Encode/AAC">AAC Encoding Guide</a> for audio.</p>
<p>Also, the <code>-t</code> option specifies a duration, not an end time. The above command will encode 8s of video starting at 3s. To start at 3s and end at 8s use <code>-t 5</code>. If you are using a current version of ffmpeg you can also replace <code>-t</code> with <code>-to</code> in the above command to end at the specified time.</p> | {
"question_id": 18444194,
"question_date": "2013-08-26T12:34:19.137Z",
"question_score": 852,
"tags": "video|ffmpeg|video-editing",
"answer_id": 18449609,
"answer_date": "2013-08-26T17:27:05.167Z",
"answer_score": 796
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.