input_text
stringlengths 115
13.8k
| output_text
stringlengths 24
15k
| metadata
dict |
---|---|---|
Please answer the following Stack Overflow question:
Title: <fieldset> resizes wrong; appears to have unremovable `min-width: min-content`
<h1>Problem</h1>
<p>I have a <code><select></code> where one of its <code><option></code>’s text values is very long. I want the <code><select></code> to resize so it is never wider than its parent, even if it has to cut off its displayed text. <code>max-width: 100%</code> should do that.</p>
<p>Before resize:</p>
<p><img src="https://i.stack.imgur.com/RIv8L.png" alt="the page before resize, showing the whole <code>select</code>"></p>
<p>What I want after resize:</p>
<p><img src="https://i.stack.imgur.com/DJnrc.png" alt="my desired page after resize, with the <code>select</code> clipping its contents"></p>
<p>But if you <strong><a href="http://jsfiddle.net/roryokane/g8N87/" rel="noreferrer">load this jsFiddle example</a></strong> and resize the Result panel’s width to be smaller than that of the <code><select></code>, you can see that the select inside the <code><fieldset></code> fails to scale its width down.</p>
<p>What I’m actually seeing after resize:</p>
<p><img src="https://i.stack.imgur.com/fcGsM.png" alt="my current page after resize, with a scroll bar"></p>
<p>However, the <a href="http://jsfiddle.net/roryokane/2YBcn/" rel="noreferrer">equivalent page with a <code><div></code> instead of a <code><fieldset></code></a> does scale properly. You can see that and <a href="http://jsfiddle.net/roryokane/hcTZG/" rel="noreferrer"><strong>test your changes more easily</strong></a> if you have <a href="http://jsfiddle.net/roryokane/hcTZG/" rel="noreferrer">a <code><fieldset></code> and a <code><div></code> next to each other on one page</a>. And if you <a href="http://jsfiddle.net/roryokane/D2U5R/" rel="noreferrer">delete the surrounding <code><fieldset></code> tags</a>, the resizing works. The <code><fieldset></code> tag is somehow causing horizontal resizing to break.</p>
<p>The <code><fieldset></code> acts is as if there is a CSS rule <code>fieldset { min-width: min-content; }</code>. (<a href="https://developer.mozilla.org/en-US/docs/Web/CSS/width" rel="noreferrer"><code>min-content</code></a> means, roughly, the smallest width that doesn’t cause a child to overflow.) If I replace the <code><fieldset></code> with a <a href="http://jsfiddle.net/roryokane/2YBcn/" rel="noreferrer"><code><div></code> with <code>min-width: min-content</code></a>, it looks exactly the same. Yet there is no rule with <code>min-content</code> in my styles, in the browser default stylesheet, or visible in Firebug’s CSS Inspector. I tried to override every style visible on the <code><fieldset></code> in Firebug’s CSS Inspector and in Firefox’s default stylesheet <a href="http://mxr.mozilla.org/mozilla-central/source/layout/style/forms.css" rel="noreferrer">forms.css</a>, but that didn’t help. Specifically overriding <code>min-width</code> and <code>width</code> didn’t do anything either.</p>
<h1>Code</h1>
<p>HTML of the fieldset:</p>
<pre class="lang-html prettyprint-override"><code><fieldset>
<div class="wrapper">
<select id="section" name="section">
<option value="-1"></option>
<option value="1501" selected="selected">Sphinx of black quartz, judge my vow. The quick brown fox jumps over the lazy dog.</option>
<option value="1480">Subcontractor</option>
<option value="3181">Valley</option>
<option value="3180">Ventura</option>
<option value="3220">Very Newest Section</option>
<option value="1481">Visitor</option>
<option value="3200">N/A</option>
</select>
</div>
</fieldset>
</code></pre>
<p>My CSS that should be working but isn’t:</p>
<pre class="lang-css prettyprint-override"><code>fieldset {
/* hide fieldset-specific visual features: */
margin: 0;
padding: 0;
border: none;
}
select {
max-width: 100%;
}
</code></pre>
<p>Resetting the <code>width</code> properties to <a href="http://dev.w3.org/csswg/css-box/#the-width-and-height-properties" rel="noreferrer">the defaults</a> does nothing:</p>
<pre class="lang-css prettyprint-override"><code>fieldset {
width: auto;
min-width: 0;
max-width: none;
}
</code></pre>
<p>Further CSS in which I <a href="http://jsfiddle.net/roryokane/bfmsz/" rel="noreferrer">try and fail to fix the problem</a>:</p>
<pre class="lang-css prettyprint-override"><code>/* try lots of things to fix the width, with no success: */
fieldset {
display: block;
min-width: 0;
max-width: 100%;
width: 100%;
text-overflow: clip;
}
div.wrapper {
width: 100%;
}
select {
overflow: hidden;
}
</code></pre>
<h1>More details</h1>
<p>The problem also occurs in this <a href="http://jsfiddle.net/roryokane/XDFuW/" rel="noreferrer">more comprehensive, more complicated jsFiddle example</a>, which is more similar to the web page I’m actually trying to fix. You can see from that that the <code><select></code> is not the problem – an inline-block <code>div</code> also fails to resize. Though this example is more complicated, I assume that the fix for the simple case above will also fix this more complicated case.</p>
<p>[Edit: see browser support details below.]</p>
<p>One curious thing about this problem is that <a href="http://jsfiddle.net/roryokane/hfa69/" rel="noreferrer">if you set <code>div.wrapper { width: 50%; }</code></a>, the <code><fieldset></code> stops resizing itself at the point then the full-size <code><select></code> would have hit the edge of the viewport. The resizing happens as if the <code><select></code> has <code>width: 100%</code>, even though the <code><select></code> looks like it has <code>width: 50%</code>.</p>
<p><img src="https://i.stack.imgur.com/ne1lu.png" alt="after resize with 50%-width wrapper div"></p>
<p>If you <a href="http://jsfiddle.net/roryokane/q3WMF/" rel="noreferrer">give the <code><select></code> itself <code>width: 50%</code></a>, that behavior does not occur; the width is simply correctly set.</p>
<p><img src="https://i.stack.imgur.com/kcHbr.png" alt="after resize with 50%-width select"></p>
<p>I don’t understand the reason for that difference. But it may not be relevant.</p>
<p>I also found the very similar question <a href="https://stackoverflow.com/q/1716183/578288">HTML fieldset allows children to expand indefinitely</a>. The asker couldn’t find a solution and <a href="https://stackoverflow.com/a/1827502/578288">guesses that there is no solution</a> apart from removing the <code><fieldset></code>. But I’m wondering, if it really is impossible to make the <code><fieldset></code> display right, why is that? What in <code><fieldset></code>’s <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#the-fieldset-element" rel="noreferrer">spec</a> or <a href="https://dxr.mozilla.org/mozilla-central/source/layout/style/res/forms.css" rel="noreferrer">default CSS</a> (<a href="https://hg.mozilla.org/mozilla-central/file/18f85a091e65/layout/style/forms.css" rel="noreferrer">as of this question</a>) causes this behavior? This special behavior is probably be documented somewhere, since multiple browsers work like this.</p>
<h1>Background goal and requirements</h1>
<p>The reason I’m trying to do this is as part of writing mobile styles for an existing page with a big form. The form has multiple sections, and one part of it is wrapped in a <code><fieldset></code>. On a smartphone (or if you make your browser window small), the part of the page with the <code><fieldset></code> is much wider than the rest of the form. Most of the form constrains its width just fine, but the section with the <code><fieldset></code> does not, forcing the user to zoom out or scroll right to see all of that section.</p>
<p>I’m wary of simply removing the <code><fieldset></code>, as it is generated on many pages in a big app, and I’m not sure what selectors in CSS or JavaScript might depend on it.</p>
<p>I can use JavaScript if I need to, and a JavaScript solution is better than nothing. But if JavaScript is the only way to do this, I’d be curious to hear an explanation for why this is not possible using only CSS and HTML.</p>
<hr>
<h1>Edit: browser support</h1>
<p>On the site, I need to support Internet Explorer 8 and later (we just dropped support for IE7), the latest Firefox, and the latest Chrome. This particular page should also work on iOS and Android smartphones. Slightly degraded but still usable behavior is acceptable for Internet Explorer 8.</p>
<p>I retested <a href="http://jsfiddle.net/roryokane/g8N87/" rel="noreferrer">my broken <code>fieldset</code> example</a> on different browsers. It actually already works in these browsers:</p>
<ul>
<li>Internet Explorer 8, 9, and 10</li>
<li>Chrome</li>
<li>Chrome for Android</li>
</ul>
<p>It breaks in these browsers:</p>
<ul>
<li>Firefox</li>
<li>Firefox for Android</li>
<li>Internet Explorer 7</li>
</ul>
<p>Thus, the only browser I care about that the current code breaks in is Firefox (on both desktop and mobile). If the code were fixed so it worked in Firefox without breaking it in any other browsers, that would solve my problem.</p>
<p>The site HTML template uses Internet Explorer conditional comments to add classes such <code>.ie8</code> and <code>.oldie</code> to the <code><html></code> element. You can use those classes in your CSS if you need to work around styling differences in IE. The classes added are the same as in <a href="https://github.com/h5bp/html5-boilerplate/blob/b23de068c5a3cafe2dc642d095221245e578af34/index.html#L2-L7" rel="noreferrer">this old version of HTML5 Boilerplate</a>.</p> | <h2>Update (25 Sept 2017)</h2>
<p>The <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=504622#c5" rel="noreferrer">Firefox bug</a> described below is fixed as of Firefox 53 and the link to this answer has finally been <a href="https://github.com/twbs/bootstrap/pull/21262" rel="noreferrer">removed from Bootstrap's documentation</a>.</p>
<p>Also, my sincere apologies to the Mozilla contributors who had to block removing support for <code>-moz-document</code> partly due to this answer.</p>
<h2>The fix</h2>
<p>In WebKit and Firefox 53+, you just set <code>min-width: 0;</code> on the fieldset to override the default value of <code>min-content</code>.¹</p>
<p>Still, Firefox is a bit… odd when it comes to fieldsets. To make this work in earlier versions, you must change the <code>display</code> property of the fieldset to one of the following values:</p>
<ul>
<li><code>table-cell</code> <strong>(recommended)</strong></li>
<li><code>table-column</code></li>
<li><code>table-column-group</code></li>
<li><code>table-footer-group</code></li>
<li><code>table-header-group</code></li>
<li><code>table-row</code></li>
<li><code>table-row-group</code></li>
</ul>
<p><strong>Of these, I recommend <code>table-cell</code></strong>. Both <code>table-row</code> and <code>table-row-group</code> prevent you from changing width, while <code>table-column</code> and <code>table-column-group</code> prevent you from changing height.</p>
<p>This will (somewhat reasonably) break rendering in IE. Since only Gecko needs this, you can justifiably use <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/@document" rel="noreferrer"><code>@-moz-document</code></a>—one of <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Mozilla_Extensions" rel="noreferrer">Mozilla's proprietary CSS extensions</a>—to hide it from other browsers:</p>
<pre><code>@-moz-document url-prefix() {
fieldset {
display: table-cell;
}
}
</code></pre>
<p><strong>(Here's a <a href="http://jsfiddle.net/Jordan/hCzbH/1/" rel="noreferrer">jsFiddle demo</a>.)</strong></p>
<hr>
<p>That fixes things, but if you're anything like me your reaction was something like…</p>
<h2><a href="http://tvtropes.org/pmwiki/pmwiki.php/Main/FlatWhat" rel="noreferrer">What.</a></h2>
<p>There <em>is</em> a reason, but it's not pretty.</p>
<p>The default presentation of the fieldset element is absurd and essentially impossible to specify in CSS. Think about it: the fieldset's border disappears where it's overlapped by a legend element, but the background remains visible! There's no way to reproduce this with any other combination of elements.</p>
<p>To top it off, implementations are full of concessions to legacy behaviour. One such is that the minimum width of a fieldset is never less than the intrinsic width of its content. WebKit gives you a way to override this behaviour by specifying it in the default stylesheet, but Gecko² goes a step further and <a href="http://hg.mozilla.org/mozilla-central/file/5065fdc12408/layout/forms/nsFieldSetFrame.cpp#l400" rel="noreferrer">enforces it in the rendering engine</a>.</p>
<p>However, internal table elements constitute a <a href="http://hg.mozilla.org/mozilla-central/file/5065fdc12408/layout/generic/nsHTMLReflowState.h#l71" rel="noreferrer">special frame type</a> in Gecko. Dimensional constraints for elements with these <code>display</code> values set are calculated in a <a href="http://hg.mozilla.org/mozilla-central/file/5065fdc12408/layout/generic/nsHTMLReflowState.cpp#l1965" rel="noreferrer">separate code path</a>, entirely circumventing the enforced minimum width imposed on fieldsets.</p>
<p>Again—the <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=504622#c5" rel="noreferrer">bug for this</a> has been fixed as of Firefox 53, so you do not need this hack if you are only targeting newer versions.</p>
<h2>Is using <code>@-moz-document</code> safe?</h2>
<p><strong>For this one issue, yes.</strong> <code>@-moz-document</code> works as intended in all versions of Firefox up until 53, where this bug is fixed.</p>
<p>This is no accident. Due in part to this answer, the bug to <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1035091#c75" rel="noreferrer">limit <code>@-moz-document</code> to user/UA stylesheets</a> was made dependent on the underlying fieldset bug being fixed first.</p>
<p>Beyond this, <strong>do not use <code>@-moz-document</code> to target Firefox in your CSS</strong>, other resources notwithstanding.³</p>
<hr>
<p>¹ Value may be prefixed. According to one reader, this has no effect in Android 4.1.2 Stock Browser and possibly other old versions; I have not had time to verify this.</p>
<p>² All links to the Gecko source in this answer refer to the <a href="http://hg.mozilla.org/mozilla-central/file/5065fdc12408/" rel="noreferrer">5065fdc12408 changeset</a>, committed 29ᵗʰ July 2013; you may wish to compare notes with the <a href="http://mxr.mozilla.org/mozilla-central/source/" rel="noreferrer">most recent revision from Mozilla Central</a>.</p>
<p>³ See e.g. <em><a href="https://stackoverflow.com/a/953491/230390">SO #953491: Targeting only Firefox with CSS</a></em> and <em><a href="http://css-tricks.com/snippets/css/css-hacks-targeting-firefox/" rel="noreferrer">CSS Tricks: CSS hacks targeting Firefox</a></em> for widely referenced articles on high-profile sites.</p> | {
"question_id": 17408815,
"question_date": "2013-07-01T16:01:41.163Z",
"question_score": 224,
"tags": "html|width|fieldset|css",
"answer_id": 17863685,
"answer_date": "2013-07-25T16:28:35.987Z",
"answer_score": 353
} |
Please answer the following Stack Overflow question:
Title: Is there a way to check if int is legal enum in C#?
<p>I've read a few SO posts and it seems most basic operation is missing.</p>
<pre><code>public enum LoggingLevel
{
Off = 0,
Error = 1,
Warning = 2,
Info = 3,
Debug = 4,
Trace = 5
};
if (s == "LogLevel")
{
_log.LogLevel = (LoggingLevel)Convert.ToInt32("78");
_log.LogLevel = (LoggingLevel)Enum.Parse(typeof(LoggingLevel), "78");
_log.WriteDebug(_log.LogLevel.ToString());
}
</code></pre>
<p>This causes no exceptions, it's happy to store <code>78</code>. Is there a way to validate a value going into an enum?</p> | <p>Check out <a href="http://msdn.microsoft.com/en-us/library/system.enum.isdefined.aspx" rel="noreferrer">Enum.IsDefined</a></p>
<p>Usage:</p>
<pre><code>if(Enum.IsDefined(typeof(MyEnum), value))
MyEnum a = (MyEnum)value;
</code></pre>
<p>This is the example from that page:</p>
<pre><code>using System;
[Flags] public enum PetType
{
None = 0, Dog = 1, Cat = 2, Rodent = 4, Bird = 8, Reptile = 16, Other = 32
};
public class Example
{
public static void Main()
{
object value;
// Call IsDefined with underlying integral value of member.
value = 1;
Console.WriteLine("{0}: {1}", value, Enum.IsDefined(typeof(PetType), value));
// Call IsDefined with invalid underlying integral value.
value = 64;
Console.WriteLine("{0}: {1}", value, Enum.IsDefined(typeof(PetType), value));
// Call IsDefined with string containing member name.
value = "Rodent";
Console.WriteLine("{0}: {1}", value, Enum.IsDefined(typeof(PetType), value));
// Call IsDefined with a variable of type PetType.
value = PetType.Dog;
Console.WriteLine("{0}: {1}", value, Enum.IsDefined(typeof(PetType), value));
value = PetType.Dog | PetType.Cat;
Console.WriteLine("{0}: {1}", value, Enum.IsDefined(typeof(PetType), value));
// Call IsDefined with uppercase member name.
value = "None";
Console.WriteLine("{0}: {1}", value, Enum.IsDefined(typeof(PetType), value));
value = "NONE";
Console.WriteLine("{0}: {1}", value, Enum.IsDefined(typeof(PetType), value));
// Call IsDefined with combined value
value = PetType.Dog | PetType.Bird;
Console.WriteLine("{0:D}: {1}", value, Enum.IsDefined(typeof(PetType), value));
value = value.ToString();
Console.WriteLine("{0:D}: {1}", value, Enum.IsDefined(typeof(PetType), value));
}
}
</code></pre>
<p>The example displays the following output:</p>
<pre><code>// 1: True
// 64: False
// Rodent: True
// Dog: True
// Dog, Cat: False
// None: True
// NONE: False
// 9: False
// Dog, Bird: False
</code></pre> | {
"question_id": 2674730,
"question_date": "2010-04-20T11:44:06.443Z",
"question_score": 224,
"tags": "c#|enums",
"answer_id": 2674751,
"answer_date": "2010-04-20T11:46:39.020Z",
"answer_score": 372
} |
Please answer the following Stack Overflow question:
Title: Visual Studio 2010 - C++ project - remove *.sdf file
<p>I would like to know if I can safely delete the sdf file that stores information for Visual Studios Intellisense - is it going to be rebuilt the next time that I open the solution?</p>
<p>Do I lose anything by doing so? Is it possible to break the solution this way?</p>
<p>The motivation to do so is that by having multiple small projects stored - each and every sdf file is more or less 20Mb in size which adds up to a noticeable amount of disk space.</p> | <p>You can safely delete the <strong><em>.sdf file</em></strong> and <strong><em>ipch folder</em></strong> but you can also stop VS from putting those files in the project folder in the first place. (Useful if you have your source in an SVN or other synchronised folder, or if you store your project on a small volume like a USB stick or SSD and you don't want those large files stored in the same folder)</p>
<p>Go to <code>Tools -> Options -> Text Editor -> C/C++ -> Advanced</code></p>
<p>In the "<em>Fallback Location</em>", set "<em>Always Use Fallback Location</em>" to <code>True</code> and "<em>Do Not Warn If Fallback Location Used</em>" to <code>True</code>. </p>
<p>In "<em>Fallback Location</em>" you can either put a path like <code>C:\Temp</code> or if you leave it blank then VS will use the temporary directory in your <strong><em>AppData folder</em></strong>.</p> | {
"question_id": 7706984,
"question_date": "2011-10-09T22:25:45.007Z",
"question_score": 224,
"tags": "visual-studio-2010|visual-studio|visual-c++|intellisense",
"answer_id": 7707083,
"answer_date": "2011-10-09T22:46:19.293Z",
"answer_score": 351
} |
Please answer the following Stack Overflow question:
Title: Where are the Login and Register pages in an AspNet Core scaffolded app?
<p>In VS 2017, I created a new ASP.NET Core Web Application. On the second page of the wizard, I chose Web Application, and for Authentication, I chose "Individual User Accounts".</p>
<p>Now, <strong>I'm trying to find the Pages associated with /Account/Register and /Account/Login</strong>.</p>
<p>_Layout.cshtml brings in _LoginPartial.cshtml, much as it did in classic MVC:</p>
<pre class="lang-html prettyprint-override"><code><div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a asp-page="/Index">Home</a></li>
<li><a asp-page="/About">About</a></li>
<li><a asp-page="/Contact">Contact</a></li>
</ul>
<partial name="_LoginPartial" />
</div>
</code></pre>
<p>If the user is not signed in then _LoginPartial includes <code><a></code> tags that point to the login and register pages:</p>
<pre class="lang-html prettyprint-override"><code><ul class="nav navbar-nav navbar-right">
<li><a asp-area="Identity" asp-page="/Account/Register">Register</a></li>
<li><a asp-area="Identity" asp-page="/Account/Login">Login</a></li>
</ul>
</code></pre>
<p>That all seems to make sense. But I would have expected the Areas folder structure to include the Register and Login folders. It does not. The only thing I find there is _ViewStart.cshtml</p>
<p><a href="https://i.stack.imgur.com/TNVrj.png" rel="noreferrer"><img src="https://i.stack.imgur.com/TNVrj.png" alt="Areas file structure" /></a></p>
<p>I know that the scaffolded code works. When I run the project, the Register link points to "/Identity/Account/Register", and the Login link points to "/Identity/Account/Login". Clicking on the Register link gets me a registration page that includes the text "Create a new account".</p>
<p>But I can't find the text "Create a new account" anywhere in the project.</p>
<p>Can someone tell me what I'm missing?</p> | <p>It was announced during the preview of asp.net core 2.1 that the Identity UI would be moved to a new Razor Class Library.
<a href="https://blogs.msdn.microsoft.com/webdev/2018/03/02/aspnetcore-2-1-identity-ui/" rel="noreferrer">https://blogs.msdn.microsoft.com/webdev/2018/03/02/aspnetcore-2-1-identity-ui/</a></p>
<p>It is still possible to scaffold the Identity Views into your own project if you prefer local views:
<a href="https://docs.microsoft.com/en-us/aspnet/core/security/authentication/scaffold-identity?view=aspnetcore-2.1&tabs=visual-studio" rel="noreferrer">https://docs.microsoft.com/en-us/aspnet/core/security/authentication/scaffold-identity?view=aspnetcore-2.1&tabs=visual-studio</a></p> | {
"question_id": 50802781,
"question_date": "2018-06-11T17:01:27.390Z",
"question_score": 224,
"tags": "asp.net-core|asp.net-identity|razor-pages",
"answer_id": 50805403,
"answer_date": "2018-06-11T20:17:58.037Z",
"answer_score": 221
} |
Please answer the following Stack Overflow question:
Title: How exactly does CMake work?
<p>I'm not asking this for just myself. I hope this question will be a reference for the many newbies who like me, found it utterly perplexing about what exactly what was going on behind the scenes when for such a small <code>CMakeLists.txt</code> file </p>
<pre><code>cmake_minimum_required (VERSION 2.6)
project(Tutorial)
add_executable(Tutorial tutorial.cpp)
</code></pre>
<p>and such a small <code>tutorial.cpp</code> </p>
<pre><code>int main() { return 0; }
</code></pre>
<p>there are so many files generated</p>
<pre><code>CMakeCache.txt cmake_install.cmake Makefile
CMakeLists.txt tutorial.cpp
</code></pre>
<p>and a <code>CMakeFiles</code> folder with so many files and folders </p>
<pre><code>CMakeCCompiler.cmake CMakeOutput.log Makefile.cmake
cmake.check_cache CMakeSystem.cmake progress.marks
CMakeCXXCompiler.cmake CMakeTmp TargetDirectories.txt
CMakeDetermineCompilerABI_C.bin CompilerIdC Tutorial.dir
CMakeDetermineCompilerABI_CXX.bin CompilerIdCXX
CMakeDirectoryInformation.cmake Makefile2
</code></pre>
<p>Not understanding what was going on behind the scenes (i.e: why so may files had to be generated and what their purpose was), was the biggest obstacle in being able to learn CMake. </p>
<p>If anyone knows, could you please explain it for the sake of posterity? What is the purpose of these files, and when I type <code>cmake .</code>, what exactly is cmake configuring and generating before it builds the project?</p> | <p>The secret is that you don't have to understand what the generated files do.</p>
<p>CMake introduces a lot of complexity into the build system, most of which only pays off if you use it for building complex software projects.</p>
<p>The good news is that CMake does a good job of keeping a lot of this messiness away from you: Use <a href="https://gitlab.kitware.com/cmake/community/wikis/FAQ#what-is-an-out-of-source-build" rel="noreferrer">out-of-source builds</a> and you don't even have to look at the generated files. If you didn't do this so far (which I guess is the case, since you wrote <code>cmake .</code>), <em>please check them out before proceeding</em>. Mixing the build and source directory is really painful with CMake and is not how the system is supposed to be used.</p>
<p>In a nutshell: Instead of</p>
<pre><code>cd <source_dir>
cmake .
</code></pre>
<p>always use</p>
<pre><code>cd <build_dir_different_from_source_dir>
cmake <source_dir>
</code></pre>
<p>I usually use an empty subfolder <code>build</code> inside my source directory as build directory.</p>
<p>To ease your pain, let me give a quick overview of the relevant files which CMake generates:</p>
<ul>
<li><strong>Project files/Makefiles</strong> - What you are actually interested in: The files required to build your project under the selected generator. This can be anything from a Unix Makefile to a Visual Studio solution.</li>
<li><strong>CMakeCache.txt</strong> - This is a persistent key/value string storage which is used to cache value between runs. Values stored in here can be paths to library dependencies or whether an optional component is to be built at all. The list of variables is mostly identical to the one you see when running <code>ccmake</code> or <code>cmake-gui</code>. This can be useful to look at from time to time, but I would recommend to use the aforementioned tools for changing any of the values if possible.</li>
<li><strong>Generated files</strong> - This can be anything from autogenerated source files to export macros that help you re-integrate your built project with other CMake projects. Most of these are only generated on demand and will not appear in a simple project such as the one from your question.</li>
<li><strong>Anything else</strong> is pretty much noise to keep the build system happy. In particular, I never needed to care about anything that is going on inside the <code>CMakeFiles</code> subdirectory.</li>
</ul>
<p>In general you should not mess with any of the files that CMake generates for you. All problems can be solved from within <code>CMakeLists.txt</code> in one way or the other. As long as the result builds your project as expected, you are probably fine. Do not worry too much about the gory details - as this is what CMake was trying to spare you of in the first place.</p> | {
"question_id": 17525153,
"question_date": "2013-07-08T11:10:16.323Z",
"question_score": 224,
"tags": "cmake",
"answer_id": 17528542,
"answer_date": "2013-07-08T13:58:36.957Z",
"answer_score": 125
} |
Please answer the following Stack Overflow question:
Title: How to call erase with a reverse iterator
<p>I am trying to do something like this:</p>
<pre><code>for ( std::list< Cursor::Enum >::reverse_iterator i = m_CursorStack.rbegin(); i != m_CursorStack.rend(); ++i )
{
if ( *i == pCursor )
{
m_CursorStack.erase( i );
break;
}
}
</code></pre>
<p>However erase takes an iterator and not a reverse iterator. is there a way to convert a reverse iterator to a regular iterator or another way to remove this element from the list?</p> | <p>After some more research and testing I found the solution. Apparently according to the standard [24.4.1/1] the relationship between i.base() and i is:</p>
<pre><code>&*(reverse_iterator(i)) == &*(i - 1)
</code></pre>
<p>(from a <a href="http://www.ddj.com/cpp/184401406" rel="noreferrer">Dr. Dobbs article</a>):</p>
<p><img src="https://i.cmpnet.com/ddj/cuj/images/cuj0106smeyers/diagram2.gif" alt="alt text"></p>
<p>So you need to apply an offset when getting the base(). Therefore the solution is:</p>
<pre><code>m_CursorStack.erase( --(i.base()) );
</code></pre>
<p><strong>EDIT</strong></p>
<p>Updating for C++11.</p>
<p>reverse_iterator <code>i</code> is unchanged:</p>
<pre><code>m_CursorStack.erase( std::next(i).base() );
</code></pre>
<p>reverse_iterator <code>i</code> is advanced:</p>
<pre><code>std::advance(i, 1);
m_CursorStack.erase( i.base() );
</code></pre>
<p>I find this much clearer than my previous solution. Use whichever you require.</p> | {
"question_id": 1830158,
"question_date": "2009-12-02T01:41:09.920Z",
"question_score": 224,
"tags": "c++",
"answer_id": 1830240,
"answer_date": "2009-12-02T02:09:26.303Z",
"answer_score": 214
} |
Please answer the following Stack Overflow question:
Title: How to implement a typescript decorator?
<p><a href="http://blogs.msdn.com/b/typescript/archive/2015/03/27/announcing-typescript-1-5-alpha.aspx">TypeScript 1.5</a> now has <a href="https://github.com/wycats/javascript-decorators">decorators</a>.</p>
<p>Could someone provide a simple example demonstrating the proper way to implement a decorator and describe what the arguments in the possible valid decorator signatures mean?</p>
<pre><code>declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void;
declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void;
declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void;
declare type ParameterDecorator = (target: Function, propertyKey: string | symbol, parameterIndex: number) => void;
</code></pre>
<p>Additionally, are there any best practice considerations that should be kept in mind while implementing a decorator?</p> | <p>I ended up playing around with decorators and decided to document what I figured out for anyone who wants to take advantage of this before any documentation comes out. Please feel free to edit this if you see any mistakes.</p>
<h1>General Points</h1>
<ul>
<li>Decorators are called when the class is declared—not when an object is instantiated.</li>
<li>Multiple decorators can be defined on the same Class/Property/Method/Parameter.</li>
<li>Decorators are not allowed on constructors.</li>
</ul>
<blockquote>
<p>A valid decorator should be:</p>
<ol>
<li>Assignable to one of the Decorator types (<code>ClassDecorator | PropertyDecorator | MethodDecorator | ParameterDecorator</code>).</li>
<li>Return a value (in the case of class decorators and method decorator) that is assignable to the decorated value.</li>
</ol>
<p><a href="https://github.com/Microsoft/TypeScript/issues/2249" rel="noreferrer">Reference</a></p>
</blockquote>
<hr>
<h1>Method / Formal Accessor Decorator</h1>
<p>Implementation parameters:</p>
<ul>
<li><code>target</code>: The prototype of the class (<code>Object</code>).</li>
<li><code>propertyKey</code>: The name of the method (<code>string</code> | <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Symbol" rel="noreferrer"><code>symbol</code></a>).</li>
<li><code>descriptor</code>: A <a href="https://github.com/Microsoft/TypeScript/blob/727b9a9ceb37c77ba5b69c452cc118a8913d9cf2/src/lib/core.d.ts#L1241" rel="noreferrer"><code>TypedPropertyDescriptor</code></a> — If you're unfamiliar with a descriptor's keys, I would recommend reading about it in <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty" rel="noreferrer">this documentation</a> on <code>Object.defineProperty</code> (it's the third parameter).</li>
</ul>
<h2>Example - Without Arguments</h2>
<p>Use:</p>
<pre><code>class MyClass {
@log
myMethod(arg: string) {
return "Message -- " + arg;
}
}
</code></pre>
<p>Implementation:</p>
<pre><code>function log(target: Object, propertyKey: string, descriptor: TypedPropertyDescriptor<any>) {
const originalMethod = descriptor.value; // save a reference to the original method
// NOTE: Do not use arrow syntax here. Use a function expression in
// order to use the correct value of `this` in this method (see notes below)
descriptor.value = function(...args: any[]) {
// pre
console.log("The method args are: " + JSON.stringify(args));
// run and store result
const result = originalMethod.apply(this, args);
// post
console.log("The return value is: " + result);
// return the result of the original method (or modify it before returning)
return result;
};
return descriptor;
}
</code></pre>
<p>Input:</p>
<pre><code>new MyClass().myMethod("testing");
</code></pre>
<p>Output:</p>
<blockquote>
<p>The method args are: ["testing"]</p>
<p>The return value is: Message -- testing</p>
</blockquote>
<p>Notes:</p>
<ul>
<li>Do not use arrow syntax when setting the descriptor's value. <a href="https://stackoverflow.com/q/30329832/188246">The context of <code>this</code> will not be the instance's if you do.</a></li>
<li>It's better to modify the original descriptor than overwriting the current one by returning a new descriptor. This allows you to use multiple decorators that edit the descriptor without overwriting what another decorator did. Doing this allows you to use something like <code>@enumerable(false)</code> and <code>@log</code> at the same time (Example: <a href="https://www.typescriptlang.org/Playground/#src=class%20FooBar%20%7B%0D%0A%20%20%20%20%40log%0D%0A%09%40enumerable(false)%0D%0A%20%20%20%20public%20foo(arg)%3A%20void%20%7B%0D%0A%09%09%2F%2F%20this%20code%20will%20incorrectly%20output%20%22foo%22%20because%20the%20log%20decorator%20OVERWRITES%20the%20descriptor%0D%0A%20%20%20%20%20%20%20%20for%20(var%20prop%20in%20this)%20%7B%0D%0A%09%09%09console.log(prop)%3B%0D%0A%09%09%7D%0D%0A%20%20%20%20%7D%0D%0A%7D%0D%0A%0D%0Afunction%20log(target%3A%20Object%2C%20propertyKey%3A%20string%2C%20value%3A%20TypedPropertyDescriptor%3Cany%3E)%20%7B%0D%0A%09return%20%7B%0D%0A%20%20%20%20%20%20%20%20value%3A%20function%20(...args%3A%20any%5B%5D)%20%7B%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20var%20a%20%3D%20args.map(a%20%3D%3E%20JSON.stringify(a)).join()%3B%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20var%20result%20%3D%20value.value.apply(this%2C%20args)%3B%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20var%20r%20%3D%20JSON.stringify(result)%3B%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20console.log(%60Call%3A%20%24%7BpropertyKey%7D(%24%7Ba%7D)%20%3D%3E%20%24%7Br%7D%60)%3B%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20return%20result%3B%0D%0A%20%20%20%20%20%20%20%20%7D%0D%0A%20%20%20%20%7D%3B%0D%0A%7D%0D%0A%0D%0Afunction%20enumerable(isEnumerable%3A%20boolean)%20%7B%0D%0A%20%20%20%20return%20(target%3A%20Object%2C%20propertyKey%3A%20string%2C%20descriptor%3A%20TypedPropertyDescriptor%3Cany%3E)%20%3D%3E%20%7B%0D%0A%20%20%20%20%20%20%20%20descriptor.enumerable%20%3D%20isEnumerable%3B%0D%0A%20%20%20%20%20%20%20%20return%20descriptor%3B%0D%0A%20%20%20%20%7D%0D%0A%7D%0D%0A%0D%0Avar%20test%20%3D%20new%20FooBar()%3B%0D%0A%0D%0Atest.foo(%22asdf%22)%3B" rel="noreferrer">Bad</a> vs <a href="https://www.typescriptlang.org/Playground/#src=class%20FooBar%20%7B%0D%0A%20%20%20%20%40log%0D%0A%09%40enumerable(false)%0D%0A%20%20%20%20public%20foo(arg)%3A%20void%20%7B%0D%0A%09%09%2F%2F%20this%20code%20will%20correctly%20NOT%20output%20%22foo%22%20because%20the%20log%20decorator%20MODIFIES%20the%20descriptor%0D%0A%20%20%20%20%20%20%20%20for%20(var%20prop%20in%20this)%20%7B%0D%0A%09%09%09console.log(prop)%3B%0D%0A%09%09%7D%0D%0A%20%20%20%20%7D%0D%0A%7D%0D%0A%0D%0Afunction%20log(target%3A%20Object%2C%20propertyKey%3A%20string%2C%20value%3A%20TypedPropertyDescriptor%3Cany%3E)%20%7B%0D%0A%09var%20originalMethod%20%3D%20value.value%3B%0D%0A%09%0D%0A%20%20%20%20value.value%20%3D%20function%20(...args%3A%20any%5B%5D)%20%7B%0D%0A%09%09var%20a%20%3D%20args.map(a%20%3D%3E%20JSON.stringify(a)).join()%3B%0D%0A%09%09var%20result%20%3D%20originalMethod.apply(this%2C%20args)%3B%0D%0A%09%09var%20r%20%3D%20JSON.stringify(result)%3B%0D%0A%09%09console.log(%60Call%3A%20%24%7BpropertyKey%7D(%24%7Ba%7D)%20%3D%3E%20%24%7Br%7D%60)%3B%0D%0A%09%09return%20result%3B%0D%0A%09%7D%3B%0D%0A%20%20%20%20%0D%0A%09return%20value%3B%0D%0A%7D%0D%0A%0D%0Afunction%20enumerable(isEnumerable%3A%20boolean)%20%7B%0D%0A%20%20%20%20return%20(target%3A%20Object%2C%20propertyKey%3A%20string%2C%20descriptor%3A%20TypedPropertyDescriptor%3Cany%3E)%20%3D%3E%20%7B%0D%0A%20%20%20%20%20%20%20%20descriptor.enumerable%20%3D%20isEnumerable%3B%0D%0A%20%20%20%20%20%20%20%20return%20descriptor%3B%0D%0A%20%20%20%20%7D%0D%0A%7D%0D%0A%0D%0Avar%20test%20%3D%20new%20FooBar()%3B%0D%0A%0D%0Atest.foo(%22asdf%22)%3B" rel="noreferrer">Good</a>)</li>
<li><strong>Useful</strong>: The type argument of <code>TypedPropertyDescriptor</code> can be used to restrict what method signatures (<a href="https://www.typescriptlang.org/Playground/#src=class%20MyClass%20%7B%0D%0A%20%20%20%20%40numberOnly%20%2F%2F%20error%0D%0A%20%20%20%20myMethod(arg%3A%20string)%20%7B%20%0D%0A%20%20%20%20%20%20%20%20return%20%22Message%20--%20%22%20%2B%20arg%3B%0D%0A%20%20%20%20%7D%0D%0A%09%0D%0A%09%40numberOnly%20%2F%2F%20ok%0D%0A%09myNumberMethod(num%3A%20number)%20%7B%0D%0A%09%09return%20num%3B%0D%0A%09%7D%0D%0A%7D%0D%0A%0D%0Afunction%20numberOnly(target%3A%20Object%2C%20propertyKey%3A%20string%2C%20descriptor%3A%20TypedPropertyDescriptor%3C(num%3A%20number)%20%3D%3E%20number%3E)%20%7B%0D%0A%09console.log('This%20descriptor%20is%20only%20allowed%20on%20methods%20that%20have%20one%20parameter%20of%20type%20number%20and%20return%20a%20number.')%3B%0D%0A%20%20%20%20return%20descriptor%3B%0D%0A%7D" rel="noreferrer">Method Example</a>) or accessor signatures (<a href="https://www.typescriptlang.org/Playground/#src=class%20MyClass%20%7B%0D%0A%09%40numberOnly%20%2F%2F%20error%0D%0A%09get%20myString()%20%7B%0D%0A%09%09return%20%22str%22%0D%0A%09%7D%0D%0A%09%0D%0A%20%20%20%20%40numberOnly%20%2F%2F%20ok%0D%0A%20%20%20%20get%20myNumber()%20%7B%20%0D%0A%20%20%20%20%20%20%20%20return%205%3B%0D%0A%20%20%20%20%7D%0D%0A%7D%0D%0A%0D%0Afunction%20numberOnly(target%3A%20Object%2C%20propertyKey%3A%20string%2C%20descriptor%3A%20TypedPropertyDescriptor%3Cnumber%3E)%20%7B%0D%0A%09console.log('This%20descriptor%20is%20only%20allowed%20on%20accessors%20that%20return%20a%20number.')%3B%0D%0A%20%20%20%20return%20descriptor%3B%0D%0A%7D" rel="noreferrer">Accessor Example</a>) the decorator can be put on.</li>
</ul>
<h2>Example - With Arguments (Decorator Factory)</h2>
<p>When using arguments, you must declare a function with the decorator's parameters then return a function with the signature of the example without arguments.</p>
<pre><code>class MyClass {
@enumerable(false)
get prop() {
return true;
}
}
function enumerable(isEnumerable: boolean) {
return (target: Object, propertyKey: string, descriptor: TypedPropertyDescriptor<any>) => {
descriptor.enumerable = isEnumerable;
return descriptor;
};
}
</code></pre>
<hr>
<h1>Static Method Decorator</h1>
<p>Similar to a method decorator with some differences:</p>
<ul>
<li>Its <code>target</code> parameter is the constructor function itself and not the prototype.</li>
<li>The descriptor is defined on the constructor function and not the prototype.</li>
</ul>
<hr>
<h1>Class Decorator</h1>
<pre><code>@isTestable
class MyClass {}
</code></pre>
<p>Implementation parameter:</p>
<ul>
<li><code>target</code>: The class the decorator is declared on (<code>TFunction extends Function</code>).</li>
</ul>
<p><a href="https://docs.microsoft.com/archive/blogs/typescript/announcing-typescript-1-5-beta" rel="noreferrer">Example use</a>: Using the metadata api to store information on a class.</p>
<hr>
<h1>Property Decorator</h1>
<pre><code>class MyClass {
@serialize
name: string;
}
</code></pre>
<p>Implementation parameters:</p>
<ul>
<li><code>target</code>: The prototype of the class (<code>Object</code>).</li>
<li><code>propertyKey</code>: The name of the property (<code>string</code> | <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Symbol" rel="noreferrer"><code>symbol</code></a>).</li>
</ul>
<p><a href="https://stackoverflow.com/a/29706811/188246">Example use</a>: Creating a <code>@serialize("serializedName")</code> decorator and adding the property name to a list of properties to serialize.</p>
<hr>
<h1>Parameter Decorator</h1>
<pre><code>class MyClass {
myMethod(@myDecorator myParameter: string) {}
}
</code></pre>
<p>Implementation parameters:</p>
<ul>
<li><code>target</code>: The prototype of the class (<code>Function</code>—it seems <code>Function</code> doesn't work anymore. You should use <code>any</code> or <code>Object</code> here now in order to use the decorator within any class. Or specify the class type(s) you want to restrict it to)</li>
<li><code>propertyKey</code>: The name of the method (<code>string</code> | <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Symbol" rel="noreferrer"><code>symbol</code></a>).</li>
<li><code>parameterIndex</code>: The index of parameter in the list of the function's parameters (<code>number</code>).</li>
</ul>
<p><a href="https://www.typescriptlang.org/Playground/#src=class%20MyClass%20%7B%0D%0A%20%20%20%20myMethod(%40logParam%20myParameter%3A%20string)%20%7B%7D%0D%0A%7D%0D%0A%0D%0Afunction%20logParam(target%3A%20any%2C%20propertyKey%3A%20string%20%7C%20symbol%2C%20parameterIndex%3A%20number)%20%7B%0D%0A%09console.log(target)%3B%20%20%20%20%20%20%20%20%20%2F%2F%20MyClass%20prototype%0D%0A%09console.log(propertyKey)%3B%20%20%20%20%2F%2F%20%22myMethod%22%0D%0A%09console.log(parameterIndex)%3B%20%2F%2F%200%0D%0A%7D" rel="noreferrer">Simple example</a></p>
<h1>Detailed Example(s)</h1>
<ul>
<li><a href="https://gist.github.com/dsherret/cbe661faf7e3cfad8397" rel="noreferrer">Memoize decorator</a> - Method, Get/Set Accessor decorator example</li>
</ul> | {
"question_id": 29775830,
"question_date": "2015-04-21T14:55:55.353Z",
"question_score": 224,
"tags": "typescript|decorator",
"answer_id": 29837695,
"answer_date": "2015-04-24T02:26:30.487Z",
"answer_score": 429
} |
Please answer the following Stack Overflow question:
Title: Undo “git add <dir>”?
<p>I mistakenly added files using the command "git add dir". I have not yet run "git commit". Is there a way to remove this dir and everything contained within it from the commit?</p>
<p>I have tried <code>git reset dir</code>, but it didn't work. Apparently <code>git reset file</code> is the way to undo it. But I have so many files and so little time.</p> | <p>To remove a directory and everything inside it from the index,</p>
<pre><code>git rm <strong>--cached -r</strong> dir</code></pre>
<p>The <code>--cached</code> switch makes <code>git rm</code> operate on the index only and not touch the working copy. The <code>-r</code> switch makes it recursive.</p> | {
"question_id": 4639091,
"question_date": "2011-01-09T12:25:28.147Z",
"question_score": 224,
"tags": "git|git-reset",
"answer_id": 4639113,
"answer_date": "2011-01-09T12:32:10.347Z",
"answer_score": 336
} |
Please answer the following Stack Overflow question:
Title: Copying the GNU screen scrollback buffer to a file (extended hardcopy)
<p>How do I easily copy the GNU Screen scrollback buffer to a file? I.e., a more powerful version of the 'hardcopy' command?</p>
<p>In GNU screen, I can use "<kbd>Ctrl</kbd> + <kbd>A</kbd> <kbd>Esc</kbd>" to enter the scrollback
buffer. I could then mark the entire buffer and use "<kbd>Ctrl</kbd> + <kbd>A</kbd> <kbd>Ctrl</kbd> + <kbd>]</kbd>" to paste it into an <a href="https://en.wikipedia.org/wiki/Emacs" rel="noreferrer">Emacs</a> buffer, thus saving it to a file.</p>
<p>However, this is tedious. Is there a Screen command that'll simply copy the scrollback buffer to a file, like 'hardcopy' does for the visible portion of the screen?</p> | <p>To write the entire contents of the scrollback buffer to a file, type</p>
<p><kbd>Ctrl</kbd> + <kbd>A</kbd> and <kbd>:</kbd>
to get to command mode, then</p>
<pre><code>hardcopy -h <filename>
</code></pre>
<p>In older versions of <code>screen</code>, if you just do <code>hardcopy -h</code>, it just writes to the file <code>-h</code>. This was fixed in version 4.2.0, so <code>hardcopy -h</code> writes to <code>hardcopy.N</code> where <strong><code>N</code></strong> is the current window number.</p> | {
"question_id": 4807474,
"question_date": "2011-01-26T17:02:56.183Z",
"question_score": 224,
"tags": "keyboard-shortcuts|gnu-screen",
"answer_id": 6604296,
"answer_date": "2011-07-06T23:41:36.037Z",
"answer_score": 349
} |
Please answer the following Stack Overflow question:
Title: Wrap long template literal line to multiline without creating a new line in the string
<p>In es6 template literals, how can one wrap a long template literal to multiline without creating a new line in the string?</p>
<p>For example, if you do this:</p>
<pre><code>const text = `a very long string that just continues
and continues and continues`
</code></pre>
<p>Then it will create a new line symbol to the string, as interpreting it to have a new line. How can one wrap the long template literal to multiple lines without creating the newline?</p> | <p>If you introduce a <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-template-literal-lexical-components" rel="noreferrer">line continuation</a> (<code>\</code>) at the point of the newline in the literal, it won't create a newline on output:</p>
<pre><code>const text = `a very long string that just continues\
and continues and continues`;
console.log(text); // a very long string that just continuesand continues and continues
</code></pre> | {
"question_id": 37321047,
"question_date": "2016-05-19T10:51:27.977Z",
"question_score": 224,
"tags": "javascript|ecmascript-6|template-literals",
"answer_id": 37321145,
"answer_date": "2016-05-19T10:56:04.207Z",
"answer_score": 290
} |
Please answer the following Stack Overflow question:
Title: Angular - What is the meanings of module.id in component?
<p>In an Angular app, I have seen that <code>@Component</code> has property <code>moduleId</code>. What does it mean? </p>
<p>And when <code>module.id</code> is not defined anywhere, the app still works. How can it still work?</p>
<pre class="lang-javascript prettyprint-override"><code>@Component({
moduleId: module.id,
selector: 'ng-app',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css'],
directives: [AppComponent]
});
</code></pre> | <p>The beta release of Angular (since vesion 2-alpha.51) supports relative assets for components, like <strong>templateUrl</strong> and <strong>styleUrls</strong> in the <code>@Component</code> decorator.</p>
<p><code>module.id</code> works when using CommonJS. You don't need to worry about how it works.</p>
<blockquote>
<p><strong>Remember</strong>: setting moduleId: module.id in the @Component decorator is
the key here. If you don't have that then Angular 2 will be looking
for your files at the root level.</p>
</blockquote>
<p>Source from <a href="http://schwarty.com/2015/12/22/angular2-relative-paths-for-templateurl-and-styleurls/" rel="noreferrer">Justin Schwartzenberger's post</a>, thanks to <a href="https://stackoverflow.com/users/5043867/pardeep-jain">@Pradeep Jain</a></p>
<p><strong>Update on 16 Sep 2016:</strong></p>
<blockquote>
<p>If you are using <strong>webpack</strong> for bundling then you don't need
<code>module.id</code> in decorator. Webpack plugins auto handle (add it)
<code>module.id</code> in final bundle</p>
</blockquote> | {
"question_id": 37178192,
"question_date": "2016-05-12T05:43:48.657Z",
"question_score": 224,
"tags": "angular|systemjs|angular2-components",
"answer_id": 37178813,
"answer_date": "2016-05-12T06:25:08.800Z",
"answer_score": 184
} |
Please answer the following Stack Overflow question:
Title: How is "=default" different from "{}" for default constructor and destructor?
<p>I originally posted this as a question only about destructors, but now I'm adding consideration of the default constructor. Here's the original question:</p>
<blockquote>
<p>If I want to give my class a destructor that is virtual, but is
otherwise the same as what the compiler would generate, I can use <code>=default</code>:</p>
<pre><code>class Widget {
public:
virtual ~Widget() = default;
};
</code></pre>
<p>But it seems that I can get the same effect with less typing using an
empty definition:</p>
<pre><code>class Widget {
public:
virtual ~Widget() {}
};
</code></pre>
<p>Is there any way in which these two definitions behave differently?</p>
</blockquote>
<p>Based on the replies posted for this question, the situation for the default constructor seems similar. Given that there is almost no difference in meaning between "<code>=default</code>" and "<code>{}</code>" for destructors, is there similarly almost no difference in meaning between these options for default constructors? That is, assuming I want to create a type where the objects of that type will be both created and destroyed, why would I want to say</p>
<pre><code>Widget() = default;
</code></pre>
<p>instead of</p>
<pre><code>Widget() {}
</code></pre>
<p>?</p>
<p>I apologize if extending this question after its original posting is violating some SO rules. Posting an almost-identical question for default constructors struck me as the less desirable option.</p> | <p>This is a completely different question when asking about constructors than destructors.</p>
<p>If your destructor is <code>virtual</code>, then the difference is negligible, <a href="https://stackoverflow.com/a/13576544/734069">as Howard pointed out</a>. However, if your destructor was <em>non-virtual</em>, it's a completely different story. The same is true of constructors.</p>
<p>Using <code>= default</code> syntax for special member functions (default constructor, copy/move constructors/assignment, destructors etc) means something very different from simply doing <code>{}</code>. With the latter, the function becomes "user-provided". And that changes everything.</p>
<p>This is a trivial class by C++11's definition:</p>
<pre><code>struct Trivial
{
int foo;
};
</code></pre>
<p>If you attempt to default construct one, the compiler will generate a default constructor automatically. Same goes for copy/movement and destructing. Because the user did not provide any of these member functions, the C++11 specification considers this a "trivial" class. It therefore legal to do this, like memcpy their contents around to initialize them and so forth.</p>
<p>This:</p>
<pre><code>struct NotTrivial
{
int foo;
NotTrivial() {}
};
</code></pre>
<p>As the name suggests, this is no longer trivial. It has a default constructor that is user-provided. It doesn't matter if it's empty; as far as the rules of C++11 are concerned, this cannot be a trivial type.</p>
<p>This:</p>
<pre><code>struct Trivial2
{
int foo;
Trivial2() = default;
};
</code></pre>
<p>Again as the name suggests, this is a trivial type. Why? Because you told the compiler to automatically generate the default constructor. The constructor is therefore not "user-provided." And therefore, the type counts as trivial, since it doesn't have a user-provided default constructor.</p>
<p>The <code>= default</code> syntax is mainly there for doing things like copy constructors/assignment, when you add member functions that prevent the creation of such functions. But it also triggers special behavior from the compiler, so it's useful in default constructors/destructors too.</p> | {
"question_id": 13576055,
"question_date": "2012-11-27T01:25:52.080Z",
"question_score": 224,
"tags": "c++|c++11|user-defined-functions|default-constructor|deleted-functions",
"answer_id": 13578720,
"answer_date": "2012-11-27T06:40:46.717Z",
"answer_score": 136
} |
Please answer the following Stack Overflow question:
Title: Are trailing commas in arrays and objects part of the spec?
<p>Are trailing commas standard in JavaScript, or do most browsers like Chrome and Firefox just tolerate them?</p>
<p>I thought they were standard, but IE8 puked after encountering one—of course IE not supporting something hardly means it’s not standard.</p>
<p>Here’s an example of what I mean (after the last element of the books array):</p>
<pre><code>var viewModel = {
books: ko.observableArray([
{ title: "..", display: function() { return ".."; } },
{ title: "..", display: function() { return ".."; } },
{ title: "..", display: function() { return ".."; } }, // <--right there
]),
currentTemplate: ko.observable("bookTemplate1"),
displayTemplate: function() { return viewModel.currentTemplate(); }
};
</code></pre> | <p>Specs: <a href="http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf" rel="noreferrer">ECMAScript 5</a> and <a href="http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%203rd%20edition,%20December%201999.pdf" rel="noreferrer">ECMAScript 3</a></p>
<hr>
<p><a href="http://ecma262-5.com/ELS5_HTML.htm#Section_11.1.5" rel="noreferrer">Section 11.1.5</a> in the ECMAScript 5 specification: </p>
<pre><code>ObjectLiteral :
{ }
{ PropertyNameAndValueList }
{ PropertyNameAndValueList , }
</code></pre>
<p>So yes, it is part of the specification. </p>
<p><strong>Update:</strong> Apparently this is new in ES5. In ES3 (page 41), the definition was just:</p>
<pre><code>ObjectLiteral :
{ }
{ PropertyNameAndValueList }
</code></pre>
<hr>
<p>For arrays literals (<a href="http://ecma262-5.com/ELS5_HTML.htm#Section_11.1.4" rel="noreferrer">Section 11.1.4</a>) it is even more interesting (<strong>Update:</strong> this already existed in ES3):</p>
<pre><code>ArrayLiteral :
[ Elisionopt ]
[ ElementList ]
[ ElementList , Elision_opt ]
</code></pre>
<p>(where <code>Elision_opt</code> is Elision<sub>opt</sub>, meaning the Elision is optional)</p>
<p><code>Elision</code> is defined as </p>
<pre><code>Elision :
,
Elision ,
</code></pre>
<p>So, an array literal like </p>
<pre><code>var arr = [1,2,,,,];
</code></pre>
<p>is perfectly legal. This creates an array with two elements but sets the array length to <code>2 + 3 = 5</code>.</p>
<p>Don't expect too much from IE (before IE9)...</p> | {
"question_id": 7246618,
"question_date": "2011-08-30T16:33:24.080Z",
"question_score": 224,
"tags": "javascript",
"answer_id": 7246662,
"answer_date": "2011-08-30T16:36:52.147Z",
"answer_score": 217
} |
Please answer the following Stack Overflow question:
Title: What do the &,<<, * mean in this database.yml file?
<p>Up until now I have only used <code>database.yml</code> with each parameter called out explicitly, in the file below it uses some characters I do not understand. What does each line and symbol(<code>&</code>, <code>*</code>, <code><<</code>) mean? How do I read this file?</p>
<pre><code>development: &default
adapter: postgresql
database: dev_development
test: &test
<<: *default
database: test_test
cucumber:
<<: *test
production:
<<: *default
database: test_production
</code></pre> | <p>The <code>&</code> marks an alias for the node (in your example <code>&default</code> aliases the development node as "default") and the <code>*</code> references the aliased node with the name "default". The <code><<:</code> inserts the content of that node.</p>
<p>Allow me to quote the YAML spec here: </p>
<blockquote>
<p>Repeated nodes (objects) are first identified by an anchor (marked with the ampersand - “&”), and are then aliased (referenced with an asterisk - “*”) thereafter.</p>
</blockquote>
<p>So parts of your example</p>
<pre><code>development: &default
adapter: postgresql
database: dev_development
test: &test
<<: *default
database: test_test
</code></pre>
<p>actually expand to</p>
<pre><code>development: &default
adapter: postgresql
database: dev_development
test: &test
adapter: postgresql # from the "default" alias
database: test_test # overridden by the duplicate key
</code></pre>
<p>and at the same time make the "test" node as well available under the alias "test".</p>
<p>Have a look at the <a href="http://www.yaml.org/spec/1.2/spec.html#id2760395" rel="noreferrer">YAML specification - 2.2 Structures</a> for further details (or if you need even moar docs++: <a href="http://www.yaml.org/spec/1.2/spec.html#id2765878" rel="noreferrer">3.2.2.2. Anchors and Aliases</a>)</p> | {
"question_id": 6651275,
"question_date": "2011-07-11T14:00:55.523Z",
"question_score": 224,
"tags": "ruby-on-rails|database-connection|yaml|alias|cross-reference",
"answer_id": 6651436,
"answer_date": "2011-07-11T14:14:06.887Z",
"answer_score": 281
} |
Please answer the following Stack Overflow question:
Title: Pythonic way to avoid "if x: return x" statements
<p>I have a method that calls 4 other methods in sequence to check for specific conditions, and returns immediately (not checking the following ones) whenever one returns something Truthy.</p>
<pre><code>def check_all_conditions():
x = check_size()
if x:
return x
x = check_color()
if x:
return x
x = check_tone()
if x:
return x
x = check_flavor()
if x:
return x
return None
</code></pre>
<p>This seems like a lot of baggage code. Instead of each 2-line if statement, I'd rather do something like:</p>
<pre><code>x and return x
</code></pre>
<p>But that is invalid Python. Am I missing a simple, elegant solution here? Incidentally, in this situation, those four check methods may be expensive, so I do not want to call them multiple times.</p> | <p>You could use a loop:</p>
<pre><code>conditions = (check_size, check_color, check_tone, check_flavor)
for condition in conditions:
result = condition()
if result:
return result
</code></pre>
<p>This has the added advantage that you can now make the number of conditions variable.</p>
<p>You could use <a href="https://docs.python.org/3/library/functions.html#map" rel="noreferrer"><code>map()</code></a> + <a href="https://docs.python.org/3/library/functions.html#filter" rel="noreferrer"><code>filter()</code></a> (the Python 3 versions, use the <a href="https://docs.python.org/2/library/future_builtins.html" rel="noreferrer"><code>future_builtins</code> versions</a> in Python 2) to get the first such matching value:</p>
<pre><code>try:
# Python 2
from future_builtins import map, filter
except ImportError:
# Python 3
pass
conditions = (check_size, check_color, check_tone, check_flavor)
return next(filter(None, map(lambda f: f(), conditions)), None)
</code></pre>
<p>but if this is more readable is debatable.</p>
<p>Another option is to use a generator expression:</p>
<pre><code>conditions = (check_size, check_color, check_tone, check_flavor)
checks = (condition() for condition in conditions)
return next((check for check in checks if check), None)
</code></pre> | {
"question_id": 36117583,
"question_date": "2016-03-20T18:11:44.380Z",
"question_score": 224,
"tags": "python|if-statement",
"answer_id": 36117603,
"answer_date": "2016-03-20T18:13:00.980Z",
"answer_score": 283
} |
Please answer the following Stack Overflow question:
Title: Why is the STL so heavily based on templates instead of inheritance?
<p>I mean, aside from its name <em>the Standard Template Library</em> (which evolved into the C++ standard library).</p>
<p>C++ initially introduce OOP concepts into C. That is: you could tell what a specific entity could and couldn't do (regardless of how it does it) based on its class and class hierarchy. Some compositions of abilities are more difficult to describe in this manner due to the complexities of multiple inheritance, and the fact that C++ supports interface-only inheritance in a somewhat clumsy way (compared to java, etc), but it's there (and could be improved).</p>
<p>And then templates came into play, along with the STL. The STL seems to take the classical OOP concepts and flush them down the drain, using templates instead.</p>
<p>There should be a distinction between cases when templates are used to generalize types where the types themselves are irrelevant for the operation of the template (containers, for examples). Having a <code>vector<int></code> makes perfect sense.</p>
<p>However, in many other cases (iterators and algorithms), templated types are supposed to follow a "concept" (Input Iterator, Forward Iterator, etc...) where the actual details of the concept are defined entirely by the implementation of the template function/class, and not by the class of the type used with the template, which is a somewhat anti-usage of OOP.</p>
<p>For example, you can tell the function:</p>
<pre><code>void MyFunc(ForwardIterator<...> *I);
</code></pre>
<p><strong>Update:</strong> As it was unclear in the original question, ForwardIterator is ok to be templated itself to allow any ForwardIterator type. The contrary is having ForwardIterator as a concept.</p>
<p>expects a Forward Iterator only by looking at its definition, where you'd need either to look at the implementation or the documentation for:</p>
<pre><code>template <typename Type> void MyFunc(Type *I);
</code></pre>
<p>Two claims I can make in favor of using templates: 1. Compiled code can be made more efficient, by recompiling the template for each used type, instead of using dynamic dispatch (mostly via vtables). 2. And the fact that templates can be used with native types.</p>
<p>However, I am looking for a more profound reason for abandoning classic OOP in favor of templating for the STL?</p> | <p>The short answer is "because C++ has moved on". Yes, back in the late 70's, Stroustrup intended to create an upgraded C with OOP capabilities, but that is a long time ago. By the time the language was standardized in 1998, it was no longer an OOP language. It was a multi-paradigm language. It certainly had some support for OOP code, but it also had a turing-complete template language overlaid, it allowed compile-time metaprogramming, and people had discovered generic programming. Suddenly, OOP just didn't seem all that important. Not when we can write simpler, more concise <em>and</em> more efficient code by using techniques available through templates and generic programming.</p>
<p>OOP is not the holy grail. It's a cute idea, and it was quite an improvement over procedural languages back in the 70's when it was invented. But it's honestly not all it's cracked up to be. In many cases it is clumsy and verbose and it doesn't really promote reusable code or modularity.</p>
<p>That is why the C++ community is today far more interested in generic programming, and why <em>everyone</em> are finally starting to realize that functional programming is quite clever as well. OOP on its own just isn't a pretty sight.</p>
<p>Try drawing a dependency graph of a hypothetical "OOP-ified" STL. How many classes would have to know about each others? There would be a <em>lot</em> of dependencies. Would you be able to include just the <code>vector</code> header, without also getting <code>iterator</code> or even <code>iostream</code> pulled in? The STL makes this easy. A vector knows about the iterator type it defines, and that's all. The STL algorithms know <em>nothing</em>. They don't even need to include an iterator header, even though they all accept iterators as parameters. Which is more modular then? </p>
<p>The STL may not follow the rules of OOP as Java defines it, but doesn't it achieve the <em>goals</em> of OOP? Doesn't it achieve reusability, low coupling, modularity and encapsulation?</p>
<p>And doesn't it achieve these goals <em>better</em> than an OOP-ified version would?</p>
<p>As for why the STL was adopted into the language, several things happened that led to the STL.</p>
<p>First, templates were added to C++. They were added for much the same reason that generics were added to .NET. It seemed a good idea to be able to write stuff like "containers of a type T" without throwing away type safety. Of course, the implementation they settled on was quite a lot more complex and powerful.</p>
<p>Then people discovered that the template mechanism they had added was even more powerful than expected. And someone started experimenting with using templates to write a more generic library. One inspired by functional programming, and one which used all the new capabilities of C++.</p>
<p>He presented it to the C++ language committee, who took quite a while to grow used to it because it looked so strange and different, but ultimately realized that <em>it worked better than the traditional OOP equivalents they'd have to include otherwise</em>. So they made a few adjustments to it, and adopted it into the standard library.</p>
<p>It wasn't an ideological choice, it wasn't a political choice of "do we want to be OOP or not", but a very pragmatic one. They evaluated the library, and saw that it worked very well. </p>
<p>In any case, both of the reasons you mention for favoring the STL are absolutely essential.</p>
<p>The C++ standard library <strong>has</strong> to be efficient. If it is less efficient than, say, the equivalent hand-rolled C code, then people would not use it. That would lower productivity, increase the likelihood of bugs, and overall just be a bad idea.</p>
<p>And the STL <strong>has</strong> to work with primitive types, because primitive types are all you have in C, and they're a major part of both languages. If the STL did not work with native arrays, it would be <strong>useless</strong>.</p>
<p>Your question has a strong assumption that OOP is "best". I'm curious to hear why. You ask why they "abandoned classical OOP". I'm wondering why they should have stuck with it. Which advantages would it have had?</p> | {
"question_id": 1039853,
"question_date": "2009-06-24T17:43:24.947Z",
"question_score": 224,
"tags": "c++|oop|templates|stl|c++-standard-library",
"answer_id": 1039904,
"answer_date": "2009-06-24T17:52:50.220Z",
"answer_score": 631
} |
Please answer the following Stack Overflow question:
Title: How can I see all the issues I'm watching on Github?
<p>Github has a great feature where you can "watch" an issue. This is handy for getting notifications about progress on that issue.</p>
<p>However, sometimes you want to find the status of an issue you know you've flagged to watch, but can't remember what it was. This is particularly interesting, imho, for projects that are not your own projects. E.g. watching a bug in a library that your project uses but you don't contribute to frequently.</p>
<p><em>What I tried</em>: Note that this is different from <a href="https://github.com/watching" rel="noreferrer">watching a repo</a>. I tried searching github help (for "watch issue" and "subscribe issue" with no luck. I read the <a href="https://help.github.com/articles/unsubscribing-from-conversations" rel="noreferrer">Unsubscribing from Conversations</a> with some hope, but it didn't quite apply. While looking at the issues for the repository that I (think! I) subscribed to, I tried the various search criteria dropdowns with no luck. Last but not least, I read <a href="https://stackoverflow.com/questions/14140564/how-to-follow-only-specific-issues-on-github-instead-of-watching-an-entire-proj">how to subscribe</a> here at SO in case it mentioned how to see the subscribed list.</p>
<p><em>To those who might flag this as not being about programming, I can only ask for a better place to put this? As Github is a commonly used programming tool, I view this as highly relevant.</em></p> | <p>You can see all the Github issues you are currently subscribed to at <a href="https://github.com/notifications/subscriptions" rel="noreferrer">https://github.com/notifications/subscriptions</a></p>
<p>You can navigate to this page from any page by clicking the notification/bell icon on the top right and then selecting "Manage notifications" > "Subscriptions" from the left menu panel.</p> | {
"question_id": 25438721,
"question_date": "2014-08-22T02:29:16.360Z",
"question_score": 224,
"tags": "github",
"answer_id": 55781931,
"answer_date": "2019-04-21T10:30:30.080Z",
"answer_score": 188
} |
Please answer the following Stack Overflow question:
Title: Convert a string to int using sql query
<p>How to convert a string to integer using SQL query on SQL Server 2005?</p> | <p>You could use <a href="http://msdn.microsoft.com/en-us/library/ms187928(SQL.90).aspx" rel="noreferrer">CAST or CONVERT</a>:</p>
<pre><code>SELECT CAST(MyVarcharCol AS INT) FROM Table
SELECT CONVERT(INT, MyVarcharCol) FROM Table
</code></pre> | {
"question_id": 728833,
"question_date": "2009-04-08T07:09:00.830Z",
"question_score": 223,
"tags": "sql|sql-server-2005",
"answer_id": 728840,
"answer_date": "2009-04-08T07:13:15.250Z",
"answer_score": 372
} |
Please answer the following Stack Overflow question:
Title: ImportError: No module named matplotlib.pyplot
<p>I am currently practicing matplotlib. This is the first example I practice.</p>
<pre><code>#!/usr/bin/python
import matplotlib.pyplot as plt
radius = [1.0, 2.0, 3.0, 4.0]
area = [3.14159, 12.56636, 28.27431, 50.26544]
plt.plot(radius, area)
plt.show()
</code></pre>
<p>When I run this script with <code>python ./plot_test.py</code>, it shows plot correctly. However, I run it by itself, <code>./plot_test.py</code>, it throws the followings:</p>
<pre><code>Traceback (most recent call last):
File "./plot_test.py", line 3, in <module>
import matplotlib.pyplot as plt
ImportError: No module named matplotlib.pyplot
</code></pre>
<p>Does python look for matplotlib in different locations?</p>
<p>The environment is:</p>
<pre><code>Mac OS X 10.8.4 64bit
built-in python 2.7
</code></pre>
<p>numpy, scipy, matplotlib is installed with:</p>
<pre><code>sudo port install py27-numpy py27-scipy py27-matplotlib \
py27-ipython +notebook py27-pandas py27-sympy py27-nose
</code></pre> | <p>You have two pythons installed on your machine, one is the standard python that comes with Mac OSX and the second is the one you installed with ports (this is the one that has <code>matplotlib</code> installed in its library, the one that comes with macosx does not).</p>
<pre><code>/usr/bin/python
</code></pre>
<p>Is the standard mac python and since it doesn't have <code>matplotlib</code> you should always start your script with the one installed with ports.</p>
<p>If <code>python your_script.py</code> works then change the <code>#!</code> to:</p>
<pre><code>#!/usr/bin/env python
</code></pre>
<p>Or put the full path to the python interpreter that has the <code>matplotlib</code> installed in its library.</p> | {
"question_id": 18176591,
"question_date": "2013-08-11T20:54:59.610Z",
"question_score": 223,
"tags": "python|matplotlib",
"answer_id": 18176743,
"answer_date": "2013-08-11T21:13:50.847Z",
"answer_score": 63
} |
Please answer the following Stack Overflow question:
Title: 'Java' is not recognized as an internal or external command
<p>When trying to check the current version of Java in which I am running, I received the error "java is not recognized as an internal or external command, operable program or batch file.".</p>
<p>I am running Windows 7 OS and have downloaded the latest JDK and felt I may have accidentally deleted the java from machine as before I was able to check the Java version using the command "java -version".</p>
<p>What software must I download to get Java working on my machine again?</p>
<p>EDIT:</p>
<p>I have managed to get Java running from my cmd again after ensuring all environment variables pointed to the current Java SDK.</p> | <p>You need to configure your environment variables, <code>JAVA_HOME</code> and <code>PATH</code>.</p>
<p><code>JAVA_HOME</code> must contain the path to java, and you should add <strong>%JAVA_HOME%\bin</strong> to <code>PATH</code></p>
<p>Alternatively, you can simply add to your <code>PATH</code> the whole path to the bin folder, without the <code>JAVA_HOME</code> variable, however, this makes a little more annoying when you need to have more than one java version on your machine (that way you only need to change <code>JAVA_HOME</code> and don't even bother with <code>PATH</code>)</p> | {
"question_id": 15796855,
"question_date": "2013-04-03T19:57:37.800Z",
"question_score": 223,
"tags": "java",
"answer_id": 15796878,
"answer_date": "2013-04-03T19:59:07.810Z",
"answer_score": 262
} |
Please answer the following Stack Overflow question:
Title: How can I get dictionary key as variable directly in Python (not by searching from value)?
<p>Sorry for this basic question but my searches on this are not turning up anything other than how to get a dictionary's key based on its value which I would prefer not to use as I simply want the text/name of the key and am worried that searching by value may end up returning 2 or more keys if the dictionary has a lot of entries... what I am trying to do is this:</p>
<pre><code>mydictionary={'keyname':'somevalue'}
for current in mydictionary:
result = mydictionary.(some_function_to_get_key_name)[current]
print result
"keyname"
</code></pre>
<p>The reason for this is that I am printing these out to a document and I want to use the key name and the value in doing this</p>
<p>I have seen the method below but this seems to just return the key's value</p>
<pre><code>get(key[, default])
</code></pre> | <p>You should iterate over keys with:</p>
<pre><code>for key in mydictionary:
print "key: %s , value: %s" % (key, mydictionary[key])
</code></pre> | {
"question_id": 3545331,
"question_date": "2010-08-23T07:01:32.713Z",
"question_score": 223,
"tags": "python|dictionary|key",
"answer_id": 3545353,
"answer_date": "2010-08-23T07:04:48.887Z",
"answer_score": 262
} |
Please answer the following Stack Overflow question:
Title: Responsive css background images
<p>I have a website (g-floors.eu) and I want to make the background (in css I have defined a bg-image for the content) also responsive. Unfortunately I really don't have any idea on how to do this except for one thing that I can think of but it's quite a workaround. Creating multiple images and then using css screen size to change the images but I wanna know if there is a more practical way in order to achieve this.</p>
<p>Basically what I wanna achieve is that the image (with the watermark 'G') automatically resizes without displaying less of the image. If it's possible of course</p>
<p>link: <a href="http://www.g-floors.eu" rel="noreferrer">g-floors.eu</a></p>
<p>Code I have so far (content part)</p>
<pre class="lang-css prettyprint-override"><code>#content {
background-image: url('../images/bg.png');
background-repeat: no-repeat;
position: relative;
width: 85%;
height: 610px;
margin-left: auto;
margin-right: auto;
}
</code></pre> | <p>If you want the same image to scale based on the size of the browser window:</p>
<pre><code>background-image:url('../images/bg.png');
background-repeat:no-repeat;
background-size:contain;
background-position:center;
</code></pre>
<p>Do not set width, height, or margins.</p>
<p>EDIT:
The previous line about not setting width, height or margin refers to OP's original question about scaling with the window size. In other use cases, you may want to set width/height/margins if necessary.</p> | {
"question_id": 12609110,
"question_date": "2012-09-26T19:35:23.877Z",
"question_score": 223,
"tags": "css|responsive-design|background-image|image-resizing",
"answer_id": 12609315,
"answer_date": "2012-09-26T19:51:02.147Z",
"answer_score": 411
} |
Please answer the following Stack Overflow question:
Title: GET URL parameter in PHP
<p>I'm trying to pass a URL as a url parameter in php but when I try to get this parameter I get nothing </p>
<p>I'm using the following url form:</p>
<pre><code>http://localhost/dispatch.php?link=www.google.com
</code></pre>
<p>I'm trying to get it through:</p>
<pre><code>$_GET['link'];
</code></pre>
<p>But nothing returned. What is the problem?</p> | <p><code>$_GET</code> is not a function or language construct—it's just a variable (an array). Try:</p>
<pre><code><?php
echo $_GET['link'];
</code></pre>
<p>In particular, it's a <a href="http://es1.php.net/manual/en/language.variables.superglobals.php" rel="noreferrer">superglobal</a>: a built-in variable that's populated by PHP and is available in all scopes (you can use it from inside a function without the <a href="http://es1.php.net/manual/en/language.variables.scope.php" rel="noreferrer">global</a> keyword).</p>
<p>Since the variable might not exist, you could (and should) ensure your code does not trigger notices with:</p>
<pre><code><?php
if (isset($_GET['link'])) {
echo $_GET['link'];
} else {
// Fallback behaviour goes here
}
</code></pre>
<p>Alternatively, if you want to skip manual index checks and maybe add further validations you can use the <a href="http://php.net/filter" rel="noreferrer">filter</a> extension:</p>
<pre><code><?php
echo filter_input(INPUT_GET, 'link', FILTER_SANITIZE_URL);
</code></pre>
<p>Last but not least, you can use the <a href="https://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.coalesce" rel="noreferrer">null coalescing operator</a> (available since <a href="https://www.php.net/manual/en/migration70.new-features.php" rel="noreferrer">PHP/7.0</a>) to handle missing parameters:</p>
<pre><code>echo $_GET['link'] ?? 'Fallback value';
</code></pre> | {
"question_id": 5884807,
"question_date": "2011-05-04T14:16:20.980Z",
"question_score": 223,
"tags": "php|url|redirect",
"answer_id": 5884896,
"answer_date": "2011-05-04T14:21:53.380Z",
"answer_score": 334
} |
Please answer the following Stack Overflow question:
Title: How to generate a simple popup using jQuery
<p>I am designing a web page. When we click the content of div named mail, how can I show a popup window containing a label email and text box?</p> | <p>First the CSS - tweak this however you like:</p>
<pre><code>a.selected {
background-color:#1F75CC;
color:white;
z-index:100;
}
.messagepop {
background-color:#FFFFFF;
border:1px solid #999999;
cursor:default;
display:none;
margin-top: 15px;
position:absolute;
text-align:left;
width:394px;
z-index:50;
padding: 25px 25px 20px;
}
label {
display: block;
margin-bottom: 3px;
padding-left: 15px;
text-indent: -15px;
}
.messagepop p, .messagepop.div {
border-bottom: 1px solid #EFEFEF;
margin: 8px 0;
padding-bottom: 8px;
}
</code></pre>
<p>And the JavaScript:</p>
<pre><code>function deselect(e) {
$('.pop').slideFadeToggle(function() {
e.removeClass('selected');
});
}
$(function() {
$('#contact').on('click', function() {
if($(this).hasClass('selected')) {
deselect($(this));
} else {
$(this).addClass('selected');
$('.pop').slideFadeToggle();
}
return false;
});
$('.close').on('click', function() {
deselect($('#contact'));
return false;
});
});
$.fn.slideFadeToggle = function(easing, callback) {
return this.animate({ opacity: 'toggle', height: 'toggle' }, 'fast', easing, callback);
};
</code></pre>
<p>And finally the html:</p>
<pre><code><div class="messagepop pop">
<form method="post" id="new_message" action="/messages">
<p><label for="email">Your email or name</label><input type="text" size="30" name="email" id="email" /></p>
<p><label for="body">Message</label><textarea rows="6" name="body" id="body" cols="35"></textarea></p>
<p><input type="submit" value="Send Message" name="commit" id="message_submit"/> or <a class="close" href="/">Cancel</a></p>
</form>
</div>
<a href="/contact" id="contact">Contact Us</a>
</code></pre>
<p><a href="http://jsfiddle.net/SRw67/" rel="noreferrer">Here is a jsfiddle demo and implementation.</a></p>
<p>Depending on the situation you may want to load the popup content via an ajax call. It's best to avoid this if possible as it may give the user a more significant delay before seeing the content. Here couple changes that you'll want to make if you take this approach.</p>
<p>HTML becomes:</p>
<pre><code><div>
<div class="messagepop pop"></div>
<a href="/contact" id="contact">Contact Us</a>
</div>
</code></pre>
<p>And the general idea of the JavaScript becomes:</p>
<pre><code>$("#contact").on('click', function() {
if($(this).hasClass("selected")) {
deselect();
} else {
$(this).addClass("selected");
$.get(this.href, function(data) {
$(".pop").html(data).slideFadeToggle(function() {
$("input[type=text]:first").focus();
});
}
}
return false;
});
</code></pre> | {
"question_id": 1328723,
"question_date": "2009-08-25T14:37:40.333Z",
"question_score": 223,
"tags": "javascript|jquery|css|ajax|popup",
"answer_id": 1329605,
"answer_date": "2009-08-25T17:03:51.707Z",
"answer_score": 247
} |
Please answer the following Stack Overflow question:
Title: How can I stop the browser back button using JavaScript?
<p>I am doing an online quiz application in PHP. I want to restrict the user from going back in an exam.</p>
<p>I have tried the following script, but it stops my timer.</p>
<p>What should I do?</p>
<p>The timer is stored in file <em>cdtimer.js</em>.</p>
<pre class="lang-html prettyprint-override"><code><script type="text/javascript">
window.history.forward();
function noBack()
{
window.history.forward();
}
</script>
<body onLoad="noBack();" onpageshow="if (event.persisted) noBack();" onUnload="">
</code></pre>
<p>I have the exam timer which takes a duration for the exam from a MySQL value. The timer starts accordingly, but it stops when I put the code in for disabling the back button. What is my problem?</p> | <p>There are numerous reasons why disabling the back button will not really work. Your best bet is to warn the user:</p>
<pre><code>window.onbeforeunload = function() { return "Your work will be lost."; };
</code></pre>
<p>This page does list a number of ways you <em>could</em> try to disable the back button, but none are guaranteed:</p>
<p><a href="http://www.irt.org/script/311.htm" rel="noreferrer">http://www.irt.org/script/311.htm</a></p> | {
"question_id": 12381563,
"question_date": "2012-09-12T05:09:11.440Z",
"question_score": 223,
"tags": "javascript|browser",
"answer_id": 12381610,
"answer_date": "2012-09-12T05:15:51.120Z",
"answer_score": 191
} |
Please answer the following Stack Overflow question:
Title: CSS: Set a background color which is 50% of the width of the window
<p>Trying to achieve a background on a page that is "split in two"; two colors on opposite sides (seemingly done by setting a default <code>background-color</code> on the <code>body</code> tag, then applying another onto a <code>div</code> that stretches the entire width of the window).</p>
<p>I did come up with a solution but unfortunately the <code>background-size</code> property doesn't work in IE7/8 which is a must for this project -</p>
<pre><code>body { background: #fff; }
#wrapper {
background: url(1px.png) repeat-y;
background-size: 50% auto;
width: 100%;
}
</code></pre>
<p>Since it's just about solid colors maybe there is a way using only the regular <code>background-color</code> property?</p> | <h1>Older Browser Support</h1>
<p>If older browser support is a must, so you can't go with multiple backgrounds or gradients, you're probably going to want to do something like this on a spare <code>div</code> element:</p>
<pre class="lang-css prettyprint-override"><code>#background {
position: fixed;
top: 0;
left: 0;
width: 50%;
height: 100%;
background-color: pink;
}
</code></pre>
<p>Example: <a href="http://jsfiddle.net/PLfLW/1704/" rel="noreferrer">http://jsfiddle.net/PLfLW/1704/</a></p>
<p>The solution uses an extra fixed div that fills half the screen. Since it's fixed, it will remain in position even when your users scroll. You may have to fiddle with some z-indexes later, to make sure your other elements are above the background div, but it shouldn't be too complex.</p>
<p>If you have issues, just make sure the rest of your content has a z-index higher than the background element and you should be good to go.</p>
<hr>
<h1>Modern Browsers</h1>
<p>If newer browsers are your only concern, there are a couple other methods you can use:</p>
<p><strong>Linear Gradient:</strong></p>
<p>This is definitely the easiest solution. You can use a linear-gradient in the background property of the body for a variety of effects.</p>
<pre class="lang-css prettyprint-override"><code>body {
height: 100%;
background: linear-gradient(90deg, #FFC0CB 50%, #00FFFF 50%);
}
</code></pre>
<p>This causes a hard cutoff at 50% for each color, so there isn't a "gradient" as the name implies. Try experimenting with the "50%" piece of the style to see the different effects you can achieve.</p>
<p>Example: <a href="http://jsfiddle.net/v14m59pq/2/" rel="noreferrer">http://jsfiddle.net/v14m59pq/2/</a></p>
<p><strong>Multiple Backgrounds with background-size:</strong></p>
<p>You can apply a background color to the <code>html</code> element, and then apply a background-image to the <code>body</code> element and use the <code>background-size</code> property to set it to 50% of the page width. This results in a similar effect, though would really only be used over gradients if you happen to be using an image or two.</p>
<pre class="lang-css prettyprint-override"><code>html {
height: 100%;
background-color: cyan;
}
body {
height: 100%;
background-image: url('http://i.imgur.com/9HMnxKs.png');
background-repeat: repeat-y;
background-size: 50% auto;
}
</code></pre>
<p>Example: <a href="http://jsfiddle.net/6vhshyxg/2/" rel="noreferrer">http://jsfiddle.net/6vhshyxg/2/</a></p>
<hr>
<p><strong>EXTRA NOTE:</strong> Notice that both the <code>html</code> and <code>body</code> elements are set to <code>height: 100%</code> in the latter examples. This is to make sure that even if your content is smaller than the page, the background will be at least the height of the user's viewport. Without the explicit height, the background effect will only go down as far as your page content. It's also just a good practice in general.</p> | {
"question_id": 8541081,
"question_date": "2011-12-16T22:51:14.083Z",
"question_score": 223,
"tags": "css|background-color",
"answer_id": 8541575,
"answer_date": "2011-12-16T23:59:20.893Z",
"answer_score": 376
} |
Please answer the following Stack Overflow question:
Title: How can I completely uninstall nodejs, npm and node in Ubuntu
<p>The Question is similar to <a href="https://stackoverflow.com/questions/11177954/how-do-i-completely-uninstall-node-js-and-reinstall-from-beginning-mac-os-x">How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X)</a> but for Ubuntu, and just for uninstalling.</p>
<p>Installation was done by: <code>sudo apt-get install node</code></p>
<p>How do I completely remove npm along with all libraries, packages and any other files installed by npm on my system, via e.g. <code>npm install -g @vue/cli</code>?</p>
<p>I do plan to reinstall npm afterwards.</p> | <pre class="lang-none prettyprint-override"><code>sudo apt-get remove nodejs
sudo apt-get remove npm
</code></pre>
<p>Then go to <code>/etc/apt/sources.list.d</code> and remove any node list if you have. Then do a</p>
<pre class="lang-none prettyprint-override"><code>sudo apt-get update
</code></pre>
<p><strong>Check for any <code>.npm</code> or <code>.node</code> folder in your home folder and delete those.</strong></p>
<p>If you type</p>
<pre class="lang-none prettyprint-override"><code>which node
</code></pre>
<p>you can see the location of the node. Try <code>which nodejs</code> and <code>which npm</code> too.</p>
<p>I would recommend installing node using Node Version Manager(NVM). That saved a lot of headache for me. You can install nodejs and npm without <code>sudo</code> using nvm.</p> | {
"question_id": 32426601,
"question_date": "2015-09-06T18:00:19.137Z",
"question_score": 223,
"tags": "node.js|ubuntu",
"answer_id": 33947181,
"answer_date": "2015-11-26T21:20:57.823Z",
"answer_score": 472
} |
Please answer the following Stack Overflow question:
Title: Numpy - add row to array
<p>How does one add rows to a numpy array?</p>
<p>I have an array A:</p>
<pre><code>A = array([[0, 1, 2], [0, 2, 0]])
</code></pre>
<p>I wish to add rows to this array from another array X if the first element of each row in X meets a specific condition.</p>
<p>Numpy arrays do not have a method 'append' like that of lists, or so it seems.</p>
<p>If A and X were lists I would merely do:</p>
<pre><code>for i in X:
if i[0] < 3:
A.append(i)
</code></pre>
<p>Is there a <em>numpythonic</em> way to do the equivalent?</p>
<p>Thanks,
S ;-)</p> | <p>What is <code>X</code>? If it is a 2D-array, how can you then compare its row to a number: <code>i < 3</code>?</p>
<p>EDIT after OP's comment:</p>
<pre><code>A = array([[0, 1, 2], [0, 2, 0]])
X = array([[0, 1, 2], [1, 2, 0], [2, 1, 2], [3, 2, 0]])
</code></pre>
<p>add to <code>A</code> all rows from <code>X</code> where the first element <code>< 3</code>:</p>
<pre><code>import numpy as np
A = np.vstack((A, X[X[:,0] < 3]))
# returns:
array([[0, 1, 2],
[0, 2, 0],
[0, 1, 2],
[1, 2, 0],
[2, 1, 2]])
</code></pre> | {
"question_id": 3881453,
"question_date": "2010-10-07T12:09:13.730Z",
"question_score": 223,
"tags": "python|arrays|numpy|rows",
"answer_id": 3881487,
"answer_date": "2010-10-07T12:14:02.987Z",
"answer_score": 150
} |
Please answer the following Stack Overflow question:
Title: Only one expression can be specified in the select list when the subquery is not introduced with EXISTS
<p>My query is as follows, and contains a subquery within it:</p>
<pre><code> select count(distinct dNum)
from myDB.dbo.AQ
where A_ID in
(SELECT DISTINCT TOP (0.1) PERCENT A_ID,
COUNT(DISTINCT dNum) AS ud
FROM myDB.dbo.AQ
WHERE M > 1 and B = 0
GROUP BY A_ID ORDER BY ud DESC)
</code></pre>
<p>The error I am receiving is ...</p>
<blockquote>
<p>Only one expression can be specified in the select list when the subquery is not
introduced with EXISTS.`</p>
</blockquote>
<p>When I run the sub-query alone, it returns just fine, so I am assuming there is some issue with the main query?</p> | <p>You can't return two (or multiple) columns in your subquery to do the comparison in the <code>WHERE A_ID IN (subquery)</code> clause - which column is it supposed to compare <code>A_ID</code> to? Your subquery must only return the one column needed for the comparison to the column on the other side of the <code>IN</code>. So the query needs to be of the form:</p>
<pre><code>SELECT * From ThisTable WHERE ThisColumn IN (SELECT ThatColumn FROM ThatTable)
</code></pre>
<p>You also want to add sorting so you can select just from the top rows, but you don't need to return the COUNT as a column in order to do your sort; sorting in the <code>ORDER</code> clause is independent of the columns returned by the query. </p>
<p>Try something like this:</p>
<pre><code>select count(distinct dNum)
from myDB.dbo.AQ
where A_ID in
(SELECT DISTINCT TOP (0.1) PERCENT A_ID
FROM myDB.dbo.AQ
WHERE M > 1 and B = 0
GROUP BY A_ID
ORDER BY COUNT(DISTINCT dNum) DESC)
</code></pre> | {
"question_id": 1904314,
"question_date": "2009-12-14T23:39:14.193Z",
"question_score": 223,
"tags": "sql|sql-server|tsql|exists",
"answer_id": 1904426,
"answer_date": "2009-12-15T00:09:34.840Z",
"answer_score": 286
} |
Please answer the following Stack Overflow question:
Title: SVN Error - Not a working copy
<p>Recently our svn server was changed and we did a svn switch.</p>
<p>Since the working copy had a huge amount of unversioned resources, the working copy got locked and we started switching folder by folder for all folders under svn, which works perfectly fine.</p>
<p>But at the top most level of the repository, when I try to update files, I get the <em>svn: Working copy '.' locked</em> error and cleanup is not helping either. When I do cleanup, I get errors like these - <em>svn: 'content' is not a working copy directory</em></p>
<p>Fresh checkout is NOT an option at all. Are there any other ways to cleanup and release the locks and do the switch completely ?</p>
<p><strong>EDIT:</strong>
The last paragraph in JesperE's answer</p>
<blockquote>
<p>If you get a "not a working copy" when
doing a recursive "svn cleanup" my
guess is that you have a directory
which should be a working copy (i.e.
the .svn directory at the toplevel
says so), but it is missing its own
.svn directory. In that case, you
could try to just remove/move that
directory and then do a local update</p>
</blockquote>
<p>seems to be the solution to the problem in the repository. I have identified those folders and did a fresh checkout of those specific folders alone and wow, the locks are released in the subsequent cleanup! Thanks a lot JesperE !!</p>
<p>But, I still cannot figure out the svn switch error which now reads something like,</p>
<blockquote>
<p>svn: The repository at
'svn://repourl/reponame/foldername'
has uuid 'm/reponame', but the WC
has 'b5b39681-0ff6-784b-ad26-2846b9ea8e7d'</p>
</blockquote>
<p>Any ideas ?</p> | <p>If you get a "not a working copy" when doing a recursive <code>svn cleanup</code> my guess is that you have a directory which should be a working copy (i.e. the <code>.svn</code> directory at the top level says so), but it is missing its own <code>.svn</code> directory.</p>
<p>In that case, you could try to just remove/move that directory and then do a local update (i.e. <code>rm -rf content; svn checkout content</code>).</p>
<p><strong>WARNING: <code>rm -rf</code> deletes the folder content permanently. Backup before executing it</strong></p>
<p>If you get a <code>not a working copy</code> error, it means that Subversion cannot find a proper <code>.svn</code> directory in there. Check to see if there is an <code>.svn</code> directory in <code>contents</code></p>
<p>The ideal solution is a fresh checkout, if possible.</p> | {
"question_id": 374313,
"question_date": "2008-12-17T11:51:40.110Z",
"question_score": 223,
"tags": "svn",
"answer_id": 374337,
"answer_date": "2008-12-17T11:59:04.120Z",
"answer_score": 132
} |
Please answer the following Stack Overflow question:
Title: How do I get the type of a variable?
<p>In C++, how does one find the type of a variable?</p> | <p>For static assertions, C++11 introduced <a href="https://en.cppreference.com/w/cpp/language/decltype" rel="noreferrer"><code>decltype</code></a> which is quite useful in certain scenarios.</p> | {
"question_id": 11310898,
"question_date": "2012-07-03T12:27:02.087Z",
"question_score": 223,
"tags": "c++|variables|typeof",
"answer_id": 38834026,
"answer_date": "2016-08-08T16:14:46.150Z",
"answer_score": 56
} |
Please answer the following Stack Overflow question:
Title: Find the host name and port using PSQL commands
<p>I have PSQL running, and am trying to get a perl application connecting to the database. Is there a command to find the current port and host that the database is running on?</p> | <p>The default PostgreSQL port is <code>5432</code>. The host that the database is operating on should have been provided by your hosting provider; I'd guess it would be the same host as the web server if one wasn't specified. Typically this would be configured as localhost, assuming your web server and database server are on the same host.</p> | {
"question_id": 5598517,
"question_date": "2011-04-08T17:13:20.150Z",
"question_score": 223,
"tags": "postgresql|psql",
"answer_id": 5598558,
"answer_date": "2011-04-08T17:18:21.980Z",
"answer_score": 72
} |
Please answer the following Stack Overflow question:
Title: Extract public/private key from PKCS12 file for later use in SSH-PK-Authentication
<p>I want to extract the public and private key from my <code>PKCS#12</code> file for later use in SSH-Public-Key-Authentication. </p>
<p>Right now, I'm generating keys via ssh-keygen which I put into <code>.ssh/authorized_key</code>, respective somewhere on the client-side.</p>
<p>In future, I want to use the keys from a <code>PKCS#12</code> container, so I've to extract the public-key first from <code>PKCS#12</code> and then put them into the <code>.ssh/authorized_keys</code> file. Is there any chance to get this working via <code>openssl</code>? Are the keys in <code>PKCS#12</code> compatible for ssh-public-key authentication?</p> | <p>You can use following commands to extract public/private key from a PKCS#12 container:</p>
<ul>
<li><p>PKCS#1 Private key</p>
<pre><code>openssl pkcs12 -in yourP12File.pfx -nocerts -out privateKey.pem
</code></pre></li>
<li><p>Certificates:</p>
<pre><code>openssl pkcs12 -in yourP12File.pfx -clcerts -nokeys -out publicCert.pem
</code></pre></li>
</ul> | {
"question_id": 9497719,
"question_date": "2012-02-29T10:53:05.567Z",
"question_score": 223,
"tags": "ssh|openssl|certificate|x509|pkcs#12",
"answer_id": 9516936,
"answer_date": "2012-03-01T13:19:04.567Z",
"answer_score": 327
} |
Please answer the following Stack Overflow question:
Title: How can I clear the SQL Server query cache?
<p>I've got a simple query running against SQL Server 2005</p>
<pre><code>SELECT *
FROM Table
WHERE Col = 'someval'
</code></pre>
<p>The first time I execute the query can take <code>> 15 secs</code>. Subsequent executes are back in <code>< 1 sec</code>.</p>
<p>How can I get SQL Server 2005 not to use any cached results? I've tried running</p>
<pre><code>DBCC DROPCLEANBUFFERS
DBCC FREEPROCCACHE
</code></pre>
<p>But this seems to have no effect on the query speed (still <code>< 1 sec</code>).</p> | <p>Here is some good explaination. check out it.</p>
<p><a href="http://www.mssqltips.com/tip.asp?tip=1360" rel="noreferrer">http://www.mssqltips.com/tip.asp?tip=1360</a></p>
<pre><code>CHECKPOINT;
GO
DBCC DROPCLEANBUFFERS;
GO
</code></pre>
<p>From the linked article:</p>
<blockquote>
<p>If all of the performance testing is conducted in SQL Server the best approach may be to issue a CHECKPOINT and then issue the DBCC DROPCLEANBUFFERS command. Although the CHECKPOINT process is an automatic internal system process in SQL Server and occurs on a regular basis, it is important to issue this command to write all of the dirty pages for the current database to disk and clean the buffers. Then the DBCC DROPCLEANBUFFERS command can be executed to remove all buffers from the buffer pool.</p>
</blockquote> | {
"question_id": 1873025,
"question_date": "2009-12-09T10:37:43.270Z",
"question_score": 223,
"tags": "sql-server|caching",
"answer_id": 1873064,
"answer_date": "2009-12-09T10:45:53.990Z",
"answer_score": 284
} |
Please answer the following Stack Overflow question:
Title: Using G++ to compile multiple .cpp and .h files
<p>I've just inherited some C++ code that was written poorly with one cpp file which contained the main and a bunch of other functions. There are also <code>.h</code> files that contain classes and their function definitions.</p>
<p>Until now the program was compiled using the command <code>g++ main.cpp</code>. Now that I've separated the classes to <code>.h</code> and <code>.cpp</code> files do I need to use a makefile or can I still use the <code>g++ main.cpp</code> command?</p> | <p>list all the other cpp files after main.cpp.</p>
<p>ie </p>
<pre><code>g++ main.cpp other.cpp etc.cpp
</code></pre>
<p>and so on.</p>
<p>Or you can compile them all individually. You then link all the resulting ".o" files together.</p> | {
"question_id": 3202136,
"question_date": "2010-07-08T09:18:58.267Z",
"question_score": 223,
"tags": "c++|compilation|header|makefile",
"answer_id": 3202161,
"answer_date": "2010-07-08T09:22:25.213Z",
"answer_score": 287
} |
Please answer the following Stack Overflow question:
Title: Link to reload current page
<p>Is it possible to have a normal link pointing to the current location?</p>
<p>I have currently found 2 solutions, but one of them includes JavaScript and in the other you have to know the absolute path to the page:</p>
<pre><code><a href="#" onclick="window.location.reload(true);">1</a>
<a href="/foobar/">2</a>
<a href="#">3 (of course not working)</a>
</code></pre>
<p>Is there any way of doing this, without using JavaScript or knowing the absolute path?</p> | <p>I have been using:</p>
<pre><code><a href=".">link</a>
</code></pre>
<p>Have yet to find a case and/or browser where it does not work as intended.</p>
<p>Period means the current path. You can also use <code>..</code> to refer to the folder above the current path, for instance, if you have this file structure:</p>
<pre><code>page1.html
folder1
page2.html
</code></pre>
<p>You can then in <code>page2.html</code> write:</p>
<pre><code><a href="../page1.html">link to page 1</a>
</code></pre>
<p><strong>EDIT:</strong></p>
<p>I'm not sure if the behaviour has changed or if it was always like this, but Chrome (and maybe others) will treat periods as described above as regarding <em>directories</em>, not files. This means that if you are at <code>http://example.com/foo/bar.html</code> you are really in the directory <code>/foo/</code> and a <code>href</code> value of <code>.</code> in <code>bar.html</code> will refer to <code>/foo/</code> rather than <code>bar.html</code></p>
<p>Think of it as navigating the file system in a terminal; you can never <code>cd</code> into a file :)</p>
<p><strong>EDIT 2:</strong></p>
<p>It seems like the behaviour of using <code>href="."</code> is not as predictable anymore, both Firefox and Chrome might have changed how they handle these. I wouldn't rely entirely on my original answer, but rather try both the empty string and the period in different browsers for your specific use and make sure you get the desired behaviour.</p> | {
"question_id": 8174282,
"question_date": "2011-11-17T21:04:56.017Z",
"question_score": 223,
"tags": "html|hyperlink",
"answer_id": 12108553,
"answer_date": "2012-08-24T11:28:35.757Z",
"answer_score": 236
} |
Please answer the following Stack Overflow question:
Title: Invalid default value for 'create_date' timestamp field
<p>I have the following sql create statement</p>
<pre><code>mysql> CREATE TABLE IF NOT EXISTS `erp`.`je_menus` (
-> `id` INT(11) NOT NULL AUTO_INCREMENT ,
-> `name` VARCHAR(100) NOT NULL ,
-> `description` VARCHAR(255) NOT NULL ,
-> `live_start_date` DATETIME NULL DEFAULT NULL ,
-> `live_end_date` DATETIME NULL DEFAULT NULL ,
-> `notes` VARCHAR(255) NULL ,
-> `create_date` TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
-> `created_by` INT(11) NOT NULL ,
-> `update_date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
-> `updated_by` INT(11) NOT NULL ,
-> `status` VARCHAR(45) NOT NULL ,
-> PRIMARY KEY (`id`) )
-> ENGINE = InnoDB;
</code></pre>
<p>giving following error</p>
<p><code>ERROR 1067 (42000): Invalid default value for 'create_date'</code></p>
<p>What is the error here?</p> | <p>That is because of server SQL Mode - <a href="http://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_no_zero_date" rel="noreferrer">NO_ZERO_DATE</a>.</p>
<p>From the reference: <code>NO_ZERO_DATE</code> - In strict mode, doesn't allow <code>'0000-00-00'</code> as a valid date. You can still insert zero dates with the <em>IGNORE</em> option. When not in strict mode, the date is accepted but a warning is generated.</p> | {
"question_id": 9192027,
"question_date": "2012-02-08T11:01:42.393Z",
"question_score": 223,
"tags": "mysql",
"answer_id": 9192372,
"answer_date": "2012-02-08T11:24:34.053Z",
"answer_score": 206
} |
Please answer the following Stack Overflow question:
Title: Separating class code into a header and cpp file
<p>I am confused on how to separate implementation and declarations code of a simple class into a new header and cpp file. For example, how would I separate the code for the following class?</p>
<pre><code>class A2DD
{
private:
int gx;
int gy;
public:
A2DD(int x,int y)
{
gx = x;
gy = y;
}
int getSum()
{
return gx + gy;
}
};
</code></pre> | <p>The class declaration goes into the header file. It is important that you add the <code>#ifndef </code> include guards. Most compilers now also support <a href="https://stackoverflow.com/q/23696115/2311167"><code>#pragma once</code></a>. Also I have omitted the private, by default C++ class members are private.</p>
<pre><code>// A2DD.h
#ifndef A2DD_H
#define A2DD_H
class A2DD
{
int gx;
int gy;
public:
A2DD(int x,int y);
int getSum();
};
#endif
</code></pre>
<p>and the implementation goes in the CPP file:</p>
<pre><code>// A2DD.cpp
#include "A2DD.h"
A2DD::A2DD(int x,int y)
{
gx = x;
gy = y;
}
int A2DD::getSum()
{
return gx + gy;
}
</code></pre> | {
"question_id": 9579930,
"question_date": "2012-03-06T08:05:55.613Z",
"question_score": 223,
"tags": "c++|oop|class",
"answer_id": 9579974,
"answer_date": "2012-03-06T08:09:56.137Z",
"answer_score": 313
} |
Please answer the following Stack Overflow question:
Title: Get everything after the dash in a string in JavaScript
<p>What would be the cleanest way of doing this that would work in both IE and Firefox?</p>
<p>My string looks like this <code>sometext-20202</code></p>
<p>Now the <code>sometext</code> and the integer after the dash can be of varying length.</p>
<p>Should I just use <code>substring</code> and index of or are there other ways?</p> | <p>How I would do this:</p>
<pre><code>// function you can use:
function getSecondPart(str) {
return str.split('-')[1];
}
// use the function:
alert(getSecondPart("sometext-20202"));
</code></pre> | {
"question_id": 573145,
"question_date": "2009-02-21T14:47:18.793Z",
"question_score": 223,
"tags": "javascript",
"answer_id": 573337,
"answer_date": "2009-02-21T16:39:04.687Z",
"answer_score": 370
} |
Please answer the following Stack Overflow question:
Title: Why is Docker installed but not Docker Compose?
<p>I have installed docker on CentOS 7 by running following commands,</p>
<pre><code>curl -sSL https://get.docker.com/ | sh
systemctl enable docker && systemctl start docker
docker run hello-world
</code></pre>
<p><strong>NOTE: helloworld runs correctly and no issues.</strong></p>
<p>however when I try to run <code>docker-compose</code> (docker-compose.yml exists and valid) it gives me the error on CentOS only (Windows version works fine for the docker-compose file)</p>
<pre><code>/usr/local/bin/docker-compose: line 1: {error:Not Found}: command not found
</code></pre> | <p>You also need to install Docker Compose. See the <a href="https://docs.docker.com/compose/install/" rel="noreferrer">manual</a>. Here are the commands you need to execute</p>
<pre><code>sudo curl -L "https://github.com/docker/compose/releases/download/1.26.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo mv /usr/local/bin/docker-compose /usr/bin/docker-compose
sudo chmod +x /usr/bin/docker-compose
</code></pre> | {
"question_id": 36685980,
"question_date": "2016-04-18T05:22:17.163Z",
"question_score": 223,
"tags": "docker|docker-compose|dockerfile",
"answer_id": 36689427,
"answer_date": "2016-04-18T08:54:26.650Z",
"answer_score": 408
} |
Please answer the following Stack Overflow question:
Title: How can I find which tables reference a given table in Oracle SQL Developer?
<p>In <a href="http://www.oracle.com/technology/products/database/sql_developer/index.html" rel="noreferrer">Oracle SQL Developer</a>, if I'm viewing the information on a table, I can view the constraints, which let me see the foreign keys (and thus which tables are referenced by this table), and I can view the dependencies to see what packages and such reference the table. But I'm not sure how to find which tables reference the table.</p>
<p>For example, say I'm looking at the <code>emp</code> table. There is another table <code>emp_dept</code> which captures which employees work in which departments, which references the <code>emp</code> table through <code>emp_id</code>, the primary key of the <code>emp</code> table. Is there a way (through some UI element in the program, not through SQL) to find that the <code>emp_dept</code> table references the <code>emp</code> table, without me having to know that the <code>emp_dept</code> table exists?</p> | <p>No. There is no such option available from Oracle SQL Developer. </p>
<p>You have to execute a query by hand or use other tool (For instance <a href="http://www.allroundautomations.com/plsqldev.html" rel="noreferrer">PLSQL Developer</a> has such option). The following SQL is that one used by PLSQL Developer:</p>
<pre><code>select table_name, constraint_name, status, owner
from all_constraints
where r_owner = :r_owner
and constraint_type = 'R'
and r_constraint_name in
(
select constraint_name from all_constraints
where constraint_type in ('P', 'U')
and table_name = :r_table_name
and owner = :r_owner
)
order by table_name, constraint_name
</code></pre>
<p>Where <code>r_owner</code> is the schema, and <code>r_table_name</code> is the table for which you are looking for references. The names are case sensitive</p>
<hr>
<p>Be careful because on the reports tab of Oracle SQL Developer there is the option "All tables / Dependencies" this is from <a href="http://download.oracle.com/docs/cd/B19306_01/server.102/b14237/statviews_1041.htm#i1576452" rel="noreferrer">ALL_DEPENDENCIES</a> which refers to "<em>dependencies between procedures, packages, functions, package bodies, and triggers accessible to the current user, including dependencies on views created without any database links."</em>. Then, this report have no value for your question.</p> | {
"question_id": 1143728,
"question_date": "2009-07-17T14:46:46.270Z",
"question_score": 223,
"tags": "sql|oracle|foreign-keys|oracle-sqldeveloper",
"answer_id": 1144079,
"answer_date": "2009-07-17T15:40:07.660Z",
"answer_score": 283
} |
Please answer the following Stack Overflow question:
Title: How to get current available GPUs in tensorflow?
<p>I have a plan to use distributed TensorFlow, and I saw TensorFlow can use GPUs for training and testing. In a cluster environment, each machine could have 0 or 1 or more GPUs, and I want to run my TensorFlow graph into GPUs on as many machines as possible.</p>
<p>I found that when running <code>tf.Session()</code> TensorFlow gives information about GPU in the log messages like below:</p>
<pre><code>I tensorflow/core/common_runtime/gpu/gpu_init.cc:126] DMA: 0
I tensorflow/core/common_runtime/gpu/gpu_init.cc:136] 0: Y
I tensorflow/core/common_runtime/gpu/gpu_device.cc:838] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 1080, pci bus id: 0000:01:00.0)
</code></pre>
<p>My question is how do I get information about current available GPU from TensorFlow? I can get loaded GPU information from the log, but I want to do it in a more sophisticated, programmatic way.
I also could restrict GPUs intentionally using the CUDA_VISIBLE_DEVICES environment variable, so I don't want to know a way of getting GPU information from OS kernel.</p>
<p>In short, I want a function like <code>tf.get_available_gpus()</code> that will return <code>['/gpu:0', '/gpu:1']</code> if there are two GPUs available in the machine. How can I implement this?</p> | <p>There is an undocumented method called <a href="https://github.com/tensorflow/tensorflow/blob/d42facc3cc9611f0c9722c81551a7404a0bd3f6b/tensorflow/python/client/device_lib.py#L27" rel="noreferrer"><code>device_lib.list_local_devices()</code></a> that enables you to list the devices available in the local process. (<strong>N.B.</strong> As an undocumented method, this is subject to backwards incompatible changes.) The function returns a list of <a href="https://github.com/tensorflow/tensorflow/blob/8a4f6abb395b3f1bca732797068021c786c1ec76/tensorflow/core/framework/device_attributes.proto" rel="noreferrer"><code>DeviceAttributes</code> protocol buffer</a> objects. You can extract a list of string device names for the GPU devices as follows:</p>
<pre><code>from tensorflow.python.client import device_lib
def get_available_gpus():
local_device_protos = device_lib.list_local_devices()
return [x.name for x in local_device_protos if x.device_type == 'GPU']
</code></pre>
<p>Note that (at least up to TensorFlow 1.4), calling <code>device_lib.list_local_devices()</code> will run some initialization code that, by default, will allocate all of the GPU memory on all of the devices (<a href="https://github.com/tensorflow/tensorflow/issues/9374" rel="noreferrer">GitHub issue</a>). To avoid this, first create a session with an explicitly small <code>per_process_gpu_fraction</code>, or <code>allow_growth=True</code>, to prevent all of the memory being allocated. See <a href="https://stackoverflow.com/q/34199233/3574081">this question</a> for more details.</p> | {
"question_id": 38559755,
"question_date": "2016-07-25T04:30:38.390Z",
"question_score": 223,
"tags": "python|gpu|tensorflow",
"answer_id": 38580201,
"answer_date": "2016-07-26T02:34:21.540Z",
"answer_score": 304
} |
Please answer the following Stack Overflow question:
Title: Get time difference between two dates in seconds
<p>I'm trying to get a difference between two dates in seconds. The logic would be like this :</p>
<ul>
<li>set an initial date which would be now;</li>
<li>set a final date which would be the initial date plus some amount of seconds in future ( let's say 15 for instance )</li>
<li>get the difference between those two ( the amount of seconds )</li>
</ul>
<p>The reason why I'm doing it it with dates it's because the final date / time depends on some other variables and it's never the same ( it depends on how fast a user does something ) and I also store the initial date for other things.</p>
<p>I've been trying something like this : </p>
<pre><code>var _initial = new Date(),
_initial = _initial.setDate(_initial.getDate()),
_final = new Date(_initial);
_final = _final.setDate(_final.getDate() + 15 / 1000 * 60);
var dif = Math.round((_final - _initial) / (1000 * 60));
</code></pre>
<p>The thing is that I never get the right difference. I tried dividing by <code>24 * 60</code> which would leave me with the seconds, but I never get it right. So what is it wrong with my logic ? I might be making some stupid mistake as it's quite late, but it bothers me that I cannot get it to work :)</p> | <h3>The Code</h3>
<pre><code>var startDate = new Date();
// Do your operations
var endDate = new Date();
var seconds = (endDate.getTime() - startDate.getTime()) / 1000;
</code></pre>
<p>Or even simpler <code>(endDate - startDate) / 1000</code> as pointed out in the comments unless you're using typescript.</p>
<hr/>
<h3>The explanation</h3>
<p>You need to call the <code>getTime()</code> method for the <code>Date</code> objects, and then simply subtract them and divide by 1000 (since it's originally in milliseconds). As an extra, when you're calling the <code>getDate()</code> method, you're in fact getting the day of the month as an integer between 1 and 31 (not zero based) as opposed to the epoch time you'd get from calling the <code>getTime()</code> method, representing the number of milliseconds since <em>January 1st 1970, 00:00</em></p>
<hr/>
<h3>Rant</h3>
<p>Depending on what your date related operations are, you might want to invest in integrating a library such as <a href="http://www.datejs.com/" rel="noreferrer">date.js</a> or <a href="https://momentjs.com/" rel="noreferrer">moment.js</a> which make things <em>so much easier</em> for the developer, but that's just a matter of personal preference.</p>
<p>For example in <a href="https://momentjs.com/" rel="noreferrer">moment.js</a> we would do <code>moment1.diff(moment2, "seconds")</code> which is beautiful.</p>
<hr />
<h3>Useful docs for this answer</h3>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Unix_time" rel="noreferrer">Why 1970?</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ie/cd9w2te4%28v=vs.94%29.aspx" rel="noreferrer">Date object</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ie/7hcawkw2%28v=vs.94%29.aspx" rel="noreferrer">Date's getTime method</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ie/217fw5tk%28v=vs.94%29.aspx" rel="noreferrer">Date's getDate method</a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Performance/now" rel="noreferrer">Need more accuracy than just seconds?</a></li>
</ul> | {
"question_id": 13894632,
"question_date": "2012-12-15T17:48:07.187Z",
"question_score": 223,
"tags": "javascript|date",
"answer_id": 13894670,
"answer_date": "2012-12-15T17:51:56.357Z",
"answer_score": 440
} |
Please answer the following Stack Overflow question:
Title: Git clone particular version of remote repository
<p>I cloned a remote git repository about a month ago. The remote repository has undergone many changes and has now become unstable. Now I need another copy of the repository, version identical to the one I cloned a month ago.</p>
<p>How do I do this?</p> | <p>You could "reset" your repository to any commit you want (e.g. 1 month ago). </p>
<p>Use <a href="http://git-scm.com/docs/git-reset" rel="noreferrer">git-reset</a> for that:</p>
<pre><code>git clone [remote_address_here] my_repo
cd my_repo
git reset --hard [ENTER HERE THE COMMIT HASH YOU WANT]
</code></pre> | {
"question_id": 3555107,
"question_date": "2010-08-24T09:26:18.483Z",
"question_score": 223,
"tags": "git|git-clone",
"answer_id": 3555202,
"answer_date": "2010-08-24T09:41:20.153Z",
"answer_score": 275
} |
Please answer the following Stack Overflow question:
Title: Error "initializer element is not constant" when trying to initialize variable with const
<p>I get an error on line 6 (initialize my_foo to foo_init) of the following program and I'm not sure I understand why.</p>
<pre><code>typedef struct foo_t {
int a, b, c;
} foo_t;
const foo_t foo_init = { 1, 2, 3 };
foo_t my_foo = foo_init;
int main()
{
return 0;
}
</code></pre>
<p>Keep in mind this is a simplified version of a larger, multi-file project I'm working on. The goal was to have a single constant in the object file, that multiple files could use to initialize a state structure. Since it's an embedded target with limited resources and the struct isn't that small, I don't want multiple copies of the source. I'd prefer not to use:</p>
<pre><code>#define foo_init { 1, 2, 3 }
</code></pre>
<p>I'm also trying to write portable code, so I need a solution that's valid C89 or C99.</p>
<p>Does this have to do with the ORGs in an object file? That initialized variables go into one ORG and are initialized by copying the contents of a second ORG?</p>
<p>Maybe I'll just need to change my tactic, and have an initializing function do all of the copies at startup. Unless there are other ideas out there?</p> | <p>In C language, objects with static storage duration have to be initialized with <em>constant expressions</em>, or with aggregate initializers containing constant expressions.</p>
<p>A "large" object is never a constant expression in C, even if the object is declared as <code>const</code>. </p>
<p>Moreover, in C language, the term "constant" refers to <em>literal constants</em> (like <code>1</code>, <code>'a'</code>, <code>0xFF</code> and so on), enum members, and results of such operators as <code>sizeof</code>. Const-qualified objects (of any type) are <em>not constants</em> in C language terminology. They cannot be used in initializers of objects with static storage duration, regardless of their type.</p>
<p>For example, this is <em>NOT</em> a constant</p>
<pre><code>const int N = 5; /* `N` is not a constant in C */
</code></pre>
<p>The above <code>N</code> would be a constant in C++, but it is not a constant in C. So, if you try doing </p>
<pre><code>static int j = N; /* ERROR */
</code></pre>
<p>you will get the same error: an attempt to initialize a static object with a non-constant.</p>
<p>This is the reason why, in C language, we predominantly use <code>#define</code> to declare named constants, and also resort to <code>#define</code> to create named aggregate initializers.</p> | {
"question_id": 3025050,
"question_date": "2010-06-11T17:55:27.023Z",
"question_score": 223,
"tags": "c|initialization",
"answer_id": 3025106,
"answer_date": "2010-06-11T18:04:02.143Z",
"answer_score": 321
} |
Please answer the following Stack Overflow question:
Title: How to find memory leak in a C++ code/project?
<p>I am a C++ programmer on the Windows platform. I am using Visual Studio 2008.</p>
<p>I usually end up in the code with memory leaks.</p>
<p>Normally I find the memory leak by inspecting the code, but it is cumbersome and is not always a good approach. </p>
<p>Since I can't afford a paid memory leak detection tool, I wanted you guys to suggest the best possible ways to avoid memory leaks.</p>
<ol>
<li>I want to the know how the programmer can find memory leaks.</li>
<li>Is there any standard or procedure one should follow to ensure there is no memory leak in the program?</li>
</ol> | <p><strong>Instructions</strong></p>
<p>Things You'll Need</p>
<ul>
<li>Proficiency in C++</li>
<li>C++ compiler</li>
<li>Debugger and other investigative software tools</li>
</ul>
<h1>1</h1>
<p>Understand the operator basics. The C++ operator <code>new</code> allocates heap memory. The <code>delete</code> operator frees heap memory. For every <code>new</code>, you should use a <code>delete</code> so that you free the same memory you allocated:</p>
<pre><code>char* str = new char [30]; // Allocate 30 bytes to house a string.
delete [] str; // Clear those 30 bytes and make str point nowhere.
</code></pre>
<h1>2</h1>
<p>Reallocate memory only if you've deleted. In the code below, <code>str</code> acquires a new address with the second allocation. The first address is lost irretrievably, and so are the 30 bytes that it pointed to. Now they're impossible to free, and you have a memory leak:</p>
<pre><code>char* str = new char [30]; // Give str a memory address.
// delete [] str; // Remove the first comment marking in this line to correct.
str = new char [60]; /* Give str another memory address with
the first one gone forever.*/
delete [] str; // This deletes the 60 bytes, not just the first 30.
</code></pre>
<h1>3</h1>
<p>Watch those pointer assignments. Every dynamic variable (allocated memory on the heap) needs to be associated with a pointer. When a dynamic variable becomes disassociated from its pointer(s), it becomes impossible to erase. Again, this results in a memory leak:</p>
<pre><code>char* str1 = new char [30];
char* str2 = new char [40];
strcpy(str1, "Memory leak");
str2 = str1; // Bad! Now the 40 bytes are impossible to free.
delete [] str2; // This deletes the 30 bytes.
delete [] str1; // Possible access violation. What a disaster!
</code></pre>
<h1>4</h1>
<p>Be careful with local pointers. A pointer you declare in a function is allocated on the stack, but the dynamic variable it points to is allocated on the heap. If you don't delete it, it will persist after the program exits from the function:</p>
<pre><code>void Leak(int x){
char* p = new char [x];
// delete [] p; // Remove the first comment marking to correct.
}
</code></pre>
<h1>5</h1>
<p>Pay attention to the square braces after "delete." Use <code>delete</code> by itself to free a single object. Use <code>delete []</code> with square brackets to free a heap array. Don't do something like this:</p>
<pre><code>char* one = new char;
delete [] one; // Wrong
char* many = new char [30];
delete many; // Wrong!
</code></pre>
<h1>6</h1>
<p>If the leak yet allowed - I'm usually seeking it with deleaker (check it here: <a href="http://deleaker.com" rel="noreferrer">http://deleaker.com</a>).</p> | {
"question_id": 6261201,
"question_date": "2011-06-07T06:09:04.223Z",
"question_score": 223,
"tags": "c++|memory-leaks",
"answer_id": 8417851,
"answer_date": "2011-12-07T15:28:21.253Z",
"answer_score": 333
} |
Please answer the following Stack Overflow question:
Title: How to update SQLAlchemy row entry?
<p>Assume table has three columns: <code>username</code>, <code>password</code> and <code>no_of_logins</code>.</p>
<p>When user tries to login, it's checked for an entry with a query like</p>
<pre><code>user = User.query.filter_by(username=form.username.data).first()
</code></pre>
<p>If password matches, he proceeds further. What I would like to do is count how many times the user logged in. Thus whenever he successfully logs in, I would like to increment the <code>no_of_logins</code> field and store it back to the user table. I'm not sure how to run update query with SqlAlchemy.</p> | <pre><code>user.no_of_logins += 1
session.commit()
</code></pre> | {
"question_id": 9667138,
"question_date": "2012-03-12T12:37:12.500Z",
"question_score": 223,
"tags": "python|sqlalchemy|flask-sqlalchemy",
"answer_id": 9667308,
"answer_date": "2012-03-12T12:49:05.723Z",
"answer_score": 186
} |
Please answer the following Stack Overflow question:
Title: How to set enum to null
<p>I have an enum</p>
<pre><code>string name;
public enum Color
{
Red,
Green,
Yellow
}
</code></pre>
<p>How to set it to NULL on load.</p>
<pre><code>name = "";
Color color = null; //error
</code></pre>
<p>Edited:
My bad, I didn't explain it properly. But all the answers related to nullable is perfect. My situation is What if, I have get/set for the enum in a class with other elements like name, etc. On page load I initiallize the class and try to default the values to null. Here is the scenario (Code is in C#):</p>
<pre><code>namespace Testing
{
public enum ValidColors
{
Red,
Green,
Yellow
}
public class EnumTest
{
private string name;
private ValidColors myColor;
public string Name
{
get { return name; }
set { name = value; }
}
public ValidColors MyColor
{
get { return myColor; }
set { myColor = value; }
}
}
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
EnumTest oEnumTest = new EnumTest();
oEnumTest.Name = "";
oEnumTest.MyColor = null; //???
}
}
}
</code></pre>
<p>Then using the suggestions below I changed the above code to make it work with get and set methods. I just need to add "?" in EnumTest class during declaration of private enum variable and in get/set method:</p>
<pre><code>public class EnumTest
{
private string name;
private ValidColors? myColor; //added "?" here in declaration and in get/set method
public string Name
{
get { return name; }
set { name = value; }
}
public ValidColors? MyColor
{
get { return myColor; }
set { myColor = value; }
}
}
</code></pre>
<p>Thanks all for the lovely suggestions.</p> | <p>You can either use the "?" operator for a nullable type.</p>
<pre><code>public Color? myColor = null;
</code></pre>
<p>Or use the standard practice for enums that cannot be null by having the FIRST value in the enum (aka 0) be the default value. For example in a case of color None.</p>
<pre><code>public Color myColor = Color.None;
</code></pre> | {
"question_id": 4337193,
"question_date": "2010-12-02T16:20:34.800Z",
"question_score": 223,
"tags": "c#|enums|null|nullable",
"answer_id": 4337236,
"answer_date": "2010-12-02T16:23:53.830Z",
"answer_score": 429
} |
Please answer the following Stack Overflow question:
Title: How to scroll to bottom in react?
<p>I want to build a chat system and automatically scroll to the bottom when entering the window and when new messages come in. How do you automatically scroll to the bottom of a container in React?</p> | <p>As Tushar mentioned, you can keep a dummy div at the bottom of your chat:</p>
<pre class="lang-js prettyprint-override"><code>render () {
return (
<div>
<div className="MessageContainer" >
<div className="MessagesList">
{this.renderMessages()}
</div>
<div style={{ float:"left", clear: "both" }}
ref={(el) => { this.messagesEnd = el; }}>
</div>
</div>
</div>
);
}
</code></pre>
<p>and then scroll to it whenever your component is updated (i.e. state updated as new messages are added):</p>
<pre class="lang-js prettyprint-override"><code>scrollToBottom = () => {
this.messagesEnd.scrollIntoView({ behavior: "smooth" });
}
componentDidMount() {
this.scrollToBottom();
}
componentDidUpdate() {
this.scrollToBottom();
}
</code></pre>
<p>I'm using the standard <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView" rel="noreferrer">Element.scrollIntoView</a> method here.</p> | {
"question_id": 37620694,
"question_date": "2016-06-03T17:54:25.430Z",
"question_score": 223,
"tags": "reactjs",
"answer_id": 41700815,
"answer_date": "2017-01-17T15:20:28.773Z",
"answer_score": 325
} |
Please answer the following Stack Overflow question:
Title: How can I set the JDK NetBeans runs on?
<p>I have the older NetBeans 6.7, NetBeans 6.9, and NetBeans 7.0, which used to run on jdk1.6.0_21 and jdk1.6.0_25. Now I've removed those JDKs and only have jdk1.6.0_26 and jdk1.7.0 left, but I still want to keep the older versions of NetBeans, but now when I run them, I get this message:</p>
<blockquote>
<p>"Cannot locate java installation in specified jdkhome C:\Program Files (x86)\Java\jdk1.6.0_25 <br />
Do you want to try to use default version?"</p>
</blockquote>
<p>I tried to find where it's looking for the "jdk1.6.0_25", and updated a few configuration files in "C:\Program Files (x86)\NetBeans 6.7" and "C:\Users\USER.nbi\registry.xml", and yet the message keeps coming. Where and what do I need to change to point it to <code>C:\Program Files (x86)\Java\jdk1.6.0_26</code>?</p> | <p>Thanks to <a href="https://stackoverflow.com/questions/6950960/how-can-i-set-the-jdk-netbeans-runs-on/6951067#6951067">Kasun Gajasinghe's tip</a>, I found the solution in the "suggested" link. Update the following file (replace <strong>7.x</strong> with your NetBeans version):</p>
<pre class="lang-none prettyprint-override"><code>C:\Program Files\NetBeans 7.x\etc\netbeans.conf
</code></pre>
<p>Change the following line to point it where your Java installation is:</p>
<pre class="lang-none prettyprint-override"><code>netbeans_jdkhome="C:\Program Files\Java\jdk1.7xxxxx"
</code></pre>
<p>You may need administrator privileges to edit <code>netbeans.conf</code>.</p> | {
"question_id": 6950960,
"question_date": "2011-08-05T03:06:27.453Z",
"question_score": 223,
"tags": "java|netbeans",
"answer_id": 6958342,
"answer_date": "2011-08-05T14:57:30.717Z",
"answer_score": 393
} |
Please answer the following Stack Overflow question:
Title: How to change the decimal separator of DecimalFormat from comma to dot/point?
<p>I have this little crazy method that converts BigDecimal values into nice and readable Strings.</p>
<pre><code>private String formatBigDecimal(BigDecimal bd){
DecimalFormat df = new DecimalFormat();
df.setMinimumFractionDigits(3);
df.setMaximumFractionDigits(3);
df.setMinimumIntegerDigits(1);
df.setMaximumIntegerDigits(3);
df.setGroupingSize(20);
return df.format(bd);
}
</code></pre>
<p>It however, also produces a so called grouping separator <code>","</code> that makes all my values come out like this:</p>
<pre><code>xxx,xxx
</code></pre>
<p>I do need the separator to be a dot or a point and not a comma.
Does anybody have a clue of how to accomplish this little feat?</p>
<p>I have read <a href="http://developer.android.com/reference/java/math/BigDecimal.html">this</a> and in particular <a href="http://developer.android.com/reference/java/text/DecimalFormat.html">this</a> to death now but I cannot find a way to get this done.
Am I approaching this the wrong way? Is there a much more elegant way of doing this? Maybe even a solution that accounts for different local number representations, since the comma would be perfect by European standards.</p> | <p>You can change the separator either by setting a locale or using the <a href="http://download.oracle.com/javase/7/docs/api/java/text/DecimalFormatSymbols.html" rel="noreferrer">DecimalFormatSymbols</a>.</p>
<p>If you want the grouping separator to be a point, you can use an european locale:</p>
<pre><code>NumberFormat nf = NumberFormat.getNumberInstance(Locale.GERMAN);
DecimalFormat df = (DecimalFormat)nf;
</code></pre>
<p>Alternatively you can use the DecimalFormatSymbols class to change the symbols that appear in the formatted numbers produced by the format method. These symbols include the decimal separator, the grouping separator, the minus sign, and the percent sign, among others:</p>
<pre><code>DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(currentLocale);
otherSymbols.setDecimalSeparator(',');
otherSymbols.setGroupingSeparator('.');
DecimalFormat df = new DecimalFormat(formatString, otherSymbols);
</code></pre>
<p><em>currentLocale</em> can be obtained from Locale.getDefault() i.e.:</p>
<pre><code>Locale currentLocale = Locale.getDefault();
</code></pre> | {
"question_id": 5054132,
"question_date": "2011-02-19T23:11:23.863Z",
"question_score": 223,
"tags": "java|android|bigdecimal|decimal-point|decimalformat",
"answer_id": 5054217,
"answer_date": "2011-02-19T23:33:48.180Z",
"answer_score": 372
} |
Please answer the following Stack Overflow question:
Title: Python Pandas - Find difference between two data frames
<p>I have two data frames df1 and df2, where df2 is a subset of df1. How do I get a new data frame (df3) which is the difference between the two data frames?</p>
<p>In other word, a data frame that has all the rows/columns in df1 that are not in df2?</p>
<p><a href="https://i.stack.imgur.com/aOCGb.png" rel="noreferrer"><img src="https://i.stack.imgur.com/aOCGb.png" alt="enter image description here"></a></p> | <p>By using <code>drop_duplicates</code></p>
<pre><code>pd.concat([df1,df2]).drop_duplicates(keep=False)
</code></pre>
<hr />
<p><strong><code>Update :</code></strong></p>
<blockquote>
<p><strong><code>The above method only works for those data frames that don't already have duplicates themselves. For example:</code></strong></p>
</blockquote>
<pre><code>df1=pd.DataFrame({'A':[1,2,3,3],'B':[2,3,4,4]})
df2=pd.DataFrame({'A':[1],'B':[2]})
</code></pre>
<p>It will output like below , which is wrong</p>
<blockquote>
<p>Wrong Output :</p>
</blockquote>
<pre><code>pd.concat([df1, df2]).drop_duplicates(keep=False)
Out[655]:
A B
1 2 3
</code></pre>
<blockquote>
<p>Correct Output</p>
</blockquote>
<pre><code>Out[656]:
A B
1 2 3
2 3 4
3 3 4
</code></pre>
<hr />
<blockquote>
<p>How to achieve that?</p>
</blockquote>
<p>Method 1: Using <code>isin</code> with <code>tuple</code></p>
<pre><code>df1[~df1.apply(tuple,1).isin(df2.apply(tuple,1))]
Out[657]:
A B
1 2 3
2 3 4
3 3 4
</code></pre>
<p>Method 2: <code>merge</code> with <code>indicator</code></p>
<pre><code>df1.merge(df2,indicator = True, how='left').loc[lambda x : x['_merge']!='both']
Out[421]:
A B _merge
1 2 3 left_only
2 3 4 left_only
3 3 4 left_only
</code></pre> | {
"question_id": 48647534,
"question_date": "2018-02-06T16:25:41.793Z",
"question_score": 223,
"tags": "python|pandas|dataframe",
"answer_id": 48647840,
"answer_date": "2018-02-06T16:39:36.440Z",
"answer_score": 282
} |
Please answer the following Stack Overflow question:
Title: How can I enable cURL for an installed Ubuntu LAMP stack?
<p>I have installed the Ubuntu LAMP stack. But cURL is not enabled, and neither can I can find the extension listed in the INI file. I added it manually, but it didn't work either.</p>
<p>How should I enable cURL then?</p> | <p>From <em><a href="http://buzznol.blogspot.com/2008/12/install-curl-extension-for-php-in.html" rel="noreferrer">Install Curl Extension for PHP in Ubuntu</a></em>:</p>
<pre><code>sudo apt-get install php5-curl
</code></pre>
<p>After installing libcurl, you should restart the web server with one of the following commands,</p>
<pre><code>sudo /etc/init.d/apache2 restart
</code></pre>
<p><em>or</em></p>
<pre><code>sudo service apache2 restart
</code></pre> | {
"question_id": 2939820,
"question_date": "2010-05-30T18:33:48.157Z",
"question_score": 223,
"tags": "php|ubuntu|curl|lamp",
"answer_id": 2939827,
"answer_date": "2010-05-30T18:36:56.787Z",
"answer_score": 429
} |
Please answer the following Stack Overflow question:
Title: Verifying that a string contains only letters in C#
<p>I have an input string and I want to verify that it contains:</p>
<ul>
<li>Only letters or</li>
<li>Only letters and numbers or</li>
<li>Only letters, numbers or underscore </li>
</ul>
<p>To clarify, I have 3 different cases in the code, each calling for different validation. What's the simplest way to achieve this in C#?</p> | <p>Only letters: </p>
<pre><code>Regex.IsMatch(input, @"^[a-zA-Z]+$");
</code></pre>
<p>Only letters and numbers: </p>
<pre><code>Regex.IsMatch(input, @"^[a-zA-Z0-9]+$");
</code></pre>
<p>Only letters, numbers and underscore: </p>
<pre><code>Regex.IsMatch(input, @"^[a-zA-Z0-9_]+$");
</code></pre> | {
"question_id": 1181419,
"question_date": "2009-07-25T06:50:36.430Z",
"question_score": 223,
"tags": "c#|string",
"answer_id": 1181426,
"answer_date": "2009-07-25T06:57:29.770Z",
"answer_score": 342
} |
Please answer the following Stack Overflow question:
Title: String is immutable. What exactly is the meaning?
<p>I wrote the following code on immutable Strings.</p>
<pre><code>public class ImmutableStrings {
public static void main(String[] args) {
testmethod();
}
private static void testmethod() {
String a = "a";
System.out.println("a 1-->" + a);
a = "ty";
System.out.println("a 2-->" + a);
}
}
</code></pre>
<p>Output:</p>
<pre><code>a 1-->a
a 2-->ty
</code></pre>
<p>Here the value of variable <code>a</code> has been changed (while many say that contents of the immutable objects cannot be changed). But what exactly does one mean by saying <strong><code>String</code> is immutable</strong>? Could you please clarify this topic for me?</p>
<p>source : <a href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html" rel="noreferrer">https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html</a></p> | <p>Before proceeding further with the fuss of <em>immutability</em>, let's just take a look into the <code>String</code> class and its functionality a little before coming to any conclusion.</p>
<p>This is how <code>String</code> works:</p>
<pre><code>String str = "knowledge";
</code></pre>
<p>This, as usual, creates a string containing <code>"knowledge"</code> and assigns it a reference <code>str</code>. Simple enough? Lets perform some more functions:</p>
<pre><code> String s = str; // assigns a new reference to the same string "knowledge"
</code></pre>
<p>Lets see how the below statement works:</p>
<pre><code> str = str.concat(" base");
</code></pre>
<p>This appends a string <code>" base"</code> to <code>str</code>. But wait, how is this possible, since <code>String</code> objects are immutable? Well to your surprise, it is.</p>
<p>When the above statement is executed, the VM takes the value of <code>String str</code>, i.e. <code>"knowledge"</code> and appends <code>" base"</code>, giving us the value <code>"knowledge base"</code>. Now, since <code>String</code>s are immutable, the VM can't assign this value to <code>str</code>, so it creates a new <code>String</code> object, gives it a value <code>"knowledge base"</code>, and gives it a reference <code>str</code>.</p>
<p>An important point to note here is that, while the <code>String</code> object is immutable, <strong>its reference variable is not.</strong> So that's why, in the above example, the reference was made to refer to a newly formed <code>String</code> object.</p>
<p>At this point in the example above, we have two <code>String</code> objects: the first one we created with value <code>"knowledge"</code>, pointed to by <code>s</code>, and the second one <code>"knowledge base"</code>, pointed to by <code>str</code>. But, technically, we have three <code>String</code> objects, the third one being the literal <code>"base"</code> in the <code>concat</code> statement.</p>
<h1>Important Facts about String and Memory usage</h1>
<p>What if we didn't have another reference <code>s</code> to <code>"knowledge"</code>? We would have lost that <code>String</code>. However, it still would have existed, but would be considered lost due to having no references.
Look at one more example below</p>
<pre><code>String s1 = "java";
s1.concat(" rules");
System.out.println("s1 refers to "+s1); // Yes, s1 still refers to "java"
</code></pre>
<p><strong>What's happening:</strong> </p>
<ol>
<li>The first line is pretty straightforward: create a new <code>String</code> <code>"java"</code> and refer <code>s1</code> to it.</li>
<li>Next, the VM creates another new <code>String</code> <code>"java rules"</code>, but nothing
refers to it. So, the second <code>String</code> is instantly lost. We can't reach
it.</li>
</ol>
<p>The reference variable <code>s1</code> still refers to the original <code>String</code> <code>"java"</code>.</p>
<p>Almost every method, applied to a <code>String</code> object in order to modify it, creates new <code>String</code> object. So, where do these <code>String</code> objects go? Well, <em>these exist in memory, and one of the key goals of any programming language is to make efficient use of memory.</em></p>
<p>As applications grow, <em>it's very common for <code>String</code> literals to occupy large area of memory, which can even cause redundancy.</em> So, in order to make Java more efficient, <strong>the JVM sets aside a special area of memory called the "String constant pool".</strong></p>
<p>When the compiler sees a <code>String</code> literal, it looks for the <code>String</code> in the pool. If a match is found, the reference to the new literal is directed to the existing <code>String</code> and no new <code>String</code> object is created. The existing <code>String</code> simply has one more reference. Here comes the point of making <code>String</code> objects immutable:</p>
<p>In the <code>String</code> constant pool, a <code>String</code> object is likely to have one or many references. <em>If several references point to same <code>String</code> without even knowing it, it would be bad if one of the references modified that <code>String</code> value. That's why <code>String</code> objects are immutable.</em></p>
<p>Well, now you could say, <em>what if someone overrides the functionality of <code>String</code> class?</em> That's the reason that <strong>the <code>String</code> class is marked <code>final</code></strong> so that nobody can override the behavior of its methods.</p> | {
"question_id": 8798403,
"question_date": "2012-01-10T04:04:14.470Z",
"question_score": 223,
"tags": "java|string|immutability",
"answer_id": 17942294,
"answer_date": "2013-07-30T08:45:51.207Z",
"answer_score": 465
} |
Please answer the following Stack Overflow question:
Title: How to check the extension of a filename in a bash script?
<p>I am writing a nightly build script in bash.<br>
Everything is fine and dandy except for one little snag:</p>
<pre><code>
#!/bin/bash
for file in "$PATH_TO_SOMEWHERE"; do
if [ -d $file ]
then
# do something directory-ish
else
if [ "$file" == "*.txt" ] # this is the snag
then
# do something txt-ish
fi
fi
done;
</code></pre>
<p>My problem is determining the file extension and then acting accordingly. I know the issue is in the if-statement, testing for a txt file. </p>
<p>How can I determine if a file has a .txt suffix?</p> | <p>I think you want to say "Are the last four characters of $file equal to <code>.txt</code>?" If so, you can use the following:</p>
<pre><code>if [ "${file: -4}" == ".txt" ]
</code></pre>
<p>Note that the space between <code>file:</code> and <code>-4</code> is required, as the ':-' modifier means something different.</p> | {
"question_id": 407184,
"question_date": "2009-01-02T15:46:04.010Z",
"question_score": 223,
"tags": "bash|scripting|file",
"answer_id": 407229,
"answer_date": "2009-01-02T15:59:50.020Z",
"answer_score": 300
} |
Please answer the following Stack Overflow question:
Title: Show current assembly instruction in GDB
<p>I'm doing some assembly-level debugging in GDB. Is there a way to get GDB to show me the current assembly instruction in the same way that it shows the current source line? The default output after every command looks like this:</p>
<pre><code>0x0001433f 990 Foo::bar(p);
</code></pre>
<p>This gives me the address of the current instruction, but I have to keep referring back to the output of <code>disassemble</code> in order to see which instruction I'm currently executing.</p> | <p>You can switch to assembly layout in GDB:</p>
<pre><code>(gdb) layout asm
</code></pre>
<p>See <a href="http://sourceware.org/gdb/current/onlinedocs/gdb/TUI-Commands.html#TUI-Commands" rel="noreferrer">here</a> for more information. The current assembly instruction will be shown in assembler window.</p>
<pre><code> ┌───────────────────────────────────────────────────────────────────────────┐
│0x7ffff740d756 <__libc_start_main+214> mov 0x39670b(%rip),%rax #│
│0x7ffff740d75d <__libc_start_main+221> mov 0x8(%rsp),%rsi │
│0x7ffff740d762 <__libc_start_main+226> mov 0x14(%rsp),%edi │
│0x7ffff740d766 <__libc_start_main+230> mov (%rax),%rdx │
│0x7ffff740d769 <__libc_start_main+233> callq *0x18(%rsp) │
>│0x7ffff740d76d <__libc_start_main+237> mov %eax,%edi │
│0x7ffff740d76f <__libc_start_main+239> callq 0x7ffff7427970 <exit> │
│0x7ffff740d774 <__libc_start_main+244> xor %edx,%edx │
│0x7ffff740d776 <__libc_start_main+246> jmpq 0x7ffff740d6b9 <__libc_start│
│0x7ffff740d77b <__libc_start_main+251> mov 0x39ca2e(%rip),%rax #│
│0x7ffff740d782 <__libc_start_main+258> ror $0x11,%rax │
│0x7ffff740d786 <__libc_start_main+262> xor %fs:0x30,%rax │
│0x7ffff740d78f <__libc_start_main+271> callq *%rax │
└───────────────────────────────────────────────────────────────────────────┘
multi-thre process 3718 In: __libc_start_main Line: ?? PC: 0x7ffff740d76d
#3 0x00007ffff7466eb5 in _IO_do_write () from /lib/x86_64-linux-gnu/libc.so.6
#4 0x00007ffff74671ff in _IO_file_overflow ()
from /lib/x86_64-linux-gnu/libc.so.6
#5 0x0000000000408756 in ?? ()
#6 0x0000000000403980 in ?? ()
#7 0x00007ffff740d76d in __libc_start_main ()
from /lib/x86_64-linux-gnu/libc.so.6
(gdb)
</code></pre> | {
"question_id": 1902901,
"question_date": "2009-12-14T19:17:22.870Z",
"question_score": 223,
"tags": "assembly|gdb",
"answer_id": 2015523,
"answer_date": "2010-01-06T19:19:23.360Z",
"answer_score": 367
} |
Please answer the following Stack Overflow question:
Title: How to upgrade docker-compose to latest version
<p>I have installed docker-compose using the command</p>
<p><code>sudo apt install docker-compose</code></p>
<p>It installed docker-compose version 1.8.0 and build unknown</p>
<p>I need the latest version of docker-compose or at least a version of 1.9.0</p>
<p>Can anyone please let me know what approach I should take to upgrade it or uninstall and re-install the latest version.</p>
<p>I have checked the docker website and can see that they are recommending this to install the latest version'</p>
<p><code>sudo curl -L https://github.com/docker/compose/releases/download/1.21.0/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compose</code></p>
<p>But before that, I have to uninstall the present version, which can be done using the command </p>
<p><code>sudo rm /usr/local/bin/docker-compose</code></p>
<p>but this can be used only when the installation was done using curl. I am not sure if the installation was done by curl as I have used </p>
<p><code>sudo apt install docker-compose</code></p>
<p>Please let me know what should I do now to uninstall and re-install the docker-compose.</p> | <p>First, <em>remove the old version</em>:</p>
<p>If installed via <strong>apt-get</strong></p>
<pre><code>sudo apt-get remove docker-compose
</code></pre>
<p>If installed via <strong>curl</strong></p>
<pre><code>sudo rm /usr/local/bin/docker-compose
</code></pre>
<p>If installed via <strong>pip</strong></p>
<pre><code>pip uninstall docker-compose
</code></pre>
<p>Then <em>find the newest version</em> on <a href="https://github.com/docker/compose/releases" rel="noreferrer">the release page at GitHub</a> or by curling the API and extracting the version from the response using <code>grep</code> or <code>jq</code> (thanks to <a href="https://stackoverflow.com/users/3794873/dragon788">dragon788</a>, <a href="https://stackoverflow.com/users/2071450/frbl">frbl</a>, and <a href="https://stackoverflow.com/users/11392333/saber-hayati">Saber Hayati</a> for these improvements):</p>
<pre><code># curl + grep
VERSION=$(curl --silent https://api.github.com/repos/docker/compose/releases/latest | grep -Po '"tag_name": "\K.*\d')
# curl + jq
VERSION=$(curl --silent https://api.github.com/repos/docker/compose/releases/latest | jq .name -r)
</code></pre>
<p>Finally, <em>download</em> to your favorite $PATH-accessible location and set permissions:</p>
<pre><code>DESTINATION=/usr/local/bin/docker-compose
sudo curl -L https://github.com/docker/compose/releases/download/${VERSION}/docker-compose-$(uname -s)-$(uname -m) -o $DESTINATION
sudo chmod 755 $DESTINATION
</code></pre> | {
"question_id": 49839028,
"question_date": "2018-04-15T06:12:29.040Z",
"question_score": 223,
"tags": "docker-compose|debian-based",
"answer_id": 49839172,
"answer_date": "2018-04-15T06:39:36.547Z",
"answer_score": 321
} |
Please answer the following Stack Overflow question:
Title: What is the difference between .text, .value, and .value2?
<p>What is the difference between <code>.text</code>, <code>.value</code>, and <code>.value2</code>? Such as when should target.text, target.value, and target.value2 be used?</p> | <p><code>.Text</code> gives you a string representing what is displayed on the screen for the cell. Using <code>.Text</code> is usually a bad idea because you could get <code>####</code></p>
<p><code>.Value2</code> gives you the underlying value of the cell (could be empty, string, error, number (double) or boolean)</p>
<p><code>.Value</code> gives you the same as <code>.Value2</code> except if the cell was formatted as currency or date it gives you a VBA currency (which may truncate decimal places) or VBA date.</p>
<p>Using <code>.Value</code> or <code>.Text</code> is usually a bad idea because you may not get the real value from the cell, and they are slower than <code>.Value2</code></p>
<p>For a more extensive discussion see my <a href="http://fastexcel.wordpress.com/2011/11/30/text-vs-value-vs-value2-slow-text-and-how-to-avoid-it/" rel="noreferrer">Text vs Value vs Value2</a></p> | {
"question_id": 17359835,
"question_date": "2013-06-28T07:51:16.320Z",
"question_score": 223,
"tags": "excel|vba",
"answer_id": 17363466,
"answer_date": "2013-06-28T11:17:34.877Z",
"answer_score": 290
} |
Please answer the following Stack Overflow question:
Title: How do you set EditText to only accept numeric values in Android?
<p>I have an <code>EditText</code> in which I want only integer values to be inserted. Can somebody tell me which property I have to use?</p> | <p>Add <a href="https://developer.android.com/reference/android/widget/TextView.html#attr_android:inputType" rel="noreferrer"><code>android:inputType="number"</code></a> as an XML attribute.</p> | {
"question_id": 4645119,
"question_date": "2011-01-10T09:06:11.743Z",
"question_score": 223,
"tags": "android|android-edittext",
"answer_id": 4645278,
"answer_date": "2011-01-10T09:28:01.330Z",
"answer_score": 418
} |
Please answer the following Stack Overflow question:
Title: "for" vs "each" in Ruby
<p>I just had a quick question regarding loops in Ruby. Is there a difference between these two ways of iterating through a collection?</p>
<pre><code># way 1
@collection.each do |item|
# do whatever
end
# way 2
for item in @collection
# do whatever
end
</code></pre>
<p>Just wondering if these are exactly the same or if maybe there's a subtle difference (possibly when <code>@collection</code> is nil).</p> | <p>This is the only difference:</p>
<p><strong>each:</strong></p>
<pre><code>irb> [1,2,3].each { |x| }
=> [1, 2, 3]
irb> x
NameError: undefined local variable or method `x' for main:Object
from (irb):2
from :0
</code></pre>
<p><strong>for:</strong></p>
<pre><code>irb> for x in [1,2,3]; end
=> [1, 2, 3]
irb> x
=> 3
</code></pre>
<p>With the <code>for</code> loop, the iterator variable still lives after the block is done. With the <code>each</code> loop, it doesn't, unless it was already defined as a local variable before the loop started.</p>
<p>Other than that, <code>for</code> is just syntax sugar for the <code>each</code> method.</p>
<p>When <code>@collection</code> is <code>nil</code> both loops throw an exception:</p>
<blockquote>
<p>Exception: undefined local variable or method `@collection' for main:Object</p>
</blockquote> | {
"question_id": 3294509,
"question_date": "2010-07-20T21:28:11.857Z",
"question_score": 223,
"tags": "ruby|loops|foreach|iteration|each",
"answer_id": 3294561,
"answer_date": "2010-07-20T21:35:16.680Z",
"answer_score": 331
} |
Please answer the following Stack Overflow question:
Title: How to perform update operations on columns of type JSONB in Postgres 9.4
<p>Looking through the documentation for the Postgres 9.4 datatype JSONB, it is not immediately obvious to me how to do updates on JSONB columns. </p>
<p>Documentation for JSONB types and functions: </p>
<p><a href="http://www.postgresql.org/docs/9.4/static/functions-json.html" rel="noreferrer">http://www.postgresql.org/docs/9.4/static/functions-json.html</a>
<a href="http://www.postgresql.org/docs/9.4/static/datatype-json.html" rel="noreferrer">http://www.postgresql.org/docs/9.4/static/datatype-json.html</a></p>
<p>As an examples, I have this basic table structure:</p>
<pre><code>CREATE TABLE test(id serial, data jsonb);
</code></pre>
<p>Inserting is easy, as in:</p>
<pre><code>INSERT INTO test(data) values ('{"name": "my-name", "tags": ["tag1", "tag2"]}');
</code></pre>
<p>Now, how would I update the 'data' column? This is invalid syntax:</p>
<pre><code>UPDATE test SET data->'name' = 'my-other-name' WHERE id = 1;
</code></pre>
<p>Is this documented somewhere obvious that I missed? Thanks. </p> | <p>Ideally, you don't use JSON documents for structured, regular data that you want to manipulate inside a relational database. Use a <strong>normalized relational design</strong> instead.</p>
<p>JSON is primarily intended to store whole documents that do not need to be manipulated inside the RDBMS. Related:</p>
<ul>
<li><a href="https://dba.stackexchange.com/questions/115825/jsonb-with-indexing-vs-hstore/115849#115849">JSONB with indexing vs. hstore</a></li>
</ul>
<p>Updating a row in Postgres always writes a new version of the <em>whole</em> row. That's the basic principle of <a href="https://www.postgresql.org/docs/current/mvcc-intro.html" rel="nofollow noreferrer">Postgres' MVCC model</a>. From a performance perspective, it hardly matters whether you change a single piece of data inside a JSON object or all of it: a new version of the row has to be written.</p>
<p>Thus the <a href="https://www.postgresql.org/docs/current/datatype-json.html#JSON-DOC-DESIGN" rel="nofollow noreferrer">advice in the manual</a>:</p>
<blockquote>
<p>JSON data is subject to the same concurrency-control considerations as
any other data type when stored in a table. Although storing large
documents is practicable, keep in mind that any update acquires a
row-level lock on the whole row. Consider limiting JSON documents to a
manageable size in order to decrease lock contention among updating
transactions. Ideally, JSON documents should each represent an atomic
datum that business rules dictate cannot reasonably be further
subdivided into smaller datums that could be modified independently.</p>
</blockquote>
<p>The gist of it: to modify <em>anything</em> inside a JSON object, you have to assign a modified object to the column. Postgres supplies limited means to build and manipulate <code>json</code> data in addition to its storage capabilities. The arsenal of tools has grown substantially with every new release since version 9.2. But the principal remains: You <em>always</em> have to assign a complete modified object to the column and Postgres always writes a new row version for any update.</p>
<p>Some techniques how to work with the tools of Postgres 9.3 or later:</p>
<ul>
<li><a href="https://stackoverflow.com/q/18209625/939860">How do I modify fields inside the new PostgreSQL JSON datatype?</a></li>
</ul>
<p>This answer has attracted about as many downvotes as all my other answers on SO <em>together</em>. People don't seem to like the idea: a normalized design is superior for regular data. This excellent blog post by Craig Ringer explains in more detail:</p>
<ul>
<li><a href="https://blog.2ndquadrant.com/postgresql-anti-patterns-unnecessary-jsonhstore-dynamic-columns/" rel="nofollow noreferrer">"PostgreSQL anti-patterns: Unnecessary json/hstore dynamic columns"</a></li>
</ul>
<p>Another blog post by Laurenz Albe, another <a href="https://www.postgresql.org/community/contributors/" rel="nofollow noreferrer">official Postgres contributor</a> like Craig and myself:</p>
<ul>
<li><a href="https://www.cybertec-postgresql.com/en/json-postgresql-how-to-use-it-right/" rel="nofollow noreferrer">JSON in PostgreSQL: how to use it right</a></li>
</ul> | {
"question_id": 26703476,
"question_date": "2014-11-02T19:37:24.470Z",
"question_score": 223,
"tags": "postgresql|sql-update|crud|postgresql-9.4|jsonb",
"answer_id": 26704636,
"answer_date": "2014-11-02T21:28:49.187Z",
"answer_score": 47
} |
Please answer the following Stack Overflow question:
Title: How to call a parent method from child class in javascript?
<p>I've spent the last couple of hours trying to find a solution to my problem but it seems to be hopeless.</p>
<p>Basically I need to know how to call a parent method from a child class.
All the stuff that I've tried so far ends up in either not working or over-writing the parent method.</p>
<p>I am using the following code to set up OOP in javascript:</p>
<pre><code>// SET UP OOP
// surrogate constructor (empty function)
function surrogateCtor() {}
function extend(base, sub) {
// copy the prototype from the base to setup inheritance
surrogateCtor.prototype = base.prototype;
sub.prototype = new surrogateCtor();
sub.prototype.constructor = sub;
}
// parent class
function ParentObject(name) {
this.name = name;
}
// parent's methods
ParentObject.prototype = {
myMethod: function(arg) {
this.name = arg;
}
}
// child
function ChildObject(name) {
// call the parent's constructor
ParentObject.call(this, name);
this.myMethod = function(arg) {
// HOW DO I CALL THE PARENT METHOD HERE?
// do stuff
}
}
// setup the prototype chain
extend(ParentObject, ChildObject);
</code></pre>
<p>I need to call the parent's method first and then add some more stuff to it in the child class.</p>
<p>In most OOP languages that would be as simple as calling <code>parent.myMethod()</code>
But I really cant grasp how its done in javascript.</p>
<p>Any help is much appreciated, thank you! </p> | <p>Here's how its done: <code>ParentClass.prototype.myMethod();</code></p>
<p>Or if you want to call it in the context of the current instance, you can do:
<code>ParentClass.prototype.myMethod.call(this)</code></p>
<p>Same goes for calling a parent method from child class with arguments:
<code>ParentClass.prototype.myMethod.call(this, arg1, arg2, ..)</code> * <em>Hint: use <code>apply()</code> instead of <code>call()</code> to pass arguments as an array.</em></p> | {
"question_id": 11854958,
"question_date": "2012-08-07T22:21:49.770Z",
"question_score": 223,
"tags": "javascript|oop|methods|parent",
"answer_id": 11855048,
"answer_date": "2012-08-07T22:29:19.310Z",
"answer_score": 237
} |
Please answer the following Stack Overflow question:
Title: Escaping single quote in PHP when inserting into MySQL
<p>I have a perplexing issue that I can't seem to comprehend...</p>
<p>I have two SQL statements:</p>
<ul>
<li>The first enters information from a form into the database.</li>
<li>The second takes data from the database entered above, sends an email, and then logs the details of the transaction</li>
</ul>
<p>The problem is that it appears that a single quote is triggering a MySQL error on the second entry only! The first instance works without issue, but the second instance triggers the <code>mysql_error()</code>.</p>
<p>Does the data from a form get handled differently from the data captured in a form?</p>
<p>Query 1 - This works without issue (and without escaping the single quote)</p>
<pre><code>$result = mysql_query("INSERT INTO job_log
(order_id, supplier_id, category_id, service_id, qty_ordered, customer_id, user_id, salesperson_ref, booking_ref, booking_name, address, suburb, postcode, state_id, region_id, email, phone, phone2, mobile, delivery_date, stock_taken, special_instructions, cost_price, cost_price_gst, sell_price, sell_price_gst, ext_sell_price, retail_customer, created, modified, log_status_id)
VALUES
('$order_id', '$supplier_id', '$category_id', '{$value['id']}', '{$value['qty']}', '$customer_id', '$user_id', '$salesperson_ref', '$booking_ref', '$booking_name', '$address', '$suburb', '$postcode', '$state_id', '$region_id', '$email', '$phone', '$phone2', '$mobile', STR_TO_DATE('$delivery_date', '%d/%m/%Y'), '$stock_taken', '$special_instructions', '$cost_price', '$cost_price_gst', '$sell_price', '$sell_price_gst', '$ext_sell_price', '$retail_customer', '".date('Y-m-d H:i:s', time())."', '".date('Y-m-d H:i:s', time())."', '1')");
</code></pre>
<p>Query 2 - This fails when entering a name with a single quote (for example, <em>O'Brien</em>)</p>
<pre><code>$query = mysql_query("INSERT INTO message_log
(order_id, timestamp, message_type, email_from, supplier_id, primary_contact, secondary_contact, subject, message_content, status)
VALUES
('$order_id', '".date('Y-m-d H:i:s', time())."', '$email', '$from', '$row->supplier_id', '$row->primary_email' ,'$row->secondary_email', '$subject', '$message_content', '1')");
</code></pre> | <p>You should be escaping each of these strings (in both snippets) with <code>mysql_real_escape_string()</code>.</p>
<p><a href="http://us3.php.net/mysql-real-escape-string" rel="noreferrer">http://us3.php.net/mysql-real-escape-string</a></p>
<p>The reason your two queries are behaving differently is likely because you have <code>magic_quotes_gpc</code> turned on (which you should know is a bad idea). This means that strings gathered from $_GET, $_POST and $_COOKIES are escaped for you (i.e., <code>"O'Brien" -> "O\'Brien"</code>).</p>
<p>Once you store the data, and subsequently retrieve it again, the string you get back from the database will <em>not</em> be automatically escaped for you. You'll get back <code>"O'Brien"</code>. So, you will need to pass it through <code>mysql_real_escape_string()</code>.</p> | {
"question_id": 2687866,
"question_date": "2010-04-22T02:25:33.393Z",
"question_score": 223,
"tags": "php|mysql|insert|escaping",
"answer_id": 2687891,
"answer_date": "2010-04-22T02:32:35.913Z",
"answer_score": 158
} |
Please answer the following Stack Overflow question:
Title: In Python, how do I iterate over a dictionary in sorted key order?
<p>There's an existing function that ends in the following, where <code>d</code> is a dictionary:</p>
<pre><code>return d.iteritems()
</code></pre>
<p>that returns an unsorted iterator for a given dictionary. I would like to return an iterator that goes through the items sorted <em>by key</em>. How do I do that?</p> | <p>Haven't tested this very extensively, but works in Python 2.5.2.</p>
<pre><code>>>> d = {"x":2, "h":15, "a":2222}
>>> it = iter(sorted(d.iteritems()))
>>> it.next()
('a', 2222)
>>> it.next()
('h', 15)
>>> it.next()
('x', 2)
>>>
</code></pre>
<p>If you are used to doing <code>for key, value in d.iteritems(): ...</code> instead of iterators, this will still work with the solution above</p>
<pre><code>>>> d = {"x":2, "h":15, "a":2222}
>>> for key, value in sorted(d.iteritems()):
>>> print(key, value)
('a', 2222)
('h', 15)
('x', 2)
>>>
</code></pre>
<p>With Python 3.x, use <code>d.items()</code> instead of <code>d.iteritems()</code> to return an iterator.</p> | {
"question_id": 364519,
"question_date": "2008-12-12T23:57:05.143Z",
"question_score": 223,
"tags": "python|sorting|dictionary",
"answer_id": 364599,
"answer_date": "2008-12-13T00:49:38.063Z",
"answer_score": 182
} |
Please answer the following Stack Overflow question:
Title: How do I mock an autowired @Value field in Spring with Mockito?
<p>I'm using Spring 3.1.4.RELEASE and Mockito 1.9.5. In my Spring class I have:</p>
<pre><code>@Value("#{myProps['default.url']}")
private String defaultUrl;
@Value("#{myProps['default.password']}")
private String defaultrPassword;
// ...
</code></pre>
<p>From my JUnit test, which I currently have set up like so:</p>
<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:test-context.xml" })
public class MyTest
{
</code></pre>
<p>I would like to mock a value for my "defaultUrl" field. Note that I don't want to mock values for the other fields — I'd like to keep those as they are, only the "defaultUrl" field. Also note that I have no explicit "setter" methods (e.g. <code>setDefaultUrl</code>) in my class and I don't want to create any just for the purposes of testing.</p>
<p>Given this, how can I mock a value for that one field?</p> | <p>You can use the magic of Spring's <code>ReflectionTestUtils.setField</code> in order to avoid making any modifications whatsoever to your code.</p>
<p>The comment from <a href="https://stackoverflow.com/users/7974082/micha%c5%82-stochmal">Michał Stochmal</a> provides an example:</p>
<blockquote>
<p>use <code>ReflectionTestUtils.setField(bean, "fieldName", "value");</code> before invoking your <code>bean</code> method during test.</p>
</blockquote>
<p>Check out <a href="http://www.briandupreez.net/2011/04/little-spring-gem-reflectiontestutils.html" rel="noreferrer">this</a> tutorial for even more information, although you probably won't need it since the method is very easy to use</p>
<p><strong>UPDATE</strong></p>
<p>Since the introduction of Spring 4.2.RC1 it is now possible to set a static field without having to supply an instance of the class. See <a href="https://docs.spring.io/spring-framework/docs/4.2.x/spring-framework-reference/htmlsingle/#_testing_improvements_3" rel="noreferrer">this</a> part of the documentation and <a href="https://github.com/spring-projects/spring-framework/commit/063ef240c185fe6ba2ed39ef2fc6767c7a8dd900" rel="noreferrer">this</a> commit.</p> | {
"question_id": 23162777,
"question_date": "2014-04-18T21:36:37.710Z",
"question_score": 223,
"tags": "spring|mockito|autowired|value-initialization",
"answer_id": 23162797,
"answer_date": "2014-04-18T21:38:44.013Z",
"answer_score": 248
} |
Please answer the following Stack Overflow question:
Title: How to assert two list contain the same elements in Python?
<p>When writing test cases, I often need to assert that two list contain the same elements without regard to their order.</p>
<p>I have been doing this by converting the lists to sets.</p>
<p>Is there any simpler way to do this?</p>
<p><strong>EDIT</strong>:</p>
<p>As @MarkDickinson pointed out, I can just use <a href="http://docs.python.org/library/unittest.html#unittest.TestCase.assertItemsEqual" rel="noreferrer">TestCase.assertItemsEqual</a>.</p>
<p>Notes that <code>TestCase.assertItemsEqual</code> is new in Python2.7.
If you are using an older version of Python, you can use <a href="http://pypi.python.org/pypi/unittest2" rel="noreferrer">unittest2</a> - a backport of new features of Python 2.7.</p> | <p>As of Python 3.2 <code>unittest.TestCase.assertItemsEqual</code>(<a href="https://docs.python.org/2/library/unittest.html#unittest.TestCase.assertItemsEqual" rel="noreferrer">doc</a>) has been replaced by <code>unittest.TestCase.assertCountEqual</code>(<a href="https://docs.python.org/3.2/library/unittest.html#unittest.TestCase.assertCountEqual" rel="noreferrer">doc</a>) which does exactly what you are looking for, as you can read from the python <a href="https://docs.python.org/3.2/library/unittest.html" rel="noreferrer">standard library documentation</a>. The method is somewhat misleadingly named but it does exactly what you are looking for.</p>
<blockquote>
<p>a and b have the same elements in the same number, regardless of their order</p>
</blockquote>
<p>Here a simple example which compares two lists having the same elements but in a different order.</p>
<ul>
<li>using <code>assertCountEqual</code> the test will succeed</li>
<li>using <code>assertListEqual</code> the test will fail due to the order difference of the two lists</li>
</ul>
<p>Here a little example script.</p>
<pre><code>import unittest
class TestListElements(unittest.TestCase):
def setUp(self):
self.expected = ['foo', 'bar', 'baz']
self.result = ['baz', 'foo', 'bar']
def test_count_eq(self):
"""Will succeed"""
self.assertCountEqual(self.result, self.expected)
def test_list_eq(self):
"""Will fail"""
self.assertListEqual(self.result, self.expected)
if __name__ == "__main__":
unittest.main()
</code></pre>
<p><strong>Side Note :</strong> Please make sure that the elements in the lists you are comparing are sortable.</p> | {
"question_id": 12813633,
"question_date": "2012-10-10T06:56:45.183Z",
"question_score": 223,
"tags": "python|unit-testing",
"answer_id": 31832447,
"answer_date": "2015-08-05T12:24:32.767Z",
"answer_score": 227
} |
Please answer the following Stack Overflow question:
Title: Ruby on Rails - Import Data from a CSV file
<p>I would like to import data from a CSV file into an existing database table. I do not want to save the CSV file, just take the data from it and put it into the existing table. I am using Ruby 1.9.2 and Rails 3.</p>
<p>This is my table:</p>
<pre><code>create_table "mouldings", :force => true do |t|
t.string "suppliers_code"
t.datetime "created_at"
t.datetime "updated_at"
t.string "name"
t.integer "supplier_id"
t.decimal "length", :precision => 3, :scale => 2
t.decimal "cost", :precision => 4, :scale => 2
t.integer "width"
t.integer "depth"
end
</code></pre>
<p>Can you give me some code to show me the best way to do this, thanks.</p> | <pre><code>require 'csv'
csv_text = File.read('...')
csv = CSV.parse(csv_text, :headers => true)
csv.each do |row|
Moulding.create!(row.to_hash)
end
</code></pre> | {
"question_id": 4410794,
"question_date": "2010-12-10T16:08:57.683Z",
"question_score": 223,
"tags": "ruby-on-rails|csv|import",
"answer_id": 4410880,
"answer_date": "2010-12-10T16:15:50.930Z",
"answer_score": 408
} |
Please answer the following Stack Overflow question:
Title: H2 in-memory database. Table not found
<p>I've got a H2 database with URL <code>"jdbc:h2:test"</code>. I create a table using <code>CREATE TABLE PERSON (ID INT PRIMARY KEY, FIRSTNAME VARCHAR(64), LASTNAME VARCHAR(64));</code>. I then select everything from this (empty) table using <code>SELECT * FROM PERSON</code>. So far, so good.</p>
<p>However, if I change the URL to <code>"jdbc:h2:mem:test"</code>, the only difference being the database is now in memory only, this gives me an <code>org.h2.jdbc.JdbcSQLException: Table "PERSON" not found; SQL statement: SELECT * FROM PERSON [42102-154]</code>. I'm probably missing something simple here, but any help would be appreciated.</p> | <h1><code>DB_CLOSE_DELAY=-1</code></h1>
<p>hbm2ddl closes the connection after creating the table, so h2 discards it.</p>
<p>If you have your connection-url configured like this</p>
<pre><code>jdbc:h2:mem:test
</code></pre>
<p>the content of the database is lost at the moment the last connection is closed.</p>
<p>If you want to keep your content you have to configure the url like this</p>
<pre><code>jdbc:h2:mem:test;DB_CLOSE_DELAY=-1
</code></pre>
<p>If doing so, <strong>h2</strong> will keep its content as long as the <strong>vm</strong> lives.</p>
<p>Notice the semicolon (<code>;</code>) rather than colon (<code>:</code>).</p>
<p>See the <a href="http://h2database.com/html/features.html#in_memory_databases" rel="noreferrer"><em>In-Memory Databases</em></a> section of the <em>Features</em> page. To quote:</p>
<blockquote>
<p>By default, closing the last connection to a database closes the database. For an in-memory database, this means the content is lost. To keep the database open, add <code>;DB_CLOSE_DELAY=-1</code> to the database URL. To keep the content of an in-memory database as long as the virtual machine is alive, use <code>jdbc:h2:mem:test;DB_CLOSE_DELAY=-1</code>.</p>
</blockquote> | {
"question_id": 5763747,
"question_date": "2011-04-23T10:51:30.313Z",
"question_score": 223,
"tags": "java|database|h2",
"answer_id": 5936988,
"answer_date": "2011-05-09T12:39:09.510Z",
"answer_score": 401
} |
Please answer the following Stack Overflow question:
Title: jQuery - Detecting if a file has been selected in the file input
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/1299052/jquery-get-the-file-name-selected-from-input-type-file">jQuery: get the file name selected from <input type=“file” /></a> </p>
</blockquote>
<p>I have a standard file input box</p>
<pre><code><input type="file" name="imafile">
</code></pre>
<p>I also have a bit of text down the page like so</p>
<pre><code><span class="filename">Nothing selected</span>
</code></pre>
<p>I was wondering if it is possible to have the text update with the name of the file selected in the file input box?</p>
<p>Cheers,</p> | <p>You should be able to attach an event handler to the onchange event of the input and have that call a function to set the text in your span.</p>
<pre><code><script type="text/javascript">
$(function() {
$("input:file").change(function (){
var fileName = $(this).val();
$(".filename").html(fileName);
});
});
</script>
</code></pre>
<p>You may want to add IDs to your input and span so you can select based on those to be specific to the elements you are concerned with and not other file inputs or spans in the DOM.</p> | {
"question_id": 5670769,
"question_date": "2011-04-14T23:13:32.397Z",
"question_score": 223,
"tags": "jquery",
"answer_id": 5670938,
"answer_date": "2011-04-14T23:42:12.613Z",
"answer_score": 336
} |
Please answer the following Stack Overflow question:
Title: How can I make a ComboBox non-editable in .NET?
<p>I want to have a "select-only" <code>ComboBox</code> that provides a list of items for the user to select from. Typing should be disabled in the text portion of the <code>ComboBox</code> control.</p>
<p>My initial googling of this turned up an overly complex, misguided suggestion to capture the <code>KeyPress</code> event.</p> | <p>To make the text portion of a ComboBox non-editable, set the DropDownStyle property to "DropDownList". The ComboBox is now essentially select-only for the user. You can do this in the Visual Studio designer, or in C# like this:</p>
<pre><code>stateComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
</code></pre>
<p>Link to the documentation for the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.dropdownstyle.aspx" rel="noreferrer">ComboBox DropDownStyle property</a> on MSDN.</p> | {
"question_id": 85702,
"question_date": "2008-09-17T17:37:52.200Z",
"question_score": 223,
"tags": "c#|.net|winforms|combobox",
"answer_id": 85706,
"answer_date": "2008-09-17T17:38:14.650Z",
"answer_score": 413
} |
Please answer the following Stack Overflow question:
Title: 'this' implicitly has type 'any' because it does not have a type annotation
<p>When I enable <code>noImplicitThis</code> in <code>tsconfig.json</code>, I get this error for the following code:</p>
<blockquote>
<pre><code>'this' implicitly has type 'any' because it does not have a type annotation.
</code></pre>
</blockquote>
<pre><code>class Foo implements EventEmitter {
on(name: string, fn: Function) { }
emit(name: string) { }
}
const foo = new Foo();
foo.on('error', function(err: any) {
console.log(err);
this.emit('end'); // error: `this` implicitly has type `any`
});
</code></pre>
<p>Adding a typed <code>this</code> to the callback parameters results in the same error:</p>
<pre><code>foo.on('error', (this: Foo, err: any) => { // error: `this` implicitly has type `any`
</code></pre>
<p>A workaround is to replace <code>this</code> with the object:</p>
<pre><code>foo.on('error', (err: any) => {
console.log(err);
foo.emit('end');
});
</code></pre>
<p>But what is the proper fix for this error?</p>
<hr>
<p><strong>UPDATE:</strong> It turns out adding a typed <code>this</code> to the callback indeed addresses the error. I was seeing the error because I was using an arrow function with a type annotation for <code>this</code>:</p>
<p><a href="https://i.stack.imgur.com/k4dmb.png" rel="noreferrer"><img src="https://i.stack.imgur.com/k4dmb.png" alt="typescript playground"></a></p> | <p>The error is indeed fixed by inserting <code>this</code> with a type annotation as the first callback parameter. My attempt to do that was botched by simultaneously changing the callback into an arrow-function:</p>
<pre><code>foo.on('error', (this: Foo, err: any) => { // DON'T DO THIS
</code></pre>
<p>It should've been this:</p>
<pre><code>foo.on('error', function(this: Foo, err: any) {
</code></pre>
<p>or this:</p>
<pre><code>foo.on('error', function(this: typeof foo, err: any) {
</code></pre>
<hr>
<p>A GitHub <a href="https://github.com/Microsoft/TypeScript/issues/13768" rel="noreferrer">issue</a> was created to improve the compiler's error message and highlight the actual grammar error with <code>this</code> and arrow-functions.</p> | {
"question_id": 41944650,
"question_date": "2017-01-30T20:16:19.583Z",
"question_score": 223,
"tags": "typescript|typescript2.0",
"answer_id": 41945742,
"answer_date": "2017-01-30T21:31:05.990Z",
"answer_score": 239
} |
Please answer the following Stack Overflow question:
Title: MySQL - length() vs char_length()
<p>What's the main difference between <code>length()</code> and <code>char_length()</code>?</p>
<p>I believe it has something to do with binary and non-binary strings. Is there any practical reason to store strings as binary?</p>
<pre><code>mysql> select length('MySQL'), char_length('MySQL');
+-----------------+----------------------+
| length('MySQL') | char_length('MySQL') |
+-----------------+----------------------+
| 5 | 5 |
+-----------------+----------------------+
1 row in set (0.01 sec)
</code></pre> | <p><code>LENGTH()</code> returns the length of the <strong>string measured in bytes</strong>. <br>
<code>CHAR_LENGTH()</code> returns the length of the <strong>string measured in characters</strong>.</p>
<p>This is especially relevant for Unicode, in which most characters are encoded in two bytes. Or UTF-8, where the number of bytes varies. For example:</p>
<pre><code>select length(_utf8 '€'), char_length(_utf8 '€')
--> 3, 1
</code></pre>
<p>As you can see the Euro sign occupies 3 bytes (it's encoded as <code>0xE282AC</code> in UTF-8) even though it's only one character.</p> | {
"question_id": 1734334,
"question_date": "2009-11-14T14:12:31.827Z",
"question_score": 223,
"tags": "mysql|string",
"answer_id": 1734340,
"answer_date": "2009-11-14T14:14:29.157Z",
"answer_score": 366
} |
Please answer the following Stack Overflow question:
Title: event.returnValue is deprecated. Please use the standard event.preventDefault() instead
<p>I have this script:</p>
<pre><code><script>
$(document).ready(function () {
$("#changeResumeStatus").click(function () {
$.get("{% url 'main:changeResumeStatus' %}", function (data) {
if (data['message'] == 'hidden') {
$("#resumeStatus").text("скрыто");
} else {
$("#resumeStatus").text("опубликовано");
}
}, "json");
});
});
</script>
</code></pre>
<p>I receive the following error in my Google Chrome console: </p>
<blockquote>
<p>event.returnValue is deprecated. Please use the standard event.preventDefault() instead. </p>
</blockquote>
<p>I am using jQuery v1.10.2 and <code>#changeResumeStatus</code> is a <code><span></code>.</p>
<p>What's wrong with my script?</p> | <p>This is only a warning: your code still works, but probably won't work in the future as the method is deprecated. See the <a href="https://code.google.com/p/chromium/codesearch#chromium/src/third_party/WebKit/Source/core/frame/UseCounter.cpp&q=event.returnValue%20deprecated&sq=package:chromium&type=cs&l=673" rel="nofollow">relevant source of Chromium</a> and <a href="http://src.chromium.org/viewvc/blink/trunk/Source/core/frame/UseCounter.cpp?revision=156916" rel="nofollow">corresponding patch</a>.</p>
<p>This has already been recognised and fixed in jQuery 1.11 (see <a href="https://web.archive.org/web/20150905072429/http://bugs.jquery.com/ticket/14282" rel="nofollow">here</a> and <a href="https://web.archive.org/web/20150524010302/http://bugs.jquery.com/ticket/14320" rel="nofollow">here</a>).</p> | {
"question_id": 20045162,
"question_date": "2013-11-18T10:12:19.427Z",
"question_score": 223,
"tags": "javascript|jquery|ajax",
"answer_id": 20045473,
"answer_date": "2013-11-18T10:27:46.613Z",
"answer_score": 204
} |
Please answer the following Stack Overflow question:
Title: php Replacing multiple spaces with a single space
<p>I'm trying to replace multiple spaces with a single space. When I use <code>ereg_replace</code>, I get an error about it being deprecated.</p>
<pre><code>ereg_replace("[ \t\n\r]+", " ", $string);
</code></pre>
<p>Is there an identical replacement for it. I need to replace multiple <code>" "</code> white spaces and multiple <code>nbsp</code> white spaces with a single white space.</p> | <p>Use <a href="http://php.net/manual/en/function.preg-replace.php" rel="noreferrer"><code>preg_replace()</code></a> and instead of <code>[ \t\n\r]</code> use <code>\s</code>:</p>
<pre><code>$output = preg_replace('!\s+!', ' ', $input);
</code></pre>
<p>From <a href="http://www.regular-expressions.info/reference.html" rel="noreferrer">Regular Expression Basic Syntax Reference</a>:</p>
<blockquote>
<p>\d, \w and \s</p>
<p>Shorthand character classes matching
digits, word characters (letters,
digits, and underscores), and
whitespace (spaces, tabs, and line
breaks). Can be used inside and
outside character classes.</p>
</blockquote> | {
"question_id": 2368539,
"question_date": "2010-03-03T03:23:13.263Z",
"question_score": 223,
"tags": "php|regex|formatting|string-formatting|ereg-replace",
"answer_id": 2368546,
"answer_date": "2010-03-03T03:25:18.267Z",
"answer_score": 463
} |
Please answer the following Stack Overflow question:
Title: What does '<?=' mean in PHP?
<pre><code><?php
$a=1;
?>
<?=$a;?>
</code></pre>
<p>What does <code><?=</code> mean exactly?</p> | <p>It's a shorthand for <code><?php echo $a; ?></code>.</p>
<p>It's enabled by default <a href="https://www.php.net/ChangeLog-5.php#5.4.0" rel="noreferrer">since 5.4.0</a> regardless of <code>php.ini</code> settings.</p> | {
"question_id": 2020445,
"question_date": "2010-01-07T13:08:43.357Z",
"question_score": 223,
"tags": "php|syntax",
"answer_id": 2020452,
"answer_date": "2010-01-07T13:09:33.767Z",
"answer_score": 306
} |
Please answer the following Stack Overflow question:
Title: Download a working local copy of a webpage
<p>I would like to download a local copy of a web page and get all of the css, images, javascript, etc. </p>
<p>In previous discussions (e.g. <a href="https://stackoverflow.com/questions/706934/download-an-offline-version-of-a-webpage">here</a> and <a href="https://superuser.com/questions/130306/suggestions-for-a-site-ripper">here</a>, both of which are more than two years old), two suggestions are generally put forward: <code>wget -p</code> and <a href="http://www.httrack.com" rel="noreferrer">httrack</a>. However, these suggestions both fail. I would very much appreciate help with using either of these tools to accomplish the task; alternatives are also lovely. </p>
<p><br />
<strong>Option 1: <code>wget -p</code></strong></p>
<p><code>wget -p</code> successfully downloads all of the web page's prerequisites (css, images, js). However, when I load the local copy in a web browser, the page is unable to load the prerequisites because the paths to those prerequisites haven't been modified from the version on the web. </p>
<p>For example:</p>
<ul>
<li>In the page's html, <code><link rel="stylesheet href="/stylesheets/foo.css" /></code> will need to be corrected to point to the new relative path of <code>foo.css</code></li>
<li>In the css file, <code>background-image: url(/images/bar.png)</code> will similarly need to be adjusted.</li>
</ul>
<p>Is there a way to modify <code>wget -p</code> so that the paths are correct?</p>
<p><br />
<strong>Option 2: <a href="http://www.httrack.com" rel="noreferrer">httrack</a></strong></p>
<p><code>httrack</code> seems like a great tool for mirroring entire websites, but it's unclear to me how to use it to create a local copy of a single page. There is a great deal of discussion in the httrack forums about this topic (e.g. <a href="http://forum.httrack.com/readmsg/19088/index.html" rel="noreferrer">here</a>) but no one seems to have a bullet-proof solution.</p>
<p><br />
<strong>Option 3: another tool?</strong></p>
<p>Some people have suggested paid tools, but I just can't believe there isn't a free solution out there.</p> | <p>wget is capable of doing what you are asking. Just try the following:</p>
<pre><code>wget -p -k http://www.example.com/
</code></pre>
<p>The <code>-p</code> will get you all the required elements to view the site correctly (css, images, etc).
The <code>-k</code> will change all links (to include those for CSS & images) to allow you to view the page offline as it appeared online.</p>
<p>From the Wget docs:</p>
<pre><code>‘-k’
‘--convert-links’
After the download is complete, convert the links in the document to make them
suitable for local viewing. This affects not only the visible hyperlinks, but
any part of the document that links to external content, such as embedded images,
links to style sheets, hyperlinks to non-html content, etc.
Each link will be changed in one of the two ways:
The links to files that have been downloaded by Wget will be changed to refer
to the file they point to as a relative link.
Example: if the downloaded file /foo/doc.html links to /bar/img.gif, also
downloaded, then the link in doc.html will be modified to point to
‘../bar/img.gif’. This kind of transformation works reliably for arbitrary
combinations of directories.
The links to files that have not been downloaded by Wget will be changed to
include host name and absolute path of the location they point to.
Example: if the downloaded file /foo/doc.html links to /bar/img.gif (or to
../bar/img.gif), then the link in doc.html will be modified to point to
http://hostname/bar/img.gif.
Because of this, local browsing works reliably: if a linked file was downloaded,
the link will refer to its local name; if it was not downloaded, the link will
refer to its full Internet address rather than presenting a broken link. The fact
that the former links are converted to relative links ensures that you can move
the downloaded hierarchy to another directory.
Note that only at the end of the download can Wget know which links have been
downloaded. Because of that, the work done by ‘-k’ will be performed at the end
of all the downloads.
</code></pre> | {
"question_id": 6348289,
"question_date": "2011-06-14T18:32:32.470Z",
"question_score": 223,
"tags": "download|wget|offline-browsing",
"answer_id": 6510193,
"answer_date": "2011-06-28T16:54:29.790Z",
"answer_score": 284
} |
Please answer the following Stack Overflow question:
Title: Regex - Should hyphens be escaped?
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/4068629/how-to-match-hyphens-with-regular-expression">How to match hyphens with Regular Expression?</a> </p>
</blockquote>
<p>Hyphen is a special character in regex, for instance, to select a range, I could do something like: </p>
<pre><code>[0-9A-F]
</code></pre>
<p>But outside of square brackets it's just a regular character right? I've tested this on a couple of online regex testers, and hyphens seem to function as a normal character outside of square brackets (or even inside of square brackets if it's not in-between two characters - eg [-g] seems to match - or g) whether it's escaped or not. I couldn't find the answer to this, but I'm wondering whether or not it is conventional to escape hyphens.</p>
<p>Thanks!</p> | <p>Correct on all fronts. Outside of a character class (that's what the "square brackets" are called) the hyphen has no special meaning, and within a character class, you can place a hyphen as the first or last character in the range (e.g. <code>[-a-z]</code> or <code>[0-9-]</code>), <strong>OR</strong> escape it (e.g. <code>[a-z\-0-9]</code>) in order to add "hyphen" to your class.</p>
<p>It's more common to find a hyphen placed first or last within a character class, but by no means will you be lynched by hordes of furious neckbeards for choosing to escape it instead.</p>
<p>(Actually... my experience has been that a lot of regex is employed by folks who don't fully grok the syntax. In these cases, you'll typically see everything escaped (e.g. <code>[a-z\%\$\#\@\!\-\_]</code>) simply because the engineer doesn't know what's "special" and what's not... so they "play it safe" and obfuscate the expression with loads of excessive backslashes. You'll be doing yourself, your contemporaries, and your posterity a huge favor by taking the time to really understand regex syntax before using it.)</p>
<p>Great question!</p> | {
"question_id": 9589074,
"question_date": "2012-03-06T17:46:26.287Z",
"question_score": 223,
"tags": "regex",
"answer_id": 9589642,
"answer_date": "2012-03-06T18:25:03.523Z",
"answer_score": 331
} |
Please answer the following Stack Overflow question:
Title: Unable to obtain LocalDateTime from TemporalAccessor when parsing LocalDateTime (Java 8)
<p>I am simply trying to convert a date string into a DateTime object in Java 8. Upon running the following lines:</p>
<pre><code>DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDateTime dt = LocalDateTime.parse("20140218", formatter);
</code></pre>
<p>I get the following error:</p>
<pre><code>Exception in thread "main" java.time.format.DateTimeParseException:
Text '20140218' could not be parsed:
Unable to obtain LocalDateTime from TemporalAccessor:
{},ISO resolved to 2014-02-18 of type java.time.format.Parsed
at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1918)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1853)
at java.time.LocalDateTime.parse(LocalDateTime.java:492)
</code></pre>
<p>The syntax is identical to what has been suggested <a href="https://stackoverflow.com/questions/22463062/how-to-parse-format-dates-with-localdatetime-java-8">here</a>, yet I am served with an exception. I am using <code>JDK-8u25</code>.</p> | <p>It turns out Java does not accept a bare Date value as DateTime. Using LocalDate instead of LocalDateTime solves the issue:</p>
<pre><code>DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate dt = LocalDate.parse("20140218", formatter);
</code></pre> | {
"question_id": 27454025,
"question_date": "2014-12-13T00:04:04.020Z",
"question_score": 223,
"tags": "java|datetime|java-8|datetime-format",
"answer_id": 27454146,
"answer_date": "2014-12-13T00:20:20.870Z",
"answer_score": 241
} |
Please answer the following Stack Overflow question:
Title: Responsively change div size keeping aspect ratio
<p>When I give an image a percent width or height only it will grow/shrink keeping its aspect ratio, but if I want the same effect with another element, is it possible at all to tie the width and the height together using percentage?</p> | <p>You can do this using pure CSS; no JavaScript needed. This utilizes the (somewhat counterintuitive) fact that <a href="http://www.w3.org/TR/CSS21/box.html#propdef-padding-top" rel="noreferrer"><code>padding-top</code> percentages are relative to the containing block's <strong>width</strong></a>. Here's an 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-css lang-css prettyprint-override"><code>.wrapper {
width: 50%;
/* whatever width you want */
display: inline-block;
position: relative;
}
.wrapper:after {
padding-top: 56.25%;
/* 16:9 ratio */
display: block;
content: '';
}
.main {
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
/* fill parent */
background-color: deepskyblue;
/* let's see it! */
color: white;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
<div class="main">
This is your div with the specified aspect ratio.
</div>
</div></code></pre>
</div>
</div>
</p> | {
"question_id": 12121090,
"question_date": "2012-08-25T10:13:22.663Z",
"question_score": 223,
"tags": "html|css|responsive-design",
"answer_id": 12121309,
"answer_date": "2012-08-25T10:47:42.980Z",
"answer_score": 544
} |
Please answer the following Stack Overflow question:
Title: Creating stored procedure and SQLite?
<p>Is it somehow possible to create a stored procedure, when using SQLite?</p> | <blockquote>
<p>SQLite has had to sacrifice other characteristics that some people find useful, such as high concurrency, fine-grained access control, a rich set of built-in functions, <strong><em>stored procedures</em></strong>, esoteric SQL language features, XML and/or Java extensions, tera- or peta-byte scalability, and so forth</p>
</blockquote>
<p>Source : <a href="http://www.sqlite.org/whentouse.html" rel="noreferrer">Appropriate Uses For SQLite</a></p> | {
"question_id": 3335162,
"question_date": "2010-07-26T13:23:53.893Z",
"question_score": 223,
"tags": "sqlite|stored-procedures",
"answer_id": 3335202,
"answer_date": "2010-07-26T13:28:14.850Z",
"answer_score": 254
} |
Please answer the following Stack Overflow question:
Title: has_next in Python iterators?
<p>Haven't Python iterators got a <code>has_next</code> method?</p> | <p>No, there is no such method. The end of iteration is indicated by an exception. See the <a href="http://docs.python.org/library/stdtypes.html#iterator-types" rel="noreferrer">documentation</a>.</p> | {
"question_id": 1966591,
"question_date": "2009-12-27T18:04:51.250Z",
"question_score": 223,
"tags": "python|iterator",
"answer_id": 1966609,
"answer_date": "2009-12-27T18:08:52.380Z",
"answer_score": 149
} |
Please answer the following Stack Overflow question:
Title: Ruby/Rails: converting a Date to a UNIX timestamp
<p>How would I get a UNIX timestamp (number of seconds since 1970 GMT) from a Date object in a Rails app?</p>
<p>I know <code>Time#to_i</code> returns a timestamp, but doing <code>Date#to_time</code> and then getting the timestamp results in something that's off by about a month (not sure why...). </p>
<p>Any help is appreciated, thanks!</p>
<p>Edit: OK, I think I figured it out- I was processing a date several times in a loop, and each time the date was moved a little because of a time zone mismatch, ultimately leading to my timestamp being a month off. Still, I'd be interested in knowing if there's any way to do this without relying on <code>Date#to_time</code>.</p> | <p>The code <code>date.to_time.to_i</code> should work fine. The Rails console session below shows an example:</p>
<pre><code>>> Date.new(2009,11,26).to_time
=> Thu Nov 26 00:00:00 -0800 2009
>> Date.new(2009,11,26).to_time.to_i
=> 1259222400
>> Time.at(1259222400)
=> Thu Nov 26 00:00:00 -0800 2009
</code></pre>
<p>Note that the intermediate DateTime object is in local time, so the timestamp might be several hours off from what you expect. If you want to work in UTC time, you can use DateTime's method "utc".</p> | {
"question_id": 1805950,
"question_date": "2009-11-26T22:29:37.733Z",
"question_score": 223,
"tags": "ruby-on-rails|ruby|date|timestamp",
"answer_id": 1806007,
"answer_date": "2009-11-26T22:46:31.397Z",
"answer_score": 382
} |
Please answer the following Stack Overflow question:
Title: How to drop SQL default constraint without knowing its name?
<p>In Microsoft SQL Server, I know the query to check if a default constraint exists for a column and drop a default constraint is:</p>
<pre><code>IF EXISTS(SELECT * FROM sysconstraints
WHERE id=OBJECT_ID('SomeTable')
AND COL_NAME(id,colid)='ColName'
AND OBJECTPROPERTY(constid, 'IsDefaultCnst')=1)
ALTER TABLE SomeTable DROP CONSTRAINT DF_SomeTable_ColName
</code></pre>
<p>But due to typo in previous versions of the database, the name of the constraint could be <code>DF_SomeTable_ColName</code> or <code>DF_SmoeTable_ColName</code>.</p>
<p>How can I delete the default constraint without any SQL errors? Default constraint names don't show up in INFORMATION_SCHEMA table, which makes things a bit trickier.</p>
<p>So, something like 'delete the default constraint in this table/column', or 'delete <code>DF_SmoeTable_ColName</code>', but don't give any errors if it can't find it.</p> | <p>Expanding on Mitch Wheat's code, the following script will generate the command to drop the constraint and dynamically execute it.</p>
<pre><code>declare @schema_name nvarchar(256)
declare @table_name nvarchar(256)
declare @col_name nvarchar(256)
declare @Command nvarchar(1000)
set @schema_name = N'MySchema'
set @table_name = N'Department'
set @col_name = N'ModifiedDate'
select @Command = 'ALTER TABLE ' + @schema_name + '.[' + @table_name + '] DROP CONSTRAINT ' + d.name
from sys.tables t
join sys.default_constraints d on d.parent_object_id = t.object_id
join sys.columns c on c.object_id = t.object_id and c.column_id = d.parent_column_id
where t.name = @table_name
and t.schema_id = schema_id(@schema_name)
and c.name = @col_name
--print @Command
execute (@Command)
</code></pre> | {
"question_id": 1430456,
"question_date": "2009-09-16T01:20:54.620Z",
"question_score": 223,
"tags": "sql|sql-server|tsql",
"answer_id": 1433384,
"answer_date": "2009-09-16T14:37:07.040Z",
"answer_score": 293
} |
Please answer the following Stack Overflow question:
Title: In HTML5, should the main navigation be inside or outside the <header> element?
<p>In HTML5, I know that <code><nav></code> can be used either inside or outside the page's masthead <code><header></code> element. For websites having both secondary and main navigation, it seems common to include the secondary navigation as a <code><nav></code> element inside the masthead <code><header></code> element with the main navigation as a <code><nav></code> element outside the masthead <code><header></code> element. However, if the website lacks secondary navigation, it appears common to include the main navigation in a <code><nav></code> element within the masthead <code><header></code> element.</p>
<p>If I follow these examples, my content structure will be based on the inclusion or exclusion of secondary navigation. This introduces a coupling between the content and the style that feels unnecessary and unnatural.</p>
<p>Is there a better way so that I'm not moving the main navigation from inside to outside the masthead <code><header></code> element based on the inclusion or exclusion of secondary navigation?</p>
<h2>Main and Secondary Navigation Example</h2>
<pre><code><header>
<nav>
<!-- Secondary Navigation inside <header> -->
<ul>
<li></li>
</ul>
</nav>
<h1>Website Title</h1>
</header>
<nav>
<!-- Main Navigation outside <header> -->
<ul>
<li></li>
</ul>
</nav>
</code></pre>
<p><a href="http://onlinedegrees.org">OnlineDegrees.org</a> is an example site that follows the above pattern.</p>
<p><img src="https://i.stack.imgur.com/jolBc.png" alt="enter image description here"></p>
<h2>Main Only Navigation Example</h2>
<pre><code><header>
<h1>Website Title</h1>
<nav>
<!-- Main Navigation inside <header> -->
<ul>
<li></li>
</ul>
</nav>
</header>
</code></pre>
<p><a href="http://keyzo.co.uk/">Keyzo.co.uk</a> is an example site that follows the above pattern.</p>
<p><img src="https://i.stack.imgur.com/0JD0t.png" alt="enter image description here"></p>
<h2>Excerpts from <em>Introducing HTML5</em> — Added on 02-Feb-11, 7:38 AM</h2>
<p><a href="http://amzn.com/0321687299"><em>Introducing HTML5</em></a> by Bruce Lawson and Remy Sharp has this to say about the subject:</p>
<blockquote>
<p>The header can also contain navigation. This can be very useful for site-wide navigation, especially on template-driven sites where the whole of the <code><header></code> element could come from a template file.</p>
<p>Of course, it's not required that the <code><nav></code> be in the <code><header></code>.</p>
<p>If depends largely on whether you believe the site-wide navigation belongs in the site-wide header and also pragmatic considerations about ease of styling.</p>
</blockquote>
<p>Based on that last sentence, it appears that Bruce Lawson—author of the chapter those excerpts are from—admits that "pragmatic considerations about ease of styling" yield a coupling between the content and the style.</p> | <p>It's completely up to you. You can either put them in the header or not, as long as the elements within them are internal navigation elements only (i.e. don't link to external sites such as a twitter or facebook account) then it's fine.</p>
<p>They tend to get placed in a header simply because that's where navigation often goes, but it's not set in stone.</p>
<p>You can read more about it at <a href="http://html5doctor.com/nav-element/" rel="noreferrer">HTML5 Doctor</a>.</p> | {
"question_id": 4870955,
"question_date": "2011-02-02T05:03:15.927Z",
"question_score": 223,
"tags": "html",
"answer_id": 4872533,
"answer_date": "2011-02-02T09:12:05.917Z",
"answer_score": 119
} |
Please answer the following Stack Overflow question:
Title: How to programmatically send a 404 response with Express/Node?
<p>I want to simulate a 404 error on my Express/Node server. How can I do that?</p> | <p>Since Express 4.0, there's a dedicated <a href="https://expressjs.com/en/api.html#res.sendStatus" rel="noreferrer"><code>sendStatus</code> function</a>:</p>
<pre class="lang-js prettyprint-override"><code>res.sendStatus(404);
</code></pre>
<hr />
<p>If you're using an earlier version of Express, use the <a href="http://expressjs.com/en/api.html#res.status" rel="noreferrer"><code>status</code> function</a> instead.</p>
<pre class="lang-js prettyprint-override"><code>res.status(404).send('Not found');
</code></pre> | {
"question_id": 8393275,
"question_date": "2011-12-05T23:15:30.290Z",
"question_score": 223,
"tags": "javascript|node.js|express|http-status-codes",
"answer_id": 16438739,
"answer_date": "2013-05-08T10:49:35.587Z",
"answer_score": 327
} |
Please answer the following Stack Overflow question:
Title: How to assign an action for UIImageView object in Swift
<p>I'm trying to assign an <code>UIImageView</code> to an action when the user taps it.</p>
<p>I know how to create an action for a <code>UIButton</code>, but how could I mimic the same behavior of a <code>UIButton</code>, but using a <code>UIImageView</code>?</p> | <p>You'll need a <code>UITapGestureRecognizer</code>.
To set up use this:</p>
<pre><code>override func viewDidLoad()
{
super.viewDidLoad()
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
imageView.isUserInteractionEnabled = true
imageView.addGestureRecognizer(tapGestureRecognizer)
}
@objc func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
{
let tappedImage = tapGestureRecognizer.view as! UIImageView
// Your action
}
</code></pre>
<p>(You could also use a <code>UIButton</code> and assign an image to it, without text and than simply connect an <code>IBAction</code>)</p> | {
"question_id": 27880607,
"question_date": "2015-01-10T19:59:27.993Z",
"question_score": 223,
"tags": "ios|swift|uiimageview",
"answer_id": 27880669,
"answer_date": "2015-01-10T20:05:30.953Z",
"answer_score": 512
} |
Please answer the following Stack Overflow question:
Title: C++ equivalent of java's instanceof
<p>What is the preferred method to achieve the C++ equivalent of java's <code>instanceof</code>?</p> | <p>Try using:</p>
<pre><code>if(NewType* v = dynamic_cast<NewType*>(old)) {
// old was safely casted to NewType
v->doSomething();
}
</code></pre>
<p>This requires your compiler to have rtti support enabled.</p>
<p>EDIT:
I've had some good comments on this answer!</p>
<p>Every time you need to use a dynamic_cast (or instanceof) you'd better ask yourself whether it's a necessary thing. It's generally a sign of poor design. </p>
<p>Typical workarounds is putting the special behaviour for the class you are checking for into a virtual function on the base class or perhaps introducing something like a <a href="http://en.wikipedia.org/wiki/Visitor_pattern" rel="noreferrer">visitor</a> where you can introduce specific behaviour for subclasses without changing the interface (except for adding the visitor acceptance interface of course).</p>
<p>As pointed out dynamic_cast doesn't come for free. A simple and consistently performing hack that handles most (but not all cases) is basically adding an enum representing all the possible types your class can have and check whether you got the right one. </p>
<pre><code>if(old->getType() == BOX) {
Box* box = static_cast<Box*>(old);
// Do something box specific
}
</code></pre>
<p>This is not good oo design, but it can be a workaround and its cost is more or less only a virtual function call. It also works regardless of RTTI is enabled or not.</p>
<p>Note that this approach doesn't support multiple levels of inheritance so if you're not careful you might end with code looking like this:</p>
<pre><code>// Here we have a SpecialBox class that inherits Box, since it has its own type
// we must check for both BOX or SPECIAL_BOX
if(old->getType() == BOX || old->getType() == SPECIAL_BOX) {
Box* box = static_cast<Box*>(old);
// Do something box specific
}
</code></pre> | {
"question_id": 500493,
"question_date": "2009-02-01T09:32:48.990Z",
"question_score": 223,
"tags": "java|c++|oop|instanceof",
"answer_id": 500495,
"answer_date": "2009-02-01T09:34:33.930Z",
"answer_score": 214
} |
Please answer the following Stack Overflow question:
Title: Stop all active ajax requests in jQuery
<p>I have a problem, when submitting a form all active ajax request fail, and that triggers error event.</p>
<p>How to stop all active ajax requests in jQuery without trigerring error event?</p> | <p>Every time you create an ajax request you could use a variable to store it:</p>
<pre><code>var request = $.ajax({
type: 'POST',
url: 'someurl',
success: function(result){}
});
</code></pre>
<p>Then you can abort the request:</p>
<pre><code>request.abort();
</code></pre>
<p>You could use an array keeping track of all pending ajax requests and abort them if necessary.</p> | {
"question_id": 1802936,
"question_date": "2009-11-26T10:42:22.723Z",
"question_score": 223,
"tags": "jquery|ajax",
"answer_id": 1802948,
"answer_date": "2009-11-26T10:44:32.003Z",
"answer_score": 281
} |
Please answer the following Stack Overflow question:
Title: Android Preventing Double Click On A Button
<p>What is the best way to prevent double clicks on a button in Android? </p> | <p>Disable the button with <code>setEnabled(false)</code> until it is safe for the user to click it again.</p> | {
"question_id": 5608720,
"question_date": "2011-04-09T23:49:53.590Z",
"question_score": 223,
"tags": "android|android-button|double-click",
"answer_id": 5608757,
"answer_date": "2011-04-09T23:56:23.580Z",
"answer_score": 104
} |
Please answer the following Stack Overflow question:
Title: Why use @Scripts.Render("~/bundles/jquery")
<p>How does </p>
<pre><code>@Scripts.Render("~/bundles/jquery")
</code></pre>
<p>differ from just referencing the script from html like this</p>
<pre><code><script src="~/bundles/jquery.js" type="text/javascript"></script>
</code></pre>
<p>Are there any performance gains?</p> | <p>Bundling is all about compressing several JavaScript or stylesheets files without any formatting (also referred as minified) into a single file for saving bandwith and number of requests to load a page.</p>
<p>As example you could create your own bundle:</p>
<pre><code>bundles.Add(New ScriptBundle("~/bundles/mybundle").Include(
"~/Resources/Core/Javascripts/jquery-1.7.1.min.js",
"~/Resources/Core/Javascripts/jquery-ui-1.8.16.min.js",
"~/Resources/Core/Javascripts/jquery.validate.min.js",
"~/Resources/Core/Javascripts/jquery.validate.unobtrusive.min.js",
"~/Resources/Core/Javascripts/jquery.unobtrusive-ajax.min.js",
"~/Resources/Core/Javascripts/jquery-ui-timepicker-addon.js"))
</code></pre>
<p>And render it like this:</p>
<pre><code>@Scripts.Render("~/bundles/mybundle")
</code></pre>
<p>One more advantage of <code>@Scripts.Render("~/bundles/mybundle")</code> over the native <code><script src="~/bundles/mybundle" /></code> is that <code>@Scripts.Render()</code> will respect the <code>web.config</code> debug setting:</p>
<pre><code> <system.web>
<compilation debug="true|false" />
</code></pre>
<p>If <code>debug="true"</code> then it will instead render individual script tags for each source script, without any minification.</p>
<p>For stylesheets you will have to use a StyleBundle and @Styles.Render().</p>
<p>Instead of loading each script or style with a single request (with script or link tags), all files are compressed into a single JavaScript or stylesheet file and loaded together.</p> | {
"question_id": 12192646,
"question_date": "2012-08-30T08:16:54.747Z",
"question_score": 223,
"tags": "asp.net-mvc-4|asp.net-optimization",
"answer_id": 12192725,
"answer_date": "2012-08-30T08:22:02.727Z",
"answer_score": 296
} |
Please answer the following Stack Overflow question:
Title: String, StringBuffer, and StringBuilder
<p>Please tell me a real time situation to compare <code>String</code>, <code>StringBuffer</code>, and <code>StringBuilder</code>?</p> | <p><strong>Mutability Difference:</strong></p>
<p><code>String</code> is <strong>immutable</strong>, if you try to alter their values, another object gets created, whereas <code>StringBuffer</code> and <code>StringBuilder</code> are <strong>mutable</strong> so they can change their values.</p>
<p><strong>Thread-Safety Difference:</strong></p>
<p>The difference between <code>StringBuffer</code> and <code>StringBuilder</code> is that <code>StringBuffer</code> is thread-safe. So when the application needs to be run only in a single thread then it is better to use <code>StringBuilder</code>. <code>StringBuilder</code> is more efficient than <code>StringBuffer</code>.</p>
<p><strong>Situations:</strong></p>
<ul>
<li>If your string is not going to change use a String class because a <code>String</code> object is immutable.</li>
<li>If your string can change (example: lots of logic and operations in the construction of the string) and will only be accessed from a single thread, using a <code>StringBuilder</code> is good enough.</li>
<li>If your string can change, and will be accessed from multiple threads, use a <code>StringBuffer</code> because <code>StringBuffer</code> is synchronous so you have thread-safety.</li>
</ul> | {
"question_id": 2971315,
"question_date": "2010-06-04T03:28:55.043Z",
"question_score": 223,
"tags": "java|string|oop|stringbuilder",
"answer_id": 2971343,
"answer_date": "2010-06-04T03:35:13.197Z",
"answer_score": 395
} |
Please answer the following Stack Overflow question:
Title: What is output buffering?
<p>What is output buffering and why is one using it in PHP?</p> | <p><a href="http://web.archive.org/web/20101216035343/http://dev-tips.com/featured/output-buffering-for-web-developers-a-beginners-guide" rel="noreferrer">Output Buffering for Web Developers, a Beginner’s Guide</a>:</p>
<blockquote>
<p>Without output buffering (the default), your HTML is sent to the browser in pieces as PHP processes through your script. With output buffering, your HTML is stored in a variable and sent to the browser as one piece at the end of your script.</p>
<p>Advantages of output buffering for Web developers</p>
<ul>
<li>Turning on output buffering alone decreases the amount of time it takes to download and render our HTML because it's not being sent to the browser in pieces as PHP processes the HTML.</li>
<li>All the fancy stuff we can do with PHP strings, we can now do with our whole HTML page as one variable.</li>
<li>If you've ever encountered the message "Warning: Cannot modify header information - headers already sent by (output)" while setting cookies, you'll be happy to know that output buffering is your answer.</li>
</ul>
</blockquote> | {
"question_id": 2832010,
"question_date": "2010-05-14T05:29:05.560Z",
"question_score": 223,
"tags": "php|output-buffering",
"answer_id": 2832179,
"answer_date": "2010-05-14T06:12:47.620Z",
"answer_score": 293
} |
Please answer the following Stack Overflow question:
Title: How do I disable Git Credential Manager for Windows?
<p>I notice that in the latest version of Git, the default is now to popup a "Git Credential Manager for Windows" dialog instead of prompting me for me password at the Bash prompt every time.</p>
<p>I really hate this behaviour. How can I just disable it and go back to entering the password at the Bash shell every time?</p>
<p>By the way, I don't want Git caching my credentials <em>in any way</em>, whether through Windows credentials or some internal daemon. I want to disable <em>all credential caching</em>.</p> | <p>OK, I discovered that you need to either <em>avoid</em> checking the "Git Credential Manager" checkbox during the Git for Windows installer, or (after installation) run the Bash shell as <em>Administrator</em> and use <code>git config --edit --system</code> to remove the <code>helper = manager</code> line so that it is no longer registered as a credential helper.</p>
<p>For bonus points, use <code>git config --edit --global</code> and insert:</p>
<pre><code>[core]
askpass =
</code></pre>
<p>To disable the OpenSSH credentials popup too.</p> | {
"question_id": 37182847,
"question_date": "2016-05-12T09:32:08.200Z",
"question_score": 223,
"tags": "git|bash",
"answer_id": 37185202,
"answer_date": "2016-05-12T11:11:33.820Z",
"answer_score": 286
} |
Please answer the following Stack Overflow question:
Title: Trigger 404 in Spring-MVC controller?
<p>How do I get a <a href="http://en.wikipedia.org/wiki/Spring_Framework" rel="noreferrer">Spring</a> 3.0 controller to trigger a 404?</p>
<p>I have a controller with <code>@RequestMapping(value = "/**", method = RequestMethod.GET)</code> and for some <a href="http://en.wikipedia.org/wiki/Uniform_Resource_Locator" rel="noreferrer">URLs</a> accessing the controller, I want the container to come up with a 404.</p> | <p>Since Spring 3.0 you also can throw an Exception declared with <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/bind/annotation/ResponseStatus.html" rel="noreferrer"><code>@ResponseStatus</code></a> annotation:</p>
<pre><code>@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
...
}
@Controller
public class SomeController {
@RequestMapping.....
public void handleCall() {
if (isFound()) {
// whatever
}
else {
throw new ResourceNotFoundException();
}
}
}
</code></pre> | {
"question_id": 2066946,
"question_date": "2010-01-14T19:30:13.370Z",
"question_score": 223,
"tags": "java|spring|spring-mvc",
"answer_id": 2067043,
"answer_date": "2010-01-14T19:43:06.277Z",
"answer_score": 344
} |
Please answer the following Stack Overflow question:
Title: When a 'blur' event occurs, how can I find out which element focus went *to*?
<p>Suppose I attach an <code>blur</code> function to an HTML input box like this:</p>
<pre><code><input id="myInput" onblur="function() { ... }"></input>
</code></pre>
<p>Is there a way to get the ID of the element which caused the <code>blur</code> event to fire (the element which was clicked) inside the function? How?</p>
<p>For example, suppose I have a span like this:</p>
<pre><code><span id="mySpan">Hello World</span>
</code></pre>
<p>If I click the span right after the input element has focus, the input element will lose its focus. How does the function know that it was <code>mySpan</code> that was clicked?</p>
<p>PS: If the onclick event of the span would occur before the onblur event of the input element my problem would be solved, because I could set some status value indicating a specific element had been clicked.</p>
<p>PPS: The background of this problem is that I want to trigger an AJAX autocompleter control externally (from a clickable element) to show its suggestions, without the suggestions disappearing immediately because of the <code>blur</code> event on the input element. So I want to check in the <code>blur</code> function if one specific element has been clicked, and if so, ignore the blur event. </p> | <p>Hmm... In Firefox, you can use <code>explicitOriginalTarget</code> to pull the element that was clicked on. I expected <code>toElement</code> to do the same for IE, but it does not appear to work... However, you can pull the newly-focused element from the document:</p>
<pre><code>function showBlur(ev)
{
var target = ev.explicitOriginalTarget||document.activeElement;
document.getElementById("focused").value =
target ? target.id||target.tagName||target : '';
}
...
<button id="btn1" onblur="showBlur(event)">Button 1</button>
<button id="btn2" onblur="showBlur(event)">Button 2</button>
<button id="btn3" onblur="showBlur(event)">Button 3</button>
<input id="focused" type="text" disabled="disabled" />
</code></pre>
<hr>
<p><strong>Caveat:</strong> This technique does <em>not</em> work for focus changes caused by <em>tabbing</em> through fields with the keyboard, and does not work at all in Chrome or Safari. The big problem with using <code>activeElement</code> (except in IE) is that it is not consistently updated until <em>after</em> the <code>blur</code> event has been processed, and may have no valid value at all during processing! This can be mitigated with a variation on <a href="https://stackoverflow.com/questions/121499/when-onblur-occurs-how-can-i-find-out-which-element-focus-went-to/128452#128452">the technique Michiel ended up using</a>:</p>
<pre><code>function showBlur(ev)
{
// Use timeout to delay examination of activeElement until after blur/focus
// events have been processed.
setTimeout(function()
{
var target = document.activeElement;
document.getElementById("focused").value =
target ? target.id||target.tagName||target : '';
}, 1);
}
</code></pre>
<p>This should work in most modern browsers (tested in Chrome, IE, and Firefox), with the caveat that Chrome does not set focus on buttons that are <em>clicked</em> (vs. tabbed to). </p> | {
"question_id": 121499,
"question_date": "2008-09-23T14:48:43.483Z",
"question_score": 223,
"tags": "javascript|events",
"answer_id": 121708,
"answer_date": "2008-09-23T15:25:04.660Z",
"answer_score": 94
} |
Please answer the following Stack Overflow question:
Title: Is there a way to detect if an image is blurry?
<p>I was wondering if there is a way to determine if an image is blurry or not by analyzing the image data.</p> | <p>Yes, it is. Compute the Fast Fourier Transform and analyse the result. The Fourier transform tells you which frequencies are present in the image. If there is a low amount of high frequencies, then the image is blurry.</p>
<p>Defining the terms 'low' and 'high' is up to you.</p>
<p><strong>Edit</strong>:</p>
<p>As stated in the comments, if you want a single float representing the <em>blurryness</em> of a given image, you have to work out a suitable metric. </p>
<p><a href="https://stackoverflow.com/a/7767755/50065">nikie's answer</a> provide such a metric. Convolve the image with a Laplacian kernel:</p>
<pre><code> 1
1 -4 1
1
</code></pre>
<p>And use a robust maximum metric on the output to get a number which you can use for thresholding. Try to avoid smoothing too much the images before computing the Laplacian, because you will only find out that a smoothed image is indeed blurry :-).</p> | {
"question_id": 7765810,
"question_date": "2011-10-14T09:41:52.997Z",
"question_score": 223,
"tags": "image-processing|opencv",
"answer_id": 7766036,
"answer_date": "2011-10-14T10:01:11.630Z",
"answer_score": 144
} |
Please answer the following Stack Overflow question:
Title: Deleting rows with MySQL LEFT JOIN
<p>I have two tables, one for job deadlines, one for describe a job. Each job can take a status and some statuses means the jobs' deadlines must be deleted from the other table.</p>
<p>I can easily <code>SELECT</code> the jobs/deadlines that meets my criteria with a <code>LEFT JOIN</code>:</p>
<pre><code>SELECT * FROM `deadline`
LEFT JOIN `job` ON deadline.job_id = job.job_id
WHERE `status` = 'szamlazva'
OR `status` = 'szamlazhato'
OR `status` = 'fizetve'
OR `status` = 'szallitva'
OR `status` = 'storno'
</code></pre>
<p>(<code>status</code> belongs to <code>job</code> table not <code>deadline</code>)</p>
<p>But when I'd like to delete these rows from <code>deadline</code>, MySQL throws an error. My query is:</p>
<pre><code>DELETE FROM `deadline`
LEFT JOIN `job`
ON deadline.job_id = job.job_id
WHERE `status` = 'szamlazva'
OR `status` = 'szamlazhato'
OR `status` = 'fizetve'
OR `status` = 'szallitva'
OR `status` = 'storno'
</code></pre>
<p>MySQL error says nothing:</p>
<blockquote>
<p>You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LEFT JOIN <code>job</code> ON deadline.job_id = job.job_id WHERE <code>status</code> = 'szaml' at line 1</p>
</blockquote>
<p>How can I turn my <code>SELECT</code> into a working <code>DELETE</code> query?</p> | <p>You simply need to specify on which tables to apply the <code>DELETE</code>. </p>
<p>Delete only the <code>deadline</code> rows:</p>
<pre><code>DELETE `deadline` FROM `deadline` LEFT JOIN `job` ....
</code></pre>
<p>Delete the <code>deadline</code> and <code>job</code> rows:</p>
<pre><code>DELETE `deadline`, `job` FROM `deadline` LEFT JOIN `job` ....
</code></pre>
<p>Delete only the <code>job</code> rows:</p>
<pre><code>DELETE `job` FROM `deadline` LEFT JOIN `job` ....
</code></pre> | {
"question_id": 2763206,
"question_date": "2010-05-04T06:20:32.377Z",
"question_score": 223,
"tags": "mysql|left-join|delete-row|sql-delete",
"answer_id": 2763245,
"answer_date": "2010-05-04T06:26:51.887Z",
"answer_score": 418
} |
Please answer the following Stack Overflow question:
Title: Disable all gcc warnings
<p>I'm working on a project that will read compiler error messages of a particular variety and do useful things with them. The sample codebase I'm testing this on (a random open-source application), and hence rebuilding frequently, contains a few bits that generate warnings, which are of no interest to me.</p>
<p>How do I disable all warnings from GCC, so I can just see error messages if there are any?</p> | <p><code>-w</code> is the GCC-wide option to disable warning messages.</p> | {
"question_id": 1452671,
"question_date": "2009-09-21T02:48:41.707Z",
"question_score": 223,
"tags": "gcc|g++|warnings",
"answer_id": 1452674,
"answer_date": "2009-09-21T02:49:00.177Z",
"answer_score": 357
} |
Please answer the following Stack Overflow question:
Title: How do I get the path of the current executed file in Python?
<p>This may seem like a newbie question, but it is not. Some common approaches don't work in all cases:</p>
<h1>sys.argv[0]</h1>
<p>This means using <code>path = os.path.abspath(os.path.dirname(sys.argv[0]))</code>, but this does not work if you are running from another Python script in another directory, and this can happen in real life.</p>
<h1>__file__</h1>
<p>This means using <code>path = os.path.abspath(os.path.dirname(__file__))</code>, but I found that this doesn't work:</p>
<ul>
<li><code>py2exe</code> doesn't have a <code>__file__</code> attribute, but there is <a href="http://www.py2exe.org/index.cgi/WhereAmI" rel="noreferrer">a workaround</a></li>
<li>When you run from <a href="https://en.wikipedia.org/wiki/IDLE" rel="noreferrer">IDLE</a> with <code>execute()</code> there is no <code>__file__</code> attribute</li>
<li><a href="https://en.wikipedia.org/wiki/Mac_OS_X_Snow_Leopard" rel="noreferrer">Mac OS X v10.6</a> (Snow Leopard) where I get <code>NameError: global name '__file__' is not defined</code></li>
</ul>
<p>Related questions with incomplete answers:</p>
<ul>
<li><em><a href="https://stackoverflow.com/questions/1296501/python-find-path-to-file-being-run">Find path to currently running file</a></em></li>
<li><em><a href="https://stackoverflow.com/questions/1483827/python-path-to-current-file-depends-on-how-i-execute-the-program">Path to current file depends on how I execute the program</a></em></li>
<li><em><a href="https://stackoverflow.com/questions/2259503/how-to-know-the-path-of-the-running-script-in-python">How can I know the path of the running script in Python?</a></em></li>
<li><em><a href="https://stackoverflow.com/questions/509742/python-chdir-to-dir-the-py-script-is-in">Change directory to the directory of a Python script</a></em></li>
</ul>
<p>I'm looking for a <strong>generic solution</strong>, one that would work in all above use cases.</p>
<h3>Update</h3>
<p>Here is the result of a testcase:</p>
<h3>Output of <code>python a.py</code> (on Windows)</h3>
<pre><code>a.py: __file__= a.py
a.py: os.getcwd()= C:\zzz
b.py: sys.argv[0]= a.py
b.py: __file__= a.py
b.py: os.getcwd()= C:\zzz
</code></pre>
<h3>a.py</h3>
<pre><code>#! /usr/bin/env python
import os, sys
print "a.py: sys.argv[0]=", sys.argv[0]
print "a.py: __file__=", __file__
print "a.py: os.getcwd()=", os.getcwd()
print
execfile("subdir/b.py")
</code></pre>
<h3>File <em>subdir/b.py</em></h3>
<pre><code>#! /usr/bin/env python
import os, sys
print "b.py: sys.argv[0]=", sys.argv[0]
print "b.py: __file__=", __file__
print "b.py: os.getcwd()=", os.getcwd()
print
</code></pre>
<h3>tree</h3>
<pre><code>C:.
| a.py
\---subdir
b.py
</code></pre> | <p>You can't directly determine the location of the main script being executed. After all, sometimes the script didn't come from a file at all. For example, it could come from the interactive interpreter or dynamically generated code stored only in memory.</p>
<p>However, you can reliably determine the location of a module, since modules are always loaded from a file. If you create a module with the following code and put it in the same directory as your main script, then the main script can import the module and use that to locate itself.</p>
<p>some_path/module_locator.py:</p>
<pre><code>def we_are_frozen():
# All of the modules are built-in to the interpreter, e.g., by py2exe
return hasattr(sys, "frozen")
def module_path():
encoding = sys.getfilesystemencoding()
if we_are_frozen():
return os.path.dirname(unicode(sys.executable, encoding))
return os.path.dirname(unicode(__file__, encoding))
</code></pre>
<p>some_path/main.py:</p>
<pre><code>import module_locator
my_path = module_locator.module_path()
</code></pre>
<p>If you have several main scripts in different directories, you may need more than one copy of module_locator.</p>
<p>Of course, if your main script is loaded by some other tool that doesn't let you import modules that are co-located with your script, then you're out of luck. In cases like that, the information you're after simply doesn't exist anywhere in your program. Your best bet would be to file a bug with the authors of the tool.</p> | {
"question_id": 2632199,
"question_date": "2010-04-13T18:37:45.683Z",
"question_score": 223,
"tags": "python|path|directory",
"answer_id": 2632297,
"answer_date": "2010-04-13T18:48:28.040Z",
"answer_score": 86
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.