input_text
stringlengths
115
13.8k
output_text
stringlengths
24
15k
metadata
dict
Please answer the following Stack Overflow question: Title: Which selector do I need to select an option by its text? <p>I need to check if a <code>&lt;select&gt;</code> has an option whose text is equal to a specific value.</p> <p>For example, if there's an <code>&lt;option value="123"&gt;abc&lt;/option&gt;</code>, I would be looking for "abc".</p> <p>Is there a selector to do this?</p> <p>Im looking for something similar to <code>$('#select option[value="123"]');</code> but for the text.</p>
<p>This could help:</p> <pre><code>$('#test').find('option[text=&quot;B&quot;]').val(); </code></pre> <p><a href="http://jsfiddle.net/nmvf6/1/" rel="noreferrer">Demo fiddle</a></p> <p>This would give you the option with text <code>B</code> and not the ones which has text that contains <code>B</code>.</p> <p><em>For recent versions of jQuery the above does not work.</em> As commented by <a href="https://stackoverflow.com/users/155077/quandary">Quandary</a> below, this is what works for jQuery 1.9.1:</p> <pre><code>$('#test option').filter(function () { return $(this).html() == &quot;B&quot;; }).val(); </code></pre> <p><a href="http://jsfiddle.net/FloydPink/nmvf6/2019/" rel="noreferrer">Updated fiddle</a></p>
{ "question_id": 3744289, "question_date": "2010-09-19T02:15:19.193Z", "question_score": 228, "tags": "jquery", "answer_id": 3744323, "answer_date": "2010-09-19T02:39:41.957Z", "answer_score": 351 }
Please answer the following Stack Overflow question: Title: When I run `npm install`, it returns with `ERR! code EINTEGRITY` (npm 5.3.0) <p>I am getting this error while running <code>sudo npm install</code>. On my server, npm was installed earlier. I've tried to delete the <code>package-lock.json</code> file, and ran <code>npm cache clean --force</code>, but it didn't work. </p> <p>My npm version is 5.3.0.</p> <p>The error:</p> <pre><code>npm ERR! code EINTEGRITY npm ERR! sha512-MKiLiV+I1AA596t9w1sQJ8jkiSr5+ZKi0WKrYGUn6d1Fx+Ij4tIj+m2WMQSGczs5jZVxV339chE8iwk6F64wjA== integrity checksum failed when using sha512: wanted sha512-MKiLiV+I1AA596t9w1sQJ8jkiSr5+ZKi0WKrYGUn6d1Fx+Ij4tIj+m2WMQSGczs5jZVxV339chE8iwk6F64wjA== but got sha512-WXI95kpJrxw4Nnx8vVI90PuUhrQjnNgghBl5tn54rUNKZYbxv+4ACxUzPVpJEtWxKmeDwnQrzjc0C2bYmRJVKg==. (65117 bytes) npm ERR! A complete log of this run can be found in: npm ERR! /home/ubuntu/.npm/_logs/2017-11-29T05_33_52_182Z-debug.log </code></pre>
<p>Actually the above is related to the network connectivity in side the server. When I've good connectivity in the server, the npm install gone good and didn't throw any error</p>
{ "question_id": 47545940, "question_date": "2017-11-29T05:50:45.280Z", "question_score": 228, "tags": "node.js|ubuntu|npm", "answer_id": 47587137, "answer_date": "2017-12-01T05:24:50.540Z", "answer_score": 35 }
Please answer the following Stack Overflow question: Title: C#: Printing all properties of an object <p>Is there a method built into .NET that can write all the properties and such of an object to the console?</p> <p>One could make use of reflection of course, but I'm curious if this already exists...especially since you can do it in Visual Studio in the Immediate Window. There you can type an object name (while in debug mode), press enter, and it is printed fairly prettily with all its stuff.</p> <p>Does a method like this exist?</p>
<p>The <code>ObjectDumper</code> class has been known to do that. I've never confirmed, but I've always suspected that the immediate window uses that.</p> <p>EDIT: I just realized, that the code for <code>ObjectDumper</code> is actually on your machine. Go to:</p> <pre><code>C:/Program Files/Microsoft Visual Studio 9.0/Samples/1033/CSharpSamples.zip </code></pre> <p>This will unzip to a folder called <em>LinqSamples</em>. In there, there's a project called <em>ObjectDumper</em>. Use that.</p>
{ "question_id": 852181, "question_date": "2009-05-12T10:53:04.550Z", "question_score": 228, "tags": "c#|object|serialization|console", "answer_id": 852216, "answer_date": "2009-05-12T11:03:31.883Z", "answer_score": 73 }
Please answer the following Stack Overflow question: Title: Variable name as a string in Javascript <p>Is there a way to get a variable name as a string in Javascript? (like <a href="https://developer.apple.com/documentation/foundation/1395257-nsstringfromselector" rel="noreferrer"><code>NSStringFromSelector</code></a> in <a href="https://en.wikipedia.org/wiki/Cocoa_(API)" rel="noreferrer">Cocoa</a>)</p> <p>I would like to do like this:</p> <pre><code>var myFirstName = 'John'; alert(variablesName(myFirstName) + ":" + myFirstName); --&gt; myFirstName:John </code></pre> <hr> <p><strong>UPDATE</strong></p> <p>I'm trying to connect a browser and another program using JavaScript. I would like to send instance names from a browser to another program for callback method:</p> <pre><code>FooClass = function(){}; FooClass.someMethod = function(json) { // Do something } instanceA = new FooClass(); instanceB = new FooClass(); doSomethingInAnotherProcess(instanceB); // result will be substituted by using instanceB.someMethod(); ... </code></pre> <p>From another program:</p> <pre><code>evaluateJavascriptInBrowser("(instanceName).someMethod("resultA");"); </code></pre> <p>In PHP: <a href="https://stackoverflow.com/questions/255312/how-to-get-a-variable-name-as-a-string-in-php/255335#255335">How to get a variable name as a string in PHP?</a></p>
<p>Typically, you would use a hash table for a situation where you want to map a name to some value, and be able to retrieve both.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var obj = { myFirstName: 'John' }; obj.foo = 'Another name'; for(key in obj) console.log(key + ': ' + obj[key]);</code></pre> </div> </div> </p>
{ "question_id": 4602141, "question_date": "2011-01-05T08:40:03.470Z", "question_score": 228, "tags": "javascript", "answer_id": 4602165, "answer_date": "2011-01-05T08:43:47.003Z", "answer_score": 55 }
Please answer the following Stack Overflow question: Title: How can I make a clickable link in an NSAttributedString? <p>It's trivial to make hyperlinks clickable in a <code>UITextView</code>. You just set the "detect links" checkbox on the view in IB, and it detects HTTP links and turns them into hyperlinks. </p> <p>However, that still means that what the user sees is the "raw" link. RTF files and HTML both allow you to set up a user-readable string with a link "behind" it. </p> <p>It's easy to install attributed text into a text view (or a <code>UILabel</code> or <code>UITextField</code>, for that matter.) However, when that attributed text includes a link, it is not clickable.</p> <p>Is there a way to make user-readable text clickable in a <code>UITextView</code>, <code>UILabel</code> or <code>UITextField</code>?</p> <p>The markup is different on SO, but here is the general idea. What I want is text like this:</p> <blockquote> <p>This morph was generated with <a href="http://example.com/facedancer" rel="noreferrer">Face Dancer</a>, Click to view in the app store.</p> </blockquote> <p>The only thing I can get is this:</p> <blockquote> <p>This morph was generated with Face Dancer, Click on <a href="http://example.com/facedancer" rel="noreferrer">http://example.com/facedancer</a> to view in the app store.</p> </blockquote>
<p>I found this really useful but I needed to do it in quite a few places so I've wrapped my approach up in a simple extension to <code>NSMutableAttributedString</code>:</p> <p><strong>Swift 3</strong></p> <pre><code>extension NSMutableAttributedString { public func setAsLink(textToFind:String, linkURL:String) -&gt; Bool { let foundRange = self.mutableString.range(of: textToFind) if foundRange.location != NSNotFound { self.addAttribute(.link, value: linkURL, range: foundRange) return true } return false } } </code></pre> <p><strong>Swift 2</strong></p> <pre><code>import Foundation extension NSMutableAttributedString { public func setAsLink(textToFind:String, linkURL:String) -&gt; Bool { let foundRange = self.mutableString.rangeOfString(textToFind) if foundRange.location != NSNotFound { self.addAttribute(NSLinkAttributeName, value: linkURL, range: foundRange) return true } return false } } </code></pre> <p>Example usage:</p> <pre><code>let attributedString = NSMutableAttributedString(string:"I love stackoverflow!") let linkWasSet = attributedString.setAsLink("stackoverflow", linkURL: "http://stackoverflow.com") if linkWasSet { // adjust more attributedString properties } </code></pre> <p><strong>Objective-C</strong></p> <p>I've just hit a requirement to do the same in a pure Objective-C project, so here's the Objective-C category.</p> <pre><code>@interface NSMutableAttributedString (SetAsLinkSupport) - (BOOL)setAsLink:(NSString*)textToFind linkURL:(NSString*)linkURL; @end @implementation NSMutableAttributedString (SetAsLinkSupport) - (BOOL)setAsLink:(NSString*)textToFind linkURL:(NSString*)linkURL { NSRange foundRange = [self.mutableString rangeOfString:textToFind]; if (foundRange.location != NSNotFound) { [self addAttribute:NSLinkAttributeName value:linkURL range:foundRange]; return YES; } return NO; } @end </code></pre> <p>Example usage:</p> <pre><code>NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:"I love stackoverflow!"]; BOOL linkWasSet = [attributedString setAsLink:@"stackoverflow" linkURL:@"http://stackoverflow.com"]; if (linkWasSet) { // adjust more attributedString properties } </code></pre> <p>Make Sure that the NSTextField's Behavior attribute is set as Selectable. <a href="https://i.stack.imgur.com/FjGTh.png" rel="noreferrer"><img src="https://i.stack.imgur.com/FjGTh.png" alt="Xcode NSTextField behavior attribute"></a></p>
{ "question_id": 21629784, "question_date": "2014-02-07T14:05:05.453Z", "question_score": 228, "tags": "ios|objective-c|hyperlink|uitextview|nsattributedstring", "answer_id": 28572505, "answer_date": "2015-02-17T22:37:13.977Z", "answer_score": 156 }
Please answer the following Stack Overflow question: Title: How to remove undefined and null values from an object using lodash? <p>I have a Javascript object like:</p> <pre><code>var my_object = { a:undefined, b:2, c:4, d:undefined }; </code></pre> <p>How to remove all the undefined properties? False attributes should stay.</p>
<p>If you want to remove all <em><a href="https://stackoverflow.com/a/19839953/16940">falsey</a></em> values then the most compact way is:</p> <p>For <strong>Lodash 4.x and later</strong>:</p> <pre><code>_.pickBy({ a: null, b: 1, c: undefined }, _.identity); &gt;&gt; Object {b: 1} </code></pre> <p>For <em>legacy</em> Lodash 3.x:</p> <pre><code>_.pick(obj, _.identity); _.pick({ a: null, b: 1, c: undefined }, _.identity); &gt;&gt; Object {b: 1} </code></pre>
{ "question_id": 30812765, "question_date": "2015-06-12T21:58:25.153Z", "question_score": 228, "tags": "javascript|object|lodash", "answer_id": 33432857, "answer_date": "2015-10-30T09:41:01.137Z", "answer_score": 255 }
Please answer the following Stack Overflow question: Title: How do I get and set Environment variables in C#? <p>How can I get Environnment variables and if something is missing, set the value?</p>
<p>Use the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.environment" rel="noreferrer">System.Environment</a> class.</p> <p>The methods</p> <pre><code>var value = System.Environment.GetEnvironmentVariable(variable [, Target]) </code></pre> <p>and </p> <pre><code>System.Environment.SetEnvironmentVariable(variable, value [, Target]) </code></pre> <p>will do the job for you. </p> <p>The optional parameter <code>Target</code> is an enum of type <code>EnvironmentVariableTarget</code> and it can be one of: <code>Machine</code>, <code>Process</code>, or <code>User</code>. If you omit it, the default target is the <strong>current process.</strong></p>
{ "question_id": 185208, "question_date": "2008-10-08T22:43:17.277Z", "question_score": 228, "tags": "c#|.net|.net-2.0|environment-variables", "answer_id": 185214, "answer_date": "2008-10-08T22:44:20.753Z", "answer_score": 310 }
Please answer the following Stack Overflow question: Title: Get push notification while App in foreground iOS <p>I am using push notification service in my app. When app is in background I am able to see notification on notification screen(screen shown when we swipe down from top of iOS device). But if application is in foreground the delegate method </p> <pre><code>- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo </code></pre> <p>is getting called but notification is not displayed in notification screen. </p> <p>I want to show notification on notification screen independent of whether app is in background or foreground. I am tired by searching for a solution. Any help is greatly appreciated.</p>
<p>If the application is running in the foreground, iOS won't show a notification banner/alert. That's by design. But we can achieve it by using <code>UILocalNotification</code> as follows</p> <ul> <li><p>Check whether application is in active state on receiving a remote<br> notification. If in active state fire a UILocalNotification.</p> <pre><code>if (application.applicationState == UIApplicationStateActive ) { UILocalNotification *localNotification = [[UILocalNotification alloc] init]; localNotification.userInfo = userInfo; localNotification.soundName = UILocalNotificationDefaultSoundName; localNotification.alertBody = message; localNotification.fireDate = [NSDate date]; [[UIApplication sharedApplication] scheduleLocalNotification:localNotification]; } </code></pre></li> </ul> <p>SWIFT: </p> <pre><code>if application.applicationState == .active { var localNotification = UILocalNotification() localNotification.userInfo = userInfo localNotification.soundName = UILocalNotificationDefaultSoundName localNotification.alertBody = message localNotification.fireDate = Date() UIApplication.shared.scheduleLocalNotification(localNotification) } </code></pre>
{ "question_id": 14872088, "question_date": "2013-02-14T09:57:10.200Z", "question_score": 228, "tags": "iphone|ios|objective-c|push-notification", "answer_id": 14888017, "answer_date": "2013-02-15T03:56:57.023Z", "answer_score": 27 }
Please answer the following Stack Overflow question: Title: How to Publish Web with msbuild? <p>Visual Studio 2010 has a Publish command that allows you to publish your Web Application Project to a file system location. I'd like to do this on my TeamCity build server, so I need to do it with the solution runner or msbuild. I tried using the Publish target, but I think that might be for ClickOnce:</p> <pre><code>msbuild Project.csproj /t:Publish /p:Configuration=Deploy </code></pre> <p>I basically want to do exactly what a web deployment project does, but without the add-in. I need it to compile the WAP, remove any files unnecessary for execution, perform any <a href="http://msdn.microsoft.com/en-us/library/dd465326.aspx" rel="noreferrer">web.config transformations</a>, and copy the output to a specified location.</p> <p><strong>My Solution</strong>, based on Jeff Siver's answer</p> <pre><code>&lt;Target Name="Deploy"&gt; &lt;MSBuild Projects="$(SolutionFile)" Properties="Configuration=$(Configuration);DeployOnBuild=true;DeployTarget=Package" ContinueOnError="false" /&gt; &lt;Exec Command="&amp;quot;$(ProjectPath)\obj\$(Configuration)\Package\$(ProjectName).deploy.cmd&amp;quot; /y /m:$(DeployServer) -enableRule:DoNotDeleteRule" ContinueOnError="false" /&gt; &lt;/Target&gt; </code></pre>
<p>I got it mostly working without a custom msbuild script. Here are the relevant TeamCity build configuration settings:</p> <pre> Artifact paths: %system.teamcity.build.workingDir%\MyProject\obj\Debug\Package\PackageTmp Type of runner: MSBuild (Runner for MSBuild files) Build file path: MyProject\MyProject.csproj Working directory: same as checkout directory MSBuild version: Microsoft .NET Framework 4.0 MSBuild ToolsVersion: 4.0 Run platform: x86 Targets: Package Command line parameters to MSBuild.exe: /p:Configuration=Debug </pre> <p>This will compile, package (with web.config transformation), and save the output as artifacts. The only thing missing is copying the output to a specified location, but that could be done either in another TeamCity build configuration with an artifact dependency or with an msbuild script.</p> <p><strong>Update</strong></p> <p>Here is an msbuild script that will compile, package (with web.config transformation), and copy the output to my staging server</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"&gt; &lt;PropertyGroup&gt; &lt;Configuration Condition=" '$(Configuration)' == '' "&gt;Release&lt;/Configuration&gt; &lt;SolutionName&gt;MySolution&lt;/SolutionName&gt; &lt;SolutionFile&gt;$(SolutionName).sln&lt;/SolutionFile&gt; &lt;ProjectName&gt;MyProject&lt;/ProjectName&gt; &lt;ProjectFile&gt;$(ProjectName)\$(ProjectName).csproj&lt;/ProjectFile&gt; &lt;/PropertyGroup&gt; &lt;Target Name="Build" DependsOnTargets="BuildPackage;CopyOutput" /&gt; &lt;Target Name="BuildPackage"&gt; &lt;MSBuild Projects="$(SolutionFile)" ContinueOnError="false" Targets="Rebuild" Properties="Configuration=$(Configuration)" /&gt; &lt;MSBuild Projects="$(ProjectFile)" ContinueOnError="false" Targets="Package" Properties="Configuration=$(Configuration)" /&gt; &lt;/Target&gt; &lt;Target Name="CopyOutput"&gt; &lt;ItemGroup&gt; &lt;PackagedFiles Include="$(ProjectName)\obj\$(Configuration)\Package\PackageTmp\**\*.*"/&gt; &lt;/ItemGroup&gt; &lt;Copy SourceFiles="@(PackagedFiles)" DestinationFiles="@(PackagedFiles-&gt;'\\build02\wwwroot\$(ProjectName)\$(Configuration)\%(RecursiveDir)%(Filename)%(Extension)')"/&gt; &lt;/Target&gt; &lt;/Project&gt; </code></pre> <p>You can also remove the SolutionName and ProjectName properties from the PropertyGroup tag and pass them to msbuild.</p> <pre><code>msbuild build.xml /p:Configuration=Deploy;SolutionName=MySolution;ProjectName=MyProject </code></pre> <p><strong>Update 2</strong></p> <p>Since this question still gets a good deal of traffic, I thought it was worth updating my answer with my current script that uses <a href="http://www.iis.net/download/WebDeploy" rel="noreferrer">Web Deploy</a> (also known as MSDeploy).</p> <pre><code>&lt;Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build" ToolsVersion="4.0"&gt; &lt;PropertyGroup&gt; &lt;Configuration Condition=" '$(Configuration)' == '' "&gt;Release&lt;/Configuration&gt; &lt;ProjectFile Condition=" '$(ProjectFile)' == '' "&gt;$(ProjectName)\$(ProjectName).csproj&lt;/ProjectFile&gt; &lt;DeployServiceUrl Condition=" '$(DeployServiceUrl)' == '' "&gt;http://staging-server/MSDeployAgentService&lt;/DeployServiceUrl&gt; &lt;/PropertyGroup&gt; &lt;Target Name="VerifyProperties"&gt; &lt;!-- Verify that we have values for all required properties --&gt; &lt;Error Condition=" '$(ProjectName)' == '' " Text="ProjectName is required." /&gt; &lt;/Target&gt; &lt;Target Name="Build" DependsOnTargets="VerifyProperties"&gt; &lt;!-- Deploy using windows authentication --&gt; &lt;MSBuild Projects="$(ProjectFile)" Properties="Configuration=$(Configuration); MvcBuildViews=False; DeployOnBuild=true; DeployTarget=MSDeployPublish; CreatePackageOnPublish=True; AllowUntrustedCertificate=True; MSDeployPublishMethod=RemoteAgent; MsDeployServiceUrl=$(DeployServiceUrl); SkipExtraFilesOnServer=True; UserName=; Password=;" ContinueOnError="false" /&gt; &lt;/Target&gt; &lt;/Project&gt; </code></pre> <p>In TeamCity, I have parameters named <code>env.Configuration</code>, <code>env.ProjectName</code> and <code>env.DeployServiceUrl</code>. The MSBuild runner has the build file path and the parameters are passed automagically (you don't have to specify them in Command line parameters).</p> <p>You can also run it from the command line:</p> <pre><code>msbuild build.xml /p:Configuration=Staging;ProjectName=MyProject;DeployServiceUrl=http://staging-server/MSDeployAgentService </code></pre>
{ "question_id": 3097489, "question_date": "2010-06-22T22:02:57.297Z", "question_score": 228, "tags": "asp.net|visual-studio-2010|msbuild|teamcity|msdeploy", "answer_id": 3098613, "answer_date": "2010-06-23T02:49:24.673Z", "answer_score": 141 }
Please answer the following Stack Overflow question: Title: Does return stop a loop? <p>Suppose I have a loop like this:</p> <pre><code>for (var i = 0; i &lt; SomeArrayOfObject.length; i++) { if (SomeArray[i].SomeValue === SomeCondition) { var SomeVar = SomeArray[i].SomeProperty; return SomeVar; } } </code></pre> <p>Quick question: does the <code>return</code> stop the execution of the loop in and of itself?</p>
<p>Yes, <code>return</code> stops execution and exits the function. <code>return</code> always** exits its function immediately, with no further execution if it's inside a for loop.</p> <p>It is easily verified for yourself:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function returnMe() { for (var i = 0; i &lt; 2; i++) { if (i === 1) return i; } } console.log(returnMe());</code></pre> </div> </div> </p> <p>** Notes: See <a href="https://stackoverflow.com/a/11714537/3991403">this other answer</a> about the special case of <code>try/catch/finally</code> and <a href="https://stackoverflow.com/questions/34653612/what-does-return-keyword-mean-inside-foreach-function/34653650">this answer</a> about how forEach loops has its own function scope will not break out of the containing function.</p>
{ "question_id": 11714503, "question_date": "2012-07-30T01:39:49.353Z", "question_score": 228, "tags": "javascript|loops|return", "answer_id": 11714515, "answer_date": "2012-07-30T01:41:25.830Z", "answer_score": 304 }
Please answer the following Stack Overflow question: Title: How to cherry pick from 1 branch to another <p>I have 2 branches, <code>master</code> and <code>dev</code>.</p> <p>I am on <code>dev</code> branch and I want to cherry-pick 1 commit from <code>master</code> to <code>dev</code>. So I did </p> <pre><code>$ git cherry-pick be530cec7748e037c665bd5a585e6d9ce11bc8ad Finished one cherry-pick. </code></pre> <p>But when I do <code>git status</code> and <code>gitx</code>, I don't see my commit <code>be530cec7748e037c665bd5a585e6d9ce11bc8ad</code> in git history.</p> <p>How can I see my commit in the <code>dev</code> branch?</p>
<p>When you cherry-pick, it creates a new commit with a new SHA. If you do: </p> <pre><code>git cherry-pick -x &lt;sha&gt; </code></pre> <p>then at least you'll get the commit message from the original commit appended to your new commit, along with the original SHA, which is very useful for tracking cherry-picks.</p>
{ "question_id": 5304391, "question_date": "2011-03-14T20:53:33.677Z", "question_score": 228, "tags": "git|cherry-pick|git-cherry-pick", "answer_id": 5304455, "answer_date": "2011-03-14T20:59:14.707Z", "answer_score": 380 }
Please answer the following Stack Overflow question: Title: How to change the floating label color of TextInputLayout <p>With reference to the new <code>TextInputLayout</code> released by Google, how do I change the floating label text color?</p> <p>Setting <code>colorControlNormal</code>, <code>colorControlActivated</code>, <code>colorControlHighLight</code> in styles does not help.</p> <p>This is what I have now:</p> <p><img src="https://i.stack.imgur.com/EES16.png" alt="This is what I have now"></p>
<p><strong>Try The Below Code It Works In Normal State</strong></p> <pre><code> &lt;android.support.design.widget.TextInputLayout android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;wrap_content&quot; android:theme=&quot;@style/TextLabel&quot;&gt; &lt;android.support.v7.widget.AppCompatEditText android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;wrap_content&quot; android:hint=&quot;Hiiiii&quot; android:id=&quot;@+id/edit_id&quot;/&gt; &lt;/android.support.design.widget.TextInputLayout&gt; </code></pre> <p><strong>In Styles Folder TextLabel Code</strong></p> <pre><code> &lt;style name=&quot;TextLabel&quot; parent=&quot;TextAppearance.AppCompat&quot;&gt; &lt;!-- Hint color and label color in FALSE state --&gt; &lt;item name=&quot;android:textColorHint&quot;&gt;@color/Color Name&lt;/item&gt; &lt;item name=&quot;android:textSize&quot;&gt;20sp&lt;/item&gt; &lt;!-- Label color in TRUE state and bar color FALSE and TRUE State --&gt; &lt;item name=&quot;colorAccent&quot;&gt;@color/Color Name&lt;/item&gt; &lt;item name=&quot;colorControlNormal&quot;&gt;@color/Color Name&lt;/item&gt; &lt;item name=&quot;colorControlActivated&quot;&gt;@color/Color Name&lt;/item&gt; &lt;/style&gt; </code></pre> <p><strong>Set To Main Theme of App,It Works Only Highlight State Only</strong></p> <pre><code> &lt;item name=&quot;colorAccent&quot;&gt;@color/Color Name&lt;/item&gt; </code></pre> <p><strong>Update:</strong></p> <blockquote> <p>UnsupportedOperationException: Can't convert to color: type=0x2 in api 16 or below</p> </blockquote> <p><a href="https://stackoverflow.com/a/31723120/421467">Solution</a></p> <p><strong>Update:</strong></p> <p><strong>Are you using Material Components Library</strong></p> <p>You can add below lines to your main theme</p> <pre><code> &lt;item name=&quot;colorPrimary&quot;&gt;@color/your_color&lt;/item&gt; // Activated State &lt;item name=&quot;colorOnSurface&quot;&gt;@color/your_color&lt;/item&gt; // Normal State </code></pre> <p>or else do you want different colors in noraml state and activated state and with customization follow below code</p> <pre><code>&lt;style name=&quot;Widget.App.TextInputLayout&quot; parent=&quot;Widget.MaterialComponents.TextInputLayout.OutlinedBox&quot;&gt; &lt;item name=&quot;materialThemeOverlay&quot;&gt;@style/ThemeOverlay.App.TextInputLayout&lt;/item&gt; &lt;item name=&quot;shapeAppearance&quot;&gt;@style/ShapeAppearance.App.SmallComponent&lt;/item&gt; //Changes the Shape Apperance &lt;!--&lt;item name=&quot;hintTextColor&quot;&gt;?attr/colorOnSurface&lt;/item&gt;--&gt; //When you added this line it will applies only one color in normal and activate state i.e colorOnSurface color &lt;/style&gt; &lt;style name=&quot;ThemeOverlay.App.TextInputLayout&quot; parent=&quot;&quot;&gt; &lt;item name=&quot;colorPrimary&quot;&gt;@color/colorPrimaryDark&lt;/item&gt; //Activated color &lt;item name=&quot;colorOnSurface&quot;&gt;@color/colorPrimary&lt;/item&gt; //Normal color &lt;item name=&quot;colorError&quot;&gt;@color/colorPrimary&lt;/item&gt; //Error color //Text Appearance styles &lt;item name=&quot;textAppearanceSubtitle1&quot;&gt;@style/TextAppearance.App.Subtitle1&lt;/item&gt; &lt;item name=&quot;textAppearanceCaption&quot;&gt;@style/TextAppearance.App.Caption&lt;/item&gt; &lt;!--Note: When setting a materialThemeOverlay on a custom TextInputLayout style, don’t forget to set editTextStyle to either a @style/Widget.MaterialComponents.TextInputEditText.* style or to a custom one that inherits from that. The TextInputLayout styles set materialThemeOverlay that overrides editTextStyle with the specific TextInputEditText style needed. Therefore, you don’t need to specify a style tag on the edit text.--&gt; &lt;item name=&quot;editTextStyle&quot;&gt;@style/Widget.MaterialComponents.TextInputEditText.OutlinedBox&lt;/item&gt; &lt;/style&gt; &lt;style name=&quot;TextAppearance.App.Subtitle1&quot; parent=&quot;TextAppearance.MaterialComponents.Subtitle1&quot;&gt; &lt;item name=&quot;fontFamily&quot;&gt;@font/your_font&lt;/item&gt; &lt;item name=&quot;android:fontFamily&quot;&gt;@font/your_font&lt;/item&gt; &lt;/style&gt; &lt;style name=&quot;TextAppearance.App.Caption&quot; parent=&quot;TextAppearance.MaterialComponents.Caption&quot;&gt; &lt;item name=&quot;fontFamily&quot;&gt;@font/your_font&lt;/item&gt; &lt;item name=&quot;android:fontFamily&quot;&gt;@font/your_font&lt;/item&gt; &lt;/style&gt; &lt;style name=&quot;ShapeAppearance.App.SmallComponent&quot; parent=&quot;ShapeAppearance.MaterialComponents.SmallComponent&quot;&gt; &lt;item name=&quot;cornerFamily&quot;&gt;cut&lt;/item&gt; &lt;item name=&quot;cornerSize&quot;&gt;4dp&lt;/item&gt; &lt;/style&gt; </code></pre> <p>Add the below line to your main theme or else you can set style to textinputlayout in your xml</p> <pre><code>&lt;item name=&quot;textInputStyle&quot;&gt;@style/Widget.App.TextInputLayout&lt;/item&gt; </code></pre>
{ "question_id": 30546430, "question_date": "2015-05-30T12:52:36.227Z", "question_score": 228, "tags": "android|android-edittext|android-design-library|android-textinputlayout", "answer_id": 30914037, "answer_date": "2015-06-18T11:24:52.057Z", "answer_score": 380 }
Please answer the following Stack Overflow question: Title: Execute bash script from URL <p>Say I have a file at the URL <code>http://mywebsite.example/myscript.txt</code> that contains a script:</p> <pre><code>#!/bin/bash echo &quot;Hello, world!&quot; read -p &quot;What is your name? &quot; name echo &quot;Hello, ${name}!&quot; </code></pre> <p>And I'd like to run this script without first saving it to a file. How do I do this?</p> <p>Now, I've seen the syntax:</p> <pre><code>bash &lt; &lt;(curl -s http://mywebsite.example/myscript.txt) </code></pre> <p>But this doesn't seem to work like it would if I saved to a file and then executed. For example readline doesn't work, and the output is just:</p> <pre><code>$ bash &lt; &lt;(curl -s http://mywebsite.example/myscript.txt) Hello, world! </code></pre> <p>Similarly, I've tried:</p> <pre><code>curl -s http://mywebsite.example/myscript.txt | bash -s -- </code></pre> <p>With the same results.</p> <p>Originally I had a solution like:</p> <pre><code>timestamp=`date +%Y%m%d%H%M%S` curl -s http://mywebsite.example/myscript.txt -o /tmp/.myscript.${timestamp}.tmp bash /tmp/.myscript.${timestamp}.tmp rm -f /tmp/.myscript.${timestamp}.tmp </code></pre> <p>But this seems sloppy, and I'd like a more elegant solution.</p> <p>I'm aware of the security issues regarding running a shell script from a URL, but let's ignore all of that for right now.</p>
<pre><code>source &lt;(curl -s http://mywebsite.example/myscript.txt) </code></pre> <p>ought to do it. Alternately, leave off the initial redirection on yours, which is redirecting standard input; <code>bash</code> takes a filename to execute just fine without redirection, and <code>&lt;(command)</code> syntax provides a path.</p> <pre><code>bash &lt;(curl -s http://mywebsite.example/myscript.txt) </code></pre> <p>It may be clearer if you look at the output of <code>echo &lt;(cat /dev/null)</code></p>
{ "question_id": 5735666, "question_date": "2011-04-20T19:35:22.737Z", "question_score": 228, "tags": "linux|bash|curl", "answer_id": 5735767, "answer_date": "2011-04-20T19:45:51.910Z", "answer_score": 272 }
Please answer the following Stack Overflow question: Title: Detecting Browser Autofill <p>How do you tell if a browser has auto filled a text-box? Especially with username &amp; password boxes that autofill around page load.</p> <p>My first question is when does this occur in the page load sequence? Is it before or after document.ready?</p> <p>Secondly how can I use logic to find out if this occurred? Its not that i want to stop this from occurring, just hook into the event. Preferably something like this:</p> <pre><code>if (autoFilled == true) { } else { } </code></pre> <p>If possible I would love to see a jsfiddle showing your answer.</p> <p><strong>Possible duplicates</strong></p> <p><a href="https://stackoverflow.com/questions/3535738/dom-event-for-browser-password-autofill">DOM event for browser password autofill?</a></p> <p><a href="https://stackoverflow.com/questions/4938242/browser-autofill-and-javascript-triggered-events">Browser Autofill and Javascript triggered events</a></p> <p>--Both these questions don't really explain what events are triggered, they just continuously recheck the text-box (not good for performance!).</p>
<p>The problem is autofill is handled differently by different browsers. Some dispatch the change event, some don't. So it is almost impossible to hook onto an event which is triggered when browser autocompletes an input field.</p> <ul> <li><p>Change event trigger for different browsers:</p> <ul> <li><p>For username/password fields:</p> <ol> <li>Firefox 4, IE 7, and IE 8 don't dispatch the change event.</li> <li>Safari 5 and Chrome 9 do dispatch the change event.</li> </ol></li> <li><p>For other form fields:</p> <ol> <li>IE 7 and IE 8 don't dispatch the change event.</li> <li>Firefox 4 does dispatch the change change event when users select a value from a list of suggestions and tab out of the field.</li> <li>Chrome 9 does not dispatch the change event.</li> <li>Safari 5 does dispatch the change event.</li> </ol></li> </ul></li> </ul> <p>You best options are to either disable autocomplete for a form using <code>autocomplete="off"</code> in your form or poll at regular interval to see if its filled.</p> <p>For your question on whether it is filled on or before document.ready again it varies from browser to browser and even version to version. For username/password fields only when you select a username password field is filled. So altogether you would have a very messy code if you try to attach to any event.</p> <p>You can have a good read on this <a href="http://avernet.blogspot.in/2010/11/autocomplete-and-javascript-change.html" rel="noreferrer">HERE</a></p>
{ "question_id": 11708092, "question_date": "2012-07-29T09:20:06.877Z", "question_score": 228, "tags": "javascript|jquery|events|event-handling|autofill", "answer_id": 11710295, "answer_date": "2012-07-29T15:07:47.180Z", "answer_score": 147 }
Please answer the following Stack Overflow question: Title: Cannot find module 'webpack/bin/config-yargs' <p>Getting error when running <code>webpack-dev-server --config config/webpack.dev.js --progress --profile --watch --content-base src/</code>. Here is the error log: </p> <pre><code>module.js:442 throw err; ^ Error: Cannot find module 'webpack/bin/config-yargs' at Function.Module._resolveFilename (module.js:440:15) at Function.Module._load (module.js:388:25) at Module.require (module.js:468:17) at require (internal/module.js:20:19) at Module._compile (module.js:541:32) at Object.Module._extensions..js (module.js:550:10) at Module.load (module.js:458:32) at tryModuleLoad (module.js:417:12) at Function.Module._load (module.js:409:3) </code></pre>
<p>I've had a similar problem. I think it's related to webpack version. After changing webpack version the latest everything was fine...</p>
{ "question_id": 40379139, "question_date": "2016-11-02T11:43:59.207Z", "question_score": 228, "tags": "webpack|webpack-dev-server", "answer_id": 41182205, "answer_date": "2016-12-16T10:24:21.307Z", "answer_score": 52 }
Please answer the following Stack Overflow question: Title: How can I specify working directory for popen <p>Is there a way to specify the running directory of command in Python's <code>subprocess.Popen()</code>?</p> <p>For example:</p> <pre><code>Popen('c:\mytool\tool.exe', workingdir='d:\test\local') </code></pre> <p>My Python script is located in <code>C:\programs\python</code></p> <p>Is is possible to run <code>C:\mytool\tool.exe</code> in the directory <code>D:\test\local</code>? </p> <p>How do I set the working directory for a sub-process?</p>
<p><code>subprocess.Popen</code> <a href="http://docs.python.org/library/subprocess.html#using-the-subprocess-module" rel="noreferrer">takes a <code>cwd</code> argument</a> to set the Current Working Directory; you'll also want to escape your backslashes (<code>'d:\\test\\local'</code>), or use <code>r'd:\test\local'</code> so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the <code>\t</code> part will be translated to a <kbd>tab</kbd>.</p> <p>So, your new line should look like:</p> <pre><code>subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local') </code></pre> <hr> <p>To use your Python script path as cwd, <code>import os</code> and define cwd using this:</p> <pre><code>os.path.dirname(os.path.realpath(__file__)) </code></pre>
{ "question_id": 1685157, "question_date": "2009-11-06T03:06:21.530Z", "question_score": 228, "tags": "python|subprocess|popen", "answer_id": 1685166, "answer_date": "2009-11-06T03:10:03.240Z", "answer_score": 338 }
Please answer the following Stack Overflow question: Title: Why use HttpClient for Synchronous Connection <p>I am building a class library to interact with an API. I need to call the API and process the XML response. I can see the benefits of using <code>HttpClient</code> for Asynchronous connectivity, but what I am doing is purely synchronous, so I cannot see any significant benefit over using <code>HttpWebRequest</code>.</p> <p>If anyone can shed any light I would greatly appreciate it. I am not one for using new technology for the sake of it.</p>
<p>For anyone coming across this now, .NET 5.0 has added a synchronous <code>Send</code> method to <code>HttpClient</code>. <a href="https://github.com/dotnet/runtime/pull/34948" rel="noreferrer">https://github.com/dotnet/runtime/pull/34948</a></p> <p>The merits as to why where discussed at length here: <a href="https://github.com/dotnet/runtime/issues/32125" rel="noreferrer">https://github.com/dotnet/runtime/issues/32125</a></p> <p>You can therefore use this instead of <code>SendAsync</code>. For example</p> <pre><code>public string GetValue() { var client = new HttpClient(); var webRequest = new HttpRequestMessage(HttpMethod.Post, &quot;http://your-api.com&quot;) { Content = new StringContent(&quot;{ 'some': 'value' }&quot;, Encoding.UTF8, &quot;application/json&quot;) }; var response = client.Send(webRequest); using var reader = new StreamReader(response.Content.ReadAsStream()); return reader.ReadToEnd(); } </code></pre> <p>This code is just a simplified example - it's not production ready.</p>
{ "question_id": 14435520, "question_date": "2013-01-21T09:17:31.323Z", "question_score": 228, "tags": "c#|asp.net|dotnet-httpclient", "answer_id": 66656039, "answer_date": "2021-03-16T13:18:57.687Z", "answer_score": 22 }
Please answer the following Stack Overflow question: Title: Count the number of occurrences of a string in a VARCHAR field? <p>I have a table like this:</p> <pre><code>TITLE | DESCRIPTION ------------------------------------------------ test1 | value blah blah value test2 | value test test3 | test test test test4 | valuevaluevaluevaluevalue </code></pre> <p>I am trying to figure out how to return the number of times a string occurs in each of the DESCRIPTION's.</p> <p>So, if I want to count the number of times 'value' appears, the sql statement will return this:</p> <pre><code>TITLE | DESCRIPTION | COUNT ------------------------------------------------------------ test1 | value blah blah value | 2 test2 | value test | 1 test3 | test test test | 0 test4 | valuevaluevaluevaluevalue | 5 </code></pre> <p>Is there any way to do this? I do not want to use php at all, just mysql.</p>
<p>This should do the trick:</p> <pre><code>SELECT title, description, ROUND ( ( LENGTH(description) - LENGTH( REPLACE ( description, &quot;value&quot;, &quot;&quot;) ) ) / LENGTH(&quot;value&quot;) ) AS count FROM &lt;table&gt; </code></pre>
{ "question_id": 12344795, "question_date": "2012-09-10T02:39:14.377Z", "question_score": 228, "tags": "mysql|sql", "answer_id": 12344881, "answer_date": "2012-09-10T02:56:58.783Z", "answer_score": 431 }
Please answer the following Stack Overflow question: Title: Default argument values in JavaScript functions <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/894860/how-do-i-make-a-default-value-for-a-parameter-to-a-javascript-function">How do I make a default value for a parameter to a javascript function</a> </p> </blockquote> <p>in PHP:</p> <pre><code>function func($a = 10, $b = 20){ // if func() is called with no arguments $a will be 10 and $ b will be 20 } </code></pre> <p>How can you do this in JavaScript?</p> <p>I get a error if I try to assign values in function arguments</p> <blockquote> <p>missing ) after formal parameters</p> </blockquote>
<p>In javascript you can call a function (even if it has parameters) without parameters.</p> <p>So you can add default values like this:</p> <pre><code>function func(a, b){ if (typeof(a)==='undefined') a = 10; if (typeof(b)==='undefined') b = 20; //your code } </code></pre> <p>and then you can call it like <code>func();</code> to use default parameters.</p> <p>Here's a test:</p> <pre><code>function func(a, b){ if (typeof(a)==='undefined') a = 10; if (typeof(b)==='undefined') b = 20; alert("A: "+a+"\nB: "+b); } //testing func(); func(80); func(100,200); </code></pre>
{ "question_id": 6486307, "question_date": "2011-06-26T19:48:17.267Z", "question_score": 228, "tags": "javascript|function|arguments", "answer_id": 6486357, "answer_date": "2011-06-26T19:57:11.377Z", "answer_score": 382 }
Please answer the following Stack Overflow question: Title: Find all unchecked checkboxes in jQuery <p>I have a list of checkboxes:</p> <pre><code>&lt;input type=&quot;checkbox&quot; name=&quot;answer&quot; id=&quot;id_1' value=&quot;1&quot; /&gt; &lt;input type=&quot;checkbox&quot; name=&quot;answer&quot; id=&quot;id_2' value=&quot;2&quot; /&gt; ... &lt;input type=&quot;checkbox&quot; name=&quot;answer&quot; id=&quot;id_n' value=&quot;n&quot; /&gt; </code></pre> <p>I can collect all the values of checked checkboxes; my question is how can get all the values of unchecked checkboxes? I tried:</p> <pre><code>$(&quot;input:unchecked&quot;).val(); </code></pre> <p>to get an unchecked checkbox's value, but I got:</p> <blockquote> <p>Syntax error, unrecognized expression: unchecked.</p> </blockquote> <p>Can anybody shed a light on this issue? Thank you!</p>
<p>As the error message states, jQuery does not include a <code>:unchecked</code> selector.<br> Instead, you need to invert the <code>:checked</code> selector:</p> <pre><code>$("input:checkbox:not(:checked)") </code></pre>
{ "question_id": 8465821, "question_date": "2011-12-11T17:07:34.200Z", "question_score": 228, "tags": "jquery|html|input|checkbox", "answer_id": 8465833, "answer_date": "2011-12-11T17:09:59.370Z", "answer_score": 486 }
Please answer the following Stack Overflow question: Title: How does tuple comparison work in Python? <p>I have been reading the <em>Core Python</em> programming book, and the author shows an example like: </p> <pre><code>(4, 5) &lt; (3, 5) # Equals false </code></pre> <p>So, I'm wondering, how/why does it equal false? How does python compare these two tuples?</p> <p>Btw, it's not explained in the book.</p>
<p>Tuples are compared position by position: the first item of the first tuple is compared to the first item of the second tuple; if they are not equal (i.e. the first is greater or smaller than the second) then that's the result of the comparison, else the second item is considered, then the third and so on.</p> <p>See <a href="https://docs.python.org/3/library/stdtypes.html#common-sequence-operations" rel="noreferrer">Common Sequence Operations</a>:</p> <blockquote> <p>Sequences of the same type also support comparisons. In particular, tuples and lists are compared lexicographically by comparing corresponding elements. This means that to compare equal, every element must compare equal and the two sequences must be of the same type and have the same length.</p> </blockquote> <p>Also <a href="https://docs.python.org/3/reference/expressions.html#value-comparisons" rel="noreferrer">Value Comparisons</a> for further details:</p> <blockquote> <p>Lexicographical comparison between built-in collections works as follows:</p> <ul> <li>For two collections to compare equal, they must be of the same type, have the same length, and each pair of corresponding elements must compare equal (for example, <code>[1,2] == (1,2)</code> is false because the type is not the same).</li> <li>Collections that support order comparison are ordered the same as their first unequal elements (for example, <code>[1,2,x] &lt;= [1,2,y]</code> has the same value as <code>x &lt;= y</code>). If a corresponding element does not exist, the shorter collection is ordered first (for example, <code>[1,2] &lt; [1,2,3]</code> is true).</li> </ul> </blockquote> <p>If not equal, the sequences are ordered the same as their first differing elements. For example, cmp([1,2,x], [1,2,y]) returns the same as cmp(x,y). If the corresponding element does not exist, the shorter sequence is considered smaller (for example, [1,2] &lt; [1,2,3] returns True).</p> <p><strong>Note 1</strong>: <code>&lt;</code> and <code>&gt;</code> do not mean &quot;smaller than&quot; and &quot;greater than&quot; but &quot;is before&quot; and &quot;is after&quot;: so (0, 1) &quot;is before&quot; (1, 0).</p> <p><strong>Note 2</strong>: tuples must not be considered as <em>vectors in a n-dimensional space</em>, compared according to their length.</p> <p><strong>Note 3</strong>: referring to question <a href="https://stackoverflow.com/questions/36911617/python-2-tuple-comparison">https://stackoverflow.com/questions/36911617/python-2-tuple-comparison</a>: do not think that a tuple is &quot;greater&quot; than another only if any element of the first is greater than the corresponding one in the second.</p>
{ "question_id": 5292303, "question_date": "2011-03-13T20:52:29.540Z", "question_score": 228, "tags": "python|comparison|tuples", "answer_id": 5292332, "answer_date": "2011-03-13T20:58:27.667Z", "answer_score": 245 }
Please answer the following Stack Overflow question: Title: Checkout old commit and make it a new commit <p>On Git, say I mess up my commits, and I want to make the version 3 commits ago as the new version. If I do <code>git checkout xxxx</code>, it creates a new branch and it seems like I can only merge it? Could I make this the new "master version"?</p> <p>I want:</p> <pre><code>A-B-C-D-E </code></pre> <p>to become</p> <pre><code>A-B-C-D-E-F </code></pre> <p>where F has exactly the same content as C</p> <p>If I use <code>git revert xxxx</code> instead, it seems like it definitely will have conflicts and I need to manually resolve it.</p> <p>What I really want is just make the old commit at some point the new commit, regardless of what's in my working directory or the latest commit.</p> <p>How would I go about doing this?</p>
<pre><code>git rm -r . git checkout HEAD~3 . git commit </code></pre> <p>After the commit, files in the new <code>HEAD</code> will be the same as they were in the revision <code>HEAD~3</code>.</p>
{ "question_id": 3380805, "question_date": "2010-08-01T05:00:52.687Z", "question_score": 228, "tags": "git", "answer_id": 3382249, "answer_date": "2010-08-01T13:46:36.957Z", "answer_score": 237 }
Please answer the following Stack Overflow question: Title: Why would one use nested classes in C++? <p>Can someone please point me towards some nice resources for understanding and using nested classes? I have some material like Programming Principles and things like this <a href="https://www.ibm.com/support/knowledgecenter/en/SSLTBW_2.1.0/com.ibm.zos.v2r1.cbclx01/cplr061.htm" rel="noreferrer"><em>IBM Knowledge Center - Nested Classes</em></a></p> <p>But I'm still having trouble understanding their purpose. Could someone please help me?</p>
<p>Nested classes are cool for hiding implementation details.</p> <p>List:</p> <pre><code>class List { public: List(): head(nullptr), tail(nullptr) {} private: class Node { public: int data; Node* next; Node* prev; }; private: Node* head; Node* tail; }; </code></pre> <p>Here I don't want to expose Node as other people may decide to use the class and that would hinder me from updating my class as anything exposed is part of the public API and must be maintained <strong>forever</strong>. By making the class private, I not only hide the implementation I am also saying this is mine and I may change it at any time so you can not use it.</p> <p>Look at <code>std::list</code> or <code>std::map</code> they all contain hidden classes (or do they?). The point is they may or may not, but because the implementation is private and hidden the builders of the STL were able to update the code without affecting how you used the code, or leaving a lot of old baggage laying around the STL because they need to maintain backwards compatibility with some fool who decided they wanted to use the Node class that was hidden inside <code>list</code>.</p>
{ "question_id": 4571355, "question_date": "2010-12-31T17:14:58.903Z", "question_score": 228, "tags": "c++|nested|inner-classes", "answer_id": 4571683, "answer_date": "2010-12-31T18:27:26.510Z", "answer_score": 273 }
Please answer the following Stack Overflow question: Title: Parcelable encountered IOException writing serializable object getactivity() <p>so I am getting this in logcat:</p> <pre><code>java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = com.resources.student_list.Student) </code></pre> <p>I know this means that my student class is not serializable, but it is, here is my student class:</p> <pre><code>import java.io.Serializable; public class Student implements Comparable&lt;Student&gt;, Serializable{ private static final long serialVersionUID = 1L; private String firstName, lastName; private DSLL&lt;Grade&gt; gradeList; public Student() { firstName = ""; lastName = ""; gradeList = new DSLL&lt;Grade&gt;(); } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public DSLL&lt;Grade&gt; getGradeList() { return gradeList; } public void setGradeList(DSLL&lt;Grade&gt; gradeList) { this.gradeList = gradeList; } public int compareTo(Student arg0) { return this.lastName.compareTo(arg0.getLastName()); } } </code></pre> <p>and this is the code that is using the getIntent() method:</p> <pre><code>public void onItemClick(AdapterView&lt;?&gt; parent, View viewClicked, int pos, long id) { Student clickedStudent = studentList.get(pos); int position = pos; Intent intent = new Intent(getActivity().getApplicationContext(), ShowStudentActivity.class); Log.e("CINTENT","CREATED!!!"); intent.putExtra("clickedStudent",clickedStudent); intent.putExtra("newStudentList",newStudentList); intent.putExtra("position",position); Log.e("putExtra","Passed"); Log.e("Start activity","passed"); startActivity(intent); } }); </code></pre> <p>please help me figure out whats wrong with this.</p> <p>here is the whole LogCat:</p> <pre><code>04-17 16:12:28.890: E/AndroidRuntime(22815): FATAL EXCEPTION: main 04-17 16:12:28.890: E/AndroidRuntime(22815): java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = com.resources.student_list.Student) 04-17 16:12:28.890: E/AndroidRuntime(22815): at android.os.Parcel.writeSerializable(Parcel.java:1181) 04-17 16:12:28.890: E/AndroidRuntime(22815): at android.os.Parcel.writeValue(Parcel.java:1135) 04-17 16:12:28.890: E/AndroidRuntime(22815): at android.os.Parcel.writeMapInternal(Parcel.java:493) 04-17 16:12:28.890: E/AndroidRuntime(22815): at android.os.Bundle.writeToParcel(Bundle.java:1612) 04-17 16:12:28.890: E/AndroidRuntime(22815): at android.os.Parcel.writeBundle(Parcel.java:507) 04-17 16:12:28.890: E/AndroidRuntime(22815): at android.content.Intent.writeToParcel(Intent.java:6111) 04-17 16:12:28.890: E/AndroidRuntime(22815): at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:1613) 04-17 16:12:28.890: E/AndroidRuntime(22815): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1422) 04-17 16:12:28.890: E/AndroidRuntime(22815): at android.app.Activity.startActivityForResult(Activity.java:3191) 04-17 16:12:28.890: E/AndroidRuntime(22815): at android.support.v4.app.FragmentActivity.startActivityFromFragment(FragmentActivity.java:848) 04-17 16:12:28.890: E/AndroidRuntime(22815): at android.support.v4.app.Fragment.startActivity(Fragment.java:878) 04-17 16:12:28.890: E/AndroidRuntime(22815): at com.example.student_lists.MainActivity$DummySectionFragment$2.onItemClick(MainActivity.java:477) 04-17 16:12:28.890: E/AndroidRuntime(22815): at android.widget.AdapterView.performItemClick(AdapterView.java:292) 04-17 16:12:28.890: E/AndroidRuntime(22815): at android.widget.AbsListView.performItemClick(AbsListView.java:1058) 04-17 16:12:28.890: E/AndroidRuntime(22815): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2514) 04-17 16:12:28.890: E/AndroidRuntime(22815): at android.widget.AbsListView$1.run(AbsListView.java:3168) 04-17 16:12:28.890: E/AndroidRuntime(22815): at android.os.Handler.handleCallback(Handler.java:605) 04-17 16:12:28.890: E/AndroidRuntime(22815): at android.os.Handler.dispatchMessage(Handler.java:92) 04-17 16:12:28.890: E/AndroidRuntime(22815): at android.os.Looper.loop(Looper.java:137) 04-17 16:12:28.890: E/AndroidRuntime(22815): at android.app.ActivityThread.main(ActivityThread.java:4447) 04-17 16:12:28.890: E/AndroidRuntime(22815): at java.lang.reflect.Method.invokeNative(Native Method) 04-17 16:12:28.890: E/AndroidRuntime(22815): at java.lang.reflect.Method.invoke(Method.java:511) 04-17 16:12:28.890: E/AndroidRuntime(22815): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 04-17 16:12:28.890: E/AndroidRuntime(22815): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 04-17 16:12:28.890: E/AndroidRuntime(22815): at dalvik.system.NativeStart.main(Native Method) 04-17 16:12:28.890: E/AndroidRuntime(22815): Caused by: java.io.NotSerializableException: com.resources.student_list.DSLL$DNode 04-17 16:12:28.890: E/AndroidRuntime(22815): at java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1364) 04-17 16:12:28.890: E/AndroidRuntime(22815): at java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1671) 04-17 16:12:28.890: E/AndroidRuntime(22815): at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1517) 04-17 16:12:28.890: E/AndroidRuntime(22815): at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1481) 04-17 16:12:28.890: E/AndroidRuntime(22815): at java.io.ObjectOutputStream.writeFieldValues(ObjectOutputStream.java:979) 04-17 16:12:28.890: E/AndroidRuntime(22815): at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:368) 04-17 16:12:28.890: E/AndroidRuntime(22815): at java.io.ObjectOutputStream.writeHierarchy(ObjectOutputStream.java:1074) 04-17 16:12:28.890: E/AndroidRuntime(22815): at java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1404) 04-17 16:12:28.890: E/AndroidRuntime(22815): at java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1671) 04-17 16:12:28.890: E/AndroidRuntime(22815): at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1517) 04-17 16:12:28.890: E/AndroidRuntime(22815): at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1481) 04-17 16:12:28.890: E/AndroidRuntime(22815): at java.io.ObjectOutputStream.writeFieldValues(ObjectOutputStream.java:979) 04-17 16:12:28.890: E/AndroidRuntime(22815): at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:368) 04-17 16:12:28.890: E/AndroidRuntime(22815): at java.io.ObjectOutputStream.writeHierarchy(ObjectOutputStream.java:1074) 04-17 16:12:28.890: E/AndroidRuntime(22815): at java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1404) 04-17 16:12:28.890: E/AndroidRuntime(22815): at java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1671) 04-17 16:12:28.890: E/AndroidRuntime(22815): at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1517) 04-17 16:12:28.890: E/AndroidRuntime(22815): at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1481) 04-17 16:12:28.890: E/AndroidRuntime(22815): at android.os.Parcel.writeSerializable(Parcel.java:1176) </code></pre>
<pre><code>Caused by: java.io.NotSerializableException: com.resources.student_list.DSLL$DNode </code></pre> <p>Your <code>DSLL</code> class appears to have a <code>DNode</code> static inner class, and <code>DNode</code> is not <code>Serializable</code>.</p>
{ "question_id": 23142893, "question_date": "2014-04-17T20:32:34.463Z", "question_score": 228, "tags": "android|android-intent|serialization", "answer_id": 23143086, "answer_date": "2014-04-17T20:43:36.910Z", "answer_score": 387 }
Please answer the following Stack Overflow question: Title: CSS horizontal centering of a fixed div? <pre><code>#menu { position: fixed; width: 800px; background: rgb(255, 255, 255); /* The Fallback */ background: rgba(255, 255, 255, 0.8); margin-top: 30px; } </code></pre> <p>I know this question is a million times out there, however I can't find a solution to my case. I've got a div, which should be fixed on the screen, even if the page is scrolled it should always stay CENTERED in the middle of the screen!</p> <p>The div should have <code>500px</code> width, should be <code>30px</code> away from the top (margin-top), should be horizontally centered in the middle of the page for all browser sizes and should not move when scrolling the rest of the page.</p> <p>Is that possible?</p>
<pre><code>left: 50%; margin-left: -400px; /* Half of the width */ </code></pre>
{ "question_id": 3157372, "question_date": "2010-07-01T11:41:32.277Z", "question_score": 228, "tags": "html|css|centering", "answer_id": 3157395, "answer_date": "2010-07-01T11:45:04.020Z", "answer_score": 167 }
Please answer the following Stack Overflow question: Title: How can I quickly sum all numbers in a file? <p>I have a file which contains several thousand numbers, each on it's own line:</p> <pre><code>34 42 11 6 2 99 ... </code></pre> <p>I'm looking to write a script which will print the sum of all numbers in the file. I've got a solution, but it's not very efficient. (It takes several minutes to run.) I'm looking for a more efficient solution. Any suggestions?</p>
<p>For a Perl one-liner, it's basically the same thing as the <code>awk</code> solution in <a href="https://stackoverflow.com/questions/2702564/script-to-sum-all-numbers-in-a-file-linux/2702577#2702577">Ayman Hourieh's answer</a>:</p> <pre><code> % perl -nle '$sum += $_ } END { print $sum' </code></pre> <p>If you're curious what Perl one-liners do, you can deparse them:</p> <pre><code> % perl -MO=Deparse -nle '$sum += $_ } END { print $sum' </code></pre> <p>The result is a more verbose version of the program, in a form that no one would ever write on their own:</p> <pre><code>BEGIN { $/ = "\n"; $\ = "\n"; } LINE: while (defined($_ = &lt;ARGV&gt;)) { chomp $_; $sum += $_; } sub END { print $sum; } -e syntax OK </code></pre> <p>Just for giggles, I tried this with a file containing 1,000,000 numbers (in the range 0 - 9,999). On my Mac Pro, it returns virtually instantaneously. That's too bad, because I was hoping using <code>mmap</code> would be really fast, but it's just the same time:</p> <pre><code>use 5.010; use File::Map qw(map_file); map_file my $map, $ARGV[0]; $sum += $1 while $map =~ m/(\d+)/g; say $sum; </code></pre>
{ "question_id": 2702564, "question_date": "2010-04-23T23:36:12.217Z", "question_score": 228, "tags": "linux|perl|bash|shell|awk", "answer_id": 2702614, "answer_date": "2010-04-23T23:49:31.150Z", "answer_score": 117 }
Please answer the following Stack Overflow question: Title: Link with target="_blank" and rel="noopener noreferrer" still vulnerable? <p>I see people recommending that whenever one uses <code>target="_blank"</code> in a link to open it in a different window, they should put <code>rel="noopener noreferrer"</code>. I wonder how does this prevent me from using Developer Tools in Chrome, for example, and removing the rel attribute. Then clicking the link...</p> <p>Is that an easy way to still keep the vulnerability?</p>
<p>You may be misunderstanding the vulnerability. You can read more about it here: <a href="https://www.jitbit.com/alexblog/256-targetblank---the-most-underestimated-vulnerability-ever/" rel="noreferrer">https://www.jitbit.com/alexblog/256-targetblank---the-most-underestimated-vulnerability-ever/</a></p> <p>Essentially, adding <code>rel=&quot;noopener noreferrer&quot;</code> to links protects your site's users against having the site you've <em>linked to</em> potentially hijacking the browser (via rogue JS).</p> <p>You're asking about removing that attribute via Developer Tools - that would only potentially expose <em>you</em> (the person tampering with the attribute) to the vulnerability.</p> <p><strong>Update as of 2021:</strong> All current versions of major browsers now automatically use the behavior of <code>rel=&quot;noopener&quot;</code> for any <code>target=&quot;_blank&quot;</code> link, nullifying this issue. See more at <a href="https://chromestatus.com/feature/6140064063029248" rel="noreferrer">chromestatus.com</a>.</p>
{ "question_id": 50709625, "question_date": "2018-06-05T22:08:25.717Z", "question_score": 228, "tags": "html", "answer_id": 50709724, "answer_date": "2018-06-05T22:19:54.710Z", "answer_score": 308 }
Please answer the following Stack Overflow question: Title: How can I enable the Windows Server Task Scheduler History recording? <p>I have a Windows Server 2008 with scheduled tasks running, mainly .bat files calling PHP files. I have 2 users on the server, one Admin and the other is a Standard user. </p> <p>I used the Standard User to clear the history log in the Task Scheduler History tab using the Event Viewer. Now it won't record any history anymore. All of the scheduled tasks no longer have history in the History tab. However, the Last Run Result returns 0x0 and the schedulers are working fine.<br> Please advise.</p>
<p>Step 1: Open an elevated Task Scheduler (ie. right-click on the Task Scheduler icon and choose <em>Run as administrator</em>)</p> <p>Step 2: In the <strong>Actions pane</strong> (right pane, <em>not</em> the actions <em>tab</em>), click <em>Enable All Tasks History</em></p> <p>That's it. Not sure why this isn't on by default, but it isn't. </p>
{ "question_id": 11013132, "question_date": "2012-06-13T10:39:20.620Z", "question_score": 228, "tags": "windows-server-2008|scheduled-tasks|windows-task-scheduler", "answer_id": 14651161, "answer_date": "2013-02-01T16:50:59.580Z", "answer_score": 413 }
Please answer the following Stack Overflow question: Title: How do I get the dialer to open with phone number displayed? <p>I don't need to call the phone number, I just need the dialer to open with the phone number already displayed. What <code>Intent</code> should I use to achieve this?</p>
<p>Two ways to achieve it.</p> <p><strong>1) Need to start the dialer via code, without user interaction.</strong></p> <p>You need <code>Action_Dial</code>,</p> <p>use below code it will open Dialer with number specified</p> <pre><code>Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse(&quot;tel:0123456789&quot;)); startActivity(intent); </code></pre> <p><strong>The 'tel:' prefix is required</strong>, otherwhise the following exception will be thrown: <em>java.lang.IllegalStateException: Could not execute method of the activity.</em></p> <p><strong>Action_Dial doesn't require any permission.</strong></p> <p><strong>If you want to initiate the call directly without user's interaction</strong> , You can use action <code>Intent.ACTION_CALL</code>. In this case, you must add the following permission in your AndroidManifest.xml:</p> <pre><code>&lt;uses-permission android:name=&quot;android.permission.CALL_PHONE&quot; /&gt; </code></pre> <p><strong>2) Need user to click on Phone_Number string and start the call.</strong></p> <pre><code>android:autoLink=&quot;phone&quot; </code></pre> <p>You need to use TextView with below property.</p> <p><a href="http://developer.android.com/reference/android/widget/TextView.html#attr_android:autoLink" rel="noreferrer">android:autoLink=&quot;phone&quot; android:linksClickable=&quot;true&quot; a textView property</a></p> <p>You don't need to use intent or to get permission via this way.</p>
{ "question_id": 11699819, "question_date": "2012-07-28T09:26:10.500Z", "question_score": 228, "tags": "android|android-intent|phone-number", "answer_id": 11699829, "answer_date": "2012-07-28T09:27:49.727Z", "answer_score": 601 }
Please answer the following Stack Overflow question: Title: Laravel Unknown Column 'updated_at' <p>I've just started with Laravel and I get the following error: </p> <blockquote> <p>Unknown column 'updated_at' insert into gebruikers (naam, wachtwoord, updated_at, created_at)</p> </blockquote> <p>I know the error is from the timestamp column when you migrate a table but I'm not using the <code>updated_at</code> field. I used to use it when I followed the Laravel tutorial but now that I am making (or attempting to make) my own stuff. I get this error even though I don't use timestamps. I can't seem to find the place where it's being used. This is the code:</p> <p><strong>Controller</strong></p> <pre class="lang-php prettyprint-override"><code>public function created() { if (!User::isValidRegister(Input::all())) { return Redirect::back()-&gt;withInput()-&gt;withErrors(User::$errors); } // Register the new user or whatever. $user = new User; $user-&gt;naam = Input::get('naam'); $user-&gt;wachtwoord = Hash::make(Input::get('password')); $user-&gt;save(); return Redirect::to('/users'); } </code></pre> <p><strong>Route</strong></p> <pre><code>Route::get('created', 'UserController@created'); </code></pre> <p><strong>Model</strong></p> <pre><code>public static $rules_register = [ 'naam' =&gt; 'unique:gebruikers,naam' ]; public static $errors; protected $table = 'gebruikers'; public static function isValidRegister($data) { $validation = Validator::make($data, static::$rules_register); if ($validation-&gt;passes()) { return true; } static::$errors = $validation-&gt;messages(); return false; } </code></pre> <p>I must be forgetting something... What am I doing wrong here?</p>
<p>In the model, write the below code;</p> <pre><code>public $timestamps = false; </code></pre> <p>This would work.</p> <p>Explanation : By default laravel will expect created_at &amp; updated_at column in your table. By making it to false it will override the default setting.</p>
{ "question_id": 28277955, "question_date": "2015-02-02T12:38:40.293Z", "question_score": 228, "tags": "php|mysql|laravel|laravel-migrations", "answer_id": 28277980, "answer_date": "2015-02-02T12:40:04.303Z", "answer_score": 604 }
Please answer the following Stack Overflow question: Title: What is Java EE? <p>I realize that literally it translates to Java Enterprise Edition. But what I'm asking is what does this really mean? When a company requires Java EE experience, what are they really asking for? Experience with EJBs? Experience with Java web apps? </p> <p>I suspect that this means something different to different people and the definition is subjective.</p>
<p>Java EE is actually a collection of technologies and APIs for the Java platform designed to support "Enterprise" Applications which can generally be classed as large-scale, distributed, transactional and highly-available applications designed to support mission-critical business requirements. </p> <p>In terms of what an employee is looking for in specific techs, it is quite hard to say, because the playing field has kept changing over the last five years. It really is about the <em>class</em> of problems that are being solved more than anything else. Transactions and distribution are key.</p>
{ "question_id": 106820, "question_date": "2008-09-20T02:29:30.773Z", "question_score": 228, "tags": "jakarta-ee", "answer_id": 106847, "answer_date": "2008-09-20T02:43:37.090Z", "answer_score": 144 }
Please answer the following Stack Overflow question: Title: `break` and `continue` in `forEach` in Kotlin <p>Kotlin has very nice iterating functions, like <code>forEach</code> or <code>repeat</code>, but I am not able to make the <code>break</code> and <code>continue</code> operators work with them (both local and non-local):</p> <pre><code>repeat(5) { break } (1..5).forEach { continue@forEach } </code></pre> <p>The goal is to mimic usual loops with the functional syntax as close as it might be. It was definitely possible in some older versions of Kotlin, but I struggle to reproduce the syntax. </p> <p>The problem might be a bug with labels (M12), but I think that the first example should work anyway.</p> <p>It seems to me that I've read somewhere about a special trick/annotation, but I could not find any reference on the subject. Might look like the following:</p> <pre><code>public inline fun repeat(times: Int, @loop body: (Int) -&gt; Unit) { for (index in 0..times - 1) { body(index) } } </code></pre>
<p><strong>Edit</strong>:<br /> According to Kotlin's <a href="https://kotlinlang.org/docs/reference/returns.html" rel="noreferrer">documentation</a>, it is possible to simulate <code>continue</code> using annotations.</p> <pre><code>fun foo() { listOf(1, 2, 3, 4, 5).forEach lit@ { if (it == 3) return@lit // local return to the caller of the lambda, i.e. the forEach loop print(it) } print(&quot; done with explicit label&quot;) } </code></pre> <p>If you want to simulate a <code>break</code>, just add a <code>run</code> block</p> <pre><code>fun foo() { run lit@ { listOf(1, 2, 3, 4, 5).forEach { if (it == 3) return@lit // local return to the caller of the lambda, i.e. the forEach loop print(it) } print(&quot; done with explicit label&quot;) } } </code></pre> <hr /> <p><strong>Original Answer</strong>:<br /> Since you supply a <code>(Int) -&gt; Unit</code>, you can't break from it, since the compiler do not know that it is used in a loop.</p> <p>You have few options:</p> <p><strong>Use a regular for loop:</strong></p> <pre><code>for (index in 0 until times) { // your code here } </code></pre> <p><strong>If the loop is the last code in the method</strong><br /> you can use <code>return</code> to get out of the method (or <code>return value</code> if it is not <code>unit</code> method).</p> <p><strong>Use a method</strong><br /> Create a custom repeat method method that returns <code>Boolean</code> for continuing.</p> <pre><code>public inline fun repeatUntil(times: Int, body: (Int) -&gt; Boolean) { for (index in 0 until times) { if (!body(index)) break } } </code></pre>
{ "question_id": 32540947, "question_date": "2015-09-12T16:11:54.193Z", "question_score": 228, "tags": "loops|foreach|lambda|kotlin", "answer_id": 32541601, "answer_date": "2015-09-12T17:18:23.863Z", "answer_score": 194 }
Please answer the following Stack Overflow question: Title: How many parameters are too many? <p>Routines can have parameters, that's no news. You can define as many parameters as you may need, but too many of them will make your routine difficult to understand and maintain.</p> <p>Of course, you could use a structured variable as a workaround: putting all those variables in a single struct and passing it to the routine. In fact, using structures to simplify parameter lists is one of the techniques described by Steve McConnell in <em>Code Complete</em>. But as he says:</p> <blockquote> <p><em>Careful programmers avoid bundling data any more than is logically necessary.</em></p> </blockquote> <p>So if your routine has too many parameters or you use a struct to disguise a big parameter list, you're probably doing something wrong. That is, you're not keeping coupling loose.</p> <p>My question is, <strong>when can I consider a parameter list too big?</strong> I think that more than 5 parameters, are too many. What do you think?</p>
<p>When is something considered so obscene as to be something that can be regulated despite the 1st Amendment guarantee to free speech? According to Justice Potter Stewart, "I know it when I see it." The same holds here.</p> <p>I hate making hard and fast rules like this because the answer changes not only depending on the size and scope of your project, but I think it changes even down to the module level. Depending on what your method is doing, or what the class is supposed to represent, it's quite possible that 2 arguments is too many and is a symptom of too much coupling.</p> <p>I would suggest that by asking the question in the first place, and qualifying your question as much as you did, that you really know all of this. The best solution here is not to rely on a hard and fast number, but instead look towards design reviews and code reviews among your peers to identify areas where you have low cohesion and tight coupling.</p> <p>Never be afraid to show your colleagues your work. If you are afraid to, that's probably the bigger sign that something is wrong with your code, and that you <em>already know it</em>.</p>
{ "question_id": 174968, "question_date": "2008-10-06T16:14:48.670Z", "question_score": 228, "tags": "parameters|language-agnostic", "answer_id": 175034, "answer_date": "2008-10-06T16:25:52.597Z", "answer_score": 162 }
Please answer the following Stack Overflow question: Title: How do I raise the same Exception with a custom message in Python? <p>I have this <code>try</code> block in my code:</p> <pre><code>try: do_something_that_might_raise_an_exception() except ValueError as err: errmsg = 'My custom error message.' raise ValueError(errmsg) </code></pre> <p>Strictly speaking, I am actually raising <em>another</em> <code>ValueError</code>, not the <code>ValueError</code> thrown by <code>do_something...()</code>, which is referred to as <code>err</code> in this case. How do I attach a custom message to <code>err</code>? I try the following code but fails due to <code>err</code>, a <code>ValueError</code> <strong>instance</strong>, not being callable:</p> <pre><code>try: do_something_that_might_raise_an_exception() except ValueError as err: errmsg = 'My custom error message.' raise err(errmsg) </code></pre>
<p>Update: <strong>For Python 3, check <a href="https://stackoverflow.com/a/29442282/42223">Ben's answer</a></strong></p> <hr> <p>To attach a message to the current exception and re-raise it: (the outer try/except is just to show the effect)</p> <p>For python 2.x where x>=6:</p> <pre><code>try: try: raise ValueError # something bad... except ValueError as err: err.message=err.message+" hello" raise # re-raise current exception except ValueError as e: print(" got error of type "+ str(type(e))+" with message " +e.message) </code></pre> <p>This will also do the right thing <strong>if <code>err</code> is <em>derived</em></strong> from <code>ValueError</code>. For example <code>UnicodeDecodeError</code>. </p> <p>Note that you can add whatever you like to <code>err</code>. For example <code>err.problematic_array=[1,2,3]</code>.</p> <hr> <p><strong>Edit:</strong> @Ducan points in a comment the above does not work with python 3 since <code>.message</code> is not a member of <code>ValueError</code>. Instead you could use this (valid python 2.6 or later or 3.x):</p> <pre><code>try: try: raise ValueError except ValueError as err: if not err.args: err.args=('',) err.args = err.args + ("hello",) raise except ValueError as e: print(" error was "+ str(type(e))+str(e.args)) </code></pre> <p><strong>Edit2:</strong></p> <p>Depending on what the purpose is, you can also opt for adding the extra information under your own variable name. For both python2 and python3:</p> <pre><code>try: try: raise ValueError except ValueError as err: err.extra_info = "hello" raise except ValueError as e: print(" error was "+ str(type(e))+str(e)) if 'extra_info' in dir(e): print e.extra_info </code></pre>
{ "question_id": 9157210, "question_date": "2012-02-06T08:07:56.937Z", "question_score": 228, "tags": "python|exception|message", "answer_id": 9157277, "answer_date": "2012-02-06T08:16:49.467Z", "answer_score": 124 }
Please answer the following Stack Overflow question: Title: Accessing an array out of bounds gives no error, why? <p>I am assigning values in a C++ program out of the bounds like this:</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main() { int array[2]; array[0] = 1; array[1] = 2; array[3] = 3; array[4] = 4; cout &lt;&lt; array[3] &lt;&lt; endl; cout &lt;&lt; array[4] &lt;&lt; endl; return 0; } </code></pre> <p>The program prints <code>3</code> and <code>4</code>. It should not be possible. I am using g++ 4.3.3</p> <p>Here is compile and run command</p> <pre><code>$ g++ -W -Wall errorRange.cpp -o errorRange $ ./errorRange 3 4 </code></pre> <p>Only when assigning <code>array[3000]=3000</code> does it give me a segmentation fault.</p> <p>If gcc doesn't check for array bounds, how can I be sure if my program is correct, as it can lead to some serious issues later?</p> <p>I replaced the above code with</p> <pre><code>vector&lt;int&gt; vint(2); vint[0] = 0; vint[1] = 1; vint[2] = 2; vint[5] = 5; cout &lt;&lt; vint[2] &lt;&lt; endl; cout &lt;&lt; vint[5] &lt;&lt; endl; </code></pre> <p>and this one also produces no error. </p>
<p>Welcome to every C/C++ programmer's bestest friend: <strong>Undefined Behavior</strong>. </p> <p>There is a lot that is not specified by the language standard, for a variety of reasons. This is one of them.</p> <p>In general, whenever you encounter undefined behavior, <em>anything</em> might happen. The application may crash, it may freeze, it may eject your CD-ROM drive or make demons come out of your nose. It may format your harddrive or email all your porn to your grandmother.</p> <p>It may even, if you are really unlucky, <em>appear</em> to work correctly.</p> <p>The language simply says what should happen if you access the elements <em>within</em> the bounds of an array. It is left undefined what happens if you go out of bounds. It might <em>seem</em> to work today, on your compiler, but it is not legal C or C++, and there is no guarantee that it'll still work the next time you run the program. Or that it hasn't overwritten essential data even now, and you just haven't encountered the problems, that it <em>is</em> going to cause — yet.</p> <p>As for <em>why</em> there is no bounds checking, there are a couple aspects to the answer:</p> <ul> <li>An array is a leftover from C. C arrays are about as primitive as you can get. Just a sequence of elements with contiguous addresses. There is no bounds checking because it is simply exposing raw memory. Implementing a robust bounds-checking mechanism would have been almost impossible in C.</li> <li>In C++, bounds-checking is possible on class types. But an array is still the plain old C-compatible one. It is not a class. Further, C++ is also built on another rule which makes bounds-checking non-ideal. The C++ guiding principle is "you don't pay for what you don't use". If your code is correct, you don't need bounds-checking, and you shouldn't be forced to pay for the overhead of runtime bounds-checking.</li> <li>So C++ offers the <code>std::vector</code> class template, which allows both. <code>operator[]</code> is designed to be efficient. The language standard does not require that it performs bounds checking (although it does not forbid it either). A vector also has the <code>at()</code> member function which <em>is guaranteed</em> to perform bounds-checking. So in C++, you get the best of both worlds if you use a vector. You get array-like performance without bounds-checking, <em>and</em> you get the ability to use bounds-checked access when you want it.</li> </ul>
{ "question_id": 1239938, "question_date": "2009-08-06T16:12:14.650Z", "question_score": 228, "tags": "c++|arrays", "answer_id": 1239977, "answer_date": "2009-08-06T16:18:28.727Z", "answer_score": 460 }
Please answer the following Stack Overflow question: Title: What is the difference between a JavaBean and a POJO? <p>I'm not sure about the difference. I'm using Hibernate and, in some books, they use JavaBean and POJO as an interchangeable term. I want to know if there is a difference, not just in the Hibernate context, but as general concepts.</p>
<p>A JavaBean follows certain conventions. Getter/setter naming, having a public default constructor, being serialisable etc. See <a href="http://docstore.mik.ua/orelly/java-ent/jnut/ch06_02.htm" rel="noreferrer">JavaBeans Conventions</a> for more details.</p> <p>A POJO (plain-old-Java-object) isn't rigorously defined. It's a Java object that doesn't have a requirement to implement a particular interface or derive from a particular base class, or make use of particular annotations in order to be compatible with a given framework, and can be any arbitrary (often relatively simple) Java object.</p>
{ "question_id": 1394265, "question_date": "2009-09-08T14:11:57.320Z", "question_score": 228, "tags": "java|terminology|pojo", "answer_id": 1394292, "answer_date": "2009-09-08T14:18:39.540Z", "answer_score": 272 }
Please answer the following Stack Overflow question: Title: Why is C so fast, and why aren't other languages as fast or faster? <p>In listening to the StackOverflow podcast, the jab keeps coming up that "real programmers" write in C, and that C is so much faster because it's "close to the machine." Leaving the former assertion for another post, what is special about C that allows it to be faster than other languages? Or put another way: what's to stop other languages from being able to compile down to binary that runs every bit as fast as C?</p>
<p><strong>There isn't much that's special about C. That's one of the reasons why it's fast.</strong></p> <p>Newer languages which have support for <a href="http://en.wikipedia.org/wiki/Garbage_collection_(computer_science)" rel="noreferrer">garbage collection</a>, <a href="http://en.wikipedia.org/wiki/Type_system#Dynamic_typing" rel="noreferrer">dynamic typing</a> and other facilities which make it easier for the programmer to write programs. </p> <p>The catch is, there is additional processing overhead which will degrade the performance of the application. C doesn't have any of that, which means that there is no overhead, but that means that the programmer needs to be able to allocate memory and free them to prevent <a href="http://en.wikipedia.org/wiki/Memory_leak" rel="noreferrer">memory leaks</a>, and must deal with static typing of variables.</p> <p>That said, many languages and platforms, such as Java (with its <a href="https://en.wikipedia.org/wiki/Java_virtual_machine" rel="noreferrer">Java Virtual Machine</a>) and .NET (with its Common Language Runtime) have improved performance over the years with advents such as <a href="http://en.wikipedia.org/wiki/Just-in-time_compilation" rel="noreferrer">just-in-time compilation</a> which produces native machine code from bytecode to achieve higher performance.</p>
{ "question_id": 418914, "question_date": "2009-01-07T01:59:06.080Z", "question_score": 228, "tags": "c|performance", "answer_id": 418956, "answer_date": "2009-01-07T02:15:41.337Z", "answer_score": 217 }
Please answer the following Stack Overflow question: Title: How can I increase the cursor speed in terminal? <p>How can I increase the cursor speed in terminal? I have Mac OS X by the way. It would also be interesting to know it for Linux.</p> <p>I don't know what I should search for in Google (or what you like).</p>
<p>If by &quot;cursor speed&quot;, you mean the repeat rate when holding down a key - then have a look here: <a href="http://hints.macworld.com/article.php?story=20090823193018149" rel="noreferrer">http://hints.macworld.com/article.php?story=20090823193018149</a></p> <p>To summarize, open up a Terminal window and type the following command:</p> <pre><code>defaults write NSGlobalDomain KeyRepeat -int 0 </code></pre> <p>More detail from the article:</p> <blockquote> <p>Everybody knows that you can get a pretty fast keyboard repeat rate by changing a slider on the Keyboard tab of the Keyboard &amp; Mouse System Preferences panel. But you can make it even faster! In Terminal, run this command:</p> <p>defaults write NSGlobalDomain KeyRepeat -int 0</p> <p>Then log out and log in again. The fastest setting obtainable via System Preferences is 2 (lower numbers are faster), so you may also want to try a value of 1 if 0 seems too fast. You can always visit the Keyboard &amp; Mouse System Preferences panel to undo your changes.</p> <p>You may find that a few applications don't handle extremely fast keyboard input very well, but most will do just fine with it.</p> </blockquote> <p><strong>Note: It requires a system restart</strong></p>
{ "question_id": 4489885, "question_date": "2010-12-20T13:06:57.480Z", "question_score": 228, "tags": "macos|terminal|text-cursor", "answer_id": 4490124, "answer_date": "2010-12-20T13:35:59.127Z", "answer_score": 198 }
Please answer the following Stack Overflow question: Title: Force LF eol in git repo and working copy <p>I have a git repository hosted on github. Many of the files were initially developed on Windows, and I wasn't too careful about line endings. When I performed the initial commit, I also didn't have any git configuration in place to enforce correct line endings. The upshot is that I have a number of files with CRLF line endings in my github repository.</p> <p>I'm now developing partially on Linux, and I'd like to clean up the line endings. How can I ensure the files are stored correctly with LF on github, and have LF in my working copy?</p> <p>I've set up a <code>.gitattributes</code> file containing <code>text eol=LF</code>; is that correct? With that committed and pushed, can I just <code>rm</code> my local repo and re-clone from github to get the desired effect?</p>
<p>Without a bit of information about what files are in your repository (pure source code, images, executables, ...), it's a bit hard to answer the question :)</p> <p>Beside this, I'll consider that you're willing to default to LF as line endings in your working directory because you're willing to make sure that text files have LF line endings in your .git repository wether you work on Windows or Linux. Indeed better safe than sorry....</p> <p>However, there's a better alternative: Benefit from LF line endings in your Linux workdir, CRLF line endings in your Windows workdir AND LF line endings in your repository.</p> <p>As you're partially working on Linux and Windows, make sure <code>core.eol</code> is set to <code>native</code> and <code>core.autocrlf</code> is set to <code>true</code>.</p> <p>Then, replace the content of your <code>.gitattributes</code> file with the following</p> <pre><code>* text=auto </code></pre> <p>This will let Git handle the automagic line endings conversion for you, on commits and checkouts. Binary files won't be altered, files detected as being text files will see the line endings converted on the fly.</p> <p>However, as you know the content of your repository, you may give Git a hand and help him detect text files from binary files.</p> <p>Provided you work on a C based image processing project, replace the content of your <code>.gitattributes</code> file with the following</p> <pre><code>* text=auto *.txt text *.c text *.h text *.jpg binary </code></pre> <p>This will make sure files which extension is c, h, or txt will be stored with LF line endings in your repo and will have native line endings in the working directory. Jpeg files won't be touched. All of the others will be benefit from the same automagic filtering as seen above.</p> <p>In order to get a get a deeper understanding of the inner details of all this, I'd suggest you to dive into this very good post <strong><a href="http://adaptivepatchwork.com/2012/03/01/mind-the-end-of-your-line/">"Mind the end of your line"</a></strong> from Tim Clem, a Githubber.</p> <p>As a real world example, you can also peek at this <strong><a href="https://github.com/libgit2/libgit2sharp/commit/4f23c3488f581191d1f4e14fcfa4623298bd6081">commit</a></strong> where those changes to a <code>.gitattributes</code> file are demonstrated.</p> <p><strong>UPDATE to the answer considering the following comment</strong></p> <blockquote> <p><em>I actually don't want CRLF in my Windows directories, because my Linux environment is actually a VirtualBox sharing the Windows directory</em></p> </blockquote> <p>Makes sense. Thanks for the clarification. In this specific context, the <code>.gitattributes</code> file by itself won't be enough.</p> <p>Run the following commands against your repository</p> <pre><code>$ git config core.eol lf $ git config core.autocrlf input </code></pre> <p>As your repository is shared between your Linux and Windows environment, this will update the local config file for both environment. <code>core.eol</code> will make sure text files bear LF line endings on checkouts. <code>core.autocrlf</code> will ensure <em>potential</em> CRLF in text files (resulting from a copy/paste operation for instance) will be converted to LF in your repository.</p> <p>Optionally, you can help Git distinguish what <em>is</em> a text file by creating a <code>.gitattributes</code> file containing something similar to the following:</p> <pre><code># Autodetect text files * text=auto # ...Unless the name matches the following # overriding patterns # Definitively text files *.txt text *.c text *.h text # Ensure those won't be messed up with *.jpg binary *.data binary </code></pre> <p>If you decided to create a <code>.gitattributes</code> file, <strong>commit it</strong>.</p> <p>Lastly, ensure <code>git status</code> mentions <em>"nothing to commit (working directory clean)"</em>, then perform the following operation</p> <pre><code>$ git checkout-index --force --all </code></pre> <p>This will recreate your files in your working directory, taking into account your config changes and the <code>.gitattributes</code> file and replacing any potential overlooked CRLF in your text files.</p> <p>Once this is done, every text file in your working directory WILL bear LF line endings and <code>git status</code> should still consider the workdir as clean.</p>
{ "question_id": 9976986, "question_date": "2012-04-02T13:02:15.780Z", "question_score": 228, "tags": "git|github|eol", "answer_id": 9977954, "answer_date": "2012-04-02T14:05:26.470Z", "answer_score": 278 }
Please answer the following Stack Overflow question: Title: What is the correct SQL type to store a .Net Timespan with values > 24:00:00? <p>I am trying to store a .Net <code>TimeSpan</code> in SQL server 2008 R2. </p> <p>EF Code First seems to be suggesting it should be stored as a <code>Time(7)</code> in SQL. </p> <p>However <code>TimeSpan</code> in .Net can handle longer periods than 24 hours. </p> <p>What is the best way to handle storing .Net <code>TimeSpan</code> in SQL server?</p>
<p>I'd store it in the database as a <code>BIGINT</code> and I'd store the number of ticks (eg. <a href="http://msdn.microsoft.com/en-us/library/system.timespan.ticks.aspx" rel="noreferrer">TimeSpan.Ticks</a> property).</p> <p>That way, if I wanted to get a TimeSpan object when I retrieve it, I could just do <a href="http://msdn.microsoft.com/en-us/library/system.timespan.fromticks.aspx" rel="noreferrer">TimeSpan.FromTicks(value)</a> which would be easy.</p>
{ "question_id": 8503825, "question_date": "2011-12-14T11:36:08.817Z", "question_score": 228, "tags": ".net|sql-server|timespan", "answer_id": 8504020, "answer_date": "2011-12-14T11:53:54.683Z", "answer_score": 248 }
Please answer the following Stack Overflow question: Title: Difference Between indexOf and findIndex function of array <p>I am confused between the difference between the two function indexOf and find Index in an array.</p> <p>The documentation says</p> <blockquote> <p>findIndex - Returns the index of the first element in the array where predicate is true, and -1 otherwise.</p> </blockquote> <p>and</p> <blockquote> <p>indexOf - Returns the index of the first occurrence of a value in an array.</p> </blockquote>
<p>The main difference are the parameters of these functions:</p> <ul> <li><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf" rel="noreferrer"><code>Array.prototype.indexOf()</code></a> expects a <em>value</em> as first parameter. This makes it a good choice to find the index in arrays of <a href="https://developer.mozilla.org/en-US/docs/Glossary/Primitive" rel="noreferrer">primitive types</a> (like string, number, or boolean).</p></li> <li><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex" rel="noreferrer"><code>Array.prototype.findIndex()</code></a> expects a <em>callback</em> as first parameter. Use this if you need the index in arrays with non-primitive types (e.g. objects) or your find condition is more complex than just a value.</p></li> </ul> <p>See the links for examples of both cases.</p>
{ "question_id": 41443029, "question_date": "2017-01-03T11:57:49.993Z", "question_score": 228, "tags": "javascript", "answer_id": 41443138, "answer_date": "2017-01-03T12:03:59.077Z", "answer_score": 348 }
Please answer the following Stack Overflow question: Title: SQLAlchemy: engine, connection and session difference <p>I use SQLAlchemy and there are at least three entities: <code>engine</code>, <code>session</code> and <code>connection</code>, which have <code>execute</code> method, so if I e.g. want to select all records from <code>table</code> I can do this</p> <pre><code>engine.execute(select([table])).fetchall() </code></pre> <p>and this</p> <pre><code>connection.execute(select([table])).fetchall() </code></pre> <p>and even this</p> <pre><code>session.execute(select([table])).fetchall() </code></pre> <p>- the results will be the same.</p> <p>As I understand it, if someone uses <code>engine.execute</code> it creates <code>connection</code>, opens <code>session</code> (Alchemy takes care of it for you) and executes the query. But is there a global difference between these three ways of performing such a task?</p>
<p><strong>A one-line overview:</strong> </p> <p>The behavior of <code>execute()</code> is same in all the cases, but they are 3 different methods, in <code>Engine</code>, <code>Connection</code>, and <code>Session</code> classes.</p> <p><strong>What exactly is <code>execute()</code>:</strong></p> <p>To understand behavior of <code>execute()</code> we need to look into the <code>Executable</code> class. <code>Executable</code> is a superclass for all “statement” types of objects, including select(), delete(),update(), insert(), text() - in simplest words possible, an <code>Executable</code> is a SQL expression construct supported in SQLAlchemy.</p> <p>In all the cases the <code>execute()</code> method takes the SQL text or constructed SQL expression i.e. any of the variety of SQL expression constructs supported in SQLAlchemy and returns query results (a <code>ResultProxy</code> - Wraps a <code>DB-API</code> cursor object to provide easier access to row columns.) </p> <hr> <p><strong>To clarify it further (only for conceptual clarification, not a recommended approach)</strong>:</p> <p>In addition to <code>Engine.execute()</code> (connectionless execution), <code>Connection.execute()</code>, and <code>Session.execute()</code>, it is also possible to use the <code>execute()</code> directly on any <code>Executable</code> construct. The <code>Executable</code> class has it's own implementation of <code>execute()</code> - As per official documentation, one line description about what the <code>execute()</code> does is "<strong>Compile and execute this <code>Executable</code></strong>". In this case we need to explicitly bind the <code>Executable</code> (SQL expression construct) with a <code>Connection</code> object or, <code>Engine</code> object (which implicitly get a <code>Connection</code> object), so the <code>execute()</code> will know where to execute the <code>SQL</code>.</p> <p>The following example demonstrates it well - Given a table as below:</p> <pre><code>from sqlalchemy import MetaData, Table, Column, Integer meta = MetaData() users_table = Table('users', meta, Column('id', Integer, primary_key=True), Column('name', String(50))) </code></pre> <p><strong>Explicit execution</strong> i.e. <code>Connection.execute()</code> - passing the SQL text or constructed SQL expression to the <code>execute()</code> method of <code>Connection</code>:</p> <pre><code>engine = create_engine('sqlite:///file.db') connection = engine.connect() result = connection.execute(users_table.select()) for row in result: # .... connection.close() </code></pre> <p><strong>Explicit connectionless execution</strong> i.e. <code>Engine.execute()</code> - passing the SQL text or constructed SQL expression directly to the <code>execute()</code> method of Engine:</p> <pre><code>engine = create_engine('sqlite:///file.db') result = engine.execute(users_table.select()) for row in result: # .... result.close() </code></pre> <p><strong>Implicit execution</strong> i.e. <code>Executable.execute()</code> - is also connectionless, and calls the <code>execute()</code> method of the <code>Executable</code>, that is, it calls <code>execute()</code> method directly on the <code>SQL</code> expression construct (an instance of <code>Executable</code>) itself.</p> <pre><code>engine = create_engine('sqlite:///file.db') meta.bind = engine result = users_table.select().execute() for row in result: # .... result.close() </code></pre> <p>Note: Stated the implicit execution example for the purpose of clarification - this way of execution is highly not recommended - as per <a href="http://docs.sqlalchemy.org/en/rel_1_0/core/connections.html#connectionless-execution-implicit-execution" rel="noreferrer">docs</a>:</p> <blockquote> <p>“implicit execution” is a very old usage pattern that in most cases is more confusing than it is helpful, and its usage is discouraged. Both patterns seem to encourage the overuse of expedient “short cuts” in application design which lead to problems later on.</p> </blockquote> <hr> <h2>Your questions:</h2> <blockquote> <p>As I understand if someone use engine.execute it creates connection, opens session (Alchemy cares about it for you) and executes query.</p> </blockquote> <p>You're right for the part "if someone use <code>engine.execute</code> it creates <code>connection</code> " but not for "opens <code>session</code> (Alchemy cares about it for you) and executes query " - Using <code>Engine.execute()</code> and <code>Connection.execute()</code> is (almost) one the same thing, in formal, <code>Connection</code> object gets created implicitly, and in later case we explicitly instantiate it. What really happens in this case is:</p> <pre><code>`Engine` object (instantiated via `create_engine()`) -&gt; `Connection` object (instantiated via `engine_instance.connect()`) -&gt; `connection.execute({*SQL expression*})` </code></pre> <blockquote> <p>But is there a global difference between these three ways of performing such task?</p> </blockquote> <p>At DB layer it's exactly the same thing, all of them are executing SQL (text expression or various SQL expression constructs). From application's point of view there are two options:</p> <ul> <li>Direct execution - Using <code>Engine.execute()</code> or <code>Connection.execute()</code></li> <li>Using <code>sessions</code> - efficiently handles transaction as single unit-of-work, with ease via <code>session.add()</code>, <code>session.rollback()</code>, <code>session.commit()</code>, <code>session.close()</code>. It is the way to interact with the DB in case of ORM i.e. mapped tables. Provides <a href="http://docs.sqlalchemy.org/en/rel_1_0/core/connections.html#" rel="noreferrer">identity_map</a> for instantly getting already accessed or newly created/added objects during a single request.</li> </ul> <p><code>Session.execute()</code> ultimately uses <code>Connection.execute()</code> statement execution method in order to execute the SQL statement. Using <code>Session</code> object is SQLAlchemy ORM's recommended way for an application to interact with the database.</p> <p>An excerpt from the <a href="http://docs.sqlalchemy.org/en/rel_1_0/core/connections.html#" rel="noreferrer">docs</a>:</p> <blockquote> <p>Its important to note that when using the SQLAlchemy ORM, these objects are not generally accessed; instead, the Session object is used as the interface to the database. However, for applications that are built around direct usage of textual SQL statements and/or SQL expression constructs without involvement by the ORM’s higher level management services, the Engine and Connection are king (and queen?) - read on.</p> </blockquote>
{ "question_id": 34322471, "question_date": "2015-12-16T21:29:31.263Z", "question_score": 228, "tags": "python|session|orm|sqlalchemy|psycopg2", "answer_id": 34364247, "answer_date": "2015-12-18T21:32:15.883Z", "answer_score": 187 }
Please answer the following Stack Overflow question: Title: How do I create a nice-looking DMG for Mac OS X using command-line tools? <p>I need to create a nice installer for a Mac application. I want it to be a disk image (DMG), with a predefined size, layout and background image.</p> <p>I need to do this programmatically in a script, to be integrated in an existing build system (more of a pack system really, since it only create installers. The builds are done separately). </p> <p>I already have the DMG creation done using "hdiutil", what I haven't found out yet is how to make an icon layout and specify a background bitmap.</p>
<p>After lots of research, I've come up with this answer, and I'm hereby putting it here as an answer for my own question, for reference:</p> <ol> <li><p>Make sure that "Enable access for assistive devices" is checked in System Preferences>>Universal Access. It is required for the AppleScript to work. You may have to reboot after this change (it doesn't work otherwise on Mac OS X Server 10.4).</p></li> <li><p>Create a R/W DMG. It must be larger than the result will be. In this example, the bash variable "size" contains the size in Kb and the contents of the folder in the "source" bash variable will be copied into the DMG:</p> <pre><code>hdiutil create -srcfolder "${source}" -volname "${title}" -fs HFS+ \ -fsargs "-c c=64,a=16,e=16" -format UDRW -size ${size}k pack.temp.dmg </code></pre></li> <li><p>Mount the disk image, and store the device name (you might want to use sleep for a few seconds after this operation):</p> <pre><code>device=$(hdiutil attach -readwrite -noverify -noautoopen "pack.temp.dmg" | \ egrep '^/dev/' | sed 1q | awk '{print $1}') </code></pre></li> <li><p>Store the background picture (in PNG format) in a folder called ".background" in the DMG, and store its name in the "backgroundPictureName" variable. </p></li> <li><p>Use AppleScript to set the visual styles (name of .app must be in bash variable "applicationName", use variables for the other properties as needed):</p> <pre><code>echo ' tell application "Finder" tell disk "'${title}'" open set current view of container window to icon view set toolbar visible of container window to false set statusbar visible of container window to false set the bounds of container window to {400, 100, 885, 430} set theViewOptions to the icon view options of container window set arrangement of theViewOptions to not arranged set icon size of theViewOptions to 72 set background picture of theViewOptions to file ".background:'${backgroundPictureName}'" make new alias file at container window to POSIX file "/Applications" with properties {name:"Applications"} set position of item "'${applicationName}'" of container window to {100, 100} set position of item "Applications" of container window to {375, 100} update without registering applications delay 5 close end tell end tell ' | osascript </code></pre></li> <li><p>Finialize the DMG by setting permissions properly, compressing and releasing it:</p> <pre><code>chmod -Rf go-w /Volumes/"${title}" sync sync hdiutil detach ${device} hdiutil convert "/pack.temp.dmg" -format UDZO -imagekey zlib-level=9 -o "${finalDMGName}" rm -f /pack.temp.dmg </code></pre></li> </ol> <p>On Snow Leopard, the above applescript will not set the icon position correctly - it seems to be a Snow Leopard bug. One workaround is to simply call close/open after setting the icons, i.e.:</p> <pre><code>.. set position of item "'${applicationName}'" of container window to {100, 100} set position of item "Applications" of container window to {375, 100} close open </code></pre>
{ "question_id": 96882, "question_date": "2008-09-18T20:57:58.373Z", "question_score": 228, "tags": "macos|scripting|installation|dmg", "answer_id": 1513578, "answer_date": "2009-10-03T12:05:26.397Z", "answer_score": 206 }
Please answer the following Stack Overflow question: Title: What is the difference between "text" and new String("text")? <p>What is the difference between these two following statements?</p> <pre><code>String s = "text"; String s = new String("text"); </code></pre>
<p><code>new String("text");</code> explicitly creates a new and referentially distinct instance of a <code>String</code> object; <code>String s = "text";</code> may reuse an instance from the <strong>string constant pool</strong> if one is available.</p> <p>You <em>very rarely</em> would ever want to use the <code>new String(anotherString)</code> constructor. From the API:</p> <blockquote> <p><a href="http://java.sun.com/javase/6/docs/api/java/lang/String.html#String%28java.lang.String%29" rel="noreferrer"><code>String(String original)</code></a> : Initializes a <em>newly created</em> <code>String</code> object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string. Unless an explicit copy of original is needed, use of this constructor is unnecessary since strings are immutable. </p> </blockquote> <h3>Related questions</h3> <ul> <li><a href="https://stackoverflow.com/questions/334518/java-strings-string-s-new-stringsilly"> Java Strings: “String s = new String(”silly“);” </a></li> <li><a href="https://stackoverflow.com/questions/2009228/strings-are-objects-in-java-so-why-dont-we-use-new-to-create-them"> Strings are objects in Java, so why don’t we use ‘new’ to create them? </a></li> </ul> <hr> <h3>What referential distinction means</h3> <p>Examine the following snippet:</p> <pre><code> String s1 = "foobar"; String s2 = "foobar"; System.out.println(s1 == s2); // true s2 = new String("foobar"); System.out.println(s1 == s2); // false System.out.println(s1.equals(s2)); // true </code></pre> <p><code>==</code> on two reference types is a reference identity comparison. Two objects that are <code>equals</code> are not necessarily <code>==</code>. It is usually wrong to use <code>==</code> on reference types; most of the time <code>equals</code> need to be used instead.</p> <p>Nonetheless, if for whatever reason you need to create two <code>equals</code> but not <code>==</code> string, you <em>can</em> use the <code>new String(anotherString)</code> constructor. It needs to be said again, however, that this is <em>very</em> peculiar, and is rarely the intention.</p> <h3>References</h3> <ul> <li><a href="http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.21.3" rel="noreferrer">JLS 15.21.3 Reference Equality Operators == and !=</a></li> <li><a href="http://java.sun.com/javase/6/docs/api/java/lang/Object.html#equals%28java.lang.Object%29" rel="noreferrer"><code>class Object</code> - <code>boolean Object(equals)</code></a></li> </ul> <h3>Related issues</h3> <ul> <li><a href="https://stackoverflow.com/questions/767372/java-string-equals-versus"> Java String.equals versus == </a></li> <li><a href="https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java">How do I compare strings in Java?</a></li> </ul>
{ "question_id": 3052442, "question_date": "2010-06-16T10:29:05.700Z", "question_score": 228, "tags": "java|string", "answer_id": 3052456, "answer_date": "2010-06-16T10:30:54.793Z", "answer_score": 222 }
Please answer the following Stack Overflow question: Title: How do I make an enum Decodable in Swift? <pre><code>enum PostType: Decodable { init(from decoder: Decoder) throws { // What do i put here? } case Image enum CodingKeys: String, CodingKey { case image } } </code></pre> <p>What do i put to complete this? Also, lets say i changed the <code>case</code> to this:</p> <pre><code>case image(value: Int) </code></pre> <p>How do I make this conform to Decodable?</p> <p>Here is my full code (which does not work)</p> <pre><code>let jsonData = &quot;&quot;&quot; { &quot;count&quot;: 4 } &quot;&quot;&quot;.data(using: .utf8)! do { let decoder = JSONDecoder() let response = try decoder.decode(PostType.self, from: jsonData) print(response) } catch { print(error) } } } enum PostType: Int, Codable { case count = 4 } </code></pre> <p>Also, how will it handle an enum like this?</p> <pre><code>enum PostType: Decodable { case count(number: Int) } </code></pre>
<p>It's pretty easy, just use <code>String</code> or <code>Int</code> raw values which are implicitly assigned.</p> <pre><code>enum PostType: Int, Codable { case image, blob } </code></pre> <p><code>image</code> is encoded to <code>0</code> and <code>blob</code> to <code>1</code></p> <p>Or</p> <pre><code>enum PostType: String, Codable { case image, blob } </code></pre> <p><code>image</code> is encoded to <code>&quot;image&quot;</code> and <code>blob</code> to <code>&quot;blob&quot;</code></p> <hr /> <p>This is a simple example how to use it:</p> <pre><code>enum PostType : Int, Codable { case count = 4 } struct Post : Codable { var type : PostType } let jsonString = &quot;{\&quot;type\&quot;: 4}&quot; let jsonData = Data(jsonString.utf8) do { let decoded = try JSONDecoder().decode(Post.self, from: jsonData) print(&quot;decoded:&quot;, decoded.type) } catch { print(error) } </code></pre> <hr /> <p><strong>Update</strong></p> <p>In iOS 13.3+ and macOS 15.1+ it's allowed to en-/decode <em>fragments</em> – single JSON values which are not wrapped in a collection type</p> <pre><code>let jsonString = &quot;4&quot; let jsonData = Data(jsonString.utf8) do { let decoded = try JSONDecoder().decode(PostType.self, from: jsonData) print(&quot;decoded:&quot;, decoded) // -&gt; decoded: count } catch { print(error) } </code></pre> <hr /> <p>In Swift 5.5+ it's even possible to en-/decode enums with associated values without any extra code. The values are mapped to a dictionary and a parameter label must be specified for each associated value</p> <pre><code>enum Rotation: Codable { case zAxis(angle: Double, speed: Int) } let jsonString = #&quot;{&quot;zAxis&quot;:{&quot;angle&quot;:90,&quot;speed&quot;:5}}&quot;# let jsonData = Data(jsonString.utf8) do { let decoded = try JSONDecoder().decode(Rotation.self, from: jsonData) print(&quot;decoded:&quot;, decoded) } catch { print(error) } </code></pre>
{ "question_id": 44580719, "question_date": "2017-06-16T04:15:21.217Z", "question_score": 228, "tags": "swift|enums", "answer_id": 44582674, "answer_date": "2017-06-16T06:51:51.007Z", "answer_score": 377 }
Please answer the following Stack Overflow question: Title: How to use `jq` in a shell pipeline? <p>I can't seem to get <code>jq</code> to behave &quot;normally&quot; in a shell pipeline. For example:</p> <pre><code>$ curl -s https://api.github.com/users/octocat/repos | jq | cat </code></pre> <p>results in <code>jq</code> simply printing out its help text*. The same thing happens if I try to redirect <code>jq</code>'s output to a file:</p> <pre><code>$ curl -s https://api.github.com/users/octocat/repos | jq &gt; /tmp/stuff.json </code></pre> <p>Is <code>jq</code> deliberately bailing out if it determines that it's not being run from a tty? How can I prevent this behavior so that I can use <code>jq</code> in a pipeline?</p> <p>Edit: it looks like this is no longer an issue in recent versions of <code>jq</code>. I have <code>jq-1.6</code> now and the examples above work as expected.</p> <hr /> <p>* <sub>(I realize this example contains a <a href="http://porkmail.org/era/unix/award.html" rel="noreferrer">useless use of cat</a>; it's for illustration purposes only)</sub></p>
<p>You need to supply a filter as an argument. To pass the JSON through unmodified other than the pretty printing <code>jq</code> provides by default, use the identity filter <code>.</code>:</p> <pre><code>curl -s https://api.github.com/users/octocat/repos | jq '.' | cat </code></pre>
{ "question_id": 33247228, "question_date": "2015-10-20T21:35:51.887Z", "question_score": 228, "tags": "shell|pipe|jq", "answer_id": 33247259, "answer_date": "2015-10-20T21:38:23.053Z", "answer_score": 376 }
Please answer the following Stack Overflow question: Title: What's the purpose of Django setting ‘SECRET_KEY’? <p>I did a few google searches and checked out the docs ( <a href="https://docs.djangoproject.com/en/dev/ref/settings/#secret-key" rel="noreferrer">https://docs.djangoproject.com/en/dev/ref/settings/#secret-key</a> ), but I was looking for a more in-depth explanation of this, and why it is required.</p> <p>For example, what could happen if the key was compromised / others knew what it was?</p>
<p>It is used for making hashes. Look:</p> <pre><code>&gt;grep -Inr SECRET_KEY * conf/global_settings.py:255:SECRET_KEY = '' conf/project_template/settings.py:61:SECRET_KEY = '' contrib/auth/tokens.py:54: hash = sha_constructor(settings.SECRET_KEY + unicode(user.id) + contrib/comments/forms.py:86: info = (content_type, object_pk, timestamp, settings.SECRET_KEY) contrib/formtools/utils.py:15: order, pickles the result with the SECRET_KEY setting, then takes an md5 contrib/formtools/utils.py:32: data.append(settings.SECRET_KEY) contrib/messages/storage/cookie.py:112: SECRET_KEY, modified to make it unique for the present purpose. contrib/messages/storage/cookie.py:114: key = 'django.contrib.messages' + settings.SECRET_KEY contrib/sessions/backends/base.py:89: pickled_md5 = md5_constructor(pickled + settings.SECRET_KEY).hexdigest() contrib/sessions/backends/base.py:95: if md5_constructor(pickled + settings.SECRET_KEY).hexdigest() != tamper_check: contrib/sessions/backends/base.py:134: # Use settings.SECRET_KEY as added salt. contrib/sessions/backends/base.py:143: settings.SECRET_KEY)).hexdigest() contrib/sessions/models.py:16: pickled_md5 = md5_constructor(pickled + settings.SECRET_KEY).hexdigest() contrib/sessions/models.py:59: if md5_constructor(pickled + settings.SECRET_KEY).hexdigest() != tamper_check: core/management/commands/startproject.py:32: # Create a random SECRET_KEY hash, and put it in the main settings. core/management/commands/startproject.py:37: settings_contents = re.sub(r"(?&lt;=SECRET_KEY = ')'", secret_key + "'", settings_contents) middleware/csrf.py:38: % (randrange(0, _MAX_CSRF_KEY), settings.SECRET_KEY)).hexdigest() middleware/csrf.py:41: return md5_constructor(settings.SECRET_KEY + session_id).hexdigest() </code></pre>
{ "question_id": 7382149, "question_date": "2011-09-11T23:59:01.740Z", "question_score": 228, "tags": "python|django|security|encryption", "answer_id": 7382198, "answer_date": "2011-09-12T00:09:44.513Z", "answer_score": 123 }
Please answer the following Stack Overflow question: Title: Is local static variable initialization thread-safe in C++11? <p>I know this is an often asked question, but as there are so many variants, I'd like to re-state it, and hopefully have an answer reflecting the current state. Something like</p> <pre><code>Logger&amp; g_logger() { static Logger lg; return lg; } </code></pre> <p>Is the constructor of variable lg guaranteed to run only once?</p> <p>I know from previous answers that in C++03, this is not; in C++0x draft, this is enforced. But I'd like a clearer answer to</p> <ol> <li>In C++11 standard (not draft), is the thread-safe initialization behavior finalized?</li> <li>If the above is yes, in current latest releases of popular compilers, namely gcc 4.7, vc 2011 and clang 3.0, are they properly implemented?</li> </ol>
<p>The relevant section 6.7:</p> <blockquote> <p>such a variable is initialized the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization. [...] If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.</p> </blockquote> <p>Then there's a footnote:</p> <blockquote> <p>The implementation must not introduce any deadlock around execution of the initializer.</p> </blockquote> <p>So yes, you're safe.</p> <p>(This says nothing of course about the subsequent access to the variable through the reference.)</p>
{ "question_id": 8102125, "question_date": "2011-11-12T02:34:55.290Z", "question_score": 228, "tags": "c++|thread-safety|c++11", "answer_id": 8102145, "answer_date": "2011-11-12T02:39:22.790Z", "answer_score": 211 }
Please answer the following Stack Overflow question: Title: What is the source code of the "this" module doing? <p>If you open a Python interpreter, and type "import this", as you know, it prints:</p> <blockquote> <p>The Zen of Python, by Tim Peters </p> <p>Beautiful is better than ugly.<br> Explicit is better than implicit.<br> Simple is better than complex.<br> Complex is better than complicated.<br> Flat is better than nested.<br> Sparse is better than dense.<br> Readability counts.<br> Special cases aren't special enough to break the rules.<br> Although practicality beats purity.<br> Errors should never pass silently.<br> Unless explicitly silenced.<br> In the face of ambiguity, refuse the temptation to guess.<br> There should be one-- and preferably only one --obvious way to do it.<br> Although that way may not be obvious at first unless you're Dutch.<br> Now is better than never.<br> Although never is often better than <em>right</em> now.<br> If the implementation is hard to explain, it's a bad idea.<br> If the implementation is easy to explain, it may be a good idea.<br> Namespaces are one honking great idea -- let's do more of those! </p> </blockquote> <p>In the python source(Lib/this.py) this text is generated by a curious piece of code:</p> <pre><code>s = """Gur Mra bs Clguba, ol Gvz Crgref Ornhgvshy vf orggre guna htyl. Rkcyvpvg vf orggre guna vzcyvpvg. Fvzcyr vf orggre guna pbzcyrk. Pbzcyrk vf orggre guna pbzcyvpngrq. Syng vf orggre guna arfgrq. Fcnefr vf orggre guna qrafr. Ernqnovyvgl pbhagf. Fcrpvny pnfrf nera'g fcrpvny rabhtu gb oernx gur ehyrf. Nygubhtu cenpgvpnyvgl orngf chevgl. Reebef fubhyq arire cnff fvyragyl. Hayrff rkcyvpvgyl fvyraprq. Va gur snpr bs nzovthvgl, ershfr gur grzcgngvba gb thrff. Gurer fubhyq or bar-- naq cersrenoyl bayl bar --boivbhf jnl gb qb vg. Nygubhtu gung jnl znl abg or boivbhf ng svefg hayrff lbh'er Qhgpu. Abj vf orggre guna arire. Nygubhtu arire vf bsgra orggre guna *evtug* abj. Vs gur vzcyrzragngvba vf uneq gb rkcynva, vg'f n onq vqrn. Vs gur vzcyrzragngvba vf rnfl gb rkcynva, vg znl or n tbbq vqrn. Anzrfcnprf ner bar ubaxvat terng vqrn -- yrg'f qb zber bs gubfr!""" d = {} for c in (65, 97): for i in range(26): d[chr(i+c)] = chr((i+13) % 26 + c) print "".join([d.get(c, c) for c in s]) </code></pre>
<p>This is called <a href="http://en.wikipedia.org/wiki/ROT13">rot13</a> encoding:</p> <pre><code>d = {} for c in (65, 97): for i in range(26): d[chr(i+c)] = chr((i+13) % 26 + c) </code></pre> <p>Builds the translation table, for both uppercase (this is what 65 is for) and lowercase (this is what 97 is for) chars.</p> <pre><code>print "".join([d.get(c, c) for c in s]) </code></pre> <p>Prints the translated string.</p>
{ "question_id": 5855758, "question_date": "2011-05-02T09:56:38.020Z", "question_score": 228, "tags": "python", "answer_id": 5855793, "answer_date": "2011-05-02T10:00:02.940Z", "answer_score": 208 }
Please answer the following Stack Overflow question: Title: What does a \ (backslash) do in PHP (5.3+)? <p>What does a <code>\</code> do in PHP?</p> <p>For example, <a href="https://github.com/foxbunny/CSRF4PHP/blob/60d9172b7f0cd93346cac9065fb17182854ebf1c/CsrfToken.php#L80-L87" rel="noreferrer">CSRF4PHP</a> has <code>\FALSE</code>, <code>\session_id</code>, and <code>\Exception</code>:</p> <pre><code>public function __construct($timeout=300, $acceptGet=\FALSE){ $this-&gt;timeout = $timeout; if (\session_id()) { $this-&gt;acceptGet = (bool) $acceptGet; } else { throw new \Exception('Could not find session id', 1); } } </code></pre>
<p><code>\</code> (backslash) is the namespace separator in PHP 5.3.</p> <p>A <code>\</code> before the beginning of a function represents the <a href="http://www.php.net/manual/en/language.namespaces.global.php" rel="noreferrer">Global Namespace</a>. </p> <p>Putting it there will ensure that the function called is from the global namespace, even if there is a function by the same name in the current namespace.</p>
{ "question_id": 4790020, "question_date": "2011-01-25T04:34:05.443Z", "question_score": 228, "tags": "php|namespaces|opcode|opcache", "answer_id": 4790031, "answer_date": "2011-01-25T04:36:24.740Z", "answer_score": 321 }
Please answer the following Stack Overflow question: Title: How to delete (not cut) in Vim? <p>How can I delete a line without putting it into my default buffer?</p> <p>Example:</p> <pre><code>line that will be copied. line that I want to be substitued with the previous one. </code></pre> <p>What I'm trying to do:</p> <pre><code>yy dd p </code></pre> <p>But Vim replaces the recent copied string with the deleted (cutted) one. I know that I can use buffers like, <code>"1yy</code>, <code>dd</code> then <code>"1p</code>, but I always forget to put the copied string in a buffer then I need to paste my contents first (line that will be copied) and then delete what I want (line that I want to be substituted with the previous one.)</p> <p>How can I really delete a text in Vi(m) without copying it?</p> <p>Another related question is how I can forward delete a word in insert mode? I want something similar to <kbd>Ctrl</kbd>+<kbd>w</kbd>.</p>
<p>Use the "black hole register", <code>"_</code> to really delete something: <code>"_d</code>.<br> Use <code>"_dP</code> to paste something and keep it available for further pasting.</p> <p>For the second question, you could use <code>&lt;C-o&gt;dw</code>. <code>&lt;C-o&gt;</code> is used to execute a normal command without leaving the <em>insert</em> mode.</p> <p>You can setup your own mappings to save typing, of course. I have these:</p> <pre><code>nnoremap &lt;leader&gt;d "_d xnoremap &lt;leader&gt;d "_d xnoremap &lt;leader&gt;p "_dP </code></pre>
{ "question_id": 11993851, "question_date": "2012-08-16T19:08:24.257Z", "question_score": 228, "tags": "vim|copy-paste", "answer_id": 11993928, "answer_date": "2012-08-16T19:13:18.920Z", "answer_score": 182 }
Please answer the following Stack Overflow question: Title: Why does ReSharper want to use 'var' for everything? <p>I've just started using ReSharper with Visual Studio (after the many recommendations on SO). To try it out I opened up a recent ASP.NET MVC project. One of the first and most frequent things I've noticed it suggesting is to change most/all my explicit declarations to <code>var</code> instead. For example:</p> <pre><code>//From This: MyObject foo = DB.MyObjects.SingleOrDefault(w =&gt; w.Id == 1); //To This: var foo = DB.MyObjects.SingleOrDefault(w =&gt; w.Id == 1); </code></pre> <p>and so on, even with simple types such as <code>int</code>, <code>bool</code>, etc.</p> <p>Why is this being recommended? I don't come from a computer science or .NET background, having "fallen into" .NET development recently, so I'd really like to understand what's going on and whether it's of benefit or not.</p>
<p>One reason is improved readability. Which is better?</p> <pre><code>Dictionary&lt;int, MyLongNamedObject&gt; dictionary = new Dictionary&lt;int, MyLongNamedObject&gt;(); </code></pre> <p>or</p> <pre><code>var dictionary = new Dictionary&lt;int, MyLongNamedObject&gt;(); </code></pre>
{ "question_id": 1873873, "question_date": "2009-12-09T13:24:22.483Z", "question_score": 228, "tags": "c#|.net|visual-studio|resharper|var", "answer_id": 1873885, "answer_date": "2009-12-09T13:26:32.110Z", "answer_score": 203 }
Please answer the following Stack Overflow question: Title: How does setting baselineAligned to false improve performance in LinearLayout? <p>I was just building some UI in xml, and Lint gave me a warning and said to set android:baselineAligned to false to improve performance in ListView.</p> <p>The docs for the Lint changes that added this warning say</p> <blockquote> <p>Layout performance: Finds LinearLayouts with weights where you should set android:baselineAligned="false" for better performance, and also finds cases where you have nested weights which can cause performance problems.</p> </blockquote> <p>Can somebody explain why this improves performance, specifically when weight is involved?</p>
<p>By setting <code>android:baselineAligned="false"</code> , you're preventing the extra work your app's layout has to do in order to Align its children's baselines; which can obviously increase the performance. (Fewer unnecessary operations on UI => Better performance)</p>
{ "question_id": 9319916, "question_date": "2012-02-16T22:14:33.990Z", "question_score": 228, "tags": "android|listview|android-lint", "answer_id": 9320857, "answer_date": "2012-02-16T23:42:13.303Z", "answer_score": 174 }
Please answer the following Stack Overflow question: Title: How do I create a teardrop in HTML? <p>How do I create a shape like this to display on a webpage? </p> <p>I don't want to use <strong>images</strong> since they would get blurry on scaling </p> <p><img src="https://i.stack.imgur.com/3dFQ5.png" alt="Teardrop shape I need to make with HTML, CSS or SVG"></p> <p>I tried with <em>CSS</em>:</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>.tear { display: inline-block; transform: rotate(-30deg); border: 5px solid green; width: 50px; height: 100px; border-top-left-radius: 50%; border-bottom-left-radius: 50%; border-bottom-right-radius: 50%; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="tear"&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>That turned out really screwed.</p> <p>And then I tried with SVG:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;svg viewBox="0 100 100"&gt; &lt;polygon points="50,0 100,70 50,100 0,70"/&gt; &lt;/svg&gt;</code></pre> </div> </div> </p> <p>It did get the shape, but the bottom part wasn't curved.</p> <p>Is there a way to create this shape so it can be used in an HTML page?</p>
<h2>SVG approach:</h2> <p>You can achieve the double curve easily with an <strong>inline SVG</strong> and the <code>&lt;path/&gt;</code> element instead of the <code>&lt;polygon/&gt;</code> element which doesn't allow curved shapes.</p> <p>The following example uses the <code>&lt;path/&gt;</code> element with:</p> <ul> <li>2 <a href="https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Paths#Bezier_Curves" rel="noreferrer">quadratic bezier curve commands</a> for the 2 top curves (lines beginning with <code>Q</code>)</li> <li>1 <a href="https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Paths#Arcs" rel="noreferrer">arc command</a> for the big bottom one (line beginning with <code>A</code>)</li> </ul> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;svg width="30%" viewbox="0 0 30 42"&gt; &lt;path fill="transparent" stroke="#000" stroke-width="1.5" d="M15 3 Q16.5 6.8 25 18 A12.8 12.8 0 1 1 5 18 Q13.5 6.8 15 3z" /&gt; &lt;/svg&gt;</code></pre> </div> </div> </p> <p>SVG is a great tool to make this kind of shapes with double curves. You can check this <a href="https://stackoverflow.com/questions/28986125/double-curved-shape">post about double curves</a> with an SVG/CSS comparison. Some of the advantages of using SVG in this case are:</p> <ul> <li>Curve control</li> <li>Fill control (opacity, color)</li> <li>Stroke control (width, opacity, color)</li> <li>Amount of code</li> <li>Time to build and maintain the shape</li> <li>Scalable</li> <li>No HTTP request (if used inline like in the example)</li> </ul> <hr> <p><strong>Browser support</strong> for inline SVG goes back to Internet Explorer 9. See <a href="http://caniuse.com/#feat=svg-html5" rel="noreferrer">canIuse</a> for more information.</p>
{ "question_id": 30711203, "question_date": "2015-06-08T14:01:16.140Z", "question_score": 228, "tags": "html|css|svg|css-shapes", "answer_id": 30712432, "answer_date": "2015-06-08T14:52:01.317Z", "answer_score": 330 }
Please answer the following Stack Overflow question: Title: What is the point of noreturn? <p><a href="http://eel.is/c++draft/dcl.attr.noreturn" rel="noreferrer">[dcl.attr.noreturn]</a> provides the following example:</p> <pre><code>[[ noreturn ]] void f() { throw "error"; // OK } </code></pre> <p>but I do not understand what is the point of <code>[[noreturn]]</code>, because the return type of the function is already <code>void</code>.</p> <p>So, what is the point of the <code>noreturn</code> attribute? How is it supposed to be used?</p>
<p>The noreturn attribute is supposed to be used for functions that don't return to the caller. That doesn't mean void functions (which do return to the caller - they just don't return a value), but functions where the control flow will not return to the calling function after the function finishes (e.g. functions that exit the application, loop forever or throw exceptions as in your example).</p> <p>This can be used by compilers to make some optimizations and generate better warnings. For example if <code>f</code> has the noreturn attribute, the compiler could warn you about <code>g()</code> being dead code when you write <code>f(); g();</code>. Similarly the compiler will know not to warn you about missing return statements after calls to <code>f()</code>.</p>
{ "question_id": 10538291, "question_date": "2012-05-10T16:22:25.517Z", "question_score": 228, "tags": "c++|c++11|attributes|noreturn", "answer_id": 10538363, "answer_date": "2012-05-10T16:27:07.230Z", "answer_score": 263 }
Please answer the following Stack Overflow question: Title: Is it possible to make a div 50px less than 100% in CSS3? <p>Is it possible to make a <code>div</code> 50px less than 100% in pure CSS? I want the <code>&lt;div&gt;</code> to be only 50px less than 100%. I don't want any JavaScript.</p>
<p>Yes you can. Without using the IE's <code>expression()</code>, you can do that in CSS3 by using <a href="http://www.w3.org/TR/css3-values/#calc" rel="noreferrer"><code>calc()</code></a>.</p> <pre class="lang-css prettyprint-override"><code>div { width: 100%; width: -webkit-calc(100% - 50px); width: -moz-calc(100% - 50px); width: calc(100% - 50px); } </code></pre> <p>Demo: <a href="http://jsfiddle.net/thirtydot/Nw3yd/66/" rel="noreferrer">http://jsfiddle.net/thirtydot/Nw3yd/66/</a></p> <p>This will make your life so much easier. It is currently supported in the 3 main browsers: Firefox, Google Chrome (WebKit), and IE9: <a href="http://caniuse.com/calc" rel="noreferrer">http://caniuse.com/calc</a></p> <p>MDN: <a href="https://developer.mozilla.org/en/CSS/-moz-calc" rel="noreferrer">https://developer.mozilla.org/en/CSS/-moz-calc</a></p>
{ "question_id": 11093943, "question_date": "2012-06-19T03:18:52.410Z", "question_score": 228, "tags": "html|css", "answer_id": 11093944, "answer_date": "2012-06-19T03:18:53.173Z", "answer_score": 294 }
Please answer the following Stack Overflow question: Title: Anonymous recursive PHP functions <p>Is it possible to have a PHP function that is both recursive and anonymous? This is my attempt to get it to work, but it doesn't pass in the function name.</p> <pre><code>$factorial = function( $n ) use ( $factorial ) { if( $n &lt;= 1 ) return 1; return $factorial( $n - 1 ) * $n; }; print $factorial( 5 ); </code></pre> <p>I'm also aware that this is a bad way to implement factorial, it's just an example.</p>
<p>In order for it to work, you need to pass $factorial as a reference</p> <pre><code>$factorial = function( $n ) use ( &amp;$factorial ) { if( $n == 1 ) return 1; return $factorial( $n - 1 ) * $n; }; print $factorial( 5 ); </code></pre>
{ "question_id": 2480179, "question_date": "2010-03-19T19:51:51.510Z", "question_score": 228, "tags": "php|recursion|lambda|closures|anonymous-function", "answer_id": 2480242, "answer_date": "2010-03-19T20:03:09.740Z", "answer_score": 425 }
Please answer the following Stack Overflow question: Title: How can a Rust program access metadata from its Cargo package? <p>How do you access a Cargo package's metadata (e.g. version) from the Rust code in the package? In my case, I am building a command line tool that I'd like to have a standard <code>--version</code> flag, and I'd like the implementation to read the version of the package from <code>Cargo.toml</code> so I don't have to maintain it in two places. I can imagine there are other reasons someone might want to access Cargo metadata from the program as well.</p>
<p>Cargo passes some metadata to the compiler through environment variables, a list of which can be found in the <a href="http://doc.crates.io/environment-variables.html" rel="noreferrer">Cargo documentation pages</a>.</p> <p>The compiler environment is populated by <a href="https://github.com/rust-lang/cargo/blob/0.33.0/src/cargo/core/compiler/compilation.rs#L171-L239" rel="noreferrer"><code>fill_env</code></a> in Cargo's code. This code has become more complex since earlier versions, and the entire list of variables is no longer obvious from it because it can be dynamic. However, at least the following variables are set there (from <a href="https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates" rel="noreferrer">the list in the docs</a>):</p> <pre class="lang-none prettyprint-override"><code>CARGO_MANIFEST_DIR CARGO_PKG_AUTHORS CARGO_PKG_DESCRIPTION CARGO_PKG_HOMEPAGE CARGO_PKG_NAME CARGO_PKG_REPOSITORY CARGO_PKG_VERSION CARGO_PKG_VERSION_MAJOR CARGO_PKG_VERSION_MINOR CARGO_PKG_VERSION_PATCH CARGO_PKG_VERSION_PRE </code></pre> <p>You can access environment variables using the <a href="https://doc.rust-lang.org/std/macro.env.html" rel="noreferrer"><code>env!()</code></a> macro. To insert the version number of your program you can do this:</p> <pre><code>const VERSION: &amp;str = env!(&quot;CARGO_PKG_VERSION&quot;); // ... println!(&quot;MyProgram v{}&quot;, VERSION); </code></pre> <p>If you want your program to compile even without Cargo, you can use <a href="https://doc.rust-lang.org/std/macro.option_env.html" rel="noreferrer"><code>option_env!()</code></a>:</p> <pre><code>const VERSION: Option&lt;&amp;str&gt; = option_env!(&quot;CARGO_PKG_VERSION&quot;); // ... println!(&quot;MyProgram v{}&quot;, VERSION.unwrap_or(&quot;unknown&quot;)); </code></pre>
{ "question_id": 27840394, "question_date": "2015-01-08T12:41:59.333Z", "question_score": 228, "tags": "rust|rust-cargo", "answer_id": 27841363, "answer_date": "2015-01-08T13:32:29.873Z", "answer_score": 327 }
Please answer the following Stack Overflow question: Title: Why do people put code like "throw 1; <dont be evil>" and "for(;;);" in front of json responses? <blockquote> <p><strong>Possible Duplicate:</strong><br /> <a href="https://stackoverflow.com/questions/2669690/why-does-google-prepend-while1-to-their-json-responses">Why does Google prepend while(1); to their JSON responses?</a></p> </blockquote> <p>Google returns json like this:</p> <pre class="lang-js prettyprint-override"><code>throw 1; &lt;dont be evil&gt; { foo: bar} </code></pre> <p>and Facebooks ajax has json like this:</p> <pre class="lang-js prettyprint-override"><code>for(;;); {&quot;error&quot;:0,&quot;errorSummary&quot;: &quot;&quot;} </code></pre> <ul> <li>Why do they put code that would stop execution and makes invalid json?</li> <li>How do they parse it if it's invalid and would crash if you tried to eval it?</li> <li>Do they just remove it from the string (seems expensive)?</li> <li>Are there any security advantages to this?</li> </ul> <p>In response to it being for security purposes:</p> <p>If the scraper is on another domain they would have to use a <code>script</code> tag to get the data because XHR won't work cross-domain. Even without the <code>for(;;);</code> how would the attacker get the data? It's not assigned to a variable so wouldn't it just be garbage collected because there's no references to it?</p> <p>Basically to get the data cross domain they would have to do</p> <pre class="lang-html prettyprint-override"><code>&lt;script src=&quot;http://target.com/json.js&quot;&gt;&lt;/script&gt; </code></pre> <p>But even without the crash script prepended the attacker can't use any of the Json data without it being assigned to a variable that you can access globally (it isn't in these cases). The crash code effectivly does nothing because even without it they have to use server sided scripting to use the data on their site.</p>
<blockquote> <p>Even without the <code>for(;;);</code> how would the attacker get the data?</p> </blockquote> <p>Attacks are based on altering the behaviour of the built-in types, in particular <code>Object</code> and <code>Array</code>, by altering their constructor function or its <code>prototype</code>. Then when the targeted JSON uses a <code>{...}</code> or <code>[...]</code> construct, they'll be the attacker's own versions of those objects, with potentially-unexpected behaviour.</p> <p>For example, you can hack a setter-property into <code>Object</code>, that would betray the values written in object literals:</p> <pre><code>Object.prototype.__defineSetter__('x', function(x) { alert('Ha! I steal '+x); }); </code></pre> <p>Then when a <code>&lt;script&gt;</code> was pointed at some JSON that used that property name:</p> <pre><code>{"x": "hello"} </code></pre> <p>the value <code>"hello"</code> would be leaked. </p> <p>The way that array and object literals cause setters to be called is controversial. Firefox removed the behaviour in version 3.5, in response to publicised attacks on high-profile web sites. However at the time of writing Safari (4) and Chrome (5) are still vulnerable to this.</p> <p>Another attack that all browsers now disallow was to redefine constructor functions:</p> <pre><code>Array= function() { alert('I steal '+this); }; [1, 2, 3] </code></pre> <p>And for now, IE8's implementation of properties (based on the ECMAScript Fifth Edition standard and <code>Object.defineProperty</code>) currently does not work on <code>Object.prototype</code> or <code>Array.prototype</code>.</p> <p>But as well as protecting past browsers, it may be that extensions to JavaScript cause more potential leaks of a similar kind in future, and in that case chaff should protect against those too.</p>
{ "question_id": 3146798, "question_date": "2010-06-30T05:58:54.100Z", "question_score": 228, "tags": "javascript|ajax|security|json", "answer_id": 3147804, "answer_date": "2010-06-30T09:02:24.667Z", "answer_score": 195 }
Please answer the following Stack Overflow question: Title: parseInt(null, 24) === 23... wait, what? <p>Alright, so I was messing around with parseInt to see how it handles values not yet initialized and I stumbled upon this gem. The below happens for any radix 24 or above.</p> <pre><code>parseInt(null, 24) === 23 // evaluates to true </code></pre> <p>I tested it in IE, Chrome and Firefox and they all alert true, so I'm thinking it must be in the specification somewhere. A quick Google search didn't give me any results so here I am, hoping someone can explain.</p> <p>I remember listening to a Crockford speech where he was saying <code>typeof null === "object"</code> because of an oversight causing Object and Null to have a near identical type identifier in memory or something along those lines, but I can't find that video now.</p> <p>Try it: <a href="http://jsfiddle.net/robert/txjwP/" rel="noreferrer">http://jsfiddle.net/robert/txjwP/</a></p> <p><strong>Edit</strong> Correction: a higher radix returns different results, 32 returns 785077<br> <strong>Edit 2</strong> From zzzzBov: <code>[24...30]:23, 31:714695, 32:785077, 33:859935, 34:939407, 35:1023631, 36:1112745</code></p> <hr> <p><strong>tl;dr</strong></p> <p>Explain why <code>parseInt(null, 24) === 23</code> is a true statement.</p>
<p>It's converting <code>null</code> to the string <code>"null"</code> and trying to convert it. For radixes 0 through 23, there are no numerals it can convert, so it returns <code>NaN</code>. At 24, <code>"n"</code>, the 14th letter, is added to the numeral system. At 31, <code>"u"</code>, the 21st letter, is added and the entire string can be decoded. At 37 on there is no longer any valid numeral set that can be generated and NaN is returned.</p> <pre><code>js&gt; parseInt(null, 36) 1112745 &gt;&gt;&gt; reduce(lambda x, y: x * 36 + y, [(string.digits + string.lowercase).index(x) for x in 'null']) 1112745 </code></pre>
{ "question_id": 6459758, "question_date": "2011-06-23T19:48:18.420Z", "question_score": 228, "tags": "javascript|parseint", "answer_id": 6459925, "answer_date": "2011-06-23T20:03:06.113Z", "answer_score": 243 }
Please answer the following Stack Overflow question: Title: What are the dangers when creating a thread with a stack size of 50x the default? <p>I'm currently working on a very performance critical program and one path I decided to explore that may help reduce resource consumption was increasing my worker threads' stack size so I can move most of the data (<code>float[]</code>s) that I'll be accesing onto the stack (using <a href="http://msdn.microsoft.com/en-us/library/cx9s2sy4(v=vs.80).aspx" rel="noreferrer"><code>stackalloc</code></a>).</p> <p>I've <a href="https://stackoverflow.com/a/823729/2246344">read</a> that the default stack size for a thread is 1 MB, so in order to move all my <code>float[]</code>s I would have to expand the stack by approximately 50 times (to 50 MB~).</p> <p>I understand this is generally considered "unsafe" and isn't recommended, but after benchmarking my current code against this method, I've discovered a <em>530%</em> increase in processing speed! So I can not simply pass by this option without further investigation, which leads me to my question; what are the dangers associated with increasing the stack to such a large size (what could go wrong), and what precautions should I take to minimise such dangers?</p> <p>My test code,</p> <pre><code>public static unsafe void TestMethod1() { float* samples = stackalloc float[12500000]; for (var ii = 0; ii &lt; 12500000; ii++) { samples[ii] = 32768; } } public static void TestMethod2() { var samples = new float[12500000]; for (var i = 0; i &lt; 12500000; i++) { samples[i] = 32768; } } </code></pre>
<p>Upon comparing test code with Sam, I determined that we are both right!<br> However, about different things: </p> <ul> <li>Accessing memory (reading and writing) is <em>just as fast</em> wherever it is - stack, global or heap. </li> <li><strong>Allocating</strong> it, however, is fastest on stack and slowest on heap. </li> </ul> <p>It goes like this: <code>stack</code> &lt; <code>global</code> &lt; <code>heap</code>. (allocation time)<br> Technically, stack allocation isn't really an allocation, the runtime just makes sure a part of the stack (frame?) is reserved for the array.</p> <p>I strongly advise being careful with this, though.<br> I recommend the following: </p> <ol> <li>When you need to create arrays frequently which never <em>leave</em> the function (e.g. by passing its reference), using the stack will be an enormous improvement. </li> <li>If you can recycle an array, do so whenever you can! The heap is the best place for long-term object storage. (polluting global memory isn't nice; stack frames can disappear)</li> </ol> <p>(<em>Note</em>: 1. only applies to value types; reference types will be allocated on the heap and the benefit will be reduced to 0) </p> <p>To answer the question itself: I have not encountered any problem at all with any large-stack test.<br> I believe the only possible problems are a stack overflow, if you are not careful with your function calls and running out of memory when creating your thread(s) if the system is running low. </p> <p><strong>The section below is my initial answer. It is wrong-ish and the tests aren't correct. It is kept only for reference.</strong></p> <hr> <p>My test indicates the stack-allocated memory and global memory is at least 15% slower than (takes 120% the time of) heap-allocated memory for usage in arrays! </p> <p><a href="https://gist.github.com/vercas/787ae822548c40b81ad6" rel="nofollow noreferrer">This is my test code</a>, and this is a sample output: </p> <pre><code>Stack-allocated array time: 00:00:00.2224429 Globally-allocated array time: 00:00:00.2206767 Heap-allocated array time: 00:00:00.1842670 ------------------------------------------ Fastest: Heap. | S | G | H | --+---------+---------+---------+ S | - | 100.80 %| 120.72 %| --+---------+---------+---------+ G | 99.21 %| - | 119.76 %| --+---------+---------+---------+ H | 82.84 %| 83.50 %| - | --+---------+---------+---------+ Rates are calculated by dividing the row's value to the column's. </code></pre> <p>I tested on Windows 8.1 Pro (with Update 1), using an i7 4700 MQ, under .NET 4.5.1<br> I tested both with x86 and x64 and the results are identical. </p> <p><strong>Edit</strong>: I increased the stack size of all threads 201 MB, the sample size to 50 million and decreased iterations to 5.<br> The results are <strong>the same as above</strong>: </p> <pre><code>Stack-allocated array time: 00:00:00.4504903 Globally-allocated array time: 00:00:00.4020328 Heap-allocated array time: 00:00:00.3439016 ------------------------------------------ Fastest: Heap. | S | G | H | --+---------+---------+---------+ S | - | 112.05 %| 130.99 %| --+---------+---------+---------+ G | 89.24 %| - | 116.90 %| --+---------+---------+---------+ H | 76.34 %| 85.54 %| - | --+---------+---------+---------+ Rates are calculated by dividing the row's value to the column's. </code></pre> <p>Though, it seems the stack is actually <em>getting slower</em>.</p>
{ "question_id": 24200904, "question_date": "2014-06-13T08:29:25.767Z", "question_score": 228, "tags": "c#|.net|memory|stack-memory", "answer_id": 24208205, "answer_date": "2014-06-13T14:50:04.813Z", "answer_score": 45 }
Please answer the following Stack Overflow question: Title: Format date and time in a Windows batch script <p>In a Windows (Windows&nbsp;XP) batch script I need to format the current date and time for later use in files names, etc.</p> <p>It is similar to Stack Overflow question <em><a href="https://stackoverflow.com/questions/864718/how-to-append-a-date-in-batch-files">How to append a date in batch files</a></em>, but with time in as well.</p> <p>I have this so far:</p> <pre><code>echo %DATE% echo %TIME% set datetimef=%date:~-4%_%date:~3,2%_%date:~0,2%__%time:~0,2%_%time:~3,2%_%time:~6,2% echo %datetimef% </code></pre> <p>which gives:</p> <pre><code>28/07/2009 8:35:31.01 2009_07_28__ 8_36_01 </code></pre> <p>Is there a way I can allow for a single digit hour in %TIME%, so I can get the following?</p> <pre><code>2009_07_28__08_36_01 </code></pre>
<p>I ended up with this script:</p> <pre><code>set hour=%time:~0,2% if "%hour:~0,1%" == " " set hour=0%hour:~1,1% echo hour=%hour% set min=%time:~3,2% if "%min:~0,1%" == " " set min=0%min:~1,1% echo min=%min% set secs=%time:~6,2% if "%secs:~0,1%" == " " set secs=0%secs:~1,1% echo secs=%secs% set year=%date:~-4% echo year=%year% </code></pre> <p>:: On WIN2008R2 e.g. I needed to make your 'set month=%date:~3,2%' like below ::otherwise 00 appears for MONTH</p> <pre><code>set month=%date:~4,2% if "%month:~0,1%" == " " set month=0%month:~1,1% echo month=%month% set day=%date:~0,2% if "%day:~0,1%" == " " set day=0%day:~1,1% echo day=%day% set datetimef=%year%%month%%day%_%hour%%min%%secs% echo datetimef=%datetimef% </code></pre>
{ "question_id": 1192476, "question_date": "2009-07-28T07:46:34.480Z", "question_score": 227, "tags": "windows|datetime|formatting|batch-file", "answer_id": 1194991, "answer_date": "2009-07-28T15:43:48.217Z", "answer_score": 164 }
Please answer the following Stack Overflow question: Title: Check if a word is in a string in Python <p>I'm working with Python, and I'm trying to find out if you can tell if a word is in a string.</p> <p>I have found some information about identifying if the word is in the string - using <code>.find</code>, but is there a way to do an <code>if</code> statement. I would like to have something like the following:</p> <pre><code>if string.find(word): print(&quot;success&quot;) </code></pre>
<p>What is wrong with:</p> <pre><code>if word in mystring: print('success') </code></pre>
{ "question_id": 5319922, "question_date": "2011-03-16T01:10:17.030Z", "question_score": 227, "tags": "python|string", "answer_id": 5319942, "answer_date": "2011-03-16T01:13:09.077Z", "answer_score": 424 }
Please answer the following Stack Overflow question: Title: PHP Pass variable to next page <p>It seems pretty simple but I can't find a good way to do it.</p> <p>Say in the first page I create a variable</p> <pre><code>$myVariable = "Some text"; </code></pre> <p>And the form's action for that page is "Page2.php". So in Page2.php, how can I have access to that variable? I know I can do it with sessions but I think it's too much for a simple string, and I do only need to pass a simple string (a file name).</p> <p>How can I achieve this?</p> <p>Thanks!</p>
<p>HTML / HTTP is stateless, in other words, what you did / saw on the previous page, is completely unconnected with the current page. <em>Except</em> if you use something like sessions, cookies or GET / POST variables. Sessions and cookies are quite easy to use, with session being by far more secure than cookies. More secure, but not completely secure.</p> <p><strong>Session:</strong></p> <pre><code>//On page 1 $_SESSION['varname'] = $var_value; //On page 2 $var_value = $_SESSION['varname']; </code></pre> <p>Remember to run the <code>session_start();</code> statement on both these pages before you try to access the <code>$_SESSION</code> array, and also before any output is sent to the browser.</p> <p><strong>Cookie:</strong></p> <pre><code>//One page 1 $_COOKIE['varname'] = $var_value; //On page 2 $var_value = $_COOKIE['varname']; </code></pre> <p>The big difference between sessions and cookies is that the value of the variable will be stored on the server if you're using sessions, and on the client if you're using cookies. I can't think of any good reason to use cookies instead of sessions, except if you want data to persist between sessions, but even then it's perhaps better to store it in a DB, and retrieve it based on a username or id.</p> <p><strong>GET and POST</strong></p> <p>You can add the variable in the link to the next page:</p> <pre><code>&lt;a href="page2.php?varname=&lt;?php echo $var_value ?&gt;"&gt;Page2&lt;/a&gt; </code></pre> <p>This will create a GET variable. </p> <p>Another way is to include a hidden field in a form that submits to page two:</p> <pre><code>&lt;form method="get" action="page2.php"&gt; &lt;input type="hidden" name="varname" value="var_value"&gt; &lt;input type="submit"&gt; &lt;/form&gt; </code></pre> <p>And then on page two:</p> <pre><code>//Using GET $var_value = $_GET['varname']; //Using POST $var_value = $_POST['varname']; //Using GET, POST or COOKIE. $var_value = $_REQUEST['varname']; </code></pre> <p>Just change the method for the form to <code>post</code> if you want to do it via post. Both are equally insecure, although GET is easier to hack.</p> <p>The fact that each new request is, except for session data, a totally new instance of the script caught me when I first started coding in PHP. Once you get used to it, it's quite simple though.</p>
{ "question_id": 871858, "question_date": "2009-05-16T06:58:45.773Z", "question_score": 227, "tags": "php|variables|session", "answer_id": 872522, "answer_date": "2009-05-16T14:24:19.303Z", "answer_score": 503 }
Please answer the following Stack Overflow question: Title: ComboBox: Adding Text and Value to an Item (no Binding Source) <p>In C# WinApp, how can I add both Text and Value to the items of my ComboBox? I did a search and usually the answers are using "Binding to a source".. but in my case I do not have a binding source ready in my program... How can I do something like this:</p> <pre><code>combo1.Item[1] = "DisplayText"; combo1.Item[1].Value = "useful Value" </code></pre>
<p>You must create your own class type and override the ToString() method to return the text you want. Here is a simple example of a class you can use:</p> <pre><code>public class ComboboxItem { public string Text { get; set; } public object Value { get; set; } public override string ToString() { return Text; } } </code></pre> <p>The following is a simple example of its usage:</p> <pre><code>private void Test() { ComboboxItem item = new ComboboxItem(); item.Text = "Item text1"; item.Value = 12; comboBox1.Items.Add(item); comboBox1.SelectedIndex = 0; MessageBox.Show((comboBox1.SelectedItem as ComboboxItem).Value.ToString()); } </code></pre>
{ "question_id": 3063320, "question_date": "2010-06-17T15:52:39.273Z", "question_score": 227, "tags": "c#|winforms|combobox", "answer_id": 3063421, "answer_date": "2010-06-17T16:04:53.640Z", "answer_score": 406 }
Please answer the following Stack Overflow question: Title: How to print a float with 2 decimal places in Java? <p>Can I do it with <code>System.out.print</code>?</p>
<p>You can use the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/io/PrintStream.html#printf%28java.lang.String,%20java.lang.Object...%29" rel="noreferrer"><code>printf</code></a> method, like so:</p> <pre><code>System.out.printf("%.2f", val); </code></pre> <p>In short, the <code>%.2f</code> syntax tells Java to return your variable (<code>val</code>) with 2 decimal places (<code>.2</code>) in decimal representation of a floating-point number (<code>f</code>) from the start of the format specifier (<code>%</code>).</p> <p>There are other conversion characters you can use besides <code>f</code>:</p> <ul> <li><code>d</code>: decimal integer</li> <li><code>o</code>: octal integer</li> <li><code>e</code>: floating-point in scientific notation</li> </ul>
{ "question_id": 2538787, "question_date": "2010-03-29T14:45:34.073Z", "question_score": 227, "tags": "java|formatting|printf|decimal-point", "answer_id": 2538803, "answer_date": "2010-03-29T14:47:06.483Z", "answer_score": 314 }
Please answer the following Stack Overflow question: Title: How to get JSON from URL in JavaScript? <p><a href="http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20yahoo.finance.quotes%20WHERE%20symbol%3D%27WRC%27&amp;format=json&amp;diagnostics=true&amp;env=store://datatables.org/alltableswithkeys&amp;callback" rel="noreferrer">This URL</a> returns JSON:</p> <pre><code>{ query: { count: 1, created: "2015-12-09T17:12:09Z", lang: "en-US", diagnostics: {}, ... } } </code></pre> <p>I tried this, and it didn't work:</p> <pre><code>responseObj = readJsonFromUrl('http://query.yahooapis.com/v1/publ...'); var count = responseObj.query.count; console.log(count) // should be 1 </code></pre> <p>How can I get a JavaScript object from this URL's JSON response?</p>
<p>You can use jQuery <a href="http://api.jquery.com/jQuery.getJSON/" rel="noreferrer"><code>.getJSON()</code></a> function:</p> <pre><code>$.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20yahoo.finance.quotes%20WHERE%20symbol%3D%27WRC%27&amp;format=json&amp;diagnostics=true&amp;env=store://datatables.org/alltableswithkeys&amp;callback', function(data) { // JSON result in `data` variable }); </code></pre> <p>If you don't want to use jQuery you should look at <a href="https://stackoverflow.com/a/2499647/1361042">this answer</a> for pure JS solution.</p>
{ "question_id": 12460378, "question_date": "2012-09-17T13:34:15.047Z", "question_score": 227, "tags": "javascript|json", "answer_id": 12460434, "answer_date": "2012-09-17T13:37:29.813Z", "answer_score": 219 }
Please answer the following Stack Overflow question: Title: Calendar date to yyyy-MM-dd format in java <p>How to convert calendar date to <code>yyyy-MM-dd</code> format.</p> <pre><code>Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, 1); Date date = cal.getTime(); SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); String date1 = format1.format(date); Date inActiveDate = null; try { inActiveDate = format1.parse(date1); } catch (ParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } </code></pre> <p>This will produce <code>inActiveDate = Wed Sep 26 00:00:00 IST 2012</code>. But what I need is <code>2012-09-26</code>. My purpose is to compare this date with another date in my database using Hibernate criteria. So I need the date object in <code>yyyy-MM-dd</code> format.</p>
<p>A Java <code>Date</code> is a container for the number of milliseconds since January 1, 1970, 00:00:00 GMT.</p> <p>When you use something like <code>System.out.println(date)</code>, Java uses <code>Date.toString()</code> to print the contents.</p> <p>The only way to change it is to override <code>Date</code> and provide your own implementation of <code>Date.toString()</code>. Now before you fire up your IDE and try this, I wouldn't; it will only complicate matters. You are better off formatting the date to the format you want to use (or display).</p> <h1>Java 8+</h1> <pre><code>LocalDateTime ldt = LocalDateTime.now().plusDays(1); DateTimeFormatter formmat1 = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH); System.out.println(ldt); // Output "2018-05-12T17:21:53.658" String formatter = formmat1.format(ldt); System.out.println(formatter); // 2018-05-12 </code></pre> <h1>Prior to Java 8</h1> <p>You should be making use of the <a href="http://www.threeten.org/threetenbp/" rel="noreferrer">ThreeTen Backport</a></p> <p>The following is maintained for historical purposes (as the original answer)</p> <p>What you can do, is format the date.</p> <pre><code>Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, 1); SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); System.out.println(cal.getTime()); // Output "Wed Sep 26 14:23:28 EST 2012" String formatted = format1.format(cal.getTime()); System.out.println(formatted); // Output "2012-09-26" System.out.println(format1.parse(formatted)); // Output "Wed Sep 26 00:00:00 EST 2012" </code></pre> <p>These are actually the same date, represented differently.</p>
{ "question_id": 12575990, "question_date": "2012-09-25T03:57:24.923Z", "question_score": 227, "tags": "java|date|calendar|converter", "answer_id": 12576219, "answer_date": "2012-09-25T04:27:57.800Z", "answer_score": 365 }
Please answer the following Stack Overflow question: Title: How can I use a batch file to write to a text file? <p>I need to make a script that can write one line of text to a text file in the same directory as the batch file.</p>
<p>You can use <a href="http://technet.microsoft.com/en-us/library/cc772462%28v=ws.10%29.aspx" rel="noreferrer"><code>echo</code></a>, and redirect the output to a text file (see notes below):</p> <pre><code>rem Saved in D:\Temp\WriteText.bat @echo off echo This is a test&gt; test.txt echo 123&gt;&gt; test.txt echo 245.67&gt;&gt; test.txt </code></pre> <p>Output:</p> <pre> D:\Temp>WriteText D:\Temp>type test.txt This is a test 123 245.67 D:\Temp> </pre> <p>Notes:</p> <ul> <li><code>@echo off</code> turns off printing of each command to the console</li> <li>Unless you give it a specific path name, redirection with <code>&gt;</code> or <code>&gt;&gt;</code> will write to the current directory (the directory the code is being run in).</li> <li>The <code>echo This is a test &gt; test.txt</code> uses one <code>&gt;</code> to overwrite any file that already exists with new content.</li> <li>The remaining <code>echo</code> statements use two <code>&gt;&gt;</code> characters to append to the text file (add to), instead of overwriting it.</li> <li>The <code>type test.txt</code> simply types the file output to the command window.</li> </ul>
{ "question_id": 19878136, "question_date": "2013-11-09T16:15:12.813Z", "question_score": 227, "tags": "file|batch-file|text", "answer_id": 19879594, "answer_date": "2013-11-09T17:05:09.910Z", "answer_score": 370 }
Please answer the following Stack Overflow question: Title: JSON to pandas DataFrame <p>What I am trying to do is extract elevation data from a google maps API along a path specified by latitude and longitude coordinates as follows:</p> <pre><code>from urllib2 import Request, urlopen import json path1 = '42.974049,-81.205203|42.974298,-81.195755' request=Request('http://maps.googleapis.com/maps/api/elevation/json?locations='+path1+'&amp;sensor=false') response = urlopen(request) elevations = response.read() </code></pre> <p>This gives me a data that looks like this:</p> <pre><code>elevations.splitlines() ['{', ' "results" : [', ' {', ' "elevation" : 243.3462677001953,', ' "location" : {', ' "lat" : 42.974049,', ' "lng" : -81.205203', ' },', ' "resolution" : 19.08790397644043', ' },', ' {', ' "elevation" : 244.1318664550781,', ' "location" : {', ' "lat" : 42.974298,', ' "lng" : -81.19575500000001', ' },', ' "resolution" : 19.08790397644043', ' }', ' ],', ' "status" : "OK"', '}'] </code></pre> <p>when putting into as DataFrame here is what I get:</p> <p><img src="https://i.stack.imgur.com/t9aSp.png" alt="enter image description here"></p> <pre><code>pd.read_json(elevations) </code></pre> <p>and here is what I want:</p> <p><img src="https://i.stack.imgur.com/4Kdlg.png" alt="enter image description here"></p> <p>I'm not sure if this is possible, but mainly what I am looking for is a way to be able to put the elevation, latitude and longitude data together in a pandas dataframe (doesn't have to have fancy mutiline headers).</p> <p>If any one can help or give some advice on working with this data that would be great! If you can't tell I haven't worked much with json data before...</p> <p>EDIT:</p> <p>This method isn't all that attractive but seems to work:</p> <pre><code>data = json.loads(elevations) lat,lng,el = [],[],[] for result in data['results']: lat.append(result[u'location'][u'lat']) lng.append(result[u'location'][u'lng']) el.append(result[u'elevation']) df = pd.DataFrame([lat,lng,el]).T </code></pre> <p>ends up dataframe having columns latitude, longitude, elevation</p> <p><img src="https://i.stack.imgur.com/seht1.png" alt="enter image description here"></p>
<p>I found a quick and easy solution to what I wanted using <code>json_normalize()</code> included in <code>pandas 1.01</code>.</p> <pre><code>from urllib2 import Request, urlopen import json import pandas as pd path1 = '42.974049,-81.205203|42.974298,-81.195755' request=Request('http://maps.googleapis.com/maps/api/elevation/json?locations='+path1+'&amp;sensor=false') response = urlopen(request) elevations = response.read() data = json.loads(elevations) df = pd.json_normalize(data['results']) </code></pre> <p>This gives a nice flattened dataframe with the json data that I got from the Google Maps API.</p>
{ "question_id": 21104592, "question_date": "2014-01-14T01:32:07.830Z", "question_score": 227, "tags": "python|json|google-maps|pandas", "answer_id": 21266043, "answer_date": "2014-01-21T18:17:22.187Z", "answer_score": 287 }
Please answer the following Stack Overflow question: Title: Display current time in 12 hour format with AM/PM <p>Currently the time displayed as <strong>13:35 PM</strong> However <strong>I want to display as 12 hour format with AM/PM, i.e 1:35 PM instead of 13:35 PM</strong></p> <p>The current code is as below </p> <pre><code>private static final int FOR_HOURS = 3600000; private static final int FOR_MIN = 60000; public String getTime(final Model model) { SimpleDateFormat formatDate = new SimpleDateFormat("HH:mm a"); formatDate.setTimeZone(userContext.getUser().getTimeZone()); model.addAttribute("userCurrentTime", formatDate.format(new Date())); final String offsetHours = String.format("%+03d:%02d", userContext.getUser().getTimeZone().getRawOffset() / FOR_HOURS, Math.abs(userContext.getUser().getTimeZone().getRawOffset() % FOR_HOURS / FOR_MIN)); model.addAttribute("offsetHours", offsetHours + " " + userContext.getUser().getTimeZone().getDisplayName(Locale.ROOT)); return "systemclock"; } </code></pre>
<p>Easiest way to get it by using date pattern - <code>h:mm a</code>, where </p> <ul> <li>h - Hour in am/pm (1-12)</li> <li>m - Minute in hour</li> <li>a - Am/pm marker</li> </ul> <p>Code snippet :</p> <pre><code>DateFormat dateFormat = new SimpleDateFormat("hh:mm a"); </code></pre> <p><a href="http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html">Read more on documentation - SimpleDateFormat java 7 </a></p>
{ "question_id": 18734452, "question_date": "2013-09-11T06:48:24.047Z", "question_score": 227, "tags": "java|date-format", "answer_id": 18734471, "answer_date": "2013-09-11T06:49:57.757Z", "answer_score": 517 }
Please answer the following Stack Overflow question: Title: How to add a string in a certain position? <p>Is there any function in Python that I can use to insert a value in a certain position of a string?</p> <p>Something like this:</p> <p><code>"3655879ACB6"</code> then in position 4 add <code>"-"</code> to become <code>"3655-879ACB6"</code></p>
<p>No. Python Strings are immutable. </p> <pre><code>&gt;&gt;&gt; s='355879ACB6' &gt;&gt;&gt; s[4:4] = '-' Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'str' object does not support item assignment </code></pre> <p>It is, however, possible to create a new string that has the inserted character:</p> <pre><code>&gt;&gt;&gt; s[:4] + '-' + s[4:] '3558-79ACB6' </code></pre>
{ "question_id": 5254445, "question_date": "2011-03-10T01:32:33.503Z", "question_score": 227, "tags": "python|string", "answer_id": 5254455, "answer_date": "2011-03-10T01:34:44.183Z", "answer_score": 381 }
Please answer the following Stack Overflow question: Title: Canvas width and height in HTML5 <p>Is it possible to fix the width and height of an HTML5 <code>canvas</code> element?</p> <p>The usual way is the following :</p> <pre><code>&lt;canvas id="canvas" width="300" height="300"&gt;&lt;/canvas&gt; </code></pre>
<p>The <code>canvas</code> DOM element has <code>.height</code> and <code>.width</code> properties that correspond to the <code>height="…"</code> and <code>width="…"</code> attributes. Set them to numeric values in JavaScript code to resize your canvas. For example:</p> <pre><code>var canvas = document.getElementsByTagName('canvas')[0]; canvas.width = 800; canvas.height = 600; </code></pre> <p>Note that this clears the canvas, though you should follow with <code>ctx.clearRect( 0, 0, ctx.canvas.width, ctx.canvas.height);</code> to handle those browsers that don't fully clear the canvas. You'll need to redraw of any content you wanted displayed after the size change.</p> <p>Note further that the height and width are the logical canvas dimensions used for drawing and are <em>different</em> from the <code>style.height</code> and <code>style.width</code> CSS attributes. If you don't set the CSS attributes, the intrinsic size of the canvas will be used as its display size; if you do set the CSS attributes, and they differ from the canvas dimensions, your content will be scaled in the browser. For example:</p> <pre><code>// Make a canvas that has a blurry pixelated zoom-in // with each canvas pixel drawn showing as roughly 2x2 on screen canvas.width = 400; canvas.height = 300; canvas.style.width = '800px'; canvas.style.height = '600px'; </code></pre> <p><em>See <a href="http://jsfiddle.net/c3Lvn84b/" rel="noreferrer">this live example</a> of a canvas that is zoomed in by 4x.</em></p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var c = document.getElementsByTagName('canvas')[0]; var ctx = c.getContext('2d'); ctx.lineWidth = 1; ctx.strokeStyle = '#f00'; ctx.fillStyle = '#eff'; ctx.fillRect( 10.5, 10.5, 20, 20 ); ctx.strokeRect( 10.5, 10.5, 20, 20 ); ctx.fillRect( 40, 10.5, 20, 20 ); ctx.strokeRect( 40, 10.5, 20, 20 ); ctx.fillRect( 70, 10, 20, 20 ); ctx.strokeRect( 70, 10, 20, 20 ); ctx.strokeStyle = '#fff'; ctx.strokeRect( 10.5, 10.5, 20, 20 ); ctx.strokeRect( 40, 10.5, 20, 20 ); ctx.strokeRect( 70, 10, 20, 20 );</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { background:#eee; margin:1em; text-align:center } canvas { background:#fff; border:1px solid #ccc; width:400px; height:160px }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;canvas width="100" height="40"&gt;&lt;/canvas&gt; &lt;p&gt;Showing that re-drawing the same antialiased lines does not obliterate old antialiased lines.&lt;/p&gt;</code></pre> </div> </div> </p>
{ "question_id": 4938346, "question_date": "2011-02-08T20:58:27.230Z", "question_score": 227, "tags": "html|canvas", "answer_id": 4939066, "answer_date": "2011-02-08T22:06:56.177Z", "answer_score": 440 }
Please answer the following Stack Overflow question: Title: How to get a dependency tree for an artifact? <p><code>dependency:tree</code> can be used to see the dependency tree for a given project. But what I need is to see the dependency tree for a 3rd party artifact.</p> <p>I guess I can create an empty project, but I'm looking for something easier (I need to do this for several artifacts).</p>
<h3>1) Use <a href="https://maven.apache.org/plugins/maven-dependency-plugin/usage.html" rel="nofollow noreferrer">maven dependency plugin</a></h3> <p>Create a simple project with <code>pom.xml</code> only. Add your dependency and run:</p> <pre><code>mvn dependency:tree </code></pre> <p>(Version for multi-module Maven project: <code>mvn compile dependency:tree </code>)</p> <p>Unfortunately <a href="https://maven.apache.org/plugins/maven-dependency-plugin/tree-mojo.html" rel="nofollow noreferrer">dependency mojo</a> must use <code>pom.xml</code> or you get following error:</p> <blockquote> <p>Cannot execute mojo: tree. It requires a project with an existing <code>pom.xml</code>, but the build is not using one.</p> </blockquote> <h3>2) Find <code>pom.xml</code> of your artifact in maven central repository</h3> <p>Dependencies are described In <code>pom.xml</code> of your artifact. Find it using maven infrastructure.</p> <p>Go to <a href="https://search.maven.org/" rel="nofollow noreferrer">https://search.maven.org/</a> and enter your <code>groupId</code> and <code>artifactId</code>.</p> <p>Or you can go to <a href="https://repo1.maven.org/maven2/" rel="nofollow noreferrer">https://repo1.maven.org/maven2/</a> and navigate first using plugins <code>groupId</code>, later using <code>artifactId</code> and finally using its version.</p> <p>For example see <a href="https://repo1.maven.org/maven2/org/springframework/spring-core/3.0.3.RELEASE/" rel="nofollow noreferrer">org.springframework:spring-core</a></p> <h3>3) Use maven dependency plugin against your artifact</h3> <p>Part of dependency artifact is a <code>pom.xml</code>. That specifies it's dependency. And you can execute <code>mvn dependency:tree</code> on this pom.</p>
{ "question_id": 3342908, "question_date": "2010-07-27T11:03:21.023Z", "question_score": 227, "tags": "maven-2|build-process|dependencies", "answer_id": 3342951, "answer_date": "2010-07-27T11:07:30.303Z", "answer_score": 314 }
Please answer the following Stack Overflow question: Title: How to clear all <div>s’ contents inside a parent <div>? <p>I have a div <code>&lt;div id="masterdiv"&gt;</code> which has several child <code>&lt;div&gt;</code>s.</p> <p>Example:</p> <pre><code>&lt;div id="masterdiv"&gt; &lt;div id="childdiv1" /&gt; &lt;div id="childdiv2" /&gt; &lt;div id="childdiv3" /&gt; &lt;/div&gt; </code></pre> <p>How to clear the contents of all child <code>&lt;div&gt;</code>s inside the master <code>&lt;div&gt;</code> using jQuery?</p>
<pre><code>jQuery('#masterdiv div').html(''); </code></pre>
{ "question_id": 1701973, "question_date": "2009-11-09T16:03:39.630Z", "question_score": 227, "tags": "javascript|jquery|html|dom-manipulation", "answer_id": 1701985, "answer_date": "2009-11-09T16:05:28.603Z", "answer_score": 280 }
Please answer the following Stack Overflow question: Title: How to get a variable type in Typescript? <p>I have a variable.</p> <pre><code>abc:number|string; </code></pre> <p>How can I check its type? I want to do something like below:</p> <pre><code>if (abc.type === "number") { // do something } </code></pre>
<p>For : </p> <pre><code>abc:number|string; </code></pre> <p>Use the <em>JavaScript</em> operator <code>typeof</code>: </p> <pre><code>if (typeof abc === "number") { // do something } </code></pre> <p>TypeScript understands <code>typeof</code> </p> <p>This is called a typeguard. </p> <h1>More</h1> <p>For classes you would use <code>instanceof</code> e.g.</p> <pre><code>class Foo {} class Bar {} // Later if (fooOrBar instanceof Foo){ // TypeScript now knows that `fooOrBar` is `Foo` } </code></pre> <p>There are also other type guards e.g. <code>in</code> etc <a href="https://basarat.gitbooks.io/typescript/content/docs/types/typeGuard.html" rel="noreferrer">https://basarat.gitbooks.io/typescript/content/docs/types/typeGuard.html</a></p>
{ "question_id": 35546421, "question_date": "2016-02-22T05:33:43.110Z", "question_score": 227, "tags": "typescript", "answer_id": 35546468, "answer_date": "2016-02-22T05:37:44.127Z", "answer_score": 355 }
Please answer the following Stack Overflow question: Title: How do I force git pull to overwrite everything on every pull? <p>I have a CENTRAL bare repository that has three developer repositories pulling and pushing to it normally.</p> <p>I also have two other repositories that pull from the CENTRAL bare repo: one is the live server, and the other is a test/stage server—each pulling from its own respective branch.</p> <p>The scenario is this: I have a <code>post-update</code> hook script on the CENTRAL repo that automatically accesses the test and live repos and runs a pull command on each. This updates both test and live servers, all depending on what branch has new commits. This all works great.</p> <p>The problem is this: there may be times in an emergency that files may be directly updated on the server (via ftp or whatever) and the CENTRAL post-update script will then fail since merge/overwrite conflicts will occur. There is no way to avoid this scenario, and it is inevitable.</p> <p>What I would like to have happen is this: I want the pull from the live and test sites to <em>always</em> overwrite/merge on pull. <strong><em>Always.</em></strong> These repos will be pull-only as they are not for development.</p> <p>In all my research, I cannot find a good solution to have a pull <em>always</em> force an overwrite of the local files. Is this at all possible? It would make for a great development scenario if so.</p>
<p>Really the ideal way to do this is to not use <code>pull</code> at all, but instead <code>fetch</code> and <code>reset</code>:</p> <pre><code>git fetch origin master git reset --hard FETCH_HEAD git clean -df </code></pre> <p>(Altering <code>master</code> to whatever branch you want to be following.)</p> <p><code>pull</code> is designed around merging changes together in some way, whereas <code>reset</code> is designed around simply making your local copy match a specific commit.</p> <p>You may want to consider slightly different options to <code>clean</code> depending on your system's needs.</p>
{ "question_id": 9589814, "question_date": "2012-03-06T18:36:28.647Z", "question_score": 227, "tags": "git|git-pull", "answer_id": 9589927, "answer_date": "2012-03-06T18:45:17.110Z", "answer_score": 566 }
Please answer the following Stack Overflow question: Title: How to remove frame from matplotlib (pyplot.figure vs matplotlib.figure ) (frameon=False Problematic in matplotlib) <p>To remove frame in figure, I write </p> <pre><code>frameon=False </code></pre> <p>works perfect with <code>pyplot.figure</code>, but with <code>matplotlib.Figure</code> it only removes the gray background, the frame stays . Also, I only want the lines to show, and all the rest of figure be transparent.</p> <p>with pyplot I can do what I want, I want to do it with matplotlib for some long reason I 'd rather not mention to extend my question.</p>
<p>First off, if you're using <code>savefig</code>, be aware that it will override the figure's background color when saving unless you specify otherwise (e.g. <code>fig.savefig('blah.png', transparent=True)</code>).</p> <p>However, to remove the axes' and figure's background on-screen, you'll need to set both <code>ax.patch</code> and <code>fig.patch</code> to be invisible. </p> <p>E.g.</p> <pre><code>import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot(range(10)) for item in [fig, ax]: item.patch.set_visible(False) with open('test.png', 'w') as outfile: fig.canvas.print_png(outfile) </code></pre> <p><img src="https://i.stack.imgur.com/JwBju.png" alt="enter image description here"></p> <p>(Of course, you can't tell the difference on SO's white background, but everything is transparent...)</p> <p>If you don't want to show anything other than the line, turn the axis off as well using <code>ax.axis('off')</code>:</p> <pre><code>import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot(range(10)) fig.patch.set_visible(False) ax.axis('off') with open('test.png', 'w') as outfile: fig.canvas.print_png(outfile) </code></pre> <p><img src="https://i.stack.imgur.com/qJaRf.png" alt="enter image description here"></p> <p>In that case, though, you may want to make the axes take up the full figure. If you manually specify the location of the axes, you can tell it to take up the full figure (alternately, you can use <code>subplots_adjust</code>, but this is simpler for the case of a single axes). </p> <pre><code>import matplotlib.pyplot as plt fig = plt.figure(frameon=False) ax = fig.add_axes([0, 0, 1, 1]) ax.axis('off') ax.plot(range(10)) with open('test.png', 'w') as outfile: fig.canvas.print_png(outfile) </code></pre> <p><img src="https://i.stack.imgur.com/gMrsE.png" alt="enter image description here"></p>
{ "question_id": 14908576, "question_date": "2013-02-16T08:49:38.117Z", "question_score": 227, "tags": "python|matplotlib", "answer_id": 14913405, "answer_date": "2013-02-16T18:03:21.257Z", "answer_score": 212 }
Please answer the following Stack Overflow question: Title: How do I make an HTML text box show a hint when empty? <p>I want the search box on my web page to display the word "Search" in gray italics. When the box receives focus, it should look just like an empty text box. If there is already text in it, it should display the text normally (black, non-italics). This will help me avoid clutter by removing the label.</p> <p>BTW, this is an on-page <a href="http://en.wikipedia.org/wiki/Ajax_%28programming%29" rel="noreferrer">Ajax</a> search, so it has no button.</p>
<p>Another option, if you're happy to have this feature only for newer browsers, is to use the support offered by HTML 5's <strong>placeholder</strong> attribute:</p> <pre><code>&lt;input name="email" placeholder="Email Address"&gt; </code></pre> <p>In the absence of any styles, in Chrome this looks like:</p> <p><a href="https://i.stack.imgur.com/tZcmY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/tZcmY.png" alt="enter image description here"></a></p> <p>You can try demos out <a href="http://diveintohtml5.info/examples/input-placeholder.html" rel="noreferrer">here</a> and in <em><a href="http://davidwalsh.name/html5-placeholder-css" rel="noreferrer">HTML5 Placeholder Styling with CSS</a></em>.</p> <p>Be sure to check the <a href="http://caniuse.com/#feat=input-placeholder" rel="noreferrer">browser compatibility of this feature</a>. Support in Firefox was added in 3.7. Chrome is fine. Internet&nbsp;Explorer only added support in 10. If you target a browser that does not support input placeholders, you can use a jQuery plugin called <a href="https://github.com/mathiasbynens/jquery-placeholder" rel="noreferrer">jQuery HTML5 Placeholder</a>, and then just add the following JavaScript code to enable it.</p> <pre><code>$('input[placeholder], textarea[placeholder]').placeholder(); </code></pre>
{ "question_id": 108207, "question_date": "2008-09-20T13:55:10.127Z", "question_score": 227, "tags": "javascript|html", "answer_id": 3612949, "answer_date": "2010-08-31T20:27:30.743Z", "answer_score": 384 }
Please answer the following Stack Overflow question: Title: XPath to select Element by attribute value <p>I have following XML.</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;Employees&gt; &lt;Employee id="3"&gt; &lt;age&gt;40&lt;/age&gt; &lt;name&gt;Tom&lt;/name&gt; &lt;gender&gt;Male&lt;/gender&gt; &lt;role&gt;Manager&lt;/role&gt; &lt;/Employee&gt; &lt;Employee id="4"&gt; &lt;age&gt;25&lt;/age&gt; &lt;name&gt;Meghna&lt;/name&gt; &lt;gender&gt;Female&lt;/gender&gt; &lt;role&gt;Manager&lt;/role&gt; &lt;/Employee&gt; &lt;/Employees&gt; </code></pre> <p>I want to select Employee element with id="4".</p> <p>I am using below XPath expression which is not returning anything.</p> <pre><code>//Employee/[@id='4']/text() </code></pre> <p>I checked it at <a href="http://chris.photobooks.com/xml/default.htm" rel="noreferrer">http://chris.photobooks.com/xml/default.htm</a> and it says invalid xpath, not sure where is the issue.</p>
<p>You need to remove the <code>/</code> before the <code>[</code>. Predicates (the parts in <code>[..]</code>) shouldn't have slashes immediately before them - they go directly after the node selector they are associated with.</p> <p>Also, to select the Employee element itself, you should leave off the <code>/text()</code> at the end. Otherwise you'd just be selecting the whitespace text values immediately under the Employee element.</p> <pre><code>//Employee[@id = '4'] </code></pre> <p>One more thing to note: <code>//</code> can be very slow because it searches the entire document for matching nodes. If the structure of the documents you're working with is going to be consistent, you are probably best off using a more explicit path, for example:</p> <pre><code>/Employees/Employee[@id = '4'] </code></pre>
{ "question_id": 14248063, "question_date": "2013-01-09T23:03:53.923Z", "question_score": 227, "tags": "xml|xpath", "answer_id": 14248104, "answer_date": "2013-01-09T23:06:59.837Z", "answer_score": 328 }
Please answer the following Stack Overflow question: Title: How to make the webpack dev server run on port 80 and on 0.0.0.0 to make it publicly accessible? <p>I am new to the whole <strong>nodejs</strong>/<strong>reactjs</strong> world so apologies if my question sounds silly. So I am playing around with <a href="https://github.com/reactabular/reactabular" rel="noreferrer">reactabular.js</a>.</p> <p>Whenever I do a <code>npm start</code> it always runs on <code>localhost:8080</code>.</p> <p>How do I change it to run on <code>0.0.0.0:8080</code> to make it publicly accessible? I have been trying to read the source code in the above repo but failed to find the file which does this setting.</p> <p>Also, to add to that - how do I make it run on port <code>80</code> if that is at all possible?</p>
<p>Something like this worked for me. I am guessing this should work for you. </p> <p>Run webpack-dev using this</p> <pre><code>webpack-dev-server --host 0.0.0.0 --port 80 </code></pre> <p>And set this in webpack.config.js</p> <pre><code>entry: [ 'webpack-dev-server/client?http://0.0.0.0:80', config.paths.demo ] </code></pre> <p><strong>Note</strong> If you are using hot loading, you will have to do this.</p> <p>Run webpack-dev using this</p> <pre><code>webpack-dev-server --host 0.0.0.0 --port 80 </code></pre> <p>And set this in webpack.config.js</p> <pre><code>entry: [ 'webpack-dev-server/client?http://0.0.0.0:80', 'webpack/hot/only-dev-server', config.paths.demo ], .... plugins:[new webpack.HotModuleReplacementPlugin()] </code></pre>
{ "question_id": 33272967, "question_date": "2015-10-22T03:35:49.653Z", "question_score": 227, "tags": "node.js|reactjs|npm|webpack|webpack-dev-server", "answer_id": 33273459, "answer_date": "2015-10-22T04:34:47.320Z", "answer_score": 282 }
Please answer the following Stack Overflow question: Title: Can you Run Xcode in Linux? <p>Can you run Xcode in Linux? Mac OS X was based on BSD Unix, so is it possible? </p> <p>From what I have heard, there is a MonoDevelop plugin that has an iPhone simulator.</p>
<p>The low-level toolchain for Xcode (the gcc compiler family, the gdb debugger, etc.) is all open source and common to Unix and Linux platforms. But the IDE--the editor, project management, indexing, navigation, build system, graphical debugger, visual data modeling, SCM system, refactoring, project snapshots, etc.--is a Mac OS X Cocoa application, and is not portable.</p>
{ "question_id": 2406151, "question_date": "2010-03-09T01:55:50.690Z", "question_score": 227, "tags": "linux|xcode|monodevelop", "answer_id": 2406839, "answer_date": "2010-03-09T05:18:43.440Z", "answer_score": 471 }
Please answer the following Stack Overflow question: Title: How do I make the scrollbar on a div only visible when necessary? <p>I have this div:</p> <pre><code>&lt;div style='overflow:scroll; width:400px;height:400px;'&gt;here is some text&lt;/div&gt; </code></pre> <p>The scrollbars are always visible, even though the text does not overflow. I want to make the scrollbars only be visible when necessary - that is, only visible when there is enough text in the box that they are needed. Like a textarea does. How do I do this? Or is my only option to style a textarea so it looks like a div?</p>
<p>Use <code>overflow: auto</code>. Scrollbars will only appear when needed.</p> <p>(Sidenote, you can also specify for only the x, or y scrollbar: <code>overflow-x: auto</code> and <code>overflow-y: auto</code>).</p>
{ "question_id": 14732448, "question_date": "2013-02-06T15:18:45.393Z", "question_score": 227, "tags": "css|html|scrollbar", "answer_id": 14732488, "answer_date": "2013-02-06T15:20:17.377Z", "answer_score": 455 }
Please answer the following Stack Overflow question: Title: Count Rows in Doctrine QueryBuilder <p>I'm using Doctrine's QueryBuilder to build a query, and I want to get the total count of results from the query. </p> <pre><code>$repository = $em-&gt;getRepository('FooBundle:Foo'); $qb = $repository-&gt;createQueryBuilder('n') -&gt;where('n.bar = :bar') -&gt;setParameter('bar', $bar); $query = $qb-&gt;getQuery(); //this doesn't work $totalrows = $query-&gt;getResult()-&gt;count(); </code></pre> <p>I just want to run a count on this query to get the total rows, but not return the actual results. (After this count query, I'm going to further modify the query with maxResults for pagination.) </p>
<p>Something like:</p> <pre class="lang-php prettyprint-override"><code>$qb = $entityManager-&gt;createQueryBuilder(); $qb-&gt;select('count(account.id)'); $qb-&gt;from('ZaysoCoreBundle:Account','account'); $count = $qb-&gt;getQuery()-&gt;getSingleScalarResult(); </code></pre> <p>Some folks feel that expressions are somehow better than just using straight DQL. One even went so far as to edit a four year old answer. I rolled his edit back. Go figure.</p>
{ "question_id": 9214471, "question_date": "2012-02-09T16:10:47.417Z", "question_score": 227, "tags": "symfony|doctrine-orm", "answer_id": 9215880, "answer_date": "2012-02-09T17:38:10.187Z", "answer_score": 533 }
Please answer the following Stack Overflow question: Title: How should I copy Strings in Java? <pre><code> String s = "hello"; String backup_of_s = s; s = "bye"; </code></pre> <p>At this point, the backup variable still contains the original value "hello" (this is because of String's immutability right?).</p> <p>But is it really <strong>safe</strong> to copy Strings with this method (which is of course not safe to copy regular mutable objects), or is better to write this? :</p> <pre><code> String s = "hello"; String backup_of_s = new String(s); s = "bye"; </code></pre> <p>In other words, what's the difference (if any) between these two snippets?</p> <hr> <p><strong>EDIT - the reason why the first snippet is safe:</strong></p> <p>Let me just explain things with a little more detail, based on the good answers already provided (which were essentially focused on the question of difference of performance between the 2 snippets):</p> <p>Strings are immutable in Java, which means that a String object cannot be modified after its construction. Hence,</p> <p><code>String s = "hello";</code> creates a new String instance and assigns its address to <code>s</code> (<code>s</code> being a reference to the instance/object)</p> <p><code>String backup_of_s = s;</code> creates a new variable <code>backup_of_s</code> and initializes it so that it references the object currently referenced by <code>s</code>.</p> <p>Note: String immutability guarantees that this object will not be modified: our backup is safe</p> <p>Note 2: Java garbage collection mechanism guarantees that this object will not be destroyed as long as it is referenced by at least one variable (<code>backup_of_s</code> in this case)</p> <p>Finally, <code>s = "bye";</code> creates another String instance (because of immutability, it's the only way), and modifies the <code>s</code> variable so that it now references the new object.</p>
<p>Since strings are immutable, both versions are safe. The latter, however, is less efficient (it creates an extra object and in some cases copies the character data).</p> <p>With this in mind, the first version should be preferred.</p>
{ "question_id": 10607990, "question_date": "2012-05-15T20:03:46.500Z", "question_score": 227, "tags": "java", "answer_id": 10608003, "answer_date": "2012-05-15T20:04:52.053Z", "answer_score": 161 }
Please answer the following Stack Overflow question: Title: How to find out if a file exists in C# / .NET? <p>I would like to test a string containing a path to a file for existence of that file (something like the <code>-e</code> test in Perl or the <code>os.path.exists()</code> in Python) in C#.</p>
<p>Use:</p> <pre><code>File.Exists(path) </code></pre> <p>MSDN: <a href="http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx</a></p> <p>Edit: In System.IO</p>
{ "question_id": 38960, "question_date": "2008-09-02T07:18:48.120Z", "question_score": 227, "tags": "c#|.net|io", "answer_id": 38962, "answer_date": "2008-09-02T07:19:51.190Z", "answer_score": 350 }
Please answer the following Stack Overflow question: Title: What is the best way to concatenate two vectors? <p>I'm using multitreading and want to merge the results. For example:</p> <pre><code>std::vector&lt;int&gt; A; std::vector&lt;int&gt; B; std::vector&lt;int&gt; AB; </code></pre> <p>I want AB to have to contents of A and the contents of B in that order. What's the most efficient way of doing something like this?</p>
<pre><code>AB.reserve( A.size() + B.size() ); // preallocate memory AB.insert( AB.end(), A.begin(), A.end() ); AB.insert( AB.end(), B.begin(), B.end() ); </code></pre>
{ "question_id": 3177241, "question_date": "2010-07-05T04:36:53.573Z", "question_score": 227, "tags": "c++|vector", "answer_id": 3177252, "answer_date": "2010-07-05T04:39:39.333Z", "answer_score": 379 }
Please answer the following Stack Overflow question: Title: How to change default text file encoding in Eclipse? <p>Whenever I add a new html file (or other text file) to the project its encoding is set to Cp1250. I am not sure why, I guess this is probably because my default language in Windows is Polish and I don't want to change it. Anyway, Eclipse says that Cp1250 is a 'default' encoding and I have to manually change it to UTF-8 each time I add anything.</p> <p>So where can I change the default encoding to UTF-8? I've set the encoding by right-clicking on whole project but it didn't help. I can't find anything in options. It's so annoying...</p> <p>I'm using 'Helios' release of the eclipse and use it with pydev if that matters.</p>
<p>Window -> Preferences -> General -> Workspace : Text file encoding</p>
{ "question_id": 3751791, "question_date": "2010-09-20T13:14:02.843Z", "question_score": 227, "tags": "eclipse", "answer_id": 3751828, "answer_date": "2010-09-20T13:19:23.683Z", "answer_score": 417 }
Please answer the following Stack Overflow question: Title: Iterate over object attributes in python <p>I have a python object with several attributes and methods. I want to iterate over object attributes. </p> <pre><code>class my_python_obj(object): attr1='a' attr2='b' attr3='c' def method1(self, etc, etc): #Statements </code></pre> <p>I want to generate a dictionary containing all of the objects attributes and their current values, but I want to do it in a dynamic way (so if later I add another attribute I don't have to remember to update my function as well).</p> <p>In php variables can be used as keys, but objects in python are unsuscriptable and if I use the dot notation for this it creates a new attribute with the name of my var, which is not my intent.</p> <p>Just to make things clearer:</p> <pre><code>def to_dict(self): '''this is what I already have''' d={} d["attr1"]= self.attr1 d["attr2"]= self.attr2 d["attr3"]= self.attr3 return d </code></pre> <p>·</p> <pre><code>def to_dict(self): '''this is what I want to do''' d={} for v in my_python_obj.attributes: d[v] = self.v return d </code></pre> <p>Update: With attributes I mean only the variables of this object, not the methods.</p>
<p>Assuming you have a class such as</p> <pre><code>&gt;&gt;&gt; class Cls(object): ... foo = 1 ... bar = 'hello' ... def func(self): ... return 'call me' ... &gt;&gt;&gt; obj = Cls() </code></pre> <p>calling <code>dir</code> on the object gives you back all the attributes of that object, including python special attributes. Although some object attributes are callable, such as methods.</p> <pre><code>&gt;&gt;&gt; dir(obj) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'bar', 'foo', 'func'] </code></pre> <p>You can always filter out the special methods by using a list comprehension.</p> <pre><code>&gt;&gt;&gt; [a for a in dir(obj) if not a.startswith('__')] ['bar', 'foo', 'func'] </code></pre> <p>or if you prefer map/filters.</p> <pre><code>&gt;&gt;&gt; filter(lambda a: not a.startswith('__'), dir(obj)) ['bar', 'foo', 'func'] </code></pre> <p>If you want to filter out the methods, you can use the builtin <code>callable</code> as a check.</p> <pre><code>&gt;&gt;&gt; [a for a in dir(obj) if not a.startswith('__') and not callable(getattr(obj, a))] ['bar', 'foo'] </code></pre> <p>You could also inspect the difference between your class and its instance object using.</p> <pre><code>&gt;&gt;&gt; set(dir(Cls)) - set(dir(object)) set(['__module__', 'bar', 'func', '__dict__', 'foo', '__weakref__']) </code></pre>
{ "question_id": 11637293, "question_date": "2012-07-24T18:44:55.827Z", "question_score": 227, "tags": "python|oop|attributes|iteration", "answer_id": 11637457, "answer_date": "2012-07-24T18:54:44.790Z", "answer_score": 314 }
Please answer the following Stack Overflow question: Title: Is SQL syntax case sensitive? <p>Is SQL case sensitive? I've used <a href="https://en.wikipedia.org/wiki/MySQL" rel="nofollow noreferrer">MySQL</a> and <a href="https://en.wikipedia.org/wiki/Microsoft_SQL_Server" rel="nofollow noreferrer">SQL Server</a> which both seem to be case insensitive. Is this always the case? Does the standard define case-sensitivity?</p>
<p>The SQL keywords are case insensitive (<code>SELECT</code>, <code>FROM</code>, <code>WHERE</code>, etc), but they are often written in all caps. However, in some setups, table and column names are case sensitive.</p> <p>MySQL has a configuration option to enable/disable it. Usually case sensitive table and column names are the default on Linux <a href="https://en.wikipedia.org/wiki/MySQL" rel="nofollow noreferrer">MySQL</a> and case insensitive used to be the default on Windows, but now the installer asked about this during setup. For <a href="https://en.wikipedia.org/wiki/Microsoft_SQL_Server" rel="nofollow noreferrer">SQL Server</a> it is a function of the database's collation setting.</p> <p>Here is the <a href="http://dev.mysql.com/doc/refman/5.0/en/identifier-case-sensitivity.html" rel="nofollow noreferrer">MySQL page about name case-sensitivity</a></p> <p>Here is the <a href="http://msdn.microsoft.com/en-us/library/ms143503(SQL.90).aspx" rel="nofollow noreferrer">article in MSDN about collations for SQL Server</a></p>
{ "question_id": 153944, "question_date": "2008-09-30T16:49:04.717Z", "question_score": 227, "tags": "sql|case-sensitive", "answer_id": 153967, "answer_date": "2008-09-30T16:52:16.083Z", "answer_score": 212 }
Please answer the following Stack Overflow question: Title: How do I rename all folders and files to lowercase on Linux? <p>I have to rename a complete folder tree recursively so that no uppercase letter appears anywhere (it's C++ source code, but that shouldn't matter).</p> <p>Bonus points for ignoring CVS and Subversion version control files/folders. The preferred way would be a shell script, since a shell should be available on any Linux box.</p> <p>There were some valid arguments about details of the file renaming.</p> <ol> <li><p>I think files with the same lowercase names should be overwritten; it's the user's problem. When checked out on a case-ignoring file system, it would overwrite the first one with the latter, too.</p></li> <li><p>I would consider A-Z characters and transform them to a-z, everything else is just calling for problems (at least with source code).</p></li> <li><p>The script would be needed to run a build on a Linux system, so I think changes to CVS or Subversion version control files should be omitted. After all, it's just a scratch checkout. Maybe an "export" is more appropriate.</p></li> </ol>
<p>A concise version using the <code>"rename"</code> command:</p> <pre><code>find my_root_dir -depth -exec rename 's/(.*)\/([^\/]*)/$1\/\L$2/' {} \; </code></pre> <p>This avoids problems with directories being renamed before files and trying to move files into non-existing directories (e.g. <code>"A/A"</code> into <code>"a/a"</code>).</p> <p>Or, a more verbose version without using <code>"rename"</code>.</p> <pre><code>for SRC in `find my_root_dir -depth` do DST=`dirname "${SRC}"`/`basename "${SRC}" | tr '[A-Z]' '[a-z]'` if [ "${SRC}" != "${DST}" ] then [ ! -e "${DST}" ] &amp;&amp; mv -T "${SRC}" "${DST}" || echo "${SRC} was not renamed" fi done </code></pre> <h3>P.S.</h3> <p>The latter allows more flexibility with the move command (for example, <code>"svn mv"</code>).</p>
{ "question_id": 152514, "question_date": "2008-09-30T10:25:17.930Z", "question_score": 227, "tags": "linux|rename|lowercase", "answer_id": 152741, "answer_date": "2008-09-30T12:03:32.720Z", "answer_score": 196 }
Please answer the following Stack Overflow question: Title: Creating a ZIP archive in memory using System.IO.Compression <p>I'm trying to create a ZIP archive with a simple demo text file using a <code>MemoryStream</code> as follows:</p> <pre><code>using (var memoryStream = new MemoryStream()) using (var archive = new ZipArchive(memoryStream , ZipArchiveMode.Create)) { var demoFile = archive.CreateEntry("foo.txt"); using (var entryStream = demoFile.Open()) using (var streamWriter = new StreamWriter(entryStream)) { streamWriter.Write("Bar!"); } using (var fileStream = new FileStream(@"C:\Temp\test.zip", FileMode.Create)) { stream.CopyTo(fileStream); } } </code></pre> <p>If I run this code, the archive file itself is created but <em>foo.txt</em> isn't.</p> <p>However, if I replace the <code>MemoryStream</code> directly with the file stream, the archive is created correctly:</p> <pre><code>using (var fileStream = new FileStream(@"C:\Temp\test.zip", FileMode.Create)) using (var archive = new ZipArchive(fileStream, FileMode.Create)) { // ... } </code></pre> <p>Is it possible to use a <code>MemoryStream</code> to create the ZIP archive without the <code>FileStream</code>?</p>
<p>Thanks to <a href="https://stackoverflow.com/q/12347775/222748#12350106">ZipArchive creates invalid ZIP file</a>, I got:</p> <pre><code>using (var memoryStream = new MemoryStream()) { using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true)) { var demoFile = archive.CreateEntry(&quot;foo.txt&quot;); using (var entryStream = demoFile.Open()) using (var streamWriter = new StreamWriter(entryStream)) { streamWriter.Write(&quot;Bar!&quot;); } } using (var fileStream = new FileStream(@&quot;C:\Temp\test.zip&quot;, FileMode.Create)) { memoryStream.Seek(0, SeekOrigin.Begin); memoryStream.CopyTo(fileStream); } } </code></pre> <p>That indicated we need to call <code>Dispose</code> on <code>ZipArchive</code> before we can use it, which as Amir suggests is likely because it writes final bytes like checksum to the archive that makes it complete. But in order not close the stream so we can re-use it after you need to pass <code>true</code> as the third parameter to <code>ZipArchive</code>.</p>
{ "question_id": 17232414, "question_date": "2013-06-21T09:57:04.620Z", "question_score": 227, "tags": "c#|.net|zip|compression|c#-ziparchive", "answer_id": 17939367, "answer_date": "2013-07-30T06:03:54.313Z", "answer_score": 389 }
Please answer the following Stack Overflow question: Title: Getting the difference between two sets <p>So if I have two sets:</p> <pre><code>Set&lt;Integer&gt; test1 = new HashSet&lt;Integer&gt;(); test1.add(1); test1.add(2); test1.add(3); Set&lt;Integer&gt; test2 = new HashSet&lt;Integer&gt;(); test2.add(1); test2.add(2); test2.add(3); test2.add(4); test2.add(5); </code></pre> <p>Is there a way to compare them and only have a set of 4 and 5 returned?</p>
<p>Try this </p> <pre><code>test2.removeAll(test1); </code></pre> <p><a href="http://docs.oracle.com/javase/7/docs/api/java/util/Set.html#removeAll">Set#removeAll</a></p> <blockquote> <p>Removes from this set all of its elements that are contained in the specified collection (optional operation). If the specified collection is also a set, this operation effectively modifies this set so that its value is the asymmetric set difference of the two sets.</p> </blockquote>
{ "question_id": 18644579, "question_date": "2013-09-05T19:40:10.440Z", "question_score": 227, "tags": "java|set", "answer_id": 18644612, "answer_date": "2013-09-05T19:42:42.420Z", "answer_score": 269 }
Please answer the following Stack Overflow question: Title: SQL Server - transactions roll back on error? <p>We have client app that is running some SQL on a SQL Server 2005 such as the following:</p> <pre><code>BEGIN TRAN; INSERT INTO myTable (myColumns ...) VALUES (myValues ...); INSERT INTO myTable (myColumns ...) VALUES (myValues ...); INSERT INTO myTable (myColumns ...) VALUES (myValues ...); COMMIT TRAN; </code></pre> <p>It is sent by one long string command.</p> <p>If one of the inserts fail, or any part of the command fails, does SQL Server roll back the transaction? If it does not rollback, do I have to send a second command to roll it back?</p> <p>I can give specifics about the api and language I'm using, but I would think SQL Server should respond the same for any language.</p>
<p>You can put <code>set xact_abort on</code> before your transaction to make sure sql rolls back automatically in case of error.</p>
{ "question_id": 1749719, "question_date": "2009-11-17T15:38:13.087Z", "question_score": 227, "tags": "sql|sql-server|sql-server-2005|transactions", "answer_id": 1749788, "answer_date": "2009-11-17T15:47:00.953Z", "answer_score": 237 }
Please answer the following Stack Overflow question: Title: How to get a list of all files that changed between two Git commits? <p>Due to bureaucracy, I need to get a list of all changed files in my repository for a report (I started with existing source code).</p> <p>What should I run to get this list?</p>
<p>For files changed between a given SHA and your current commit:</p> <pre><code>git diff --name-only &lt;starting SHA&gt; HEAD </code></pre> <p>or if you want to include changed-but-not-yet-committed files:</p> <pre><code>git diff --name-only &lt;starting SHA&gt; </code></pre> <p>More generally, the following syntax will always tell you which files changed between two commits (specified by their SHAs or other names):</p> <pre><code>git diff --name-only &lt;commit1&gt; &lt;commit2&gt; </code></pre> <p>Using <code>--name-status</code> instead of <code>--name-only</code> will show what happened to the files as well as the names.</p>
{ "question_id": 5096268, "question_date": "2011-02-23T19:50:31.680Z", "question_score": 227, "tags": "git", "answer_id": 5096294, "answer_date": "2011-02-23T19:52:44.050Z", "answer_score": 302 }
Please answer the following Stack Overflow question: Title: How to duplicate object properties in another object? <p>Given the object:</p> <pre><code>var firstObject = { key1 : 'value1', key2 : 'value2' }; </code></pre> <p><strong>how can I copy the properties inside another object</strong> (<code>secondObject</code>) like this:</p> <pre><code>var secondObject = { key1 : 'value1', key2 : 'value2', key3 : 'value3', key4 : 'value4' }; </code></pre> <p>using a reference to the <code>firstObject</code>? Something like this:</p> <pre><code>var secondObject = { firstObject, key3 : 'value3', key4 : 'value4' }; </code></pre> <p>(this doesn't work... I put it just to show in big lines how I would like to structure the code).</p> <p>Is a solution possible <strong>without</strong> using any JavaScript frameworks?</p>
<pre><code>for(var k in firstObject) secondObject[k]=firstObject[k]; </code></pre>
{ "question_id": 9362716, "question_date": "2012-02-20T14:27:10.373Z", "question_score": 227, "tags": "javascript", "answer_id": 9362763, "answer_date": "2012-02-20T14:31:20.870Z", "answer_score": 238 }
Please answer the following Stack Overflow question: Title: Can't use modulus on doubles? <p>I have a program in C++ (compiled using g++). I'm trying to apply two doubles as operands to the modulus function, but I get the following error:</p> <blockquote> <p>error: invalid operands of types 'double' and 'double' to binary 'operator%'</p> </blockquote> <p>Here's the code:</p> <pre><code>int main() { double x = 6.3; double y = 2; double z = x % y; } </code></pre>
<p>The <code>%</code> operator is for integers. You're looking for the <a href="http://en.cppreference.com/w/cpp/numeric/math/fmod" rel="noreferrer"><code>fmod()</code> function</a>.</p> <pre><code>#include &lt;cmath&gt; int main() { double x = 6.3; double y = 2.0; double z = std::fmod(x,y); } </code></pre>
{ "question_id": 9138790, "question_date": "2012-02-04T06:02:38.923Z", "question_score": 227, "tags": "c++|modulo", "answer_id": 9138794, "answer_date": "2012-02-04T06:04:16.890Z", "answer_score": 321 }
Please answer the following Stack Overflow question: Title: Choosing the default value of an Enum type without having to change values <p>In C#, is it possible to decorate an Enum type with an attribute or do something else to specify what the default value should be, without having the change the values? The numbers required might be set in stone for whatever reason, and it'd be handy to still have control over the default.</p> <pre><code>enum Orientation { None = -1, North = 0, East = 1, South = 2, West = 3 } Orientation o; // Is 'North' by default. </code></pre>
<p>The default for an <code>enum</code> (in fact, any value type) is 0 -- even if that is not a valid value for that <code>enum</code>. It cannot be changed.</p>
{ "question_id": 529929, "question_date": "2009-02-09T20:59:20.280Z", "question_score": 227, "tags": "c#|.net|enums", "answer_id": 529937, "answer_date": "2009-02-09T21:01:29.027Z", "answer_score": 383 }
Please answer the following Stack Overflow question: Title: Can I read the hash portion of the URL on my server-side application (PHP, Ruby, Python, etc.)? <p>Assuming a URL of:</p> <pre><code>www.example.com/?val=1#part2 </code></pre> <p>PHP can read the request variables <code>val1</code> using the GET array.</p> <p>Is the hash value <code>part2</code> also readable? Or is this only upto the browser and JavaScript?</p>
<p>The main problem is that the browser won't even send a request with a fragment part. The fragment part is resolved right there in the browser. So it's reachable through JavaScript.</p> <p>Anyway, you could parse a URL into bits, including the fragment part, using <a href="http://www.php.net/manual/en/function.parse-url.php" rel="noreferrer">parse_url()</a>, but it's obviously not your case.</p>
{ "question_id": 940905, "question_date": "2009-06-02T17:41:55.897Z", "question_score": 227, "tags": "http|language-agnostic|uri-fragment", "answer_id": 940923, "answer_date": "2009-06-02T17:45:22.600Z", "answer_score": 213 }
Please answer the following Stack Overflow question: Title: Is there a way to 'uniq' by column? <p>I have a .csv file like this:</p> <pre><code>[email protected],2009-11-27 01:05:47.893000000,domain.example,127.0.0.1 [email protected],2009-11-27 00:58:29.793000000,domain2.example,255.255.255.0 [email protected],2009-11-27 00:58:29.646465785,domain2.example,256.255.255.0 ... </code></pre> <p>I have to remove duplicate e-mails (the entire line) from the file (i.e. one of the lines containing <code>[email protected]</code> in the above example). How do I use <code>uniq</code> on only field 1 (separated by commas)? According to <code>man</code>, <code>uniq</code> doesn't have options for columns.</p> <p>I tried something with <code>sort | uniq</code> but it doesn't work.</p>
<pre><code>sort -u -t, -k1,1 file </code></pre> <ul> <li><code>-u</code> for unique</li> <li><code>-t,</code> so comma is the delimiter</li> <li><code>-k1,1</code> for the key field 1</li> </ul> <p>Test result:</p> <pre><code>[email protected],2009-11-27 00:58:29.793000000,xx3.net,255.255.255.0 [email protected],2009-11-27 01:05:47.893000000,xx2.net,127.0.0.1 </code></pre>
{ "question_id": 1915636, "question_date": "2009-12-16T16:03:16.660Z", "question_score": 227, "tags": "linux|shell|sorting|uniq", "answer_id": 1915750, "answer_date": "2009-12-16T16:14:50.927Z", "answer_score": 385 }