input_text
stringlengths 115
13.8k
| output_text
stringlengths 24
15k
| metadata
dict |
---|---|---|
Please answer the following Stack Overflow question:
Title: Call a function after previous function is complete
<p>I have the following JavaScript code:</p>
<pre><code>$('a.button').click(function(){
if (condition == 'true'){
function1(someVariable);
function2(someOtherVariable);
}
else {
doThis(someVariable);
}
});
</code></pre>
<p>How can I ensure that <code>function2</code> is called only after <code>function1</code> has completed?</p> | <p>Specify an anonymous callback, and make function1 accept it:</p>
<pre><code>$('a.button').click(function(){
if (condition == 'true'){
function1(someVariable, function() {
function2(someOtherVariable);
});
}
else {
doThis(someVariable);
}
});
function function1(param, callback) {
...do stuff
callback();
}
</code></pre> | {
"question_id": 5000415,
"question_date": "2011-02-15T06:07:04.143Z",
"question_score": 215,
"tags": "javascript|jquery",
"answer_id": 5000447,
"answer_date": "2011-02-15T06:11:55.020Z",
"answer_score": 242
} |
Please answer the following Stack Overflow question:
Title: Getting all selected checkboxes in an array
<p>So I have these checkboxes:</p>
<pre><code><input type="checkbox" name="type" value="4" />
<input type="checkbox" name="type" value="3" />
<input type="checkbox" name="type" value="1" />
<input type="checkbox" name="type" value="5" />
</code></pre>
<p>And so on. There are about 6 of them and are hand-coded (i.e not fetched from a db) so they are likely to remain the same for a while.</p>
<p>My question is how I can get them all in an array (in javascript), so I can use them while making an AJAX <code>$.post</code> request using Jquery.</p>
<p>Any thoughts?</p>
<p>Edit: I would only want the selected checkboxes to be added to the array</p> | <p>Formatted :</p>
<pre><code>$("input:checkbox[name=type]:checked").each(function(){
yourArray.push($(this).val());
});
</code></pre>
<p>Hopefully, it will work.</p> | {
"question_id": 590018,
"question_date": "2009-02-26T10:45:14.417Z",
"question_score": 215,
"tags": "javascript|jquery|ajax|dhtml",
"answer_id": 590040,
"answer_date": "2009-02-26T10:52:41.420Z",
"answer_score": 399
} |
Please answer the following Stack Overflow question:
Title: Set timeout for ajax (jQuery)
<pre><code>$.ajax({
url: "test.html",
error: function(){
//do something
},
success: function(){
//do something
}
});
</code></pre>
<p>Sometimes <code>success</code> function works good, sometimes not. </p>
<p>How do I set timeout for this ajax request? In example, 3 seconds, if time is out, then show an error. </p>
<p>The problem is, ajax request freezes the block until finishes. If server is down for a little time, it will never end.</p> | <p>Please read the <code>$.ajax</code> <a href="http://api.jquery.com/jQuery.ajax/" rel="noreferrer">documentation</a>, this is a covered topic. </p>
<pre><code>$.ajax({
url: "test.html",
error: function(){
// will fire when timeout is reached
},
success: function(){
//do something
},
timeout: 3000 // sets timeout to 3 seconds
});
</code></pre>
<p>You can get see what type of error was thrown by accessing the textStatus parameter of the <code>error: function(jqXHR, textStatus, errorThrown)</code> option. The options are "timeout", "error", "abort", and "parsererror".</p> | {
"question_id": 5225597,
"question_date": "2011-03-07T21:39:40.443Z",
"question_score": 215,
"tags": "javascript|jquery|html|css|ajax",
"answer_id": 5225641,
"answer_date": "2011-03-07T21:43:38.673Z",
"answer_score": 376
} |
Please answer the following Stack Overflow question:
Title: Find where python is installed (if it isn't default dir)
<p>Python is on my machine, I just don't know where, if I type python in terminal it will open Python 2.6.4, this isn't in it's default directory, there surely is a way of finding it's install location from here?</p> | <p>In unix (mac os X included) terminal you can do </p>
<pre><code>which python
</code></pre>
<p>and it will tell you.</p> | {
"question_id": 6767283,
"question_date": "2011-07-20T19:19:18.753Z",
"question_score": 215,
"tags": "python",
"answer_id": 6767301,
"answer_date": "2011-07-20T19:21:21.033Z",
"answer_score": 185
} |
Please answer the following Stack Overflow question:
Title: Redirect non-www to www in .htaccess
<p>I have this in my .htaccess file:</p>
<pre><code>RewriteCond %{HTTP_HOST} ^example.com$
RewriteRule (.*) http://www.example.com$1 [R=301,L]
</code></pre>
<p>but whenever I access a file on my root like <code>http://example.com/robots.txt</code> it will redirect to <code>http://www.example.comrobots.txt/</code>.</p>
<p>How can I correct this so that it will redirect correctly to <code>http://www.example.com/robots.txt</code>?</p> | <p>Change your configuration to this (add a slash):</p>
<pre><code>RewriteCond %{HTTP_HOST} ^example.com$ [NC]
RewriteRule (.*) http://www.example.com/$1 [R=301,L]
</code></pre>
<p>Or the solution outlined below (proposed by <a href="//stackoverflow.com/questions/12050590/redirect-non-www-to-www-in-htaccess/22299685#22299685">@absiddiqueLive</a>) will work for any domain:</p>
<pre><code>RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
</code></pre>
<p>If you need to support http and https and preserve the protocol choice try the following:</p>
<pre><code>RewriteRule ^login\$ https://www.%{HTTP_HOST}/login [R=301,L]
</code></pre>
<p>Where you replace <code>login</code> with <code>checkout.php</code> or whatever URL you need to support HTTPS on.</p>
<p>I'd argue this is a bad idea though. For the reasoning <a href="https://stackoverflow.com/questions/9105510/force-https-for-specific-url/9105894#9105894">please read this answer</a>.</p> | {
"question_id": 12050590,
"question_date": "2012-08-21T08:04:38.873Z",
"question_score": 215,
"tags": ".htaccess",
"answer_id": 12050652,
"answer_date": "2012-08-21T08:09:31.820Z",
"answer_score": 435
} |
Please answer the following Stack Overflow question:
Title: ASP.NET Core return JSON with status code
<p>I'm looking for the correct way to return JSON with a HTTP status code in my .NET Core Web API controller. I use to use it like this:</p>
<pre><code>public IHttpActionResult GetResourceData()
{
return this.Content(HttpStatusCode.OK, new { response = "Hello"});
}
</code></pre>
<p>This was in a 4.6 MVC application but now with .NET Core I don't seem to have this <code>IHttpActionResult</code> I have <code>ActionResult</code> and using like this:</p>
<pre><code>public ActionResult IsAuthenticated()
{
return Ok(Json("123"));
}
</code></pre>
<p>But the response from the server is weird, as in the image below:</p>
<p><a href="https://i.stack.imgur.com/DpSlo.png" rel="noreferrer"><img src="https://i.stack.imgur.com/DpSlo.png" alt="enter image description here"></a></p>
<p>I just want the Web API controller to return JSON with a HTTP status code like I did in Web API 2.</p> | <p>The most basic version responding with a <code>JsonResult</code> is:</p>
<pre><code>// GET: api/authors
[HttpGet]
public JsonResult Get()
{
return Json(_authorRepository.List());
}
</code></pre>
<p>However, this isn't going to help with your issue because you can't explicitly deal with your own response code.</p>
<blockquote>
<p>The way to get control over the status results, is you need to return a <code>ActionResult</code> which is where you can then take advantage of the <code>StatusCodeResult</code> type.</p>
</blockquote>
<p>for example:</p>
<pre><code>// GET: api/authors/search?namelike=foo
[HttpGet("Search")]
public IActionResult Search(string namelike)
{
var result = _authorRepository.GetByNameSubstring(namelike);
if (!result.Any())
{
return NotFound(namelike);
}
return Ok(result);
}
</code></pre>
<p>Note both of these above examples came from a great guide available from Microsoft Documentation: <a href="https://docs.microsoft.com/en-us/aspnet/core/mvc/models/formatting" rel="noreferrer">Formatting Response Data</a></p>
<hr>
<h2>Extra Stuff</h2>
<p>The issue I come across quite often is that I wanted more granular control over my WebAPI rather than just go with the defaults configuration from the "New Project" template in VS.</p>
<p>Let's make sure you have some of the basics down...</p>
<h2>Step 1: Configure your Service</h2>
<p>In order to get your ASP.NET Core WebAPI to respond with a JSON Serialized Object along full control of the status code, you should start off by making sure that you have included the <code>AddMvc()</code> service in your <code>ConfigureServices</code> method usually found in <code>Startup.cs</code>.</p>
<blockquote>
<p>It's important to note that<code>AddMvc()</code> will automatically include the Input/Output Formatter for JSON along with responding to other request types.</p>
</blockquote>
<p>If your project requires <strong>full control</strong> and you want to strictly define your services, such as how your WebAPI will behave to various request types including <code>application/json</code> and not respond to other request types (such as a standard browser request), you can define it manually with the following code:</p>
<pre><code>public void ConfigureServices(IServiceCollection services)
{
// Build a customized MVC implementation, without using the default AddMvc(), instead use AddMvcCore().
// https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNetCore.Mvc/MvcServiceCollectionExtensions.cs
services
.AddMvcCore(options =>
{
options.RequireHttpsPermanent = true; // does not affect api requests
options.RespectBrowserAcceptHeader = true; // false by default
//options.OutputFormatters.RemoveType<HttpNoContentOutputFormatter>();
//remove these two below, but added so you know where to place them...
options.OutputFormatters.Add(new YourCustomOutputFormatter());
options.InputFormatters.Add(new YourCustomInputFormatter());
})
//.AddApiExplorer()
//.AddAuthorization()
.AddFormatterMappings()
//.AddCacheTagHelper()
//.AddDataAnnotations()
//.AddCors()
.AddJsonFormatters(); // JSON, or you can build your own custom one (above)
}
</code></pre>
<p>You will notice that I have also included a way for you to add your own custom Input/Output formatters, in the event you may want to respond to another serialization format (protobuf, thrift, etc).</p>
<p>The chunk of code above is mostly a duplicate of the <code>AddMvc()</code> method. However, we are implementing each "default" service on our own by defining each and every service instead of going with the pre-shipped one with the template. I have added the repository link in the code block, or you can check out <code>AddMvc()</code> <a href="https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNetCore.Mvc/MvcServiceCollectionExtensions.cs" rel="noreferrer">from the GitHub repository.</a>.</p>
<p><em>Note that there are some guides that will try to solve this by "undoing" the defaults, rather than just not implementing it in the first place... If you factor in that we're now working with Open Source, this is redundant work, bad code and frankly an old habit that will disappear soon.</em></p>
<hr>
<h2>Step 2: Create a Controller</h2>
<p>I'm going to show you a really straight-forward one just to get your question sorted.</p>
<pre><code>public class FooController
{
[HttpPost]
public async Task<IActionResult> Create([FromBody] Object item)
{
if (item == null) return BadRequest();
var newItem = new Object(); // create the object to return
if (newItem != null) return Ok(newItem);
else return NotFound();
}
}
</code></pre>
<hr>
<h2>Step 3: Check your <code>Content-Type</code> and <code>Accept</code></h2>
<p>You need to make sure that your <code>Content-Type</code> and <code>Accept</code> headers in your <strong>request</strong> are set properly. In your case (JSON), you will want to set it up to be <code>application/json</code>.</p>
<p>If you want your WebAPI to respond as JSON as default, regardless of what the request header is specifying you can do that in a <strong>couple ways</strong>.</p>
<p><strong>Way 1</strong>
As shown in the article I recommended earlier (<a href="https://docs.microsoft.com/en-us/aspnet/core/mvc/models/formatting" rel="noreferrer">Formatting Response Data</a>) you could force a particular format at the Controller/Action level. I personally don't like this approach... but here it is for completeness:</p>
<blockquote>
<p><strong>Forcing a Particular Format</strong> If you would like to restrict the response formats for a specific action you can, you can apply the
[Produces] filter. The [Produces] filter specifies the response
formats for a specific action (or controller). Like most Filters, this
can be applied at the action, controller, or global scope.</p>
<pre><code>[Produces("application/json")]
public class AuthorsController
</code></pre>
<p>The <code>[Produces]</code> filter will force all actions within the
<code>AuthorsController</code> to return JSON-formatted responses, even if other
formatters were configured for the application and the client provided
an <code>Accept</code> header requesting a different, available format.</p>
</blockquote>
<p><strong>Way 2</strong>
My preferred method is for the WebAPI to respond to all requests with the format requested. However, in the event that it doesn't accept the requested format, then <strong>fall-back</strong> to a default (ie. JSON)</p>
<p>First, you'll need to register that in your options (we need to rework the default behavior, as noted earlier)</p>
<pre><code>options.RespectBrowserAcceptHeader = true; // false by default
</code></pre>
<p>Finally, by simply re-ordering the list of the formatters that were defined in the services builder, the web host will default to the formatter you position at the top of the list (ie position 0).</p>
<p>More information can be found in this <a href="https://blogs.msdn.microsoft.com/webdev/2014/11/24/content-negotiation-in-mvc-6-or-how-can-i-just-write-json/" rel="noreferrer">.NET Web Development and Tools Blog entry</a></p> | {
"question_id": 42360139,
"question_date": "2017-02-21T06:26:47.933Z",
"question_score": 215,
"tags": "c#|json|asp.net-core|asp.net-core-webapi",
"answer_id": 42360418,
"answer_date": "2017-02-21T06:43:58.357Z",
"answer_score": 253
} |
Please answer the following Stack Overflow question:
Title: How do I render a Word document (.doc, .docx) in the browser using JavaScript?
<p>I have successfully done code to display a PDF file in the browser instead of the "Open/Save" dialog. Now, I'm stuck trying to display a Word document in the browser. I want to display a Word document in Firefox, IE7+, Chrome etc.</p>
<p>Can any one help? I am always getting the "Open/Save" dialog while displaying the Word doc in browser. I want to implement this functionality using JavaScript.</p> | <p>No browsers currently have the code necessary to render Word Documents, and as far as I know, there are no client-side libraries that currently exist for rendering them either.</p>
<p>However, if you only need to display the Word Document, but don't need to edit it, you can use Google Documents' Viewer via an <code><iframe></code> to display a remotely hosted <code>.doc</code>/<code>.docx</code>.</p>
<pre><code><iframe src="https://docs.google.com/gview?url=http://remote.url.tld/path/to/document.doc&embedded=true"></iframe>
</code></pre>
<p>Solution adapted from "<a href="https://stackoverflow.com/questions/9418850/how-to-display-a-word-document-using-fancybox">How to display a word document using fancybox</a>".</p>
<p>Example:</p>
<p><a href="http://jsfiddle.net/kbu2gsfm/" rel="noreferrer">JSFiddle</a></p>
<p>However, if you'd rather have native support, in most, if not all browsers, I'd recommend resaving the <code>.doc</code>/<code>.docx</code> as a PDF file Those can also be independently rendered using <a href="https://mozilla.github.io/pdf.js/" rel="noreferrer">PDF.js</a> by Mozilla.</p>
<p><strong>Edit:</strong></p>
<p>Huge thanks to <a href="https://stackoverflow.com/users/2281835/cubeguerrero">cubeguerrero</a> for posting the Microsoft Office 365 viewer in the comments.</p>
<pre><code><iframe src='https://view.officeapps.live.com/op/embed.aspx?src=http://remote.url.tld/path/to/document.doc' width='1366px' height='623px' frameborder='0'>This is an embedded <a target='_blank' href='http://office.com'>Microsoft Office</a> document, powered by <a target='_blank' href='http://office.com/webapps'>Office Online</a>.</iframe>
</code></pre>
<p>One more important caveat to keep in mind, as pointed out by <a href="https://stackoverflow.com/users/912563/lightswitch05">lightswitch05</a>, is that this will upload your document to a third-party server. If this is unacceptable, then this method of display isn't the proper course of action.</p>
<p><strong>Live Examples:</strong></p>
<p><a href="https://jsfiddle.net/7xr419yb/embedded/result/" rel="noreferrer">Google Docs Viewer</a></p>
<p><a href="https://jsfiddle.net/gcuzq343/embedded/result/" rel="noreferrer">Microsoft Office Viewer</a></p> | {
"question_id": 27957766,
"question_date": "2015-01-15T06:18:03.760Z",
"question_score": 215,
"tags": "javascript|browser|ms-word",
"answer_id": 27958186,
"answer_date": "2015-01-15T06:56:58.417Z",
"answer_score": 318
} |
Please answer the following Stack Overflow question:
Title: How to set the java.library.path from Eclipse
<p>How can I set the <code>java.library.path</code> for a whole Eclipse Project? I'm using a Java library that relies on OS specific files and need to find a <code>.dll/</code> <code>.so/</code> <code>.jnilib</code>. But the Application always exits with an error message that those files are not found on the library path. </p>
<p>I would like to configure this whole project to use the library path. I tried to add the path as a VM argument to some run configurations in eclipse but that didn't work.</p> | <p>Don't mess with the library path! Eclipse builds it itself!</p>
<p>Instead, go into the library settings for your projects and, for each jar/etc that requires a native library, expand it in the <em>Libraries</em> tab. In the tree view there, each library has items for source/javadoc and native library locations.</p>
<p>Specifically: select <code>Project</code>, right click -> <em>Properties</em> / <em>Java Build Path</em> / <em>Libraries</em> tab, select a .jar, expand it, select <em>Native library location</em>, click <em>Edit</em>, folder chooser dialog will appear)</p>
<p>Messing with the library path on the command line should be your last ditch effort, because you might break something that is already properly set by eclipse.</p>
<p><img src="https://i.stack.imgur.com/zeFNt.png" alt="Native library location"></p> | {
"question_id": 957700,
"question_date": "2009-06-05T19:27:59.990Z",
"question_score": 215,
"tags": "java|eclipse|configuration|buildpath",
"answer_id": 958074,
"answer_date": "2009-06-05T20:50:06.017Z",
"answer_score": 299
} |
Please answer the following Stack Overflow question:
Title: How to subtract date/time in JavaScript?
<p>I have a field at a grid containing date/time and I need to know the difference between that and the current date/time. What could be the best way of doing so?</p>
<p>The dates are stored like <code>"2011-02-07 15:13:06"</code>.</p> | <p>This will give you the difference between two dates, in milliseconds</p>
<pre><code>var diff = Math.abs(date1 - date2);
</code></pre>
<p>In your example, it'd be</p>
<pre><code>var diff = Math.abs(new Date() - compareDate);
</code></pre>
<p>You need to make sure that <code>compareDate</code> is a valid <code>Date</code> object.</p>
<p>Something like this will probably work for you</p>
<pre><code>var diff = Math.abs(new Date() - new Date(dateStr.replace(/-/g,'/')));
</code></pre>
<p>i.e. turning <code>"2011-02-07 15:13:06"</code> into <code>new Date('2011/02/07 15:13:06')</code>, which is a format the <code>Date</code> constructor can comprehend.</p> | {
"question_id": 4944750,
"question_date": "2011-02-09T12:20:26.167Z",
"question_score": 215,
"tags": "javascript|date",
"answer_id": 4944782,
"answer_date": "2011-02-09T12:23:59.680Z",
"answer_score": 265
} |
Please answer the following Stack Overflow question:
Title: How to prevent form resubmission when page is refreshed (F5 / CTRL+R)
<p>I have a simple form that submits text to my SQL table. The problem is that after the user submits the text, they can refresh the page and the data gets submitted again without filling the form again. I could redirect the user to another page after the text is submitted, but I want users to stay on the same page.</p>
<p>I remember reading something about giving each user a unique session id and comparing it with another value which solved the problem I am having but I forgot where it is.</p> | <p>Use the Post/Redirect/Get pattern. <a href="http://en.wikipedia.org/wiki/Post/Redirect/Get" rel="noreferrer">http://en.wikipedia.org/wiki/Post/Redirect/Get</a></p>
<p>With my website, I will store a message in a cookie or session, redirect after the post, read the cookie/session, and then clear the value of that session or cookie variable.</p> | {
"question_id": 6320113,
"question_date": "2011-06-12T04:24:44.313Z",
"question_score": 215,
"tags": "php|html|forms|post|form-submit",
"answer_id": 6320124,
"answer_date": "2011-06-12T04:26:55.640Z",
"answer_score": 123
} |
Please answer the following Stack Overflow question:
Title: How can I group time by hour or by 10 minutes?
<p>Like when I do</p>
<pre class="lang-sql prettyprint-override"><code>SELECT [Date]
FROM [FRIIB].[dbo].[ArchiveAnalog]
GROUP BY [Date]
</code></pre>
<p>How can I specify the group period? I'm using MS SQL 2008.</p>
<p>I've tried this, both with <code>% 10</code> and <code>/ 10</code>.</p>
<pre class="lang-sql prettyprint-override"><code>SELECT MIN([Date]) AS RecT, AVG(Value)
FROM [FRIIB].[dbo].[ArchiveAnalog]
GROUP BY (DATEPART(MINUTE, [Date]) / 10)
ORDER BY RecT
</code></pre>
<p>Is it possible to make Date output without milliseconds?</p> | <p>finally done with</p>
<pre><code>GROUP BY
DATEPART(YEAR, DT.[Date]),
DATEPART(MONTH, DT.[Date]),
DATEPART(DAY, DT.[Date]),
DATEPART(HOUR, DT.[Date]),
(DATEPART(MINUTE, DT.[Date]) / 10)
</code></pre> | {
"question_id": 5002661,
"question_date": "2011-02-15T10:45:45.510Z",
"question_score": 215,
"tags": "sql|sql-server-2008|tsql|group-by",
"answer_id": 5101424,
"answer_date": "2011-02-24T07:00:52.990Z",
"answer_score": 259
} |
Please answer the following Stack Overflow question:
Title: Extracting specific columns in numpy array
<p>This is an easy question but say I have an MxN matrix. All I want to do is extract specific columns and store them in another numpy array but I get invalid syntax errors.
Here is the code:</p>
<pre><code>extractedData = data[[:,1],[:,9]].
</code></pre>
<p>It seems like the above line should suffice but I guess not. I looked around but couldn't find anything syntax wise regarding this specific scenario.</p> | <p>I assume you wanted columns <code>1</code> and <code>9</code>?</p>
<p>To select multiple columns at once, use</p>
<pre><code>X = data[:, [1, 9]]
</code></pre>
<p>To select one at a time, use</p>
<pre><code>x, y = data[:, 1], data[:, 9]
</code></pre>
<hr />
<p>With names:</p>
<pre><code>data[:, ['Column Name1','Column Name2']]
</code></pre>
<p>You can get the names from <code>data.dtype.names</code>…</p> | {
"question_id": 8386675,
"question_date": "2011-12-05T14:20:47.500Z",
"question_score": 215,
"tags": "python|syntax|numpy",
"answer_id": 8386737,
"answer_date": "2011-12-05T14:24:54.313Z",
"answer_score": 358
} |
Please answer the following Stack Overflow question:
Title: Iterating through directories with Python
<p>I need to iterate through the subdirectories of a given directory and search for files. If I get a file I have to open it and change the content and replace it with my own lines.</p>
<p>I tried this:</p>
<pre><code>import os
rootdir ='C:/Users/sid/Desktop/test'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
f=open(file,'r')
lines=f.readlines()
f.close()
f=open(file,'w')
for line in lines:
newline = "No you are not"
f.write(newline)
f.close()
</code></pre>
<p>but I am getting an error. What am I doing wrong? </p> | <p>The actual walk through the directories works as you have coded it. If you replace the contents of the inner loop with a simple <code>print</code> statement you can see that each file is found:</p>
<pre><code>import os
rootdir = 'C:/Users/sid/Desktop/test'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
print(os.path.join(subdir, file))
</code></pre>
<hr />
<p>If you still get errors when running the above, please provide the error message.</p> | {
"question_id": 19587118,
"question_date": "2013-10-25T10:17:39.740Z",
"question_score": 215,
"tags": "python|directory",
"answer_id": 19587581,
"answer_date": "2013-10-25T10:39:02.057Z",
"answer_score": 407
} |
Please answer the following Stack Overflow question:
Title: How to remove duplicate values from an array in PHP
<p>How can I remove duplicate values from an array in PHP?</p> | <p>Use <a href="http://php.net/array_unique" rel="noreferrer">array_unique()</a>.</p>
<p>Example:</p>
<pre><code>$array = array(1, 2, 2, 3);
$array = array_unique($array); // Array is now (1, 2, 3)
</code></pre> | {
"question_id": 307650,
"question_date": "2008-11-21T02:37:15.243Z",
"question_score": 215,
"tags": "php|arrays|duplicate-data",
"answer_id": 307655,
"answer_date": "2008-11-21T02:39:33.040Z",
"answer_score": 347
} |
Please answer the following Stack Overflow question:
Title: Pylint "unresolved import" error in Visual Studio Code
<p>I am using the following setup</p>
<ul>
<li><a href="https://en.wikipedia.org/wiki/MacOS_Mojave" rel="noreferrer">macOS v10.14</a> (Mojave)</li>
<li>Python 3.7.1</li>
<li>Visual Studio Code 1.30</li>
<li>Pylint 2.2.2</li>
<li>Django 2.1.4</li>
</ul>
<p>I want to use linting to make my life a bit easier in Visual Studio Code. However, for every import I have states "unresolved import". Even on default Django imports (i.e. from django.db import models).</p>
<p>I presume it is because it is not seeing the virtual environment Python files.</p>
<p>Everything works just fine, but it's starting to get annoying.</p>
<p>The interpreter choices I have are all system versions of Python. It does not seem to see my virtual environment Python at all (it is not in the same directory as my workspace, so that part makes sense).</p>
<p>If I set up the <em>python.PythonPath</em> in the <em>settings.json</em> file, it just ignores it and does not list my virtual environment path as an option. I also tried setting it up in my global Python settings, but it also does not show up.</p>
<p>Is there a quick fix to get it working?</p> | <p>In your <a href="https://code.visualstudio.com/docs/getstarted/settings#_settings-file-locations" rel="noreferrer">workspace settings</a>, you can set your Python path like this:</p>
<pre><code>{
"python.defaultInterpreterPath": "/path/to/your/venv/bin/python",
}
</code></pre> | {
"question_id": 53939751,
"question_date": "2018-12-27T04:27:50.630Z",
"question_score": 215,
"tags": "python|django|visual-studio-code|pylint",
"answer_id": 53940610,
"answer_date": "2018-12-27T06:21:08.863Z",
"answer_score": 168
} |
Please answer the following Stack Overflow question:
Title: Custom circle button
<p>I want to create custom button and I need it to be circle. How can I create a circle button?
I do not think that be possible with draw9patch.</p>
<p>Also I do not know how to make custom button!</p>
<p>Do you have any suggestion?</p> | <p>Use xml drawable like this:</p>
<p>Save the following contents as <code>round_button.xml</code> in <code>drawable</code> folder</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false">
<shape android:shape="oval">
<solid android:color="#fa09ad"/>
</shape>
</item>
<item android:state_pressed="true">
<shape android:shape="oval">
<solid android:color="#c20586"/>
</shape>
</item>
</selector>
</code></pre>
<p><strong>Android Material Effect:</strong> Although <a href="https://developer.android.com/intl/ko/reference/android/support/design/widget/FloatingActionButton.html" rel="noreferrer"><code>FloatingActionButton</code></a> is a better option, If you want to do it using xml selector, create a folder <code>drawable-v21</code> in <code>res</code> and save another <code>round_button.xml</code> there with following xml</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="#c20586">
<item>
<shape android:shape="oval">
<solid android:color="#fa09ad"/>
</shape>
</item>
</ripple>
</code></pre>
<p>And set it as background of <code>Button</code> in xml like this:</p>
<pre><code><Button
android:layout_width="50dp"
android:layout_height="50dp"
android:background="@drawable/round_button"
android:gravity="center_vertical|center_horizontal"
android:text="hello"
android:textColor="#fff" />
</code></pre>
<p><strong>Important:</strong></p>
<ol>
<li>If you want it to show all these states (enabled, disabled, highlighted etc), you will use selector as <a href="https://stackoverflow.com/a/1726352/593709">described here</a>.</li>
<li>You've to keep both files in order to make the drawable backward-compatible. Otherwise, you'll face weird exceptions in previous android version.</li>
</ol> | {
"question_id": 9884202,
"question_date": "2012-03-27T06:11:35.243Z",
"question_score": 215,
"tags": "android|android-button",
"answer_id": 9884428,
"answer_date": "2012-03-27T06:32:11.780Z",
"answer_score": 372
} |
Please answer the following Stack Overflow question:
Title: Xcode - ld: library not found for -lPods
<p>I get these errors when I try to build an iOS application.</p>
<pre><code>ld: library not found for -lPods
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Ld /Users/Markus/Library/Developer/Xcode/DerivedData/Totalbox-clpeqwpfvwuhpleeejnzlavncnvj/Build/Products/Debug-iphonesimulator/Totalbox.app/Totalbox normal x86_64
cd /Users/Markus/Development/xcode/totalbox-ios
export IPHONEOS_DEPLOYMENT_TARGET=7.1
export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -arch x86_64 -isysroot
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator7.1.sdk -L/Users/Markus/Library/Developer/Xcode/DerivedData/Totalbox-clpeqwpfvwuhpleeejnzlavncnvj/Build/Products/Debug-iphonesimulator -F/Users/Markus/Library/Developer/Xcode/DerivedData/Totalbox-clpeqwpfvwuhpleeejnzlavncnvj/Build/Products/Debug-iphonesimulator -filelist /Users/Markus/Library/Developer/Xcode/DerivedData/Totalbox-clpeqwpfvwuhpleeejnzlavncnvj/Build/Intermediates/Totalbox.build/Debug-iphonesimulator/Totalbox.build/Objects-normal/x86_64/Totalbox.LinkFileList -Xlinker -objc_abi_version -Xlinker 2 -ObjC -framework CoreGraphics -framework Foundation -framework MobileCoreServices -framework QuartzCore -framework Security -framework SystemConfiguration -fobjc-arc -fobjc-link-runtime -Xlinker -no_implicit_dylibs -mios-simulator-version-min=7.1 -framework CoreGraphics -framework UIKit -framework Foundation -lPods -Xlinker -dependency_info -Xlinker /Users/Markus/Library/Developer/Xcode/DerivedData/Totalbox-clpeqwpfvwuhpleeejnzlavncnvj/Build/Intermediates/Totalbox.build/Debug-iphonesimulator/Totalbox.build/Objects-normal/x86_64/Totalbox_dependency_info.dat -o /Users/Markus/Library/Developer/Xcode/DerivedData/Totalbox-clpeqwpfvwuhpleeejnzlavncnvj/Build/Products/Debug-iphonesimulator/Totalbox.app/Totalbox
</code></pre>
<p>PODS ROOT in the build settings:</p>
<pre><code>${SRCROOT}/Pods
</code></pre>
<p>I didn't create this Xcode project - just pulled it from git to check it out.</p> | <p>If the project uses CocoaPods be aware to always open the <code>.xcworkspace</code> file instead of the <code>.xcodeproj</code> file.</p> | {
"question_id": 23539147,
"question_date": "2014-05-08T10:27:33.583Z",
"question_score": 215,
"tags": "ios|objective-c|xcode|clang|cocoapods",
"answer_id": 28111728,
"answer_date": "2015-01-23T14:08:34.740Z",
"answer_score": 656
} |
Please answer the following Stack Overflow question:
Title: Combine :after with :hover
<p>I want to combine <code>:after</code> with <code>:hover</code> in CSS (or any other pseudo selector). I basically have a list and the item with the <code>selected</code> class has an arrow shape applied using <code>:after</code>. I want the same to be true for objects that are being hovered over but cant quite get it to work. Heres the code</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>#alertlist {
list-style: none;
width: 250px;
}
#alertlist li {
padding: 5px 10px;
border-bottom: 1px solid #e9e9e9;
position: relative;
}
#alertlist li.selected,
#alertlist li:hover {
color: #f0f0f0;
background-color: #303030;
}
#alertlist li.selected:after {
position: absolute;
top: 0;
right: -10px;
bottom: 0;
border-top: 10px solid transparent;
border-bottom: 10px solid transparent;
border-left: 10px solid #303030;
content: "";
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="alertlist">
<li>Alert 123</li>
<li class="selected">Alert 123</li>
<li>Alert 123</li>
</ul></code></pre>
</div>
</div>
</p> | <p>Just append <code>:after</code> to your <code>#alertlist li:hover</code> selector the same way you do with your <code>#alertlist li.selected</code> selector:</p>
<pre><code>#alertlist li.selected:after, #alertlist li:hover:after
{
position:absolute;
top: 0;
right:-10px;
bottom:0;
border-top: 10px solid transparent;
border-bottom: 10px solid transparent;
border-left: 10px solid #303030;
content: "";
}
</code></pre> | {
"question_id": 13233991,
"question_date": "2012-11-05T14:20:29.230Z",
"question_score": 215,
"tags": "css|css-selectors|pseudo-element",
"answer_id": 13234028,
"answer_date": "2012-11-05T14:22:27.987Z",
"answer_score": 285
} |
Please answer the following Stack Overflow question:
Title: node.js: read a text file into an array. (Each line an item in the array.)
<p>I would like to read a very, very large file into a JavaScript array in node.js.</p>
<p>So, if the file is like this:</p>
<pre><code>first line
two
three
...
...
</code></pre>
<p>I would have the array: </p>
<pre><code>['first line','two','three', ... , ... ]
</code></pre>
<p>The function would look like this:</p>
<pre><code>var array = load(filename);
</code></pre>
<p>Therefore the idea of loading it all as a string and then splitting it is not acceptable.</p> | <p>If you can fit the final data into an array then wouldn't you also be able to fit it in a string and split it, as has been suggested?
In any case if you would like to process the file one line at a time you can also try something like this:</p>
<pre><code>var fs = require('fs');
function readLines(input, func) {
var remaining = '';
input.on('data', function(data) {
remaining += data;
var index = remaining.indexOf('\n');
while (index > -1) {
var line = remaining.substring(0, index);
remaining = remaining.substring(index + 1);
func(line);
index = remaining.indexOf('\n');
}
});
input.on('end', function() {
if (remaining.length > 0) {
func(remaining);
}
});
}
function func(data) {
console.log('Line: ' + data);
}
var input = fs.createReadStream('lines.txt');
readLines(input, func);
</code></pre>
<p><strong>EDIT:</strong> (in response to comment by <em>phopkins</em>) I think (at least in newer versions) substring does not copy data but creates a special SlicedString object (from a quick glance at the v8 source code). In any case here is a modification that avoids the mentioned substring (tested on a file several megabytes worth of "All work and no play makes Jack a dull boy"):</p>
<pre><code>function readLines(input, func) {
var remaining = '';
input.on('data', function(data) {
remaining += data;
var index = remaining.indexOf('\n');
var last = 0;
while (index > -1) {
var line = remaining.substring(last, index);
last = index + 1;
func(line);
index = remaining.indexOf('\n', last);
}
remaining = remaining.substring(last);
});
input.on('end', function() {
if (remaining.length > 0) {
func(remaining);
}
});
}
</code></pre> | {
"question_id": 6831918,
"question_date": "2011-07-26T14:48:17.830Z",
"question_score": 215,
"tags": "javascript|node.js",
"answer_id": 6833016,
"answer_date": "2011-07-26T16:00:17.340Z",
"answer_score": 91
} |
Please answer the following Stack Overflow question:
Title: How to provide user name and password when connecting to a network share
<p>When connecting to a network share for which the current user (in my case, a network enabled service user) has no rights, name and password have to be provided.</p>
<p>I know how to do this with Win32 functions (the <code>WNet*</code> family from <code>mpr.dll</code>), but would like to do it with .Net (2.0) functionality.</p>
<p>What options are available?</p>
<p><strong>Maybe some more information helps:</strong></p>
<ul>
<li>The use case is a windows service, not an Asp.Net application.</li>
<li>The service is running under an account which has no rights on the share.</li>
<li>The user account needed for the share is not known on the client side.</li>
<li>Client and server are not members of the same domain.</li>
</ul> | <p>You can either change the thread identity, or P/Invoke WNetAddConnection2. I prefer the latter, as I sometimes need to maintain multiple credentials for different locations. I wrap it into an IDisposable and call WNetCancelConnection2 to remove the creds afterwards (avoiding the multiple usernames error):</p>
<pre><code>using (new NetworkConnection(@"\\server\read", readCredentials))
using (new NetworkConnection(@"\\server2\write", writeCredentials)) {
File.Copy(@"\\server\read\file", @"\\server2\write\file");
}
</code></pre> | {
"question_id": 295538,
"question_date": "2008-11-17T13:07:44.333Z",
"question_score": 215,
"tags": "c#|.net|winapi|networking|passwords",
"answer_id": 295703,
"answer_date": "2008-11-17T14:39:18.517Z",
"answer_score": 162
} |
Please answer the following Stack Overflow question:
Title: What is class="mb-0" in Bootstrap 4?
<p>The <a href="https://v4-alpha.getbootstrap.com/content/typography/#blockquotes" rel="nofollow noreferrer">latest documention</a> has:</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-html lang-html prettyprint-override"><code><p class="mb-0">Lorem ipsum</p></code></pre>
</div>
</div>
</p>
<p>What is <code>mb-0</code>?</p> | <p>Bootstrap has a wide range of responsive margin and padding utility classes. They work for all breakpoints: </p>
<p><strong>xs</strong> (<=576px), <strong>sm</strong> (>=576px), <strong>md</strong> (>=768px), <strong>lg</strong> (>=992px) or <strong>xl</strong> (>=1200px))</p>
<p>The classes are used in the format: </p>
<p><strong>{property}{sides}-{size}</strong> for xs & <strong>{property}{sides}-{breakpoint}-{size}</strong> for sm, md, lg, and xl.</p>
<p><strong>m</strong> - sets margin</p>
<p><strong>p</strong> - sets padding</p>
<hr>
<p><strong>t</strong> - sets margin-top or padding-top</p>
<p><strong>b</strong> - sets margin-bottom or padding-bottom</p>
<p><strong>l</strong> - sets margin-left or padding-left</p>
<p><strong>r</strong> - sets margin-right or padding-right</p>
<p><strong>x</strong> - sets both padding-left and padding-right or margin-left and margin-right</p>
<p><strong>y</strong> - sets both padding-top and padding-bottom or margin-top and margin-bottom</p>
<p><strong>blank</strong> - sets a margin or padding on all 4 sides of the element</p>
<hr>
<p><strong>0</strong> - sets <strong>margin</strong> or <strong>padding</strong> to 0</p>
<p><strong>1</strong> - sets <strong>margin</strong> or <strong>padding</strong> to .25rem (4px if font-size is 16px)</p>
<p><strong>2</strong> - sets <strong>margin</strong> or <strong>padding</strong> to .5rem (8px if font-size is 16px)</p>
<p><strong>3</strong> - sets <strong>margin</strong> or <strong>padding</strong> to 1rem (16px if font-size is 16px)</p>
<p><strong>4</strong> - sets <strong>margin</strong> or <strong>padding</strong> to 1.5rem (24px if font-size is 16px)</p>
<p><strong>5</strong> - sets <strong>margin</strong> or <strong>padding</strong> to 3rem (48px if font-size is 16px)</p>
<p><strong>auto</strong> - sets margin to auto</p>
<p>See more at <a href="https://getbootstrap.com/docs/4.5/utilities/spacing/" rel="noreferrer">Bootstrap 4.5 - Spacing</a></p>
<p><a href="https://www.w3schools.com/bootstrap4/bootstrap_utilities.asp" rel="noreferrer">Read more in w3schools</a></p> | {
"question_id": 41574776,
"question_date": "2017-01-10T17:28:37.187Z",
"question_score": 215,
"tags": "css|twitter-bootstrap|bootstrap-4",
"answer_id": 50250902,
"answer_date": "2018-05-09T10:17:15.413Z",
"answer_score": 390
} |
Please answer the following Stack Overflow question:
Title: GoTo Next Iteration in For Loop in java
<p>Is there a token in java that skips the rest of the for loop?
Something like <a href="http://msdn.microsoft.com/en-us/library/801hyx6f.aspx">VB's Continue</a> in java.</p> | <pre><code>continue;
</code></pre>
<p><code>continue;</code> key word would start the next iteration upon invocation </p>
<p><strong>For Example</strong></p>
<pre><code>for(int i= 0 ; i < 5; i++){
if(i==2){
continue;
}
System.out.print(i);
}
</code></pre>
<p>This will print</p>
<pre><code>0134
</code></pre>
<hr>
<p><strong>See</strong></p>
<ul>
<li><a href="http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html" rel="noreferrer">Document</a></li>
</ul> | {
"question_id": 11160952,
"question_date": "2012-06-22T17:09:27.927Z",
"question_score": 215,
"tags": "java|for-loop",
"answer_id": 11160969,
"answer_date": "2012-06-22T17:10:16.560Z",
"answer_score": 404
} |
Please answer the following Stack Overflow question:
Title: How to create and use resources in .NET
<p>How do I create a resource that I can reference and use in various parts of my program easily?</p>
<p>My specific problem is that I have a NotifyIcon that I want to change the icon of depending on the state of the program. A common problem, but one I've been struggling with for a long time. </p> | <p>Well, after searching around and cobbling together various points from around StackOverflow (gee, I love this place already), most of the problems were already past this stage. I did manage to work out an answer to my problem though.</p>
<p><strong>How to create a resource:</strong></p>
<p>In my case, I want to create an icon. It's a similar process, no matter what type of data you want to add as a resource though.</p>
<ul>
<li>Right click the project you want to add a resource to. Do this in the Solution Explorer. Select the "Properties" option from the list.</li>
<li>Click the "Resources" tab.</li>
<li>The first button along the top of the bar will let you select the type of resource you want to add. It should start on string. We want to add an icon, so click on it and select "Icons" from the list of options.</li>
<li>Next, move to the second button, "Add Resource". You can either add a new resource, or if you already have an icon already made, you can add that too. Follow the prompts for whichever option you choose.</li>
<li>At this point, you can double click the newly added resource to edit it. Note, resources also show up in the Solution Explorer, and double clicking there is just as effective.</li>
</ul>
<p><strong>How to use a resource:</strong></p>
<p>Great, so we have our new resource and we're itching to have those lovely changing icons... How do we do that? Well, lucky us, C# makes this exceedingly easy.</p>
<p>There is a static class called <code>Properties.Resources</code> that gives you access to all your resources, so my code ended up being as simple as:</p>
<pre><code>paused = !paused;
if (paused)
notifyIcon.Icon = Properties.Resources.RedIcon;
else
notifyIcon.Icon = Properties.Resources.GreenIcon;
</code></pre>
<p>Done! Finished! Everything is simple when you know how, isn't it?</p> | {
"question_id": 90697,
"question_date": "2008-09-18T07:21:24.407Z",
"question_score": 215,
"tags": "c#|visual-studio|resources|icons",
"answer_id": 90699,
"answer_date": "2008-09-18T07:21:43.547Z",
"answer_score": 355
} |
Please answer the following Stack Overflow question:
Title: How to insert element into arrays at specific position?
<p>Let's imagine that we have two arrays:</p>
<pre><code>$array_1 = array(
'0' => 'zero',
'1' => 'one',
'2' => 'two',
'3' => 'three',
);
$array_2 = array(
'zero' => '0',
'one' => '1',
'two' => '2',
'three' => '3',
);
</code></pre>
<p>Now, I'd like to insert <code>array('sample_key' => 'sample_value')</code> after third element of each array. How can I do it?</p> | <p><a href="http://php.net/array_slice" rel="noreferrer"><code>array_slice()</code></a> can be used to extract parts of the array, and the union <a href="http://php.net/manual/en/language.operators.array.php" rel="noreferrer">array operator (<code>+</code>)</a> can recombine the parts.</p>
<pre><code>$res = array_slice($array, 0, 3, true) +
array("my_key" => "my_value") +
array_slice($array, 3, count($array)-3, true);
</code></pre>
<p>This example:</p>
<pre><code>$array = array(
'zero' => '0',
'one' => '1',
'two' => '2',
'three' => '3',
);
$res = array_slice($array, 0, 3, true) +
array("my_key" => "my_value") +
array_slice($array, 3, count($array) - 1, true) ;
print_r($res);
</code></pre>
<p>gives:</p>
<pre>
Array
(
[zero] => 0
[one] => 1
[two] => 2
[my_key] => my_value
[three] => 3
)
</pre> | {
"question_id": 3353745,
"question_date": "2010-07-28T14:15:28.980Z",
"question_score": 215,
"tags": "php|arrays",
"answer_id": 3354804,
"answer_date": "2010-07-28T15:58:20.107Z",
"answer_score": 245
} |
Please answer the following Stack Overflow question:
Title: configure Git to accept a particular self-signed server certificate for a particular https remote
<p>The sysadmin for a project I'm on has decided that SSH is "too much trouble"; instead, he has set up Git to be accessible via an <code>https://</code> URL (and username/password authentication). The server for this URL presents a self-signed certificate, so he advised everyone to turn off certificate validation. This does not strike me as a good setup, security-wise.</p>
<p>Is it possible to tell Git that for remote X (or better, any remote in any repository that happens to begin with <code>https://$SERVERNAME/</code>) it is to accept a particular certificate, and <em>only</em> that certificate? Basically reduplicate SSH's server-key behavior.</p> | <p>Briefly:</p>
<ol>
<li>Get the self signed certificate</li>
<li>Put it into some (e.g. <code>~/git-certs/cert.pem</code>) file</li>
<li>Set <code>git</code> to trust this certificate using <code>http.sslCAInfo</code> parameter</li>
</ol>
<p>In more details:</p>
<h1>Get self signed certificate of remote server</h1>
<p>Assuming, the server URL is <code>repos.sample.com</code> and you want to access it over port <code>443</code>.</p>
<p>There are multiple options, how to get it.</p>
<h2>Get certificate using openssl</h2>
<pre><code>$ openssl s_client -connect repos.sample.com:443
</code></pre>
<p>Catch the output into a file <code>cert.pem</code> and delete all but part between (and including) <code>-BEGIN CERTIFICATE-</code> and <code>-END CERTIFICATE-</code></p>
<p>Content of resulting file ~/git-certs/cert.pem may look like this:</p>
<pre><code>-----BEGIN CERTIFICATE-----
MIIDnzCCAocCBE/xnXAwDQYJKoZIhvcNAQEFBQAwgZMxCzAJBgNVBAYTAkRFMRUw
EwYDVQQIEwxMb3dlciBTYXhvbnkxEjAQBgNVBAcTCVdvbGZzYnVyZzEYMBYGA1UE
ChMPU2FhUy1TZWN1cmUuY29tMRowGAYDVQQDFBEqLnNhYXMtc2VjdXJlLmNvbTEj
MCEGCSqGSIb3DQEJARYUaW5mb0BzYWFzLXNlY3VyZS5jb20wHhcNMTIwNzAyMTMw
OTA0WhcNMTMwNzAyMTMwOTA0WjCBkzELMAkGA1UEBhMCREUxFTATBgNVBAgTDExv
d2VyIFNheG9ueTESMBAGA1UEBxMJV29sZnNidXJnMRgwFgYDVQQKEw9TYWFTLVNl
Y3VyZS5jb20xGjAYBgNVBAMUESouc2Fhcy1zZWN1cmUuY29tMSMwIQYJKoZIhvcN
AQkBFhRpbmZvQHNhYXMtc2VjdXJlLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEP
ADCCAQoCggEBAMUZ472W3EVFYGSHTgFV0LR2YVE1U//sZimhCKGFBhH3ZfGwqtu7
mzOhlCQef9nqGxgH+U5DG43B6MxDzhoP7R8e1GLbNH3xVqMHqEdcek8jtiJvfj2a
pRSkFTCVJ9i0GYFOQfQYV6RJ4vAunQioiw07OmsxL6C5l3K/r+qJTlStpPK5dv4z
Sy+jmAcQMaIcWv8wgBAxdzo8UVwIL63gLlBz7WfSB2Ti5XBbse/83wyNa5bPJPf1
U+7uLSofz+dehHtgtKfHD8XpPoQBt0Y9ExbLN1ysdR9XfsNfBI5K6Uokq/tVDxNi
SHM4/7uKNo/4b7OP24hvCeXW8oRyRzpyDxMCAwEAATANBgkqhkiG9w0BAQUFAAOC
AQEAp7S/E1ZGCey5Oyn3qwP4q+geQqOhRtaPqdH6ABnqUYHcGYB77GcStQxnqnOZ
MJwIaIZqlz+59taB6U2lG30u3cZ1FITuz+fWXdfELKPWPjDoHkwumkz3zcCVrrtI
ktRzk7AeazHcLEwkUjB5Rm75N9+dOo6Ay89JCcPKb+tNqOszY10y6U3kX3uiSzrJ
ejSq/tRyvMFT1FlJ8tKoZBWbkThevMhx7jk5qsoCpLPmPoYCEoLEtpMYiQnDZgUc
TNoL1GjoDrjgmSen4QN5QZEGTOe/dsv1sGxWC+Tv/VwUl2GqVtKPZdKtGFqI8TLn
/27/jIdVQIKvHok2P/u9tvTUQA==
-----END CERTIFICATE-----
</code></pre>
<h2>Get certificate using your web browser</h2>
<p>I use Redmine with Git repositories and I access the same URL for web UI and for git command line access. This way, I had to add exception for that domain into my web browser.</p>
<p>Using Firefox, I went to <code>Options -> Advanced -> Certificates -> View Certificates -> Servers</code>, found there the selfsigned host, selected it and using <code>Export</code> button I got exactly the same file, as created using <code>openssl</code>.</p>
<p>Note: I was a bit surprised, there is no name of the authority visibly mentioned. This is fine.</p>
<h1>Having the trusted certificate in dedicated file</h1>
<p>Previous steps shall result in having the certificate in some file. It does not matter, what file it is as long as it is visible to your git when accessing that domain. I used <code>~/git-certs/cert.pem</code></p>
<p>Note: If you need more trusted selfsigned certificates, put them into the same file:</p>
<pre><code>-----BEGIN CERTIFICATE-----
MIIDnzCCAocCBE/xnXAwDQYJKoZIhvcNAQEFBQAwgZMxCzAJBgNVBAYTAkRFMRUw
...........
/27/jIdVQIKvHok2P/u9tvTUQA==
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
AnOtHeRtRuStEdCeRtIfIcAtEgOeShErExxxxxxxxxxxxxxxxxxxxxxxxxxxxxxw
...........
/27/jIdVQIKvHok2P/u9tvTUQA==
-----END CERTIFICATE-----
</code></pre>
<p>This shall work (but I tested it only with single certificate).</p>
<h1>Configure git to trust this certificate</h1>
<pre><code>$ git config --global http.sslCAInfo /home/javl/git-certs/cert.pem
</code></pre>
<p>You may also try to do that system wide, using <code>--system</code> instead of <code>--global</code>.</p>
<p>And test it: You shall now be able communicating with your server without resorting to:</p>
<pre><code>$ git config --global http.sslVerify false #NO NEED TO USE THIS
</code></pre>
<p>If you already set your git to ignorance of ssl certificates, unset it:</p>
<pre><code>$ git config --global --unset http.sslVerify
</code></pre>
<p>and you may also check, that you did it all correctly, without spelling errors:</p>
<pre><code>$ git config --global --list
</code></pre>
<p>what should list all variables, you have set globally. (I mispelled http to htt).</p> | {
"question_id": 9072376,
"question_date": "2012-01-30T23:31:55.043Z",
"question_score": 215,
"tags": "git|ssl-certificate",
"answer_id": 16543283,
"answer_date": "2013-05-14T12:34:17.713Z",
"answer_score": 369
} |
Please answer the following Stack Overflow question:
Title: What is the maximum length of a table name in Oracle?
<p>What are the maximum length of a table name and column name in Oracle? </p> | <p>In <a href="http://docs.oracle.com/database/122/REFRN/ALL_OBJECTS.htm#REFRN20146" rel="noreferrer">Oracle 12.2</a> and above the maximum object name length is 128 bytes.</p>
<p>In <a href="https://docs.oracle.com/database/121/SQLRF/sql_elements008.htm#SQLRF00223" rel="noreferrer">Oracle 12.1</a> and below the maximum object name length is 30 bytes.</p> | {
"question_id": 756558,
"question_date": "2009-04-16T15:03:19.827Z",
"question_score": 215,
"tags": "oracle|name-length",
"answer_id": 756569,
"answer_date": "2009-04-16T15:05:07.620Z",
"answer_score": 320
} |
Please answer the following Stack Overflow question:
Title: Group by date only on a Datetime column
<p>Having a table with a column like: <code>mydate DATETIME</code> ...</p>
<p>I have a query such as:</p>
<pre><code>SELECT SUM(foo), mydate FROM a_table GROUP BY a_table.mydate;
</code></pre>
<p>This will group by the full <code>datetime</code>, including hours and minutes. I wish to make the group by, only by the date <code>YYYY/MM/DD</code> not by the <code>YYYY/MM/DD/HH/mm</code>.</p>
<p>How to do this?</p> | <p>Cast the datetime to a date, then GROUP BY using this syntax:</p>
<pre><code>SELECT SUM(foo), DATE(mydate) FROM a_table GROUP BY DATE(a_table.mydate);
</code></pre>
<p>Or you can GROUP BY the alias as @orlandu63 suggested:</p>
<pre><code>SELECT SUM(foo), DATE(mydate) DateOnly FROM a_table GROUP BY DateOnly;
</code></pre>
<p>Though I don't think it'll make any difference to performance, it is a little clearer.</p> | {
"question_id": 366603,
"question_date": "2008-12-14T14:47:19.303Z",
"question_score": 215,
"tags": "sql|mysql",
"answer_id": 366610,
"answer_date": "2008-12-14T14:50:57.957Z",
"answer_score": 345
} |
Please answer the following Stack Overflow question:
Title: How to request Administrator access inside a batch file
<p>I am trying to write a batch file for my users to run from their Vista machines with UAC. The file is re-writing their hosts file, so it needs to be run with Administrator permissions. I need to be able to send them an email with a link to the .bat file. The desired behavior is that when they right-click on the file and say Open, they will get one of those UAC dialogs that makes the screen go dark and forces them to answer whether they want to give the application permission to run as administrator. Instead, they are just seeing "Access denied" on the command line window.</p>
<p>Is this possible to do differently?</p> | <p>This script does the trick! Just paste it into the top of your bat file. If you want to review the output of your script, add a "pause" command at the bottom of your batch file.</p>
<p>UPDATE: This script is now slightly edited to support command line arguments and a 64 bit OS.</p>
<p>Thank you Eneerge @ <a href="https://sites.google.com/site/eneerge/scripts/batchgotadmin" rel="noreferrer">https://sites.google.com/site/eneerge/scripts/batchgotadmin</a></p>
<pre><code>@echo off
:: BatchGotAdmin
:-------------------------------------
REM --> Check for permissions
IF "%PROCESSOR_ARCHITECTURE%" EQU "amd64" (
>nul 2>&1 "%SYSTEMROOT%\SysWOW64\cacls.exe" "%SYSTEMROOT%\SysWOW64\config\system"
) ELSE (
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
)
REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
echo Requesting administrative privileges...
goto UACPrompt
) else ( goto gotAdmin )
:UACPrompt
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
set params= %*
echo UAC.ShellExecute "cmd.exe", "/c ""%~s0"" %params:"=""%", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
exit /B
:gotAdmin
pushd "%CD%"
CD /D "%~dp0"
:--------------------------------------
<YOUR BATCH SCRIPT HERE>
</code></pre> | {
"question_id": 1894967,
"question_date": "2009-12-12T22:53:19.607Z",
"question_score": 215,
"tags": "batch-file|command-line|uac|elevated-privileges",
"answer_id": 10052222,
"answer_date": "2012-04-07T06:06:53.483Z",
"answer_score": 416
} |
Please answer the following Stack Overflow question:
Title: Select Tag Helper in ASP.NET Core MVC
<p>I need some help with the select tag helper in ASP.NET Core.</p>
<p>I have a list of employees that I'm trying to bind to a select tag helper. My employees are in a <code>List<Employee> EmployeesList</code> and selected value will go into <code>EmployeeId</code> property. My view model looks like this:</p>
<pre><code>public class MyViewModel
{
public int EmployeeId { get; set; }
public string Comments { get; set; }
public List<Employee> EmployeesList {get; set; }
}
</code></pre>
<p>My employee class looks like this:</p>
<pre><code>public class Employee
{
public int Id { get; set; }
public string FullName { get; set; }
}
</code></pre>
<p>My question is how do I tell my select tag helper to use the <code>Id</code> as the value while displaying <code>FullName</code> in the drop down list?</p>
<pre><code><select asp-for="EmployeeId" asp-items="???" />
</code></pre>
<p>I'd appreciate some help with this. Thanks.</p> | <h3>Using the Select Tag helpers to render a SELECT element</h3>
<p>In your GET action, create an object of your view model, load the <code>EmployeeList</code> collection property and send that to the view.</p>
<pre><code>public IActionResult Create()
{
var vm = new MyViewModel();
vm.EmployeesList = new List<Employee>
{
new Employee { Id = 1, FullName = "Shyju" },
new Employee { Id = 2, FullName = "Bryan" }
};
return View(vm);
}
</code></pre>
<p>And in your create view, create a new <code>SelectList</code> object from the <code>EmployeeList</code> property and pass that as value for the <code>asp-items</code> property.</p>
<pre><code>@model MyViewModel
<form asp-controller="Home" asp-action="Create">
<select asp-for="EmployeeId"
asp-items="@(new SelectList(Model.EmployeesList, nameof(Employee.Id), nameof(Employee.FullName)))">
<option>Please select one</option>
</select>
<input type="submit"/>
</form>
</code></pre>
<p>And your HttpPost action method to accept the submitted form data.</p>
<pre><code>[HttpPost]
public IActionResult Create(MyViewModel model)
{
// check model.EmployeeId
// to do : Save and redirect
}
</code></pre>
<p><strong>Or</strong></p>
<p>If your view model has a <code>List<SelectListItem></code> as the property for your dropdown items.</p>
<pre><code>public class MyViewModel
{
public int EmployeeId { get; set; }
public string Comments { get; set; }
public List<SelectListItem> Employees { set; get; }
}
</code></pre>
<p>And in your get action,</p>
<pre><code>public IActionResult Create()
{
var vm = new MyViewModel();
vm.Employees = new List<SelectListItem>
{
new SelectListItem {Text = "Shyju", Value = "1"},
new SelectListItem {Text = "Sean", Value = "2"}
};
return View(vm);
}
</code></pre>
<p>And in the view, you can directly use the <code>Employees</code> property for the <code>asp-items</code>.</p>
<pre><code>@model MyViewModel
<form asp-controller="Home" asp-action="Create">
<label>Comments</label>
<input type="text" asp-for="Comments"/>
<label>Lucky Employee</label>
<select asp-for="EmployeeId" asp-items="@Model.Employees" >
<option>Please select one</option>
</select>
<input type="submit"/>
</form>
</code></pre>
<p>The class <code>SelectListItem</code> belongs to <code>Microsoft.AspNet.Mvc.Rendering</code> namespace.</p>
<p>Make sure you are using an explicit closing tag for the select element. If you use the self closing tag approach, the tag helper will render an empty SELECT element!</p>
<p>The below approach <strong>will not work</strong></p>
<pre><code><select asp-for="EmployeeId" asp-items="@Model.Employees" />
</code></pre>
<p>But this will work.</p>
<pre><code><select asp-for="EmployeeId" asp-items="@Model.Employees"></select>
</code></pre>
<hr />
<h3>Getting data from your database table using entity framework</h3>
<p>The above examples are using hard coded items for the options. So i thought i will add some sample code to get data using Entity framework as a lot of people use that.</p>
<p>Let's assume your DbContext object has a property called <code>Employees</code>, which is of type <code>DbSet<Employee></code> where the <code>Employee</code> entity class has an <code>Id</code> and <code>Name</code> property like this</p>
<pre><code>public class Employee
{
public int Id { set; get; }
public string Name { set; get; }
}
</code></pre>
<p>You can use a LINQ query to get the employees and use the Select method in your LINQ expression to create a list of <code>SelectListItem</code> objects for each employee.</p>
<pre><code>public IActionResult Create()
{
var vm = new MyViewModel();
vm.Employees = context.Employees
.Select(a => new SelectListItem() {
Value = a.Id.ToString(),
Text = a.Name
})
.ToList();
return View(vm);
}
</code></pre>
<p>Assuming <code>context</code> is your db context object. The view code is same as above.</p>
<h3>Using SelectList</h3>
<p>Some people prefer to use <code>SelectList</code> class to hold the items needed to render the options.</p>
<pre><code>public class MyViewModel
{
public int EmployeeId { get; set; }
public SelectList Employees { set; get; }
}
</code></pre>
<p>Now in your GET action, you can use the <code>SelectList</code> constructor to populate the <code>Employees</code> property of the view model. Make sure you are specifying the <code>dataValueField</code> and <code>dataTextField</code> parameters. You can use a <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/nameof" rel="noreferrer">nameof expression</a> to link the field names statically.</p>
<pre><code>public IActionResult Create()
{
var vm = new MyViewModel();
vm.Employees = new SelectList(GetEmployees(), nameof(Employee.Id), nameof(Employee.FirstName));
return View(vm);
}
public IEnumerable<Employee> GetEmployees()
{
// hard coded list for demo.
// You may replace with real data from database to create Employee objects
return new List<Employee>
{
new Employee { Id = 1, FirstName = "Shyju" },
new Employee { Id = 2, FirstName = "Bryan" }
};
}
</code></pre>
<p>Here I am calling the <code>GetEmployees</code> method to get a list of Employee objects, each with an <code>Id</code> and <code>FirstName</code> property and I use those properties as <code>DataValueField</code> and <code>DataTextField</code> of the <code>SelectList</code> object we created. You can change the hardcoded list to a code which reads data from a database table.</p>
<p>The view code will be same.</p>
<pre><code><select asp-for="EmployeeId" asp-items="@Model.Employees" >
<option>Please select one</option>
</select>
</code></pre>
<h3>Render a SELECT element from a list of strings.</h3>
<p>Sometimes you might want to render a select element from a list of strings. In that case, you can use the <code>SelectList</code> constructor which only takes <code>IEnumerable<T></code></p>
<pre><code>var vm = new MyViewModel();
var items = new List<string> {"Monday", "Tuesday", "Wednesday"};
vm.Employees = new SelectList(items);
return View(vm);
</code></pre>
<p>The view code will be same.</p>
<h3>Setting selected options</h3>
<p>Some times,you might want to set one option as the default option in the SELECT element (For example, in an edit screen, you want to load the previously saved option value). To do that, you may simply set the <code>EmployeeId</code> property value to the value of the option you want to be selected.</p>
<pre><code>public IActionResult Create()
{
var vm = new MyViewModel();
vm.Employees = new List<SelectListItem>
{
new SelectListItem {Text = "Shyju", Value = "11"},
new SelectListItem {Text = "Tom", Value = "12"},
new SelectListItem {Text = "Jerry", Value = "13"}
};
vm.EmployeeId = 12; // Here you set the value
return View(vm);
}
</code></pre>
<p>This will select the option Tom in the select element when the page is rendered.</p>
<h3>Multi select dropdown</h3>
<p>If you want to render a multi select dropdown, you can simply change your view model property which you use for <code>asp-for</code> attribute in your view to an array type.</p>
<pre><code>public class MyViewModel
{
public int[] EmployeeIds { get; set; }
public List<SelectListItem> Employees { set; get; }
}
</code></pre>
<p>This will render the HTML markup for the select element with the <code>multiple</code> attribute which will allow the user to select multiple options.</p>
<pre><code>@model MyViewModel
<select id="EmployeeIds" multiple="multiple" name="EmployeeIds">
<option>Please select one</option>
<option value="1">Shyju</option>
<option value="2">Sean</option>
</select>
</code></pre>
<h3>Setting selected options in multi select</h3>
<p>Similar to single select, set the <code>EmployeeIds</code> property value to the an array of values you want.</p>
<pre><code>public IActionResult Create()
{
var vm = new MyViewModel();
vm.Employees = new List<SelectListItem>
{
new SelectListItem {Text = "Shyju", Value = "11"},
new SelectListItem {Text = "Tom", Value = "12"},
new SelectListItem {Text = "Jerry", Value = "13"}
};
vm.EmployeeIds= new int[] { 12,13} ;
return View(vm);
}
</code></pre>
<p>This will select the option Tom and Jerry in the multi select element when the page is rendered.</p>
<h3>Using ViewBag to transfer the list of items</h3>
<p>If you do not prefer to keep a collection type property to pass the list of options to the view, you can use the dynamic ViewBag to do so.(<em>This is not my personally recommended approach as viewbag is dynamic and your code is prone to uncaught typo errors</em>)</p>
<pre><code>public IActionResult Create()
{
ViewBag.Employees = new List<SelectListItem>
{
new SelectListItem {Text = "Shyju", Value = "1"},
new SelectListItem {Text = "Sean", Value = "2"}
};
return View(new MyViewModel());
}
</code></pre>
<p>and in the view</p>
<pre><code><select asp-for="EmployeeId" asp-items="@ViewBag.Employees">
<option>Please select one</option>
</select>
</code></pre>
<h3>Using ViewBag to transfer the list of items and setting selected option</h3>
<p>It is same as above. All you have to do is, set the property (for which you are binding the dropdown for) value to the value of the option you want to be selected.</p>
<pre><code>public IActionResult Create()
{
ViewBag.Employees = new List<SelectListItem>
{
new SelectListItem {Text = "Shyju", Value = "1"},
new SelectListItem {Text = "Bryan", Value = "2"},
new SelectListItem {Text = "Sean", Value = "3"}
};
vm.EmployeeId = 2; // This will set Bryan as selected
return View(new MyViewModel());
}
</code></pre>
<p>and in the view</p>
<pre><code><select asp-for="EmployeeId" asp-items="@ViewBag.Employees">
<option>Please select one</option>
</select>
</code></pre>
<h3>Grouping items</h3>
<p>The select tag helper method supports grouping options in a dropdown. All you have to do is, specify the <code>Group</code> property value of each <code>SelectListItem</code> in your action method.</p>
<pre><code>public IActionResult Create()
{
var vm = new MyViewModel();
var group1 = new SelectListGroup { Name = "Dev Team" };
var group2 = new SelectListGroup { Name = "QA Team" };
var employeeList = new List<SelectListItem>()
{
new SelectListItem() { Value = "1", Text = "Shyju", Group = group1 },
new SelectListItem() { Value = "2", Text = "Bryan", Group = group1 },
new SelectListItem() { Value = "3", Text = "Kevin", Group = group2 },
new SelectListItem() { Value = "4", Text = "Alex", Group = group2 }
};
vm.Employees = employeeList;
return View(vm);
}
</code></pre>
<p>There is no change in the view code. the select tag helper will now render the options inside 2 <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/optgroup" rel="noreferrer">optgroup</a> items.</p> | {
"question_id": 34624034,
"question_date": "2016-01-06T01:06:12.197Z",
"question_score": 215,
"tags": "c#|asp.net-core|asp.net-core-mvc|tag-helpers",
"answer_id": 34624217,
"answer_date": "2016-01-06T01:28:46.020Z",
"answer_score": 497
} |
Please answer the following Stack Overflow question:
Title: Determine the line of code that causes a segmentation fault?
<p>How does one determine where the mistake is in the code that causes a <a href="https://stackoverflow.com/questions/2346806/what-is-a-segmentation-fault">segmentation fault</a>?</p>
<p>Can my compiler (<code>gcc</code>) show the location of the fault in the program?</p> | <p>GCC can't do that but GDB (a <a href="https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems">debugger</a>) sure can. Compile you program using the <code>-g</code> switch, like this:</p>
<pre><code>gcc program.c -g
</code></pre>
<p>Then use gdb:</p>
<pre><code>$ gdb ./a.out
(gdb) run
<segfault happens here>
(gdb) backtrace
<offending code is shown here>
</code></pre>
<p><a href="http://www.unknownroad.com/rtfm/gdbtut/gdbtoc.html" rel="noreferrer">Here</a> is a nice tutorial to get you started with GDB.</p>
<p>Where the segfault occurs is generally only a clue as to where "the mistake which causes" it is in the code. The given location is not necessarily where the problem resides.</p> | {
"question_id": 2876357,
"question_date": "2010-05-20T17:39:29.653Z",
"question_score": 215,
"tags": "c++|c|debugging|segmentation-fault",
"answer_id": 2876374,
"answer_date": "2010-05-20T17:41:43.593Z",
"answer_score": 303
} |
Please answer the following Stack Overflow question:
Title: Extract part of a regex match
<p>I want a regular expression to extract the title from a HTML page. Currently I have this:</p>
<pre><code>title = re.search('<title>.*</title>', html, re.IGNORECASE).group()
if title:
title = title.replace('<title>', '').replace('</title>', '')
</code></pre>
<p>Is there a regular expression to extract just the contents of <title> so I don't have to remove the tags?</p> | <p>Use <code>(</code> <code>)</code> in regexp and <a href="https://docs.python.org/3.8/library/re.html#re.Match.group" rel="noreferrer"><code>group(1)</code></a> in python to retrieve the captured string (<a href="https://docs.python.org/3.8/library/re.html#re.search" rel="noreferrer"><code>re.search</code></a> will return <code>None</code> if it doesn't find the result, so <em>don't use <code>group()</code> directly</em>):</p>
<pre><code>title_search = re.search('<title>(.*)</title>', html, re.IGNORECASE)
if title_search:
title = title_search.group(1)
</code></pre> | {
"question_id": 1327369,
"question_date": "2009-08-25T10:24:58.580Z",
"question_score": 215,
"tags": "python|html|regex|html-content-extraction",
"answer_id": 1327389,
"answer_date": "2009-08-25T10:29:31.147Z",
"answer_score": 335
} |
Please answer the following Stack Overflow question:
Title: How to set a cookie for another domain
<p>Say I have a website called <code>a.com</code>, and when a specific page of this site is loaded, say page link, I like to set a cookie for another site called <code>b.com</code>, then redirect the user to <code>b.com</code>. </p>
<p>I mean, on load of <code>a.com/link</code> I want to set a cookie for <code>b.com</code> and redirect user to <code>b.com</code>. </p>
<p>I tested it, and browser actually received the cookie from <code>a.com/link</code>, but it didn't send that cookie on the redirection request to <code>b.com</code>. Is it normal?</p>
<p>Can we set cookies for other domains?</p> | <p>You cannot set cookies for another domain. Allowing this would present an enormous security flaw.</p>
<p>You need to get b.com to set the cookie. If a.com redirect the user to <code>b.com/setcookie.php?c=value</code></p>
<p>The setcookie script could contain the following to set the cookie and redirect to the correct page on b.com</p>
<pre><code><?php
setcookie('a', $_GET['c']);
header("Location: b.com/landingpage.php");
?>
</code></pre> | {
"question_id": 6761415,
"question_date": "2011-07-20T11:51:12.557Z",
"question_score": 215,
"tags": "javascript|cookies|redirect",
"answer_id": 6761443,
"answer_date": "2011-07-20T11:53:02.257Z",
"answer_score": 159
} |
Please answer the following Stack Overflow question:
Title: Pythonic way to return list of every nth item in a larger list
<p>Say we have a list of numbers from 0 to 1000. Is there a pythonic/efficient way to produce a list of the first and every subsequent 10th item, i.e. <code>[0, 10, 20, 30, ... ]</code>?</p>
<p>Yes, I can do this using a for loop, but I'm wondering if there is a neater way to do this, perhaps even in one line?</p> | <pre><code>>>> lst = list(range(165))
>>> lst[0::10]
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160]
</code></pre>
<p>Note that this is around 100 times faster than looping and checking a modulus for each element:</p>
<pre><code>$ python -m timeit -s "lst = list(range(1000))" "lst1 = [x for x in lst if x % 10 == 0]"
1000 loops, best of 3: 525 usec per loop
$ python -m timeit -s "lst = list(range(1000))" "lst1 = lst[0::10]"
100000 loops, best of 3: 4.02 usec per loop
</code></pre> | {
"question_id": 1403674,
"question_date": "2009-09-10T06:32:29.210Z",
"question_score": 215,
"tags": "list|python",
"answer_id": 1403693,
"answer_date": "2009-09-10T06:37:28.220Z",
"answer_score": 362
} |
Please answer the following Stack Overflow question:
Title: Passing a string with spaces as a function argument in Bash
<p>I'm writing a Bash script where I need to pass a string containing spaces to a function in my Bash script.</p>
<p>For example:</p>
<pre><code>#!/bin/bash
myFunction
{
echo $1
echo $2
echo $3
}
myFunction "firstString" "second string with spaces" "thirdString"
</code></pre>
<p>When run, the output I'd expect is:</p>
<pre><code>firstString
second string with spaces
thirdString
</code></pre>
<p>However, what's actually output is:</p>
<pre><code>firstString
second
string
</code></pre>
<p>Is there a way to pass a string with spaces as a single argument to a function in Bash?</p> | <p>You should add quotes and also, your function declaration is wrong.</p>
<pre><code>myFunction()
{
echo "$1"
echo "$2"
echo "$3"
}
</code></pre>
<p>And like the others, it works for me as well.</p> | {
"question_id": 1983048,
"question_date": "2009-12-30T23:23:21.127Z",
"question_score": 215,
"tags": "bash|function",
"answer_id": 1983070,
"answer_date": "2009-12-30T23:28:11.210Z",
"answer_score": 202
} |
Please answer the following Stack Overflow question:
Title: What is this CSS selector? [class*="span"]
<p>I saw this selector in Twitter Bootstrap:</p>
<pre><code>.show-grid [class*="span"] {
background-color: #eee;
text-align: center;
border-radius: 3px;
min-height: 30px;
line-height: 30px;
}
</code></pre>
<p>Does anyone know what this technique is called and what it does?</p> | <p>It's an attribute wildcard selector. In the sample you've given, it looks for any child element under <code>.show-grid</code> that has a class that CONTAINS <code>span</code>.</p>
<p>So would select the <code><strong></code> element in this example:</p>
<pre><code><div class="show-grid">
<strong class="span6">Blah blah</strong>
</div>
</code></pre>
<p>You can also do searches for 'begins with...'</p>
<pre><code>div[class^="something"] { }
</code></pre>
<p>which would work on something like this:-</p>
<pre><code><div class="something-else-class"></div>
</code></pre>
<p>and 'ends with...'</p>
<pre><code>div[class$="something"] { }
</code></pre>
<p>which would work on</p>
<pre><code><div class="you-are-something"></div>
</code></pre>
<p><strong>Good references</strong></p>
<ul>
<li><a href="http://www.impressivewebs.com/css3-attribute-selectors-substring-matching/" rel="noreferrer">CSS3 Attribute Selectors: Substring Matching</a></li>
<li><a href="http://net.tutsplus.com/tutorials/html-css-techniques/the-30-css-selectors-you-must-memorize/" rel="noreferrer">The 30 CSS Selectors you Must Memorize</a></li>
<li><a href="http://www.w3.org/TR/css3-selectors/" rel="noreferrer">W3C CSS3 Selectors</a></li>
</ul> | {
"question_id": 9836151,
"question_date": "2012-03-23T08:41:35.957Z",
"question_score": 215,
"tags": "css|css-selectors",
"answer_id": 9836182,
"answer_date": "2012-03-23T08:43:53.163Z",
"answer_score": 367
} |
Please answer the following Stack Overflow question:
Title: Does Java SE 8 have Pairs or Tuples?
<p>I am playing around with lazy functional operations in Java SE 8, and I want to <code>map</code> an index <code>i</code> to a pair / tuple <code>(i, value[i])</code>, then <code>filter</code> based on the second <code>value[i]</code> element, and finally output just the indices.</p>
<p>Must I still suffer this: <a href="https://stackoverflow.com/questions/156275/what-is-the-equivalent-of-the-c-pairl-r-in-java">What is the equivalent of the C++ Pair<L,R> in Java?</a> in the bold new era of lambdas and streams?</p>
<p><strong>Update:</strong> I presented a rather simplified example, which has a neat solution offered by @dkatzel in one of the answers below. However, it does <em>not</em> generalize. Therefore, let me add a more general example:</p>
<pre><code>package com.example.test;
import java.util.ArrayList;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
boolean [][] directed_acyclic_graph = new boolean[][]{
{false, true, false, true, false, true},
{false, false, false, true, false, true},
{false, false, false, true, false, true},
{false, false, false, false, false, true},
{false, false, false, false, false, true},
{false, false, false, false, false, false}
};
System.out.println(
IntStream.range(0, directed_acyclic_graph.length)
.parallel()
.mapToLong(i -> IntStream.range(0, directed_acyclic_graph[i].length)
.filter(j -> directed_acyclic_graph[j][i])
.count()
)
.filter(n -> n == 0)
.collect(() -> new ArrayList<Long>(), (c, e) -> c.add(e), (c1, c2) -> c1.addAll(c2))
);
}
}
</code></pre>
<p>This gives <strong>incorrect</strong> output of <code>[0, 0, 0]</code> which corresponds to the <em>counts</em> for the three columns that are all <code>false</code>. What I need are the <em>indices</em> of these three columns. The correct output should be <code>[0, 2, 4]</code>. How can I get this result?</p> | <p><strong>UPDATE:</strong> This answer is in response to the original question, <em>Does Java SE 8 have Pairs or Tuples?</em> (And implicitly, if not, why not?) The OP has updated the question with a more complete example, but it seems like it can be solved without using any kind of Pair structure. [Note from OP: here is <a href="https://stackoverflow.com/questions/24328679/does-java-se-8-have-pairs-or-tuples/24339157#24339157">the other correct answer</a>.]</p>
<hr>
<p>The short answer is no. You either have to roll your own or bring in one of the several libraries that implements it.</p>
<p>Having a <code>Pair</code> class in Java SE was proposed and rejected at least once. See <a href="http://mail.openjdk.java.net/pipermail/core-libs-dev/2010-March/003973.html" rel="noreferrer">this discussion thread</a> on one of the OpenJDK mailing lists. The tradeoffs are not obvious. On the one hand, there are many Pair implementations in other libraries and in application code. That demonstrates a need, and adding such a class to Java SE will increase reuse and sharing. On the other hand, having a Pair class adds to the temptation of creating complicated data structures out of Pairs and collections without creating the necessary types and abstractions. (That's a paraphrase of <a href="http://mail.openjdk.java.net/pipermail/core-libs-dev/2010-March/003995.html" rel="noreferrer">Kevin Bourillion's message</a> from that thread.)</p>
<p>I recommend everybody read that entire email thread. It's remarkably insightful and has no flamage. It's quite convincing. When it started I thought, "Yeah, there should be a Pair class in Java SE" but by the time the thread reached its end I had changed my mind.</p>
<p>Note however that JavaFX has the <a href="http://docs.oracle.com/javafx/2/api/javafx/util/Pair.html" rel="noreferrer">javafx.util.Pair</a> class. JavaFX's APIs evolved separately from the Java SE APIs.</p>
<p>As one can see from the linked question <a href="https://stackoverflow.com/questions/156275/what-is-the-equivalent-of-the-c-pairl-r-in-java">What is the equivalent of the C++ Pair in Java?</a> there is quite a large design space surrounding what is apparently such a simple API. Should the objects be immutable? Should they be serializable? Should they be comparable? Should the class be final or not? Should the two elements be ordered? Should it be an interface or a class? Why stop at pairs? Why not triples, quads, or N-tuples?</p>
<p>And of course there is the inevitable naming bikeshed for the elements:</p>
<ul>
<li>(a, b)</li>
<li>(first, second)</li>
<li>(left, right)</li>
<li>(car, cdr)</li>
<li>(foo, bar)</li>
<li>etc.</li>
</ul>
<p>One big issue that has hardly been mentioned is the relationship of Pairs to primitives. If you have an <code>(int x, int y)</code> datum that represents a point in 2D space, representing this as <code>Pair<Integer, Integer></code> consumes <strong>three objects</strong> instead of two 32-bit words. Furthermore, these objects must reside on the heap and will incur GC overhead.</p>
<p>It would seem clear that, like Streams, it would be essential for there to be primitive specializations for Pairs. Do we want to see:</p>
<pre><code>Pair
ObjIntPair
ObjLongPair
ObjDoublePair
IntObjPair
IntIntPair
IntLongPair
IntDoublePair
LongObjPair
LongIntPair
LongLongPair
LongDoublePair
DoubleObjPair
DoubleIntPair
DoubleLongPair
DoubleDoublePair
</code></pre>
<p>Even an <code>IntIntPair</code> would still require one object on the heap.</p>
<p>These are, of course, reminiscent of the proliferation of functional interfaces in the <code>java.util.function</code> package in Java SE 8. If you don't want a bloated API, which ones would you leave out? You could also argue that this isn't enough, and that specializations for, say, <code>Boolean</code> should be added as well.</p>
<p>My feeling is that if Java had added a Pair class long ago, it would have been simple, or even simplistic, and it wouldn't have satisfied many of the use cases we are envisioning now. Consider that if Pair had been added in the JDK 1.0 time frame, it probably would have been mutable! (Look at java.util.Date.) Would people have been happy with that? My guess is that if there were a Pair class in Java, it would be kinda-sort-not-really-useful and everybody will still be rolling their own to satisfy their needs, there would be various Pair and Tuple implementations in external libraries, and people would still be arguing/discussing about how to fix Java's Pair class. In other words, kind of in the same place we're at today.</p>
<p>Meanwhile, some work is going on to address the fundamental issue, which is better support in the JVM (and eventually the Java language) for <em>value types</em>. See this <a href="http://cr.openjdk.java.net/~jrose/values/values-0.html" rel="noreferrer">State of the Values</a> document. This is preliminary, speculative work, and it covers only issues from the JVM perspective, but it already has a fair amount of thought behind it. Of course there are no guarantees that this will get into Java 9, or ever get in anywhere, but it does show the current direction of thinking on this topic.</p> | {
"question_id": 24328679,
"question_date": "2014-06-20T13:40:39.627Z",
"question_score": 215,
"tags": "java|lambda|functional-programming|java-8|java-stream",
"answer_id": 24336841,
"answer_date": "2014-06-20T23:00:25.813Z",
"answer_score": 233
} |
Please answer the following Stack Overflow question:
Title: Generate the ERD for an existing database
<p>I have a PostgreSQL database. I want to generate ERD from that database. Are there any built-in tools to do it or maybe some third-party tools?</p> | <p>We used <a href="https://www.dbvis.com/features/" rel="noreferrer">DBVisualizer</a> for that.</p>
<p><strong>Description:</strong>
The references graph is a great feature as it automatically renders all primary/foreign key mappings (also called referential integrity constraints) in a graph style. The table nodes and relations are layed out automatically, with a number of layout modes available. The resulting graph is unique as it displays all information in an optimal and readable layout.
<strong>from its site</strong></p> | {
"question_id": 3474389,
"question_date": "2010-08-13T06:24:53.813Z",
"question_score": 215,
"tags": "database|postgresql|erd",
"answer_id": 3474475,
"answer_date": "2010-08-13T06:37:37.023Z",
"answer_score": 106
} |
Please answer the following Stack Overflow question:
Title: How to use pip with Python 3.x alongside Python 2.x
<p>I installed Python 3.x (besides Python 2.x on Ubuntu) and slowly started to pair modules I use in Python 2.x.</p>
<p>So I wonder, what approach should I take to make my life easy by using pip for both Python 2.x and Python 3.x?</p> | <p>The approach you should take is to install <code>pip</code> for Python 3.2.</p>
<p>You do this in the following way:</p>
<pre><code>$ curl -O https://bootstrap.pypa.io/get-pip.py
$ sudo python3.2 get-pip.py
</code></pre>
<p>Then, you can install things for Python 3.2 with <code>pip-3.2</code>, and install things for Python 2-7 with <code>pip-2.7</code>. The <code>pip</code> command will end up pointing to one of these, but I'm not sure which, so you will have to check.</p> | {
"question_id": 11268501,
"question_date": "2012-06-29T20:25:17.553Z",
"question_score": 215,
"tags": "python|python-3.x|python-2.7|pip",
"answer_id": 11272201,
"answer_date": "2012-06-30T07:06:54.150Z",
"answer_score": 200
} |
Please answer the following Stack Overflow question:
Title: Retrieving parameters from a URL
<p>Given a URL like the following, how can I parse the value of the query parameters? For example, in this case I want the value of <code>some_key </code>.</p>
<pre><code>/some_path?some_key=some_value'
</code></pre>
<p>I am using Django in my environment; is there a method on the <code>request</code> object that could help me?</p>
<p>I tried using <code>self.request.get('some_key')</code> but it is not returning the value <code>some_value</code> as I had hoped.</p> | <p>This is not specific to Django, but for Python in general. For a Django specific answer, <a href="https://stackoverflow.com/a/23615281/102401">see this one</a> from @jball037</p>
<p><strong>Python 2:</strong></p>
<pre class="lang-py prettyprint-override"><code>import urlparse
url = 'https://www.example.com/some_path?some_key=some_value'
parsed = urlparse.urlparse(url)
captured_value = urlparse.parse_qs(parsed.query)['some_key'][0]
print captured_value
</code></pre>
<p><strong>Python 3:</strong></p>
<pre class="lang-py prettyprint-override"><code>from urllib.parse import urlparse
from urllib.parse import parse_qs
url = 'https://www.example.com/some_path?some_key=some_value'
parsed_url = urlparse(url)
captured_value = parse_qs(parsed_url.query)['some_key'][0]
print(captured_value)
</code></pre>
<p><code>parse_qs</code> returns a list. The <code>[0]</code> gets the first item of the list so the output of each script is <code>some_value</code></p>
<p><a href="https://docs.python.org/3/library/urllib.parse.html#urllib.parse.parse_qs" rel="noreferrer">Here's the 'parse_qs' documentation for Python 3</a></p> | {
"question_id": 5074803,
"question_date": "2011-02-22T06:27:16.557Z",
"question_score": 215,
"tags": "python|django|parsing|url",
"answer_id": 5075477,
"answer_date": "2011-02-22T07:54:22.460Z",
"answer_score": 383
} |
Please answer the following Stack Overflow question:
Title: How to do multiple arguments to map function where one remains the same
<p>Let's say we have a function <code>add</code> as follows</p>
<pre><code>def add(x, y):
return x + y
</code></pre>
<p>we want to apply map function for an array</p>
<pre><code>map(add, [1, 2, 3], 2)
</code></pre>
<p>The semantics are I want to add 2 to every element of the array. But the <code>map</code> function requires a list in the third argument as well.</p>
<p><strong>Note:</strong> I am putting the <code>add</code> example for simplicity. My original function is much more complicated. And of course option of setting the default value of <code>y</code> in <code>add</code> function is out of question as it will be changed for every call.</p> | <p>One option is a list comprehension:</p>
<pre><code>[add(x, 2) for x in [1, 2, 3]]
</code></pre>
<p>More options:</p>
<pre><code>a = [1, 2, 3]
import functools
map(functools.partial(add, y=2), a)
import itertools
map(add, a, itertools.repeat(2, len(a)))
</code></pre> | {
"question_id": 10834960,
"question_date": "2012-05-31T13:48:48.890Z",
"question_score": 215,
"tags": "python",
"answer_id": 10834984,
"answer_date": "2012-05-31T13:50:19.020Z",
"answer_score": 248
} |
Please answer the following Stack Overflow question:
Title: python capitalize first letter only
<p>I am aware .capitalize() capitalizes the first letter of a string but what if the first character is a integer?</p>
<p>this</p>
<pre><code>1bob
5sandy
</code></pre>
<p>to this</p>
<pre><code>1Bob
5Sandy
</code></pre> | <p>If the first character is an integer, it will not capitalize the first letter.</p>
<pre><code>>>> '2s'.capitalize()
'2s'
</code></pre>
<p>If you want the functionality, strip off the digits, you can use <code>'2'.isdigit()</code> to check for each character.</p>
<pre><code>>>> s = '123sa'
>>> for i, c in enumerate(s):
... if not c.isdigit():
... break
...
>>> s[:i] + s[i:].capitalize()
'123Sa'
</code></pre> | {
"question_id": 12410242,
"question_date": "2012-09-13T15:54:32.070Z",
"question_score": 215,
"tags": "python|capitalize|letter",
"answer_id": 12410288,
"answer_date": "2012-09-13T15:56:40.733Z",
"answer_score": 256
} |
Please answer the following Stack Overflow question:
Title: What is the C# equivalent of friend?
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/203616/why-does-c-sharp-not-provide-the-c-style-friend-keyword">Why does C# not provide the C++ style ‘friend’ keyword?</a> </p>
</blockquote>
<p>I'd like the private member variables of a class to be accessible to a Tester class without exposing them to other classes. </p>
<p>In C++ I'd just declare the Tester class as a friend, how do I do this in C#? Can someone give me an example?</p> | <p>There's no direct equivalent of "friend" - the closest that's available (and it isn't very close) is <a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx" rel="noreferrer">InternalsVisibleTo</a>. I've only ever used this attribute for testing - where it's very handy!</p>
<p><strong>Example:</strong> To be placed in <code>AssemblyInfo.cs</code></p>
<pre><code>[assembly: InternalsVisibleTo("OtherAssembly")]
</code></pre> | {
"question_id": 204739,
"question_date": "2008-10-15T13:41:08.073Z",
"question_score": 215,
"tags": "c#",
"answer_id": 204744,
"answer_date": "2008-10-15T13:42:22.313Z",
"answer_score": 289
} |
Please answer the following Stack Overflow question:
Title: Array versus linked-list
<p>Why would someone want to use a linked-list over an array?</p>
<p>Coding a linked-list is, no doubt, a bit more work than using an array and one may wonder what would justify the additional effort.</p>
<p>I think insertion of new elements is trivial in a linked-list but it's a major chore in an array. Are there other advantages to using a linked list to store a set of data versus storing it in an array?</p>
<p>This question is not a duplicate of <a href="https://stackoverflow.com/questions/322715/when-to-use-linkedlist-over-arraylist">this question</a> because the other question is asking specifically about a particular Java class while this question is concerned with the general data structures. </p> | <ul>
<li>It's easier to store data of different sizes in a linked list. An array assumes every element is exactly the same size. </li>
<li>As you mentioned, it's easier for a linked list to grow organically. An array's size needs to be known ahead of time, or re-created when it needs to grow. </li>
<li>Shuffling a linked list is just a matter of changing what points to what. Shuffling an array is more complicated and/or takes more memory. </li>
<li>As long as your iterations all happen in a "foreach" context, you don't lose any performance in iteration. </li>
</ul> | {
"question_id": 166884,
"question_date": "2008-10-03T13:35:53.110Z",
"question_score": 215,
"tags": "arrays|data-structures|linked-list|language-agnostic",
"answer_id": 166907,
"answer_date": "2008-10-03T13:40:05.723Z",
"answer_score": 153
} |
Please answer the following Stack Overflow question:
Title: How to enable C++11/C++0x support in Eclipse CDT?
<p>Eclipse 3.7.1
CDT 1.4.1
GCC 4.6.2</p>
<p>This is an example of a piece of C++11 code:</p>
<pre><code>auto text = std::unique_ptr<char[]>(new char[len]);
</code></pre>
<p>The Eclipse editor complains about:</p>
<pre><code>Function 'unique_ptr' could not be resolved
</code></pre>
<p>The Makefile compilation works fine. How to make Eclipse stop complaining about these sort of errors?</p> | <p>I found <a href="http://www.eclipse.org/forums/index.php/mv/msg/282618/787571/" rel="nofollow noreferrer">this</a> article in the Eclipse forum, just followed those steps and it works for me. I am using Eclipse Indigo 20110615-0604 on Windows with a Cygwin setup.</p>
<ul>
<li>Make a new C++ project</li>
<li>Default options for everything</li>
<li>Once created, right-click the project and go to "Properties"</li>
<li>C/C++ Build -> Settings -> Tool Settings -> GCC C++ Compiler -> Miscellaneous -> Other Flags. Put <code>-std=c++0x</code> (or for newer compiler version <code>-std=c++11</code> at the end . ... instead of GCC C++ Compiler I have also Cygwin compiler</li>
<li>C/C++ General -> Paths and Symbols -> Symbols -> GNU C++. Click "Add..." and paste <code>__GXX_EXPERIMENTAL_CXX0X__</code> (ensure to append and prepend two underscores) into "Name" and leave "Value" blank.</li>
<li>Hit Apply, do whatever it asks you to do, then hit OK.</li>
</ul>
<p>There is a description of this in the Eclipse FAQ now as well: <a href="http://wiki.eclipse.org/CDT/User/FAQ#CDT_does_not_recognize_C.2B.2B11_features" rel="nofollow noreferrer">Eclipse FAQ/C++11 Features</a>.</p>
<p><strong>Eclipse setting</strong></p>
<p><a href="https://i.stack.imgur.com/VuXY7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VuXY7.png" alt="Eclipse image setting" /></a></p> | {
"question_id": 9131763,
"question_date": "2012-02-03T16:13:57.597Z",
"question_score": 215,
"tags": "c++|eclipse|c++11|eclipse-cdt",
"answer_id": 9135135,
"answer_date": "2012-02-03T20:33:54.007Z",
"answer_score": 231
} |
Please answer the following Stack Overflow question:
Title: CSS How to set div height 100% minus nPx
<p>I have a wrapper div which contans 2 divs next to each other. Above this container I have a div that contains my header. The wrapper div must be 100% minus the height of the header. The header is about 60 px. This is fixed. So my question is: how do I set the height my wrapper div to be 100% minus the 60 px?</p>
<pre><code><div id="header"></div>
<div id="wrapper">
<div id="left"></div>
<div id="right"></div>
</div>
</code></pre> | <p>Here is a working css, tested under Firefox / IE7 / Safari / Chrome / Opera.</p>
<pre><code>* {margin:0px;padding:0px;overflow:hidden}
div {position:absolute}
div#header {top:0px;left:0px;right:0px;height:60px}
div#wrapper {top:60px;left:0px;right:0px;bottom:0px;}
div#left {top:0px;bottom:0px;left:0px;width:50%;overflow-y:auto}
div#right {top:0px;bottom:0px;right:0px;width:50%;overflow-y:auto}
</code></pre>
<p>"overflow-y" is not w3c-approved, but every major browser supports it. Your two divs #left and #right will display a vertical scrollbar if their content is too high.</p>
<p>For this to work under IE7, you have to trigger the standards-compliant mode by adding a DOCTYPE : </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><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<style type="text/css">
*{margin:0px;padding:0px;overflow:hidden}
div{position:absolute}
div#header{top:0px;left:0px;right:0px;height:60px}
div#wrapper{top:60px;left:0px;right:0px;bottom:0px;}
div#left{top:0px;bottom:0px;left:0px;width:50%;overflow-y:auto}
div#right{top:0px;bottom:0px;right:0px;width:50%;overflow-y:auto}
</style>
</head>
<body>
<div id="header"></div>
<div id="wrapper">
<div id="left"><div style="height:1000px">high content</div></div>
<div id="right"></div>
</div>
</body></code></pre>
</div>
</div>
</p> | {
"question_id": 1192783,
"question_date": "2009-07-28T08:50:00.063Z",
"question_score": 215,
"tags": "css|height",
"answer_id": 1193306,
"answer_date": "2009-07-28T10:46:35.600Z",
"answer_score": 80
} |
Please answer the following Stack Overflow question:
Title: How to get the anchor from the URL using jQuery?
<p>I have a URL that is like:</p>
<pre><code>www.example.com/task1/1.3.html#a_1
</code></pre>
<p>How can I get the <code>a_1</code> anchor value using jQuery and store it as a variable?</p> | <p>You can use the <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/indexOf" rel="noreferrer"><code>.indexOf()</code></a> and <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substring" rel="noreferrer"><code>.substring()</code></a>, like this:</p>
<pre><code>var url = "www.aaa.com/task1/1.3.html#a_1";
var hash = url.substring(url.indexOf("#")+1);
</code></pre>
<p><a href="http://jsfiddle.net/nick_craver/mpdSD/" rel="noreferrer">You can give it a try here</a>, if it may not have a <code>#</code> in it, do an <code>if(url.indexOf("#") != -1)</code> check like this:</p>
<pre><code>var url = "www.aaa.com/task1/1.3.html#a_1", idx = url.indexOf("#");
var hash = idx != -1 ? url.substring(idx+1) : "";
</code></pre>
<hr>
<p>If this is the <em>current</em> page URL, you can just use <code>window.location.hash</code> to get it, and replace the <code>#</code> if you wish.</p> | {
"question_id": 3552944,
"question_date": "2010-08-24T01:25:11.667Z",
"question_score": 215,
"tags": "javascript|jquery|url|anchor",
"answer_id": 3552952,
"answer_date": "2010-08-24T01:26:50.323Z",
"answer_score": 217
} |
Please answer the following Stack Overflow question:
Title: What does flex: 1 mean?
<p>As we all know, the <code>flex</code> property is a shorthand for the <code>flex-grow</code>, <code>flex-shrink</code>, and the <code>flex-basis</code> properties. Its default value is <code>0 1 auto</code>, which means</p>
<pre><code>flex-grow: 0;
flex-shrink: 1;
flex-basis: auto;
</code></pre>
<p>but I've noticed, in many places <code>flex: 1</code> is used. Is it shorthand for <code>1 1 auto</code> or <code>1 0 auto</code>? I can't understand what it means and I get nothing when I google.</p> | <p>Here is the explanation:</p>
<p><a href="https://www.w3.org/TR/css-flexbox-1/#flex-common" rel="noreferrer">https://www.w3.org/TR/css-flexbox-1/#flex-common</a></p>
<blockquote>
<p><strong>flex: <positive-number></strong><br>
Equivalent to flex: <positive-number> 1 0. Makes the flex item flexible and sets the flex basis to zero, resulting in an item that
receives the specified proportion of the free space in the flex
container. If all items in the flex container use this pattern, their
sizes will be proportional to the specified flex factor.</p>
</blockquote>
<p>Therefore <code>flex:1</code> is equivalent to <code>flex: 1 1 0</code></p> | {
"question_id": 37386244,
"question_date": "2016-05-23T08:34:36.400Z",
"question_score": 215,
"tags": "css|flexbox",
"answer_id": 37386828,
"answer_date": "2016-05-23T09:03:39.387Z",
"answer_score": 126
} |
Please answer the following Stack Overflow question:
Title: Set cookies for cross origin requests
<p>How to share cookies cross origin? More specifically, how to use the <code>Set-Cookie</code> header in combination with the header <code>Access-Control-Allow-Origin</code>?</p>
<p>Here's an explanation of my situation:</p>
<p>I am attempting to set a cookie for an API that is running on <code>localhost:4000</code> in a web app that is hosted on <code>localhost:3000</code>. </p>
<p>It seems I'm receiving the right response headers in the browser, but unfortunately they have no effect. These are the response headers:</p>
<pre>
HTTP/1.1 200 OK
Access-Control-Allow-Origin: http://localhost:3000
Vary: Origin, Accept-Encoding
Set-Cookie: token=0d522ba17e130d6d19eb9c25b7ac58387b798639f81ffe75bd449afbc3cc715d6b038e426adeac3316f0511dc7fae3f7; Max-Age=86400; Domain=localhost:4000; Path=/; Expires=Tue, 19 Sep 2017 21:11:36 GMT; HttpOnly
Content-Type: application/json; charset=utf-8
Content-Length: 180
ETag: W/"b4-VNrmF4xNeHGeLrGehNZTQNwAaUQ"
Date: Mon, 18 Sep 2017 21:11:36 GMT
Connection: keep-alive
</pre>
<p>Furthermore, I can see the cookie under <code>Response Cookies</code> when I inspect the traffic using the Network tab of Chrome's developer tools. Yet, I can't see a cookie being set in in the Application tab under <code>Storage/Cookies</code>. I don't see any CORS errors, so I assume I'm missing something else.</p>
<p>Any suggestions?</p>
<h3>Update I:</h3>
<p>I'm using the <a href="https://www.npmjs.com/package/request" rel="noreferrer">request</a> module in a React-Redux app to issue a request to a <code>/signin</code> endpoint on the server. For the server I use express.</p>
<p>Express server:</p>
<pre>
res.cookie('token', 'xxx-xxx-xxx', { maxAge: 86400000, httpOnly: true, domain: 'localhost:3000' })
</pre>
<p>Request in browser:</p>
<pre>
request.post({ uri: '/signin', json: { userName: 'userOne', password: '123456'}}, (err, response, body) => {
// doing stuff
})</pre>
<h3>Update II:</h3>
<p>I am setting request and response headers now like crazy now, making sure that they are present in both the request and the response. Below is a screenshot. Notice the headers <code>Access-Control-Allow-Credentials</code>, <code>Access-Control-Allow-Headers</code>, <code>Access-Control-Allow-Methods</code> and <code>Access-Control-Allow-Origin</code>. Looking at the issue I found at <a href="https://github.com/mzabriskie/axios/issues/191#issuecomment-311069164" rel="noreferrer">Axios's github</a>, I'm under the impression that all required headers are now set. Yet, there's still no luck...</p>
<p><a href="https://i.stack.imgur.com/d6Qv6.png" rel="noreferrer"><img src="https://i.stack.imgur.com/d6Qv6.png" alt="enter image description here"></a></p> | <h2>Cross site approach</h2>
<p>To allow receiving & sending cookies by a CORS request successfully, do the following.</p>
<p><strong>Back-end (server) HTTP header settings:</strong></p>
<ul>
<li><p>Set the HTTP header <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials" rel="nofollow noreferrer"><code>Access-Control-Allow-Credentials</code></a> value to <code>true</code>.</p>
</li>
<li><p>Make sure the HTTP headers <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin" rel="nofollow noreferrer"><code>Access-Control-Allow-Origin</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers" rel="nofollow noreferrer"><code>Access-Control-Allow-Headers</code></a> are set and <strong>not with a wildcard <code>*</code></strong>. When you set the origin, make sure to use the entire origin including the scheme (e.g. http is not same as https in CORS)</p>
</li>
</ul>
<p>For more info on setting CORS in express js <a href="https://expressjs.com/en/resources/middleware/cors.html#configuration-options" rel="nofollow noreferrer">read the docs here</a>.</p>
<p><strong>Cookie settings:</strong>
Cookie settings per Chrome and Firefox update in 2021:</p>
<ul>
<li><code>SameSite=None</code></li>
<li><code>Secure</code></li>
</ul>
<p>When doing <code>SameSite=None</code>, setting <code>Secure</code> is a requirement. See docs on <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite" rel="nofollow noreferrer">SameSite</a> and on requirement of <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#samesitenone_requires_secure" rel="nofollow noreferrer">Secure</a>. Also note that Chrome devtools now have improved filtering and highlighting of problems with cookies in the Network tab and Application tab.</p>
<p>Tip: If you are testing locally using localhost, you can use the excellent <a href="https://github.com/FiloSottile/mkcert" rel="nofollow noreferrer">mkcert</a> library to run localhost using https which will help with the <code>secure</code> requirement. There even are <a href="https://github.com/liuweiGL/vite-plugin-mkcert" rel="nofollow noreferrer">mkcert libraries</a> for popular frontend tools such as vite</p>
<p><strong>Front-end (client):</strong> Set the <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials" rel="nofollow noreferrer"><code>XMLHttpRequest.withCredentials</code></a> flag to <code>true</code>, this can be achieved in different ways depending on the request-response library used:</p>
<ul>
<li><p><a href="https://stackoverflow.com/a/7190487/2237467"><strong>jQuery 1.5.1</strong></a> <code>xhrFields: {withCredentials: true}</code></p>
</li>
<li><p><a href="https://stackoverflow.com/a/40543547/2237467"><strong>ES6 fetch()</strong></a> <code>credentials: 'include'</code></p>
</li>
<li><p><a href="https://stackoverflow.com/a/40543547/2237467"><strong>axios</strong></a>: <code>withCredentials: true</code></p>
</li>
</ul>
<h2>Proxy approach</h2>
<p>Avoid having to do cross site (CORS) stuff altogether. You can achieve this with a proxy. Simply send all traffic to the same top level domain name and route using DNS (subdomain) and/or load balancing. With Nginx this is relatively little effort.</p>
<p>This approach is a perfect marriage with JAMStack. JAMStack dictates API and Webapp code to be completely decoupled by design. More and more users block 3rd party cookies. If API and Webapp can easily be served on the same host, the 3rd party problem (cross site / CORS) dissolves. Read about JAMStack <a href="https://jamstack.org/" rel="nofollow noreferrer">here</a> or <a href="https://www.cloudflare.com/learning/performance/what-is-jamstack/" rel="nofollow noreferrer">here</a>.</p>
<h2>Sidenote</h2>
<p>It turned out that Chrome won't set the cookie if the domain contains a port. Setting it for <code>localhost</code> (without port) is not a problem. Many thanks to <a href="https://stackoverflow.com/users/2609980/erwin-rooijakkers">Erwin</a> for this tip!</p> | {
"question_id": 46288437,
"question_date": "2017-09-18T21:23:57.730Z",
"question_score": 215,
"tags": "authentication|cookies|cors|http-headers|localhost",
"answer_id": 46412839,
"answer_date": "2017-09-25T19:32:23.283Z",
"answer_score": 342
} |
Please answer the following Stack Overflow question:
Title: Child with max-height: 100% overflows parent
<p>I'm trying to understand what appears to be unexpected behaviour to me:</p>
<p>I have an element with a max-height of 100% inside a container that also uses a max-height but, unexpectedly, the child overflows the parent: </p>
<p>Test case: <a href="http://jsfiddle.net/bq4Wu/16/" rel="noreferrer">http://jsfiddle.net/bq4Wu/16/</a></p>
<pre><code>.container {
background: blue;
padding: 10px;
max-height: 200px;
max-width: 200px;
}
img {
display: block;
max-height: 100%;
max-width: 100%;
}
</code></pre>
<p>This is fixed, however, if the parent is given an explicit height: </p>
<p>Test case: <a href="http://jsfiddle.net/bq4Wu/17/" rel="noreferrer">http://jsfiddle.net/bq4Wu/17/</a></p>
<pre><code>.container {
height: 200px;
}
</code></pre>
<p>Does anyone know why the child would not honour the max-height of its parent in the first example? Why is an explicit height required?</p> | <p>When you specify a percentage for <code>max-height</code> on a child, it is a percentage of the parent's actual height, not the parent's <code>max-height</code>, <a href="http://www.w3.org/TR/CSS21/visudet.html#min-max-heights" rel="noreferrer">oddly enough</a>. The same applies to <a href="http://www.w3.org/TR/CSS21/visudet.html#min-max-widths" rel="noreferrer"><code>max-width</code></a>.</p>
<p>So, when you don't specify an explicit height on the parent, then there's no base height for the child's <code>max-height</code> to be calculated from, so <code>max-height</code> computes to <code>none</code>, allowing the child to be as tall as possible. The only other constraint acting on the child now is the <code>max-width</code> of its parent, and since the image itself is taller than it is wide, it overflows the container's height downwards, in order to maintain its aspect ratio while still being as large as possible overall.</p>
<p>When you <em>do</em> specify an explicit height for the parent, then the child knows it has to be at most 100% of that explicit height. That allows it to be constrained to the parent's height (while still maintaining its aspect ratio).</p> | {
"question_id": 14262938,
"question_date": "2013-01-10T16:44:08.850Z",
"question_score": 215,
"tags": "css",
"answer_id": 14263416,
"answer_date": "2013-01-10T17:11:21.453Z",
"answer_score": 328
} |
Please answer the following Stack Overflow question:
Title: In SQL, how can you "group by" in ranges?
<p>Suppose I have a table with a numeric column (lets call it "score").</p>
<p>I'd like to generate a table of counts, that shows how many times scores appeared in each range.</p>
<p>For example:</p>
<pre>
score range | number of occurrences
-------------------------------------
0-9 | 11
10-19 | 14
20-29 | 3
... | ...
</pre>
<p>In this example there were 11 rows with scores in the range of 0 to 9, 14 rows with scores in the range of 10 to 19, and 3 rows with scores in the range 20-29.</p>
<p>Is there an easy way to set this up? What do you recommend?</p> | <p>Neither of the highest voted answers are correct on SQL Server 2000. Perhaps they were using a different version.</p>
<p>Here are the correct versions of both of them on SQL Server 2000.</p>
<pre><code>select t.range as [score range], count(*) as [number of occurences]
from (
select case
when score between 0 and 9 then ' 0- 9'
when score between 10 and 19 then '10-19'
else '20-99' end as range
from scores) t
group by t.range
</code></pre>
<p>or</p>
<pre><code>select t.range as [score range], count(*) as [number of occurrences]
from (
select user_id,
case when score >= 0 and score< 10 then '0-9'
when score >= 10 and score< 20 then '10-19'
else '20-99' end as range
from scores) t
group by t.range
</code></pre> | {
"question_id": 232387,
"question_date": "2008-10-24T03:26:27.310Z",
"question_score": 215,
"tags": "sql|sql-server|tsql",
"answer_id": 233223,
"answer_date": "2008-10-24T12:01:46.510Z",
"answer_score": 168
} |
Please answer the following Stack Overflow question:
Title: What is the difference between 'java', 'javaw', and 'javaws'?
<p>What is the difference between <code>java</code>, <code>javaw</code>, and <code>javaws</code>?</p>
<p>I have found that on Windows most usage of Java is done using <code>javaw</code>.</p> | <p>See Java tools documentation for:</p>
<ul>
<li><a href="http://download.oracle.com/javase/8/docs/technotes/tools/windows/java.html" rel="noreferrer"><code>java</code> command<sup>1</sup>/<code>javaw</code> command<sup>2</sup></a></li>
</ul>
<blockquote>
<ol>
<li>The <strong><code>java</code></strong> tool launches a Java application. It does this by starting a Java runtime environment, loading a specified class, and invoking that class's <code>main</code> method.</li>
<li>The <strong><code>javaw</code></strong> command is identical to <code>java</code>, except that with <code>javaw</code> there is no associated console window. Use <code>javaw</code> when you <em><strong>don't</strong> want a command prompt window to appear.</em></li>
</ol>
</blockquote>
<ul>
<li><a href="http://docs.oracle.com/javase/7/docs/technotes/tools/share/javaws.html" rel="noreferrer"><code>javaws</code> command</a>, the <em>"<a href="https://stackoverflow.com/tags/java-web-start/info">Java Web Start</a> command"</em></li>
</ul>
<blockquote>
<p>The <code>javaws</code> command launches Java Web Start, which is the reference implementation of the Java Network Launching Protocol (JNLP). Java Web Start launches Java applications/applets hosted on a network. <br/> <br/>
If a JNLP file is specified, <code>javaws</code> will launch the Java application/applet specified in the JNLP file.<br><br>
The <code>javaws</code> launcher has a set of options that are supported in the current release. However, the options may be removed in a future release.</p>
</blockquote>
<p>See also <a href="http://www.oracle.com/technetwork/java/javase/9-deprecated-features-3745636.html" rel="noreferrer">JDK 9 Release Notes
Deprecated APIs, Features, and Options</a>:</p>
<blockquote>
<p><b>Java Deployment Technologies are deprecated and will be removed in a future release</b> <br/>
Java Applet and WebStart functionality, including the Applet API, the Java plug-in, the Java Applet Viewer, JNLP and Java Web Start, including the <strong><code>javaws</code> tool</strong>, are all <strong>deprecated in JDK 9</strong> and will be removed in a future release.</p>
</blockquote> | {
"question_id": 8194713,
"question_date": "2011-11-19T14:35:41.437Z",
"question_score": 215,
"tags": "java|java-web-start|javaw",
"answer_id": 8194750,
"answer_date": "2011-11-19T14:43:48.327Z",
"answer_score": 247
} |
Please answer the following Stack Overflow question:
Title: Opening the Settings app from another app
<p>Okay, I know that there are many question about it, but they are all from many time ago.</p>
<p>So. I know that it is possible because the Map app does it.</p>
<p>In the Map app if I turn off the localization for this app, it send me a message, and if I press okay, the "Settings App" will be open.
And my question is, how is this possible?
How can I open the "Setting app" from my own app?</p>
<p>Basically I need to do the same thing, if the user turn off the location for my app, then I'll show him a message saying something that will open the "Setting app"</p> | <p>As mentioned by <a href="https://stackoverflow.com/a/24952919/418715">Karan Dua</a> this is <a href="https://developer.apple.com/library/ios/releasenotes/General/WhatsNewIniOS/Articles/iOS8.html" rel="noreferrer">now possible in iOS8</a> using <code>UIApplicationOpenSettingsURLString</code> see <a href="https://developer.apple.com/documentation/uikit/uiapplicationopensettingsurlstring" rel="noreferrer">Apple's Documentation</a>.</p>
<p><strong>Example:</strong></p>
<p><strong>Swift 4.2</strong></p>
<pre><code>UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
</code></pre>
<p><em>In Swift 3:</em></p>
<pre><code>UIApplication.shared.open(URL(string:UIApplicationOpenSettingsURLString)!)
</code></pre>
<p><em>In Swift 2:</em></p>
<pre><code>UIApplication.sharedApplication().openURL(NSURL(string:UIApplicationOpenSettingsURLString)!)
</code></pre>
<p><em>In Objective-C</em></p>
<pre><code>[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
</code></pre>
<p><strong>Prior to iOS 8:</strong></p>
<p>You can not. As you said this has been covered many times and that pop up asking you to turn on location services is supplied by Apple and not by the App itself. That is why it is able to the open the settings application.</p>
<p>Here are a few related questions & articles:</p>
<p><a href="https://stackoverflow.com/questions/1090373/is-it-possible-to-open-settings-app-using-openurl">is it possible to open Settings App using openURL?</a></p>
<p><a href="https://stackoverflow.com/questions/736047/programmatically-opening-the-settings-app-iphone">Programmatically opening the settings app (iPhone)</a></p>
<p><a href="https://stackoverflow.com/questions/4092162/how-can-i-open-the-settings-app-when-the-user-presses-a-button">How can I open the Settings app when the user presses a button?</a></p>
<p><a href="https://stackoverflow.com/questions/3113391/iphone-opening-application-preferences-panel-from-app">iPhone: Opening Application Preferences Panel From App</a></p>
<p><a href="https://stackoverflow.com/questions/2127769/open-uipickerview-by-clicking-on-an-entry-in-the-apps-preferences-how-to">Open UIPickerView by clicking on an entry in the app's preferences - How to?</a></p>
<p><a href="https://stackoverflow.com/questions/4942974/open-settings-app">Open the Settings app?</a></p>
<p><a href="https://www.natashatherobot.com/ios-taking-the-user-to-settings/" rel="noreferrer">iOS: You’re Doing Settings Wrong</a></p> | {
"question_id": 5655674,
"question_date": "2011-04-13T21:10:29.990Z",
"question_score": 215,
"tags": "ios|objective-c|iphone|application-settings|appsettings",
"answer_id": 5655727,
"answer_date": "2011-04-13T21:15:10.880Z",
"answer_score": 347
} |
Please answer the following Stack Overflow question:
Title: How do I get a plist as a Dictionary in Swift?
<p>I am playing around with Apple's new <strong>Swift</strong> programming language and have some problems...</p>
<p>Currently I'm trying to read a plist file, in Objective-C I would do the following to get the content as a NSDictionary:</p>
<pre><code>NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Config" ofType:@"plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:filePath];
</code></pre>
<p>How do I get a plist as a Dictionary in Swift?</p>
<p>I assume I can get the path to the plist with:</p>
<pre><code>let path = NSBundle.mainBundle().pathForResource("Config", ofType: "plist")
</code></pre>
<p>When this works (If it's correct?): How do I get the content as a Dictionary?</p>
<p>Also a more general question:</p>
<p>Is it OK to use the default <strong>NS*</strong> classes? I think so...or am I missing something? As far as I know the default framework <strong>NS*</strong> classes are still valid and alright to use?</p> | <p>In <strong><em>swift 3.0</em></strong> Reading from Plist.</p>
<pre><code>func readPropertyList() {
var propertyListFormat = PropertyListSerialization.PropertyListFormat.xml //Format of the Property List.
var plistData: [String: AnyObject] = [:] //Our data
let plistPath: String? = Bundle.main.path(forResource: "data", ofType: "plist")! //the path of the data
let plistXML = FileManager.default.contents(atPath: plistPath!)!
do {//convert the data to a dictionary and handle errors.
plistData = try PropertyListSerialization.propertyList(from: plistXML, options: .mutableContainersAndLeaves, format: &propertyListFormat) as! [String:AnyObject]
} catch {
print("Error reading plist: \(error), format: \(propertyListFormat)")
}
}
</code></pre>
<p><em>Read More
<a href="https://makeapppie.com/2016/02/11/how-to-use-property-lists-plist-in-swift/#comment-17173" rel="noreferrer">HOW TO USE PROPERTY LISTS (.PLIST) IN SWIFT</a>.</em></p> | {
"question_id": 24045570,
"question_date": "2014-06-04T19:05:17.653Z",
"question_score": 215,
"tags": "ios|swift",
"answer_id": 39453212,
"answer_date": "2016-09-12T14:54:35.720Z",
"answer_score": 61
} |
Please answer the following Stack Overflow question:
Title: PostgreSQL wildcard LIKE for any of a list of words
<p>I have a simple list of ~25 words. I have a varchar field in PostgreSQL, let's say that list is <code>['foo', 'bar', 'baz']</code>. I want to find any row in my table that has any of those words. This will work, but I'd like something more elegant.</p>
<pre><code>select *
from table
where (lower(value) like '%foo%' or lower(value) like '%bar%' or lower(value) like '%baz%')
</code></pre> | <p>You can use Postgres' <a href="http://www.postgresql.org/docs/9.0/interactive/functions-matching.html#FUNCTIONS-SIMILARTO-REGEXP" rel="noreferrer"><code>SIMILAR TO</code></a> operator which supports alternations, i.e. </p>
<pre><code>select * from table where lower(value) similar to '%(foo|bar|baz)%';
</code></pre> | {
"question_id": 4928054,
"question_date": "2011-02-07T23:43:29.313Z",
"question_score": 215,
"tags": "sql|postgresql",
"answer_id": 4928155,
"answer_date": "2011-02-07T23:59:33Z",
"answer_score": 213
} |
Please answer the following Stack Overflow question:
Title: Get the generated SQL statement from a SqlCommand object?
<p>I have the following code:</p>
<pre><code>Using cmd As SqlCommand = Connection.CreateCommand
cmd.CommandText = "UPDATE someTable SET Value = @Value"
cmd.CommandText &= " WHERE Id = @Id"
cmd.Parameters.AddWithValue("@Id", 1234)
cmd.Parameters.AddWithValue("@Value", "myValue")
cmd.ExecuteNonQuery
End Using
</code></pre>
<p>I wonder if there is any way to get the final SQL statment as a String, which should look like this:</p>
<pre class="lang-sql prettyprint-override"><code>UPDATE someTable SET Value = "myValue" WHERE Id = 1234
</code></pre>
<p>If anyone wonders why I would do this:</p>
<ul>
<li>for logging (failed) statements</li>
<li>for having the possibility to copy & paste it to the Enterprise Manager for testing purposes</li>
</ul> | <p>Whilst not perfect, here's something I knocked up for TSQL - could be easily tweaked for other flavors... If nothing else it will give you a start point for your own improvements :)</p>
<p>This does an OK job on data types and output parameters etc similar to using "execute stored procedure" in SSMS. We mostly used SPs so the "text" command doesn't account for parameters etc</p>
<pre><code> public static String ParameterValueForSQL(this SqlParameter sp)
{
String retval = "";
switch (sp.SqlDbType)
{
case SqlDbType.Char:
case SqlDbType.NChar:
case SqlDbType.NText:
case SqlDbType.NVarChar:
case SqlDbType.Text:
case SqlDbType.Time:
case SqlDbType.VarChar:
case SqlDbType.Xml:
case SqlDbType.Date:
case SqlDbType.DateTime:
case SqlDbType.DateTime2:
case SqlDbType.DateTimeOffset:
retval = "'" + sp.Value.ToString().Replace("'", "''") + "'";
break;
case SqlDbType.Bit:
retval = (sp.Value.ToBooleanOrDefault(false)) ? "1" : "0";
break;
default:
retval = sp.Value.ToString().Replace("'", "''");
break;
}
return retval;
}
public static String CommandAsSql(this SqlCommand sc)
{
StringBuilder sql = new StringBuilder();
Boolean FirstParam = true;
sql.AppendLine("use " + sc.Connection.Database + ";");
switch (sc.CommandType)
{
case CommandType.StoredProcedure:
sql.AppendLine("declare @return_value int;");
foreach (SqlParameter sp in sc.Parameters)
{
if ((sp.Direction == ParameterDirection.InputOutput) || (sp.Direction == ParameterDirection.Output))
{
sql.Append("declare " + sp.ParameterName + "\t" + sp.SqlDbType.ToString() + "\t= ");
sql.AppendLine(((sp.Direction == ParameterDirection.Output) ? "null" : sp.ParameterValueForSQL()) + ";");
}
}
sql.AppendLine("exec [" + sc.CommandText + "]");
foreach (SqlParameter sp in sc.Parameters)
{
if (sp.Direction != ParameterDirection.ReturnValue)
{
sql.Append((FirstParam) ? "\t" : "\t, ");
if (FirstParam) FirstParam = false;
if (sp.Direction == ParameterDirection.Input)
sql.AppendLine(sp.ParameterName + " = " + sp.ParameterValueForSQL());
else
sql.AppendLine(sp.ParameterName + " = " + sp.ParameterName + " output");
}
}
sql.AppendLine(";");
sql.AppendLine("select 'Return Value' = convert(varchar, @return_value);");
foreach (SqlParameter sp in sc.Parameters)
{
if ((sp.Direction == ParameterDirection.InputOutput) || (sp.Direction == ParameterDirection.Output))
{
sql.AppendLine("select '" + sp.ParameterName + "' = convert(varchar, " + sp.ParameterName + ");");
}
}
break;
case CommandType.Text:
sql.AppendLine(sc.CommandText);
break;
}
return sql.ToString();
}
</code></pre>
<p>this generates output along these lines...</p>
<pre><code>use dbMyDatabase;
declare @return_value int;
declare @OutTotalRows BigInt = null;
exec [spMyStoredProc]
@InEmployeeID = 1000686
, @InPageSize = 20
, @InPage = 1
, @OutTotalRows = @OutTotalRows output
;
select 'Return Value' = convert(varchar, @return_value);
select '@OutTotalRows' = convert(varchar, @OutTotalRows);
</code></pre> | {
"question_id": 265192,
"question_date": "2008-11-05T14:01:34.563Z",
"question_score": 215,
"tags": "c#|vb.net|ado.net",
"answer_id": 4146573,
"answer_date": "2010-11-10T16:22:34.313Z",
"answer_score": 126
} |
Please answer the following Stack Overflow question:
Title: How to put space character into a string name in XML?
<p>i have defined some strings in the <code>strings.xml</code> file. Now I need to put some extra space between some numbers in the string. When I type extra space characters this is not showing on the application though.</p>
<p>Before:</p>
<pre><code><string name="spelatonertext3">-4, 5, -5, 6, -6,
</code></pre>
<p>And if I put extra space like this:</p>
<pre><code><string name="spelatonertext3">-4, 5, -5, 6, -6,
</code></pre>
<p>It just looks the same on the app. How can I make space characters into the XML string?</p> | <p>to use white space in xml as string use <code>&#160;</code>. XML won't take white space as it is. it will trim the white space before setting it. So use <code>&#160;</code> instead of single white space </p> | {
"question_id": 10862975,
"question_date": "2012-06-02T14:13:34.527Z",
"question_score": 215,
"tags": "android|xml|whitespace",
"answer_id": 10862999,
"answer_date": "2012-06-02T14:17:15.997Z",
"answer_score": 478
} |
Please answer the following Stack Overflow question:
Title: Initializing C# auto-properties
<p>I'm used to writing classes like this:</p>
<pre><code>public class foo {
private string mBar = "bar";
public string Bar {
get { return mBar; }
set { mBar = value; }
}
//... other methods, no constructor ...
}
</code></pre>
<p>Converting Bar to an auto-property seems convenient and concise, but how can I retain the initialization without adding a constructor and putting the initialization in there?</p>
<pre><code>public class foo2theRevengeOfFoo {
//private string mBar = "bar";
public string Bar { get; set; }
//... other methods, no constructor ...
//behavior has changed.
}
</code></pre>
<p>You could see that adding a constructor isn't inline with the effort savings I'm supposed to be getting from auto-properties.</p>
<p>Something like this would make more sense to me:</p>
<pre><code>public string Bar { get; set; } = "bar";
</code></pre> | <p>Update - the answer below was written before C# 6 came along. In C# 6 you can write:</p>
<pre><code>public class Foo
{
public string Bar { get; set; } = "bar";
}
</code></pre>
<p>You can <em>also</em> write read-only automatically-implemented properties, which are only writable in the constructor (but can also be given a default initial value):</p>
<pre><code>public class Foo
{
public string Bar { get; }
public Foo(string bar)
{
Bar = bar;
}
}
</code></pre>
<hr />
<p>It's unfortunate that there's no way of doing this right now. You have to set the value in the constructor. (Using constructor chaining can help to avoid duplication.)</p>
<p>Automatically implemented properties are handy right now, but could certainly be nicer. I don't find myself wanting this sort of initialization as often as a read-only automatically implemented property which could only be set in the constructor and would be backed by a read-only field.</p>
<p>This hasn't happened up until and including C# 5, but is being planned for C# 6 - both in terms of allowing initialization at the point of declaration, <em>and</em> allowing for read-only automatically implemented properties to be initialized in a constructor body.</p> | {
"question_id": 169220,
"question_date": "2008-10-03T22:59:53.393Z",
"question_score": 215,
"tags": "c#|initialization|automatic-properties",
"answer_id": 169872,
"answer_date": "2008-10-04T06:38:02.283Z",
"answer_score": 253
} |
Please answer the following Stack Overflow question:
Title: Tar archiving that takes input from a list of files
<p>I have a file that contain list of files I want to archive with tar.
Let's call it <code>mylist.txt</code></p>
<p>It contains:</p>
<pre><code>file1.txt
file2.txt
...
file10.txt
</code></pre>
<p>Is there a way I can issue TAR command that takes <code>mylist.txt</code> as input?
Something like</p>
<pre><code>tar -cvf allfiles.tar -[someoption?] mylist.txt
</code></pre>
<p>So that it is similar as if I issue this command:</p>
<pre><code>tar -cvf allfiles.tar file1.txt file2.txt file10.txt
</code></pre> | <p>Yes:</p>
<pre><code>tar -cvf allfiles.tar -T mylist.txt
</code></pre> | {
"question_id": 8033857,
"question_date": "2011-11-07T07:42:48.067Z",
"question_score": 215,
"tags": "linux|unix|archive|tar",
"answer_id": 8033898,
"answer_date": "2011-11-07T07:48:38.750Z",
"answer_score": 334
} |
Please answer the following Stack Overflow question:
Title: Difference between Visual Basic 6.0 and VBA
<p>What is the difference between the two. I always thought VBA is somewhat 'crippled' version of VB, but when a friend asked me the other day I had no idea what the actual differences are.</p>
<p>Also, when you use, for example, Excel, is that VB or VBA ?</p> | <p>For nearly all programming purposes, VBA and VB 6.0 are the same thing.</p>
<p>VBA cannot compile your program into an executable binary. You'll always need the host (a Word file and MS Word, for example) to contain and execute your project. You'll also not be able to create COM DLLs with VBA.</p>
<p>Apart from that, there is a difference in the IDE - the VB 6.0 IDE is more powerful in comparison. On the other hand, you have tight integration of the host application in VBA. Application-global objects (like "ActiveDocument") and events are available without declaration, so application-specific programming is straight-forward.</p>
<p>Still, nothing keeps you from firing up Word, loading the VBA IDE and solving a problem that has no relation to Word whatsoever. I'm not sure if there is anything that VB 6.0 can do (technically), and VBA cannot. I'm looking for a comparison sheet on the MSDN though.</p> | {
"question_id": 993300,
"question_date": "2009-06-14T17:43:27.620Z",
"question_score": 215,
"tags": "vba|vb6",
"answer_id": 993427,
"answer_date": "2009-06-14T18:28:44.327Z",
"answer_score": 182
} |
Please answer the following Stack Overflow question:
Title: Is there a CSS selector for text nodes?
<p>What I would like to do (not in IE obviously) is:</p>
<pre><code>p:not(.list):last-child + :text {
margin-bottom: 10px;
}
</code></pre>
<p>Which would give a text node a margin. (Is that even possible?) How would I get the text node with CSS?</p> | <p>Text nodes cannot have margins or any other style applied to them, so anything you need style applied to must be in an element. If you want some of the text inside of your element to be styled differently, wrap it in a <code>span</code> or <code>div</code>, for example.</p> | {
"question_id": 5688712,
"question_date": "2011-04-16T18:42:48.027Z",
"question_score": 215,
"tags": "css|css-selectors",
"answer_id": 5688758,
"answer_date": "2011-04-16T18:49:45.803Z",
"answer_score": 138
} |
Please answer the following Stack Overflow question:
Title: Can I map a hostname *and* a port with /etc/hosts?
<p>Can I map an IP address like <code>127.0.0.1</code> to a domain name <em>and</em> a port?</p>
<p>For example, I would like to map <code>127.0.0.1</code> to <code>api.example.com:8000</code></p> | <p>No, that's not possible. The port is not part of the hostname, so it has no meaning in the <code>hosts</code>-file.</p> | {
"question_id": 10729034,
"question_date": "2012-05-23T23:00:30.387Z",
"question_score": 215,
"tags": "linux|dns|port|hostname",
"answer_id": 10729058,
"answer_date": "2012-05-23T23:03:22.950Z",
"answer_score": 216
} |
Please answer the following Stack Overflow question:
Title: How to find the reason for a failed Build without any error or warning
<p>I have a WebApplication which contains reference to WCF services.</p>
<p>While building using Visual Studio 2010, Build fails without any error or warning. However building the <code>.csproj</code> using <code>MsBuild</code> is successful.</p>
<p>Can't figure out what should I try in Visual Studio, to resolve / diagnose the issue. Can you please help out?</p>
<p>I find out that the build has been failing,</p>
<ol>
<li><p>From text displayed in status Bar.<br />
<img src="https://i.stack.imgur.com/ZLAz9.jpg" alt="enter image description here" /></p>
</li>
<li><p>From output window:</p>
<pre><code> ========== Build: 0 succeeded or up-to-date, 1 failed, 0 skipped ==========
</code></pre>
<p>The output tab includes configuration details.</p>
<pre><code>------ Build started: Project: <projectName here> Configuration: Debug Any CPU
</code></pre>
</li>
</ol> | <p>I just ran into a similar situation. In my case, a custom action (from the MSBuildVersioning package available on Nuget.org - <a href="http://www.nuget.org/packages/MSBuildVersioning/" rel="noreferrer">http://www.nuget.org/packages/MSBuildVersioning/</a>) which appeared in the csproj file's BeforeBuild target was failing without triggering any error message in the normal place.</p>
<p>I was able to determine this by setting the <strong>"MSBuild project build output verbosity"</strong> (in the latest Visual Studio's Tools tab [Path: <strong>Tools > Options > Build and Run</strong>]) to "<strong>Diagnostic</strong>" as shown below. This then showed that the custom action (in my case HgVersionFile) was what had failed.</p>
<p><img src="https://i.stack.imgur.com/kLoTy.png" alt="Screen capture from Visual Studio showing the modified setting." /></p> | {
"question_id": 13239325,
"question_date": "2012-11-05T19:53:04.270Z",
"question_score": 215,
"tags": "c#|asp.net|.net|visual-studio",
"answer_id": 27425455,
"answer_date": "2014-12-11T14:42:35.703Z",
"answer_score": 167
} |
Please answer the following Stack Overflow question:
Title: How To Set A JS object property name from a variable
<p>I am in need to set a JS object property name dynamically.</p>
<pre><code>for(i=1; i<3; i++) {
var key = i+'name';
data = {
key : 'name1',
}
}
</code></pre>
<p>Result should be:</p>
<pre><code>data = {
1name: 'name1'
2name: 'name1'
}
</code></pre> | <pre><code>var jsonVariable = {};
for(var i=1; i < 3; i++) {
jsonVariable[i + 'name'] = 'name' + i;
}
</code></pre> | {
"question_id": 13833204,
"question_date": "2012-12-12T05:11:08.827Z",
"question_score": 215,
"tags": "javascript",
"answer_id": 13833241,
"answer_date": "2012-12-12T05:14:33.937Z",
"answer_score": 210
} |
Please answer the following Stack Overflow question:
Title: Good MapReduce examples
<p>I couldn't think of any good examples other than the "how to count words in a long text with MapReduce" task. I found this wasn't the best example to give others an impression of how powerful this tool can be.</p>
<p>I'm not looking for code-snippets, really just "textual" examples.</p> | <p>Map reduce is a framework that was developed to process massive amounts of data efficiently.
For example, if we have 1 million records in a dataset, and it is stored in a relational representation - it is very expensive to derive values and perform any sort of transformations on these. </p>
<p>For Example In SQL, Given the Date of Birth, to find out How many people are of age > 30 for a million records would take a while, and this would only increase in order of magnitute when the complexity of the query increases.
Map Reduce provides a cluster based implementation where data is processed in a distributed manner </p>
<p>Here is a wikipedia article explaining what <a href="http://en.wikipedia.org/wiki/MapReduce" rel="noreferrer"><code>map-reduce</code> is all about</a></p>
<p>Another good example is Finding Friends via map reduce can be a powerful example to understand the concept, and
a well used use-case.</p>
<p>Personally, found <a href="http://stevekrenzel.com/finding-friends-with-mapreduce" rel="noreferrer">this link</a> quite useful to understand the concept </p>
<p><em>Copying the explanation provided in the blog (In case the link goes stale)</em></p>
<blockquote>
<h1>Finding Friends</h1>
<p>MapReduce is a framework originally developed at Google that allows
for easy large scale distributed computing across a number of domains.
Apache Hadoop is an open source implementation.</p>
<p>I'll gloss over the details, but it comes down to defining two
functions: a map function and a reduce function. The map function
takes a value and outputs key:value pairs. For instance, if we define
a map function that takes a string and outputs the length of the word
as the key and the word itself as the value then map(steve) would
return 5:steve and map(savannah) would return 8:savannah. You may have
noticed that the map function is stateless and only requires the input
value to compute it's output value. This allows us to run the map
function against values in parallel and provides a huge advantage.
Before we get to the reduce function, the mapreduce framework groups
all of the values together by key, so if the map functions output the
following key:value pairs:</p>
<pre><code>3 : the
3 : and
3 : you
4 : then
4 : what
4 : when
5 : steve
5 : where
8 : savannah
8 : research
</code></pre>
<p>They get grouped as:</p>
<pre><code>3 : [the, and, you]
4 : [then, what, when]
5 : [steve, where]
8 : [savannah, research]
</code></pre>
<p>Each of these lines would then be passed as an argument to the reduce
function, which accepts a key and a list of values. In this instance,
we might be trying to figure out how many words of certain lengths
exist, so our reduce function will just count the number of items in
the list and output the key with the size of the list, like:</p>
<pre><code>3 : 3
4 : 3
5 : 2
8 : 2
</code></pre>
<p>The reductions can also be done in parallel, again providing a huge
advantage. We can then look at these final results and see that there
were only two words of length 5 in our corpus, etc...</p>
<p>The most common example of mapreduce is for counting the number of
times words occur in a corpus. Suppose you had a copy of the internet
(I've been fortunate enough to have worked in such a situation), and
you wanted a list of every word on the internet as well as how many
times it occurred.</p>
<p>The way you would approach this would be to tokenize the documents you
have (break it into words), and pass each word to a mapper. The mapper
would then spit the word back out along with a value of <code>1</code>. The
grouping phase will take all the keys (in this case words), and make a
list of 1's. The reduce phase then takes a key (the word) and a list
(a list of 1's for every time the key appeared on the internet), and
sums the list. The reducer then outputs the word, along with it's
count. When all is said and done you'll have a list of every word on
the internet, along with how many times it appeared.</p>
<p>Easy, right? If you've ever read about mapreduce, the above scenario
isn't anything new... it's the "Hello, World" of mapreduce. So here is
a real world use case (Facebook may or may not actually do the
following, it's just an example):</p>
<p>Facebook has a list of friends (note that friends are a bi-directional
thing on Facebook. If I'm your friend, you're mine). They also have
lots of disk space and they serve hundreds of millions of requests
everyday. They've decided to pre-compute calculations when they can to
reduce the processing time of requests. One common processing request
is the "You and Joe have 230 friends in common" feature. When you
visit someone's profile, you see a list of friends that you have in
common. This list doesn't change frequently so it'd be wasteful to
recalculate it every time you visited the profile (sure you could use
a decent caching strategy, but then I wouldn't be able to continue
writing about mapreduce for this problem). We're going to use
mapreduce so that we can calculate everyone's common friends once a
day and store those results. Later on it's just a quick lookup. We've
got lots of disk, it's cheap.</p>
<p>Assume the friends are stored as Person->[List of Friends], our
friends list is then:</p>
<pre><code>A -> B C D
B -> A C D E
C -> A B D E
D -> A B C E
E -> B C D
</code></pre>
<p>Each line will be an argument to a mapper. For every friend in the
list of friends, the mapper will output a key-value pair. The key will
be a friend along with the person. The value will be the list of
friends. The key will be sorted so that the friends are in order,
causing all pairs of friends to go to the same reducer. This is hard
to explain with text, so let's just do it and see if you can see the
pattern. After all the mappers are done running, you'll have a list
like this:</p>
<pre><code>For map(A -> B C D) :
(A B) -> B C D
(A C) -> B C D
(A D) -> B C D
For map(B -> A C D E) : (Note that A comes before B in the key)
(A B) -> A C D E
(B C) -> A C D E
(B D) -> A C D E
(B E) -> A C D E
For map(C -> A B D E) :
(A C) -> A B D E
(B C) -> A B D E
(C D) -> A B D E
(C E) -> A B D E
For map(D -> A B C E) :
(A D) -> A B C E
(B D) -> A B C E
(C D) -> A B C E
(D E) -> A B C E
And finally for map(E -> B C D):
(B E) -> B C D
(C E) -> B C D
(D E) -> B C D
Before we send these key-value pairs to the reducers, we group them by their keys and get:
(A B) -> (A C D E) (B C D)
(A C) -> (A B D E) (B C D)
(A D) -> (A B C E) (B C D)
(B C) -> (A B D E) (A C D E)
(B D) -> (A B C E) (A C D E)
(B E) -> (A C D E) (B C D)
(C D) -> (A B C E) (A B D E)
(C E) -> (A B D E) (B C D)
(D E) -> (A B C E) (B C D)
</code></pre>
<p>Each line will be passed as an argument to a reducer. The reduce
function will simply intersect the lists of values and output the same
key with the result of the intersection. For example, reduce((A B) ->
(A C D E) (B C D)) will output (A B) : (C D) and means that friends A
and B have C and D as common friends.</p>
<p>The result after reduction is:</p>
<pre><code>(A B) -> (C D)
(A C) -> (B D)
(A D) -> (B C)
(B C) -> (A D E)
(B D) -> (A C E)
(B E) -> (C D)
(C D) -> (A B E)
(C E) -> (B D)
(D E) -> (B C)
</code></pre>
<p>Now when D visits B's profile, we can quickly look up <code>(B D)</code> and see
that they have three friends in common, <code>(A C E)</code>.</p>
</blockquote> | {
"question_id": 12375761,
"question_date": "2012-09-11T18:31:21.213Z",
"question_score": 215,
"tags": "mapreduce",
"answer_id": 12375878,
"answer_date": "2012-09-11T18:37:24.077Z",
"answer_score": 314
} |
Please answer the following Stack Overflow question:
Title: How to symbolicate crash log Xcode?
<p>Xcode 5 organizer had a view which would list all the crash logs. and we could drag drop crash logs here. But since Xcode 6, I know they have moved devices out of organize and have a new window for the same. But I do not find a place where I view the crash logs which i drag-dropped in Xcode 5 after upping to Xcode 6. Anybody knows the answer ?</p> | <p>Ok I realised that you can do this:</p>
<ol>
<li>In <code>Xcode > Window > Devices</code>, select a connected iPhone/iPad/etc top left.</li>
<li>View Device Logs</li>
<li>All Logs</li>
</ol>
<p>You probably have a lot of logs there, and to make it easier to find your imported log later, you could just go ahead and delete all logs at this point... unless they mean money to you. Or unless you know the exact point of time the crash happened - it should be written in the file anyway... I'm lazy so I just delete all old logs (this actually took a while).</p>
<ol start="4">
<li>Just drag and drop your file into that list. It worked for me.</li>
</ol> | {
"question_id": 25855389,
"question_date": "2014-09-15T19:22:02.297Z",
"question_score": 215,
"tags": "ios|xcode",
"answer_id": 25927122,
"answer_date": "2014-09-19T05:43:26.963Z",
"answer_score": 131
} |
Please answer the following Stack Overflow question:
Title: How to change the name of a Django app?
<p>I have changed the name of an app in Django by renaming its folder, imports and all its references (templates/indexes). But now I get this error when I try to run <code>python manage.py runserver</code></p>
<pre><code>Error: Could not import settings 'nameofmynewapp.settings' (Is it on sys.path?): No module named settings
</code></pre>
<p>How can I debug and solve this error? Any clues?</p> | <p>Follow these steps to change an app's name in Django:</p>
<ol>
<li>Rename the folder which is in your project root</li>
<li>Change any references to your app in their dependencies, i.e. the app's <code>views.py</code>, <code>urls.py</code> , <code>manage.py</code> , and <code>settings.py</code> files.</li>
<li>Edit the database table <code>django_content_type</code> with the following command: <code>UPDATE django_content_type SET app_label='<NewAppName>' WHERE app_label='<OldAppName>'</code></li>
<li>Also, if you have models, you will have to rename the model tables. For postgres, use <code>ALTER TABLE <oldAppName>_modelName RENAME TO <newAppName>_modelName</code>. For mysql too, I think it is the same (as mentioned by @null_radix).</li>
<li>(For Django >= 1.7) Update the <code>django_migrations</code> table to avoid having your previous migrations re-run: <code>UPDATE django_migrations SET app='<NewAppName>' WHERE app='<OldAppName>'</code>. <strong>Note</strong>: there is some debate (in comments) if this step is required for Django 1.8+; If someone knows for sure please update here.</li>
<li>If your <code>models.py</code> 's Meta Class has <code>app_name</code> listed, make sure to rename that too (mentioned by @will).</li>
<li>If you've namespaced your <code>static</code> or <code>templates</code> folders inside your app, you'll also need to rename those. For example, rename <code>old_app/static/old_app</code> to <code>new_app/static/new_app</code>.</li>
<li>For renaming django <code>models</code>, you'll need to change <code>django_content_type.name</code> entry in DB. For postgreSQL, use <code>UPDATE django_content_type SET name='<newModelName>' where name='<oldModelName>' AND app_label='<OldAppName>'</code></li>
<li><strong>Update 16Jul2021</strong>: Also, the <code>__pycache__/</code> folder inside the app must be removed, otherwise you get <code>EOFError: marshal data too short when trying to run the server</code>. Mentioned by @Serhii Kushchenko</li>
</ol>
<p><strong>Meta point (If using virtualenv):</strong> Worth noting, if you are renaming the directory that contains your virtualenv, there will likely be several files in your env that contain an absolute path and will also need to be updated. If you are getting errors such as <code>ImportError: No module named ...</code> this might be the culprit. (thanks to @danyamachine for providing this).</p>
<p><strong>Other references:</strong> you might also want to refer to the below links for a more complete picture:</p>
<ol>
<li><a href="https://stackoverflow.com/questions/4566978/renaming-an-app-with-django-and-south">Renaming an app with Django and South</a></li>
<li><a href="https://stackoverflow.com/questions/1258130/how-do-i-migrate-a-model-out-of-one-django-app-and-into-a-new-one">How do I migrate a model out of one django app and into a new one?</a></li>
<li><a href="https://stackoverflow.com/questions/8408046/how-to-change-the-name-of-a-django-app?noredirect=1&lq=1">How to change the name of a Django app?</a></li>
<li><a href="https://stackoverflow.com/questions/5814190/backwards-migration-with-django-south?rq=1">Backwards migration with Django South</a></li>
<li><a href="https://stackoverflow.com/questions/2862979/easiest-way-to-rename-a-model-using-django-south?rq=1">Easiest way to rename a model using Django/South?</a></li>
<li><a href="https://github.com/amirraouf/change-django-app-name" rel="noreferrer">Python code</a> (thanks to <a href="https://stackoverflow.com/users/1690893/a-raouf">A.Raouf</a>) to automate the above steps (Untested code. You have been warned!)</li>
<li><a href="https://gist.github.com/rafaponieman/201054ddf725cda1e60be3fe845850a5" rel="noreferrer">Python code</a> (thanks to <a href="https://stackoverflow.com/users/2453104/rafaponieman">rafaponieman</a>) to automate the above steps (Untested code. You have been warned!)</li>
</ol> | {
"question_id": 8408046,
"question_date": "2011-12-06T22:51:04.023Z",
"question_score": 215,
"tags": "python|django",
"answer_id": 8408131,
"answer_date": "2011-12-06T22:59:12.303Z",
"answer_score": 383
} |
Please answer the following Stack Overflow question:
Title: What is @RenderSection in asp.net MVC
<p>What is the purpose of @RenderSection and how does it function? I understand what bundles do, but I have yet to figure out what this does and it's probably important.</p>
<pre><code>@RenderSection("scripts", required: false)
</code></pre>
<p>Perhaps a small example on how to use it?</p> | <p>If you have a _Layout.cshtml view like this</p>
<pre><code><html>
<body>
@RenderBody()
@RenderSection("scripts", required: false)
</body>
</html>
</code></pre>
<p>then you can have an index.cshtml content view like this</p>
<pre><code>@section scripts {
<script type="text/javascript">alert('hello');</script>
}
</code></pre>
<p>the <em>required</em> indicates whether or not the view using the layout page must have a scripts section</p> | {
"question_id": 23327578,
"question_date": "2014-04-27T18:55:23.350Z",
"question_score": 215,
"tags": "asp.net-mvc",
"answer_id": 23327673,
"answer_date": "2014-04-27T19:03:19.297Z",
"answer_score": 341
} |
Please answer the following Stack Overflow question:
Title: How do I hide the status bar in a Swift iOS app?
<p>I'd like to remove the status bar at the top of the screen.</p>
<p>This does not work:</p>
<pre><code>func application
(application: UIApplication,
didFinishLaunchingWithOptions launchOptions: NSDictionary?)
-> Bool
{
application.statusBarHidden = true
return true
}
</code></pre>
<p>I've also tried:</p>
<pre><code>func application
(application: UIApplication,
didFinishLaunchingWithOptions launchOptions: NSDictionary?)
-> Bool
{
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
var controller = UIViewController()
application.statusBarHidden = true
controller.setNeedsStatusBarAppearanceUpdate()
var view = UIView(frame: CGRectMake(0, 0, 320, 568))
view.backgroundColor = UIColor.redColor()
controller.view = view
var label = UILabel(frame: CGRectMake(0, 0, 200, 21))
label.center = CGPointMake(160, 284)
label.textAlignment = NSTextAlignment.Center
label.text = "Hello World"
controller.view.addSubview(label)
self.window!.rootViewController = controller
self.window!.makeKeyAndVisible()
return true
}
</code></pre> | <p>You really should implement prefersStatusBarHidden on your view controller(s):</p>
<p><strong>Swift 3 and later</strong></p>
<pre><code>override var prefersStatusBarHidden: Bool {
return true
}
</code></pre> | {
"question_id": 24236912,
"question_date": "2014-06-16T05:04:05.293Z",
"question_score": 215,
"tags": "ios|iphone|ios7|swift",
"answer_id": 24236943,
"answer_date": "2014-06-16T05:08:10.460Z",
"answer_score": 473
} |
Please answer the following Stack Overflow question:
Title: How to initialize std::vector from C-style array?
<p>What is the cheapest way to initialize a <code>std::vector</code> from a C-style array?</p>
<p>Example: In the following class, I have a <code>vector</code>, but due to outside restrictions, the data will be passed in as C-style array:</p>
<pre><code>class Foo {
std::vector<double> w_;
public:
void set_data(double* w, int len){
// how to cheaply initialize the std::vector?
}
</code></pre>
<p>Obviously, I can call <code>w_.resize()</code> and then loop over the elements, or call <code>std::copy()</code>. Are there any better methods?</p> | <p>Don't forget that you can treat pointers as iterators:</p>
<pre><code>w_.assign(w, w + len);
</code></pre> | {
"question_id": 2434196,
"question_date": "2010-03-12T16:37:08.943Z",
"question_score": 215,
"tags": "c++|arrays|vector|stl",
"answer_id": 2434208,
"answer_date": "2010-03-12T16:38:36.943Z",
"answer_score": 287
} |
Please answer the following Stack Overflow question:
Title: Import local function from a module housed in another directory with relative imports in Jupyter Notebook using Python 3
<p>I have a directory structure similar to the following</p>
<pre><code>meta_project
project1
__init__.py
lib
module.py
__init__.py
notebook_folder
notebook.jpynb
</code></pre>
<p>When working in <code>notebook.jpynb</code> if I try to use a relative import to access a function <code>function()</code> in <code>module.py</code> with:</p>
<pre><code>from ..project1.lib.module import function
</code></pre>
<p>I get the following error:</p>
<pre><code>SystemError Traceback (most recent call last)
<ipython-input-7-6393744d93ab> in <module>()
----> 1 from ..project1.lib.module import function
SystemError: Parent module '' not loaded, cannot perform relative import
</code></pre>
<p>Is there any way to get this to work using relative imports? </p>
<p>Note, the notebook server is instantiated at the level of the <code>meta_project</code> directory, so it should have access to the information in those files. </p>
<p>Note, also, that at least as originally intended <code>project1</code> wasn't thought of as a module and therefore does not have an <code>__init__.py</code> file, it was just meant as a file-system directory. If the solution to the problem requires treating it as a module and including an <code>__init__.py</code> file (even a blank one) that is fine, but doing so is not enough to solve the problem.</p>
<p>I share this directory between machines and relative imports allow me to use the same code everywhere, & I often use notebooks for quick prototyping, so suggestions that involve hacking together absolute paths are unlikely to be helpful.</p>
<hr>
<p>Edit: This is unlike <a href="https://stackoverflow.com/questions/16981921/relative-imports-in-python-3">Relative imports in Python 3</a>, which talks about relative imports in Python 3 in general and – in particular – running a script from within a package directory. This has to do with working within a jupyter notebook trying to call a function in a local module in another directory which has both different general and particular aspects. </p> | <p>I had almost the same example as you in <a href="https://github.com/qPRC/qPRC/blob/master/notebook/qPRC.ipynb" rel="noreferrer">this notebook</a> where I wanted to illustrate the usage of an adjacent module's function in a DRY manner.</p>
<p>My solution was to tell Python of that additional module import path by adding a snippet like this one to the notebook:</p>
<pre><code>import os
import sys
module_path = os.path.abspath(os.path.join('..'))
if module_path not in sys.path:
sys.path.append(module_path)
</code></pre>
<p>This allows you to import the desired function from the module hierarchy:</p>
<pre><code>from project1.lib.module import function
# use the function normally
function(...)
</code></pre>
<p>Note that it is necessary to add empty <code>__init__.py</code> files to <em>project1/</em> and <em>lib/</em> folders if you don't have them already.</p> | {
"question_id": 34478398,
"question_date": "2015-12-27T07:14:20.233Z",
"question_score": 215,
"tags": "python|jupyter-notebook|relative-import",
"answer_id": 35273613,
"answer_date": "2016-02-08T15:48:01.637Z",
"answer_score": 260
} |
Please answer the following Stack Overflow question:
Title: Ruby: Is there an opposite of include? for Ruby Arrays?
<p>I've got the following logic in my code:</p>
<pre><code>if [email protected]?(p.name)
...
end
</code></pre>
<p><code>@players</code> is an array. Is there a method so I can avoid the <code>!</code>?</p>
<p>Ideally, this snippet would be:</p>
<pre><code>if @players.does_not_include?(p.name)
...
end
</code></pre> | <pre><code>if @players.exclude?(p.name)
...
end
</code></pre>
<p>ActiveSupport adds the <a href="https://apidock.com/rails/Enumerable/exclude%3F" rel="noreferrer"><code>exclude?</code></a> method to <code>Array</code>, <code>Hash</code>, and <code>String</code>. This is not pure Ruby, but is used by a LOT of rubyists.</p>
<p>Source: <a href="https://guides.rubyonrails.org/active_support_core_extensions.html#exclude-questionmark" rel="noreferrer">Active Support Core Extensions (Rails Guides)</a></p> | {
"question_id": 10355477,
"question_date": "2012-04-27T17:51:24.780Z",
"question_score": 215,
"tags": "ruby-on-rails|ruby",
"answer_id": 13155100,
"answer_date": "2012-10-31T09:44:58.203Z",
"answer_score": 420
} |
Please answer the following Stack Overflow question:
Title: Single Page Application: advantages and disadvantages
<p>I've read about SPA and it advantages. I find most of them unconvincing. There are 3 advantages that arouse my doubts.</p>
<p><em><strong>Question:</em></strong> <em>Can you act as advocate of SPA and prove that I am wrong about first three statements?</em></p>
<pre><code> === ADVANTAGES ===
</code></pre>
<p><em><strong>1. SPA is extremely good for very responsive sites:</em></strong></p>
<blockquote>
<p>Server-side rendering is hard to implement for all the intermediate
states - small view states do not map well to URLs.</p>
<p>Single page apps are distinguished by their ability to redraw any part
of the UI without requiring a server roundtrip to retrieve HTML. This
is achieved by separating the data from the presentation of data by
having a model layer that handles data and a view layer that reads
from the models.</p>
</blockquote>
<p><em>What is wrong with holding a model layer for non-SPA? Does SPA the only compatible architecture with MVC on client side?</em></p>
<p><em><strong>2. With SPA we don't need to use extra queries to the server to download pages.</em></strong></p>
<p><em>Hah, and how many pages user can download during visiting your site? Two, three? Instead there appear another security problems and you need to separate your login page, admin page etc into separate pages. In turn it conflicts with SPA architecture.</em></p>
<p><em><strong>3.May be any other advantages? Don't hear about any else..</em></strong></p>
<pre><code> === DISADVANTAGES ===
</code></pre>
<ol>
<li>Client must enable javascript.</li>
<li>Only one entry point to the site.</li>
<li>Security.</li>
</ol>
<p><em><strong>P.S.</em></strong> I've worked on SPA and non-SPA projects. And I'm asking those questions because I need to deepen my understanding. No mean to harm SPA supporters. Don't ask me to read a bit more about SPA. I just want to hear your considerations about that.</p> | <p>Let's look at one of the most popular SPA sites, GMail.</p>
<p><strong><em>1. SPA is extremely good for very responsive sites:</em></strong></p>
<p>Server-side rendering is not as hard as it used to be with simple techniques like keeping a #hash in the URL, or more recently <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history" rel="noreferrer">HTML5 <code>pushState</code></a>. With this approach the exact state of the web app is embedded in the page URL. As in GMail every time you open a mail a special hash tag is added to the URL. If copied and pasted to other browser window can open the exact same mail (provided they can authenticate). This approach maps directly to a more traditional query string, the difference is merely in the execution. With HTML5 pushState() you can eliminate the <code>#hash</code> and use completely classic URLs which can resolve on the server on the first request and then load via ajax on subsequent requests.</p>
<p><strong><em>2. With SPA we don't need to use extra queries to the server to download pages.</em></strong></p>
<p>The number of pages user downloads during visit to my web site?? really how many mails some reads when he/she opens his/her mail account. I read >50 at one go. now the structure of the mails is almost the same. if you will use a server side rendering scheme the server would then render it on every request(typical case).
- security concern - you should/ should not keep separate pages for the admins/login that entirely depends upon the structure of you site take paytm.com for example also making a web site SPA does not mean that you open all the endpoints for all the users I mean I use forms auth with my spa web site.
- in the probably most used SPA framework Angular JS the dev can load the entire html temple from the web site so that can be done depending on the users authentication level. pre loading html for all the auth types isn't SPA. </p>
<p><strong><em>3. May be any other advantages? Don't hear about any else..</em></strong></p>
<ul>
<li>these days you can safely assume the client will have javascript enabled browsers. </li>
<li>only one entry point of the site. As I mentioned earlier maintenance of state is possible you can have any number of entry points as you want but you should have one for sure. </li>
<li>even in an SPA user only see to what he has proper rights. you don't have to inject every thing at once. loading diff html templates and javascript async is also a valid part of SPA. </li>
</ul>
<p><strong><em>Advantages that I can think of are:</em></strong></p>
<ol>
<li>rendering html obviously takes some resources now every user visiting you site is doing this. also not only rendering major logics are now done client side instead of server side.</li>
<li>date time issues - I just give the client UTC time is a pre set format and don't even care about the time zones I let javascript handle it. this is great advantage to where I had to guess time zones based on location derived from users IP. </li>
<li>to me state is more nicely maintained in an SPA because once you have set a variable you know it will be there. this gives a feel of developing an app rather than a web page. this helps a lot typically in making sites like foodpanda, flipkart, amazon. because if you are not using client side state you are using expensive sessions.</li>
<li>websites surely are extremely responsive - I'll take an extreme example for this try making a calculator in a non SPA website(I know its weird).</li>
</ol>
<p>Updates from Comments</p>
<blockquote>
<p>It doesn't seem like anyone mentioned about sockets and long-polling.
If you log out from another client say mobile app, then your browser
should also log out. If you don't use SPA, you have to re-create the
socket connection every time there is a redirect. This should also
work with any updates in data like notifications, profile update etc</p>
<p>An alternate perspective: Aside from your website, will your project
involve a native mobile app? If yes, you are most likely going to be
feeding raw data to that native app from a server (ie JSON) and doing
client-side processing to render it, correct? So with this assertion,
you're ALREADY doing a client-side rendering model. Now the question
becomes, why shouldn't you use the same model for the website-version
of your project? Kind of a no-brainer. Then the question becomes
whether you want to render server-side pages only for SEO benefits and
convenience of shareable/bookmarkable URLs</p>
</blockquote> | {
"question_id": 21862054,
"question_date": "2014-02-18T18:12:54.223Z",
"question_score": 215,
"tags": "javascript|architecture|client-side|single-page-application",
"answer_id": 21862736,
"answer_date": "2014-02-18T18:48:50.170Z",
"answer_score": 148
} |
Please answer the following Stack Overflow question:
Title: Android: ScrollView vs NestedScrollView
<p>What is the difference between <code>ScrollView</code> and <code>NestedScrollView</code>? Both of them, extend <code>FrameLayout</code>. I want to know in depth pros and cons of both of them.</p> | <p><code>NestedScrollView</code> as the name suggests is used when there is a need for a scrolling view inside another scrolling view. Normally this would be difficult to accomplish since the system would be unable to decide which view to scroll.</p>
<p>This is where <code>NestedScrollView</code> comes in.</p> | {
"question_id": 34773982,
"question_date": "2016-01-13T18:08:59.077Z",
"question_score": 215,
"tags": "android|xml|android-layout|android-scrollview|android-nestedscrollview",
"answer_id": 34774098,
"answer_date": "2016-01-13T18:15:35.197Z",
"answer_score": 268
} |
Please answer the following Stack Overflow question:
Title: Are list-comprehensions and functional functions faster than "for loops"?
<p>In terms of performance in Python, is a list-comprehension, or functions like <code>map()</code>, <code>filter()</code> and <code>reduce()</code> faster than a for loop? Why, technically, they <strong>run in a C speed</strong>, while <strong>the for loop runs in the python virtual machine speed</strong>?.</p>
<p>Suppose that in a game that I'm developing I need to draw complex and huge maps using for loops. This question would be definitely relevant, for if a list-comprehension, for example, is indeed faster, it would be a much better option in order to avoid lags (Despite the visual complexity of the code).</p> | <p>The following are rough guidelines and educated guesses based on experience. You should <code>timeit</code> or profile your concrete use case to get hard numbers, and those numbers may occasionally disagree with the below.</p>
<p>A list comprehension is usually a tiny bit faster than the precisely equivalent <code>for</code> loop (that actually builds a list), most likely because it doesn't have to look up the list and its <code>append</code> method on every iteration. However, a list comprehension still does a bytecode-level loop:</p>
<pre><code>>>> dis.dis(<the code object for `[x for x in range(10)]`>)
1 0 BUILD_LIST 0
3 LOAD_FAST 0 (.0)
>> 6 FOR_ITER 12 (to 21)
9 STORE_FAST 1 (x)
12 LOAD_FAST 1 (x)
15 LIST_APPEND 2
18 JUMP_ABSOLUTE 6
>> 21 RETURN_VALUE
</code></pre>
<p>Using a list comprehension in place of a loop that <em>doesn't</em> build a list, nonsensically accumulating a list of meaningless values and then throwing the list away, is often <em>slower</em> because of the overhead of creating and extending the list. List comprehensions aren't magic that is inherently faster than a good old loop.</p>
<p>As for functional list processing functions: While these are written in C and probably outperform equivalent functions written in Python, they are <em>not</em> necessarily the fastest option. Some speed up is expected <strong>if</strong> the function is written in C too. But most cases using a <code>lambda</code> (or other Python function), the overhead of repeatedly setting up Python stack frames etc. eats up any savings. Simply doing the same work in-line, without function calls (e.g. a list comprehension instead of <code>map</code> or <code>filter</code>) is often slightly faster.</p>
<blockquote>
<p>Suppose that in a game that I'm developing I need to draw complex and huge maps using for loops. This question would be definitely relevant, for if a list-comprehension, for example, is indeed faster, it would be a much better option in order to avoid lags (Despite the visual complexity of the code).</p>
</blockquote>
<p>Chances are, if code like this isn't already fast enough when written in good non-"optimized" Python, no amount of Python level micro optimization is going to make it fast enough and you should start thinking about dropping to C. While extensive micro optimizations can often speed up Python code considerably, there is a low (in absolute terms) limit to this. Moreover, even before you hit that ceiling, it becomes simply more cost efficient (15% speedup vs. 300% speed up with the same effort) to bite the bullet and write some C.</p> | {
"question_id": 22108488,
"question_date": "2014-03-01T00:38:59.703Z",
"question_score": 215,
"tags": "python|performance|for-loop|list-comprehension|map-function",
"answer_id": 22108640,
"answer_date": "2014-03-01T00:56:05.303Z",
"answer_score": 195
} |
Please answer the following Stack Overflow question:
Title: Copy folder recursively, excluding some folders
<p>I am trying to write a simple bash script that will copy the entire contents of a folder including hidden files and folders into another folder, but I want to exclude certain specific folders. How could I achieve this?</p> | <p>Use rsync:</p>
<pre><code>rsync -av --exclude='path1/to/exclude' --exclude='path2/to/exclude' source destination
</code></pre>
<p>Note that using <code>source</code> and <code>source/</code> are different. A trailing slash means to copy the contents of the folder <code>source</code> into <code>destination</code>. Without the trailing slash, it means copy the folder <code>source</code> into <code>destination</code>.</p>
<p>Alternatively, if you have lots of directories (or files) to exclude, you can use <code>--exclude-from=FILE</code>, where <code>FILE</code> is the name of a file containing files or directories to exclude.</p>
<p><code>--exclude</code> may also contain wildcards, such as <code>--exclude=*/.svn*</code></p> | {
"question_id": 2193584,
"question_date": "2010-02-03T16:39:27.373Z",
"question_score": 215,
"tags": "bash|unix|shell|scripting",
"answer_id": 2194500,
"answer_date": "2010-02-03T18:45:10.317Z",
"answer_score": 367
} |
Please answer the following Stack Overflow question:
Title: SQLite: How do I save the result of a query as a CSV file?
<p>I'm new to SQLite. Is there a way I can export the results of a query into a CSV file?</p> | <p>From <a href="http://www.sqlite.org/sqlite.html" rel="noreferrer">here</a> and d5e5's comment:</p>
<p>You'll have to switch the output to csv-mode and switch to file output.</p>
<pre><code>sqlite> .mode csv
sqlite> .output test.csv
sqlite> select * from tbl1;
sqlite> .output stdout
</code></pre> | {
"question_id": 6076984,
"question_date": "2011-05-20T19:57:13.623Z",
"question_score": 215,
"tags": "sqlite|csv",
"answer_id": 6077039,
"answer_date": "2011-05-20T20:01:50.413Z",
"answer_score": 316
} |
Please answer the following Stack Overflow question:
Title: No resource found that matches the given name: attr 'android:keyboardNavigationCluster'. when updating to Support Library 26.0.0
<p>I've got this issue while updating to the latest Support Library version 26.0.0 (<a href="https://developer.android.com/topic/libraries/support-library/revisions.html#26-0-0" rel="noreferrer">https://developer.android.com/topic/libraries/support-library/revisions.html#26-0-0</a>): </p>
<blockquote>
<p>Error:(18, 21) No resource found that matches the given name: attr
'android:keyboardNavigationCluster'.</p>
</blockquote>
<pre><code>/.../app/build/intermediates/res/merged/beta/debug/values-v26/values-v26.xml
Error:(15, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
Error:(18, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
Error:(15, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
Error:(18, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
Error:Execution failed for task ':app:processBetaDebugResources'.
</code></pre>
<blockquote>
<p>com.android.ide.common.process.ProcessException: Failed to execute aapt</p>
</blockquote>
<p>The file is from the support library:</p>
<pre><code><style name="Base.V26.Widget.AppCompat.Toolbar" parent="Base.V7.Widget.AppCompat.Toolbar">
<item name="android:touchscreenBlocksFocus">true</item>
<item name="android:keyboardNavigationCluster">true</item>
</style>
</code></pre>
<p>We're using the following versions:</p>
<pre><code>ext.COMPILE_SDK_VERSION = 26
ext.BUILD_TOOLS_VERSION = "26.0.1"
ext.MIN_SDK_VERSION = 17
ext.TARGET_SDK_VERSION = 26
ext.ANDROID_SUPPORT_LIBRARY_VERSION = "26.0.0"
ext.GOOGLE_PLAY_SERVICES_LIBRARY_VERSION = "11.0.2"
</code></pre>
<hr>
<pre><code>compile 'com.android.support:appcompat-v7:' + ANDROID_SUPPORT_LIBRARY_VERSION
compile 'com.android.support:design:' + ANDROID_SUPPORT_LIBRARY_VERSION
compile 'com.android.support:recyclerview-v7:' + ANDROID_SUPPORT_LIBRARY_VERSION
</code></pre>
<p>Any ideas?</p> | <p>I was able to resolve it by updating sdk version and tools in gradle
<code>compileSdkVersion 26</code>
<code>buildToolsVersion "26.0.1"</code> </p>
<p>and <code>support library 26.0.1</code> <a href="https://developer.android.com/topic/libraries/support-library/revisions.html#26-0-1" rel="noreferrer">https://developer.android.com/topic/libraries/support-library/revisions.html#26-0-1</a></p> | {
"question_id": 45301203,
"question_date": "2017-07-25T10:53:04.237Z",
"question_score": 215,
"tags": "android|android-gradle-plugin|android-support-library|android-appcompat",
"answer_id": 45310170,
"answer_date": "2017-07-25T17:36:40.237Z",
"answer_score": 315
} |
Please answer the following Stack Overflow question:
Title: receiver type *** for instance message is a forward declaration
<p>In my iOS5 app, I have <code>NSObject</code> <code>States</code> class, and trying to init it:</p>
<pre><code>states = [states init];
</code></pre>
<p>here is <code>init</code> method in <code>States</code>:</p>
<pre><code>- (id) init
{
if ((self = [super init]))
{
pickedGlasses = 0;
}
return self;
}
</code></pre>
<p>But there is error in the line <code>states = [states init];</code></p>
<blockquote>
<p>receiver type "States" for instance message is a forward declaration</p>
</blockquote>
<p>What does it mean? What am I doing wrong?</p> | <p>That basically means that you need to import the .h file containing the declaration of States.</p>
<p>However, there is a <em>lot</em> of other stuff wrong with your code.</p>
<ul>
<li>You're -init'ing an object without <code>+alloc</code>'ing it. That won't work</li>
<li>You're declaring an object as a non-pointer type, that won't work either</li>
<li>You're not calling <code>[super init]</code> in <code>-init</code>.</li>
<li>You've declared the class using <code>@class</code> in the header, but never imported the class.</li>
</ul> | {
"question_id": 8815200,
"question_date": "2012-01-11T06:43:07.920Z",
"question_score": 215,
"tags": "iphone|ios|objective-c|forward-declaration",
"answer_id": 8815238,
"answer_date": "2012-01-11T06:47:38.053Z",
"answer_score": 460
} |
Please answer the following Stack Overflow question:
Title: How can I fix "unexpected element <queries> found in <manifest>" error?
<p>All of a sudden, I am getting this build error in my Android project:</p>
<pre><code>unexpected element <queries> found in <manifest>
</code></pre>
<p>How do I fix it?</p> | <p>The Android Gradle Plugin needs to know about new manifest elements, particularly
for the manifest merger process. The plugin has a tendency to get confused if it
sees elements in the manifest merger that it does not recognize, tossing out
build errors like the one in the question.</p>
<p>In this case, Android 11 introduced <code><queries></code> as a manifest element, and older versions of the Android Gradle Plugin do not know about that element.</p>
<p>The fact that this occurs from manifest merger means that simply upgrading a dependency
might bring about this error. For example, if you upgrade to the latest
version of <code>com.awesome:awesome-library</code>, and it contained a <code><queries></code> element
in its manifest, you might crash with the aforementioned error in your builds,
even without any other changes in your code.</p>
<p>Google released a series of patch versions of the Android Gradle Plugin to address this:</p>
<ul>
<li><code>3.3.3</code></li>
<li><code>3.4.3</code></li>
<li><code>3.5.4</code></li>
<li><code>3.6.4</code></li>
<li><code>4.0.1</code></li>
</ul>
<p>If you are using an existing plugin in the <code>3.3.*</code> through <code>4.0.*</code> series, upgrade
to the associated patch version (or higher) from that list, and you should no longer
run into that error (e.g., <code>classpath 'com.android.tools.build:gradle:4.0.1'</code>).</p>
<p>If you are using Android Studio 4.1 or higher, with a matching
Android Gradle Plugin (e.g., in the <code>4.1.*</code> series), you should be fine without
any changes. Those plugin versions were already aware of <code><queries></code>.</p>
<p>See <a href="https://android-developers.googleblog.com/2020/07/preparing-your-build-for-package-visibility-in-android-11.html" rel="noreferrer">this Android Developers Blog post</a> for more.</p> | {
"question_id": 62969917,
"question_date": "2020-07-18T14:48:59.560Z",
"question_score": 215,
"tags": "android|android-gradle-plugin|android-manifest|manifest",
"answer_id": 62969918,
"answer_date": "2020-07-18T14:48:59.560Z",
"answer_score": 384
} |
Please answer the following Stack Overflow question:
Title: Token Authentication vs. Cookies
<p>What is the difference between token authentication and authentication using cookies?</p>
<p>I am trying to implement the <a href="https://github.com/heartsentwined/ember-auth-rails-demo/wiki">Ember Auth Rails Demo</a> but I do not understand the reasons behind using token authentication as described in the <a href="https://github.com/heartsentwined/ember-auth/wiki/FAQ">Ember Auth FAQ</a> on the question "Why token authentication?"</p> | <p>A typical web app is mostly <strong>stateless</strong>, because of its <strong>request/response</strong> nature. The HTTP protocol is the best example of a <strong>stateless</strong> protocol. But since most web apps need <strong>state</strong>, in order to hold the <strong>state</strong> between server and client, cookies are used such that the server can send a cookie in every response back to the client. This means the next request made from the client will include this cookie and will thus be recognized by the server. This way the server can maintain a <strong>session</strong> with the <strong>stateless</strong> client, knowing mostly everything about the app's <strong>state</strong>, but stored in the server. In this scenario at no moment does the client hold <strong>state</strong>, which is not how <a href="http://emberjs.com" rel="noreferrer">Ember.js</a> works.</p>
<p>In Ember.js things are different. Ember.js makes the programmer's job easier because it holds indeed the <strong>state</strong> for you, in the client, knowing at every moment about its <strong>state</strong> without having to make a request to the server asking for <strong>state</strong> data.</p>
<p>However, holding <strong>state</strong> in the client can also sometimes introduce concurrency issues that are simply not present in <strong>stateless</strong> situations. Ember.js, however, deals also with these issues for you; specifically ember-data is built with this in mind. In conclusion, Ember.js is a framework designed for <strong>stateful</strong> clients.</p>
<p>Ember.js does not work like a typical <strong>stateless</strong> web app where the <strong>session</strong>, the <strong>state</strong> and the corresponding cookies are handled almost completely by the server. Ember.js holds its <strong>state</strong> completely in Javascript (in the client's memory, and not in the DOM like some other frameworks) and does not need the server to manage the session. This results in Ember.js being more versatile in many situations, e.g. when your app is in offline mode.</p>
<p>Obviously, for security reasons, it does need some kind of <strong>token</strong> or <strong>unique key</strong> to be sent to the server everytime a request is made in order to be <strong>authenticated</strong>. This way the server can look up the send token (which was initially issued by the server) and verify if it's valid before sending a response back to the client.</p>
<p>In my opinion, the main reason why to use an authentication token instead of cookies as stated in <a href="https://github.com/heartsentwined/ember-auth/wiki/FAQ" rel="noreferrer">Ember Auth FAQ</a> is primarily because of the nature of the Ember.js framework and also because it fits more with the <strong>stateful</strong> web app paradigm. Therefore the cookie mechanism is not the best approach when building an Ember.js app.</p>
<p>I hope my answer will give more meaning to your question.</p> | {
"question_id": 17000835,
"question_date": "2013-06-08T15:07:10.857Z",
"question_score": 215,
"tags": "authentication|cookies|ember.js",
"answer_id": 17001217,
"answer_date": "2013-06-08T15:50:51.797Z",
"answer_score": 37
} |
Please answer the following Stack Overflow question:
Title: pandas resample documentation
<p>So I completely understand how to use <a href="http://pandas-docs.github.io/pandas-docs-travis/generated/pandas.DataFrame.resample.html?highlight=dataframe%20resample#pandas.DataFrame.resample" rel="noreferrer">resample</a>, but the documentation does not do a good job explaining the options.</p>
<p>So most options in the <code>resample</code> function are pretty straight forward except for these two:</p>
<ul>
<li>rule : the offset string or object representing target conversion</li>
<li>how : string, method for down- or re-sampling, default to ‘mean’</li>
</ul>
<p>So from looking at as many examples as I found online I can see for rule you can do <code>'D'</code> for day, <code>'xMin'</code> for minutes, <code>'xL'</code> for milliseconds, but that is all I could find.</p>
<p>for how I have seen the following: <code>'first'</code>, <code>np.max</code>, <code>'last'</code>, <code>'mean'</code>, and <code>'n1n2n3n4...nx'</code> where nx is the first letter of each column index.</p>
<p>So is there somewhere in the documentation that I am missing that displays every option for <code>pandas.resample</code>'s rule and how inputs? If yes, where because I could not find it. If no, <strong>what are all the options for them?</strong></p> | <pre><code>B business day frequency
C custom business day frequency (experimental)
D calendar day frequency
W weekly frequency
M month end frequency
SM semi-month end frequency (15th and end of month)
BM business month end frequency
CBM custom business month end frequency
MS month start frequency
SMS semi-month start frequency (1st and 15th)
BMS business month start frequency
CBMS custom business month start frequency
Q quarter end frequency
BQ business quarter endfrequency
QS quarter start frequency
BQS business quarter start frequency
A year end frequency
BA, BY business year end frequency
AS, YS year start frequency
BAS, BYS business year start frequency
BH business hour frequency
H hourly frequency
T, min minutely frequency
S secondly frequency
L, ms milliseconds
U, us microseconds
N nanoseconds
</code></pre>
<p>See the <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html" rel="noreferrer">timeseries documentation</a>. It includes a list of <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases" rel="noreferrer">offsets</a> (and <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#anchored-offsets" rel="noreferrer">'anchored' offsets</a>), and a section about <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#resampling" rel="noreferrer">resampling</a>.</p>
<p>Note that there isn't a list of all the different <code>how</code> options, because it can be any NumPy array function and any function that is available via <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#groupby-dispatch" rel="noreferrer">groupby dispatching</a> can be passed to <code>how</code> by name.</p> | {
"question_id": 17001389,
"question_date": "2013-06-08T16:09:43.760Z",
"question_score": 215,
"tags": "python|documentation|pandas",
"answer_id": 17001474,
"answer_date": "2013-06-08T16:20:07.050Z",
"answer_score": 372
} |
Please answer the following Stack Overflow question:
Title: Can a C++ enum class have methods?
<p>I have an enum class with two values, and I want to create a method which receives a value
and returns the other one. I also want to maintain type safety(that's why I use enum class instead of enums).</p>
<p><a href="http://www.cplusplus.com/doc/tutorial/other_data_types/" rel="noreferrer">http://www.cplusplus.com/doc/tutorial/other_data_types/</a> doesn't mention anything about methods
However, I was under the impression that any type of class can have methods. </p> | <p>No, they can't.</p>
<p>I can understand that the <code>enum class</code> part for strongly typed enums in C++11 might seem to imply that your <code>enum</code> has <code>class</code> traits too, but it's not the case. My educated guess is that the choice of the keywords was inspired by the pattern we used before C++11 to get scoped enums:</p>
<pre><code>class Foo {
public:
enum {BAR, BAZ};
};
</code></pre>
<p>However, that's just syntax. Again, <code>enum class</code> is not a <code>class</code>.</p> | {
"question_id": 21295935,
"question_date": "2014-01-22T23:04:11.077Z",
"question_score": 215,
"tags": "c++|methods|enums",
"answer_id": 21295997,
"answer_date": "2014-01-22T23:09:01.057Z",
"answer_score": 165
} |
Please answer the following Stack Overflow question:
Title: No ConcurrentList<T> in .Net 4.0?
<p>I was thrilled to see the new <code>System.Collections.Concurrent</code> namespace in .Net 4.0, quite nice! I've seen <code>ConcurrentDictionary</code>, <code>ConcurrentQueue</code>, <code>ConcurrentStack</code>, <code>ConcurrentBag</code> and <code>BlockingCollection</code>.</p>
<p>One thing that seems to be mysteriously missing is a <code>ConcurrentList<T></code>. Do I have to write that myself (or get it off the web :) )? </p>
<p>Am I missing something obvious here?</p> | <p>I <a href="http://philosopherdeveloper.com/posts/how-to-build-a-thread-safe-lock-free-resizable-array.html" rel="noreferrer">gave it a try a while back</a> (also: <a href="https://github.com/dtao/ConcurrentList" rel="noreferrer">on GitHub</a>). My implementation had some problems, which I won't get into here. Let me tell you, more importantly, what I learned.</p>
<p>Firstly, there's no way you're going to get a full implementation of <code>IList<T></code> that is lockless and thread-safe. In particular, random insertions and removals are <em>not</em> going to work, unless you also forget about O(1) random access (i.e., unless you "cheat" and just use some sort of linked list and let the indexing suck).</p>
<p>What I <em>thought</em> might be worthwhile was a thread-safe, limited subset of <code>IList<T></code>: in particular, one that would allow an <code>Add</code> and provide random <em>read-only</em> access by index (but no <code>Insert</code>, <code>RemoveAt</code>, etc., and also no random <em>write</em> access).</p>
<p>This was the goal of <a href="http://philosopherdeveloper.com/posts/boy-can-dream.html" rel="noreferrer">my <code>ConcurrentList<T></code> implementation</a>. But when I tested its performance in multithreaded scenarios, I found that <strong>simply synchronizing adds to a <code>List<T></code> was faster</strong>. Basically, adding to a <code>List<T></code> is lightning fast already; the complexity of the computational steps involved is miniscule (increment an index and assign to an element in an array; that's <em>really it</em>). You would need a <em>ton</em> of concurrent writes to see any sort of lock contention on this; and even then, the average performance of each write would still beat out the more expensive albeit lockless implementation in <code>ConcurrentList<T></code>.</p>
<p>In the relatively rare event that the list's internal array needs to resize itself, you do pay a small cost. So ultimately I concluded that this was the <em>one</em> niche scenario where an add-only <code>ConcurrentList<T></code> collection type would make sense: when you want <em>guaranteed</em> low overhead of adding an element on <em>every single call</em> (so, as opposed to an amortized performance goal).</p>
<p>It's simply not nearly as useful a class as you would think.</p> | {
"question_id": 6601611,
"question_date": "2011-07-06T19:06:47.903Z",
"question_score": 215,
"tags": "c#|.net|parallel-processing|task-parallel-library",
"answer_id": 6601832,
"answer_date": "2011-07-06T19:27:36.917Z",
"answer_score": 176
} |
Please answer the following Stack Overflow question:
Title: ssh -L forward multiple ports
<p>I'm currently running a bunch of:</p>
<pre><code>sudo ssh -L PORT:IP:PORT root@IP
</code></pre>
<p>where IP is the target of a secured machine, and PORT represents the ports I'm forwarding.</p>
<p>This is because I use a lot of applications which I cannot access without this forwarding. After performing this, I can access through <code>localhost:PORT</code>.</p>
<p>The main problem occured now that I actually have 4 of these ports that I have to forward.</p>
<p>My solution is to open 4 shells and constantly search my history backwards to look for exactly which ports need to be forwarded etc, and then run this command - one in each shell (having to fill in passwords etc).</p>
<p>If only I could do something like:</p>
<pre><code>sudo ssh -L PORT1+PORT2+PORT+3:IP:PORT+PORT2+PORT3 root@IP
</code></pre>
<p>then that would already really help.</p>
<p>Is there a way to make it easier to do this?</p> | <p>The <code>-L</code> option can be specified multiple times within the same command. Every time with different ports. I.e. <code>ssh -L localPort0:ip:remotePort0 -L localPort1:ip:remotePort1 ...</code></p> | {
"question_id": 29936948,
"question_date": "2015-04-29T07:24:40.113Z",
"question_score": 215,
"tags": "ssh|port|portforwarding",
"answer_id": 29937009,
"answer_date": "2015-04-29T07:27:02.800Z",
"answer_score": 334
} |
Please answer the following Stack Overflow question:
Title: How to implement a secure REST API with node.js
<p>I start planning a REST API with node.js ,express and mongodb. The API provides data for a website (public and private area) and maybe later a mobile app. The frontend will be developed with AngularJS.</p>
<p>For some days I read a lot about securing REST APIs, but I don’t get to a final solution. As far as I understand is to use HTTPS to provide a basic security. But how I can protect the API in that use cases:</p>
<ul>
<li><p>Only visitors/users of the website/app are allowed to get data for the public area of the website/app</p></li>
<li><p>Only authenticated and authorized users are allowed to get data for private area (and only data, where the user granted permissions)</p></li>
</ul>
<p>At the moment I think about to only allow users with a active session to use the API. To authorize the users I will use passport and for permission I need to implement something for myself. All on the top of HTTPS.</p>
<p>Can somebody provide some best practice or experiences? Is there a lack in my “architecture”?</p> | <p>I've had the same problem you describe. The web site I'm building can be accessed from a mobile phone and from the browser so I need an api to allow users to signup, login and do some specific tasks. Furthermore, I need to support scalability, the same code running on different processes/machines.</p>
<p>Because users can CREATE resources (aka POST/PUT actions) you need to secure your api. You can use oauth or you can build your own solution but keep in mind that all the solutions can be broken if the password it's really easy to discover. The basic idea is to authenticate users using the username, password and a token, aka the apitoken. This apitoken can be generated using <a href="https://github.com/broofa/node-uuid" rel="noreferrer">node-uuid</a> and the password can be hashed using <a href="http://nodejs.org/api/crypto.html#crypto_crypto_pbkdf2_password_salt_iterations_keylen_callback" rel="noreferrer">pbkdf2</a></p>
<p>Then, you need to save the session somewhere. If you save it in memory in a plain object, if you kill the server and reboot it again the session will be destroyed. Also, this is not scalable. If you use haproxy to load balance between machines or if you simply use workers, this session state will be stored in a single process so if the same user is redirected to another process/machine it will need to authenticate again. Therefore you need to store the session in a common place. This is typically done using redis.</p>
<p>When the user is authenticated (username+password+apitoken) generate another token for the session, aka accesstoken. Again, with node-uuid. Send to the user the accesstoken and the userid. The userid (key) and the accesstoken (value) are stored in redis with and expire time, e.g. 1h.</p>
<p>Now, every time the user does any operation using the rest api it will need to send the userid and the accesstoken.</p>
<p>If you allow the users to signup using the rest api, you'll need to create an admin account with an admin apitoken and store them in the mobile app (encrypt username+password+apitoken) because new users won't have an apitoken when they sign up.</p>
<p>The web also uses this api but you don't need to use apitokens. You can use express with a redis store or use the same technique described above but bypassing the apitoken check and returning to the user the userid+accesstoken in a cookie.</p>
<p>If you have private areas compare the username with the allowed users when they authenticate. You can also apply roles to the users.</p>
<p>Summary:</p>
<p><img src="https://i.stack.imgur.com/Kbttf.png" alt="sequence diagram"></p>
<p>An alternative without apitoken would be to use HTTPS and to send the username and password in the Authorization header and cache the username in redis.</p> | {
"question_id": 15496915,
"question_date": "2013-03-19T10:27:29.483Z",
"question_score": 215,
"tags": "node.js|rest|express|passport.js",
"answer_id": 15500784,
"answer_date": "2013-03-19T13:25:59.530Z",
"answer_score": 181
} |
Please answer the following Stack Overflow question:
Title: Rails has_many with alias name
<p>In my User model I could have:</p>
<pre><code>has_many :tasks
</code></pre>
<p>and in my Task model:</p>
<pre><code>belongs_to :user
</code></pre>
<p>Then, supposing the foreign key 'user_id' was stored in the tasks table, I could use:</p>
<pre><code>@user.tasks
</code></pre>
<hr>
<p>My question is, how do I declare the has_many relationship such that I can refer to a User's Tasks as:</p>
<pre><code>@user.jobs
</code></pre>
<p>... or ...</p>
<pre><code>@user.foobars
</code></pre>
<p>Thanks a heap.</p> | <p>Give this a shot:</p>
<pre class="lang-ruby prettyprint-override"><code>has_many :jobs, foreign_key: 'user_id', class_name: 'Task'
</code></pre>
<p>Note, that <code>:as</code> is used for <a href="https://guides.rubyonrails.org/association_basics.html#polymorphic-associations" rel="nofollow noreferrer">polymorphic associations</a>.</p>
<p>Also, <a href="https://guides.rubyonrails.org/association_basics.html#options-for-has-many-foreign-key" rel="nofollow noreferrer">foreign_key option for has_many</a>.</p> | {
"question_id": 1163032,
"question_date": "2009-07-22T04:14:25.457Z",
"question_score": 215,
"tags": "ruby-on-rails|has-many",
"answer_id": 1163077,
"answer_date": "2009-07-22T04:32:07.680Z",
"answer_score": 409
} |
Please answer the following Stack Overflow question:
Title: Add .gitignore to gitignore
<p>Is it possible to add the <code>.gitignore</code> file to <code>.gitignore</code> itself?</p>
<pre><code>.gitignore
</code></pre>
<p>Doesn't work though</p>
<p>I don't want to see it in edited files</p> | <p>The <code>.gitignore</code> file's purpose is to prevent everyone who collaborates on a project from accidentally commiting some common files in a project, such as generated cache files. Therefore you should not ignore <code>.gitignore</code>, since it's supposed to be included in the repository.</p>
<p>If you want to ignore files in just one repository but want to avoid committing the ignore list (for example for personal files) you can add them to <code>.git/info/exclude</code> in that repository.</p>
<p>If you want to ignore certain files on every repository on your machine you can create the file <code>~/.gitignore_global</code> and then run</p>
<pre><code>git config --global core.excludesfile ~/.gitignore_global
</code></pre> | {
"question_id": 10176875,
"question_date": "2012-04-16T15:16:06.260Z",
"question_score": 215,
"tags": "git|gitignore",
"answer_id": 10177000,
"answer_date": "2012-04-16T15:23:49.413Z",
"answer_score": 256
} |
Please answer the following Stack Overflow question:
Title: Why does Vim save files with a ~ extension?
<p>I've found that while using Vim on Windows Vim saves the file, a <code>.ext.swp</code> file that's deleted on closing the Vim window and a <code>.ext~</code> file. </p>
<p>I assume the <code>.ext.swp</code> file is a session backup in case Vim crashes. What's the purpose of the <code>.ext~</code> file however? Is this a permanent backup file? It's annoying as I'd like to copy all the files I'm working on to my host, without these duplicates. <strong>How can I turn this off or</strong>, if it's there for a good reason, <strong>hide the files</strong>?</p> | <p>The <code>*.ext~</code> file is a backup file, containing the file as it was before you edited it.</p>
<p>The <code>*.ext.swp</code> file is the swap file, which serves as a lock file and contains the undo/redo history as well as any other internal info Vim needs. In case of a crash you can re-open your file and Vim will restore its previous state from the swap file (which I find helpful, so I don't switch it off).</p>
<p>To switch off automatic creation of backup files, use (in your vimrc):</p>
<pre><code>set nobackup
set nowritebackup
</code></pre>
<p>Where <code>nowritebackup</code> changes the default "save" behavior of Vim, which is:</p>
<ol>
<li>write buffer to new file</li>
<li>delete the original file</li>
<li>rename the new file</li>
</ol>
<p>and makes Vim write the buffer to the original file (resulting in the risk of destroying it in case of an I/O error). But you prevent "jumping files" on the Windows desktop with it, which is the primary reason for me to have <code>nowritebackup</code> in place.</p> | {
"question_id": 607435,
"question_date": "2009-03-03T17:56:45.447Z",
"question_score": 215,
"tags": "vim",
"answer_id": 607475,
"answer_date": "2009-03-03T18:04:59.810Z",
"answer_score": 244
} |
Please answer the following Stack Overflow question:
Title: Add spaces before Capital Letters
<p>Given the string "ThisStringHasNoSpacesButItDoesHaveCapitals" what is the best way to add spaces before the capital letters. So the end string would be "This String Has No Spaces But It Does Have Capitals"</p>
<p>Here is my attempt with a RegEx</p>
<pre><code>System.Text.RegularExpressions.Regex.Replace(value, "[A-Z]", " $0")
</code></pre> | <p>The regexes will work fine (I even voted up Martin Browns answer), but they are expensive (and personally I find any pattern longer than a couple of characters prohibitively obtuse)</p>
<p>This function </p>
<pre><code>string AddSpacesToSentence(string text, bool preserveAcronyms)
{
if (string.IsNullOrWhiteSpace(text))
return string.Empty;
StringBuilder newText = new StringBuilder(text.Length * 2);
newText.Append(text[0]);
for (int i = 1; i < text.Length; i++)
{
if (char.IsUpper(text[i]))
if ((text[i - 1] != ' ' && !char.IsUpper(text[i - 1])) ||
(preserveAcronyms && char.IsUpper(text[i - 1]) &&
i < text.Length - 1 && !char.IsUpper(text[i + 1])))
newText.Append(' ');
newText.Append(text[i]);
}
return newText.ToString();
}
</code></pre>
<p>Will do it 100,000 times in 2,968,750 ticks, the regex will take 25,000,000 ticks (and thats with the regex compiled).</p>
<p>It's better, for a given value of better (i.e. faster) however it's more code to maintain. "Better" is often compromise of competing requirements.</p>
<p>Hope this helps :)</p>
<p><strong>Update</strong><br>
It's a good long while since I looked at this, and I just realised the timings haven't been updated since the code changed (it only changed a little).</p>
<p>On a string with 'Abbbbbbbbb' repeated 100 times (i.e. 1,000 bytes), a run of 100,000 conversions takes the hand coded function 4,517,177 ticks, and the Regex below takes 59,435,719 making the Hand coded function run in 7.6% of the time it takes the Regex.</p>
<p><strong>Update 2</strong>
Will it take Acronyms into account? It will now!
The logic of the if statment is fairly obscure, as you can see expanding it to this ...</p>
<pre><code>if (char.IsUpper(text[i]))
if (char.IsUpper(text[i - 1]))
if (preserveAcronyms && i < text.Length - 1 && !char.IsUpper(text[i + 1]))
newText.Append(' ');
else ;
else if (text[i - 1] != ' ')
newText.Append(' ');
</code></pre>
<p>... doesn't help at all!</p>
<p>Here's the original <em>simple</em> method that doesn't worry about Acronyms</p>
<pre><code>string AddSpacesToSentence(string text)
{
if (string.IsNullOrWhiteSpace(text))
return "";
StringBuilder newText = new StringBuilder(text.Length * 2);
newText.Append(text[0]);
for (int i = 1; i < text.Length; i++)
{
if (char.IsUpper(text[i]) && text[i - 1] != ' ')
newText.Append(' ');
newText.Append(text[i]);
}
return newText.ToString();
}
</code></pre> | {
"question_id": 272633,
"question_date": "2008-11-07T16:33:53.727Z",
"question_score": 215,
"tags": "c#|regex|string",
"answer_id": 272929,
"answer_date": "2008-11-07T17:48:36.900Z",
"answer_score": 218
} |
Please answer the following Stack Overflow question:
Title: How big can a user agent string get?
<p>If you were going to store a user agent in a database, how large would you accomdate for?</p>
<p>I found this <a href="http://technet.microsoft.com/en-us/library/bb496341.aspx" rel="noreferrer">technet article</a> which recommends keeping UA under 200. It doesn't look like this is defined in the HTTP specification at least not that I found. My UA is already 149 characters, and it seems like each version of .NET will be adding to it.</p>
<p>I know I can parse the string out and break it down but I'd rather not.</p>
<hr>
<p><strong>EDIT</strong><br>
Based on this <a href="http://blogs.msdn.com/ie/archive/2010/03/23/introducing-ie9-s-user-agent-string.aspx" rel="noreferrer">Blog</a> IE9 will be changing to send the short UA string. This is a good change.</p>
<hr> | <p>HTTP specification does not limit length of headers at all.
However web-servers do limit header size they accept, throwing <code>413 Entity Too Large</code> if it exceeds. </p>
<p>Depending on web-server and their settings these limits vary from 4KB to 64KB (total for all headers).</p> | {
"question_id": 654921,
"question_date": "2009-03-17T16:10:57.033Z",
"question_score": 215,
"tags": "http|database-design|http-headers|user-agent",
"answer_id": 654997,
"answer_date": "2009-03-17T16:29:36.037Z",
"answer_score": 133
} |
Please answer the following Stack Overflow question:
Title: What causes imported Maven project in Eclipse to use Java 1.5 instead of Java 1.6 by default and how can I ensure it doesn't?
<p>I imported a Maven project and it used Java 1.5 even though I have 1.6 configured as my Eclipse default <code>Preferences->Java->Installed JREs</code>. </p>
<p>When I changed the Maven project to use the 1.6 JRE it still had the build errors left over from when the project was using Java 1.5 (I described these build errors earlier in: <a href="https://stackoverflow.com/questions/3538524/i-have-build-errors-with-m2eclipse-but-not-with-maven2-on-the-command-line-is-m">I have build errors with m2eclipse but not with maven2 on the command line - is my m2eclipse misconfigured?</a>)</p>
<p>I'm going to delete the project and try again but I want to make sure this time that it uses Java 1.6 from the start to see if this eliminates the build problems.</p>
<p>How do I make sure the project uses Java 1.6 when I import it?</p> | <p>The m2eclipse plugin doesn't use Eclipse defaults, the m2eclipse plugin derives the settings from the POM. So if you want a Maven project to be configured to use Java 1.6 settings when imported under Eclipse, configure the <code>maven-compiler-plugin</code> appropriately, as I already suggested:</p>
<pre class="lang-xml prettyprint-override"><code><plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</code></pre>
<p>If your project is already imported, update the project configuration (<strong>right-click</strong> on the project then <strong>Maven V Update Project Configuration</strong>).</p> | {
"question_id": 3539139,
"question_date": "2010-08-21T21:49:00.350Z",
"question_score": 215,
"tags": "java|eclipse|maven-2|m2eclipse|build-error",
"answer_id": 3539194,
"answer_date": "2010-08-21T22:07:36.287Z",
"answer_score": 253
} |
Please answer the following Stack Overflow question:
Title: What is the meaning of the /dist directory in open source projects?
<p>Since I first saw a <code>dist/</code> directory in many open source projects, usually on GitHub, I've been wondering what it means.</p>
<p>With <code>dist</code>, <code>vendor</code>, <code>lib</code>, <code>src</code>, and many other folder names that we see quite often, I sometimes wonder how I should name my own folders.</p>
<p>Correct me if I'm wrong!</p>
<ul>
<li>src: Contains the <strong>sources</strong>. Sometimes only the pure sources, sometimes with the minified version, depends on the project.</li>
<li>vendor: Contains other dependencies, like other open source projects.</li>
<li>lib: Good question, it's really close to <code>vendor</code> actually, depending on the project we can see one or another or both...</li>
<li>dist: From what I saw, it contains the "production" files, the one we should use if we want to use the <em>library</em>.</li>
</ul>
<p>Why is open source so confusing? Isn't it possible to do things clearer? At least per language because some languages use specific names.</p> | <p>To answer your question:</p>
<h3><strong><code>/dist</code> means "distributable", the compiled code/library.</strong></h3>
<p>Folder structure varies by build system and programming language. Here are some standard conventions:</p>
<ul>
<li><p><code>src/</code>: "source" files to build and develop the project. This is where the original source files are located, before being compiled into fewer files to <code>dist/</code>, <code>public/</code> or <code>build/</code>.</p>
</li>
<li><p><code>dist/</code>: "distribution", the compiled code/library, also named <code>public/</code> or <code>build/</code>. The files meant for production or public use are usually located here.</p>
<p>There may be a slight difference between these three:</p>
<ul>
<li><code>build/</code>: is a compiled version of your <code>src/</code> but not a production-ready.</li>
<li><code>dist/</code>: is a production-ready compiled version of your code.</li>
<li><code>public/</code>: usually used as the files runs on the browser. which it may be the server-side JS and also include some HTML and CSS.</li>
</ul>
</li>
<li><p><code>assets/</code>: static content like images, video, audio, fonts etc.</p>
</li>
<li><p><code>lib/</code>: external dependencies (when included directly).</p>
</li>
<li><p><code>test/</code>: the project's tests scripts, mocks, etc.</p>
</li>
<li><p><code>node_modules/</code>: includes libraries and dependencies for JS packages, used by Npm.</p>
</li>
<li><p><code>vendor/</code>: includes libraries and dependencies for PHP packages, used by Composer.</p>
</li>
<li><p><code>bin/</code>: files that get added to your PATH when installed.</p>
</li>
</ul>
<p>Markdown/Text Files:</p>
<ul>
<li><code>README.md</code>: A help file which addresses setup, tutorials, and documents the project. <code>README.txt</code> is also used.</li>
<li><code>LICENSE.md</code>: any <a href="https://choosealicense.com/no-permission/" rel="noreferrer">rights</a> given to you regarding the project. <code>LICENSE</code> or <code>LICENSE.txt</code> are variations of the license file name, having the same contents.</li>
<li><code>CONTRIBUTING.md</code>: how to <a href="https://github.com/blog/1184-contributing-guidelines" rel="noreferrer">help out</a> with the project. Sometimes this is addressed in the <code>README.md</code> file.</li>
</ul>
<p>Specific (these could go on forever):</p>
<ul>
<li><code>package.json</code>: defines libraries and dependencies for JS packages, used by Npm.</li>
<li><code>package-lock.json</code>: specific version lock for dependencies installed from <code>package.json</code>, used by Npm.</li>
<li><code>composer.json</code>: defines libraries and dependencies for PHP packages, used by Composer.</li>
<li><code>composer.lock</code>: specific version lock for dependencies installed from <code>composer.json</code>, used by Composer.</li>
<li><code>gulpfile.js</code>: used to define functions and tasks to be run with Gulp.</li>
<li><code>.travis.yml</code>: config file for the <a href="https://travis-ci.com" rel="noreferrer">Travis CI</a> environment.</li>
<li><code>.gitignore</code>: Specification of the files meant <a href="https://help.github.com/articles/ignoring-files/" rel="noreferrer">to be ignored</a> by Git.</li>
</ul> | {
"question_id": 22842691,
"question_date": "2014-04-03T15:46:59.123Z",
"question_score": 215,
"tags": "github|open-source",
"answer_id": 22844164,
"answer_date": "2014-04-03T16:55:18.383Z",
"answer_score": 379
} |
Please answer the following Stack Overflow question:
Title: How to implement a rule engine?
<p>I have a db table that stores the following:</p>
<pre><code>RuleID objectProperty ComparisonOperator TargetValue
1 age 'greater_than' 15
2 username 'equal' 'some_name'
3 tags 'hasAtLeastOne' 'some_tag some_tag2'
</code></pre>
<p>Now say I have a collection of these rules:</p>
<pre><code>List<Rule> rules = db.GetRules();
</code></pre>
<p>Now I have an instance of a user also:</p>
<pre><code>User user = db.GetUser(....);
</code></pre>
<p>How would I loop through these rules, and apply the logic and perform the comparisons etc?</p>
<pre><code>if(user.age > 15)
if(user.username == "some_name")
</code></pre>
<p>Since the object's property like 'age' or 'user_name' is stored in the table, along with the comparison operater 'great_than' and 'equal', how could I possible do this?</p>
<p>C# is a statically typed language, so not sure how to go forward.</p> | <p>This snippet <strong>compiles the Rules into fast executable code</strong> (using <a href="http://msdn.microsoft.com/en-us/library/bb397951.aspx" rel="noreferrer">Expression trees</a>) and does not need any complicated switch statements:</p>
<p>(Edit : <a href="https://dotnetfiddle.net/3O6vVH" rel="noreferrer"><em>full working example with generic method</em></a>)</p>
<pre><code>public Func<User, bool> CompileRule(Rule r)
{
var paramUser = Expression.Parameter(typeof(User));
Expression expr = BuildExpr(r, paramUser);
// build a lambda function User->bool and compile it
return Expression.Lambda<Func<User, bool>>(expr, paramUser).Compile();
}
</code></pre>
<p>You can then write:</p>
<pre><code>List<Rule> rules = new List<Rule> {
new Rule ("Age", "GreaterThan", "21"),
new Rule ( "Name", "Equal", "John"),
new Rule ( "Tags", "Contains", "C#" )
};
// compile the rules once
var compiledRules = rules.Select(r => CompileRule(r)).ToList();
public bool MatchesAllRules(User user)
{
return compiledRules.All(rule => rule(user));
}
</code></pre>
<p>Here is the implementation of BuildExpr:</p>
<pre><code>Expression BuildExpr(Rule r, ParameterExpression param)
{
var left = MemberExpression.Property(param, r.MemberName);
var tProp = typeof(User).GetProperty(r.MemberName).PropertyType;
ExpressionType tBinary;
// is the operator a known .NET operator?
if (ExpressionType.TryParse(r.Operator, out tBinary)) {
var right = Expression.Constant(Convert.ChangeType(r.TargetValue, tProp));
// use a binary operation, e.g. 'Equal' -> 'u.Age == 21'
return Expression.MakeBinary(tBinary, left, right);
} else {
var method = tProp.GetMethod(r.Operator);
var tParam = method.GetParameters()[0].ParameterType;
var right = Expression.Constant(Convert.ChangeType(r.TargetValue, tParam));
// use a method call, e.g. 'Contains' -> 'u.Tags.Contains(some_tag)'
return Expression.Call(left, method, right);
}
}
</code></pre>
<p>Note that I used 'GreaterThan' instead of 'greater_than' etc. - this is because 'GreaterThan' is the .NET name for the operator, therefore we don't need any extra mapping.</p>
<p>If you need custom names you can build a very simple dictionary and just translate all operators before compiling the rules:</p>
<pre><code>var nameMap = new Dictionary<string, string> {
{ "greater_than", "GreaterThan" },
{ "hasAtLeastOne", "Contains" }
};
</code></pre>
<p>The code uses the type User for simplicity. You can replace User with a generic type T to have a <a href="http://coding-time.blogspot.com/2011/07/how-to-implement-rule-engine-in-c.html" rel="noreferrer">generic Rule compiler</a> for any types of objects. Also, the code should handle errors, like unknown operator name.</p>
<p>Note that generating code on the fly was possible even before the Expression trees API was introduced, using Reflection.Emit. The method LambdaExpression.Compile() uses Reflection.Emit under the covers (you can see this using <a href="http://wiki.sharpdevelop.net/ILSpy.ashx" rel="noreferrer">ILSpy</a>).</p> | {
"question_id": 6488034,
"question_date": "2011-06-27T02:11:49.170Z",
"question_score": 215,
"tags": "c#|dynamic|rule-engine",
"answer_id": 6560284,
"answer_date": "2011-07-03T00:09:30.270Z",
"answer_score": 421
} |
Please answer the following Stack Overflow question:
Title: Rails new vs create
<p>Why is there a need to define a new method in RESTful controller, follow it up with a create method?</p>
<p>Google search didn't provide me the answer I was looking for. I understand the difference, but need to know why they are used the way they are.</p> | <p>Within Rails' implementation of REST <em>new</em> and <em>create</em> are treated differently. </p>
<p>An HTTP GET to <code>/resources/new</code> is intended to render a form suitable for creating a new resource, which it does by calling the <em>new</em> action within the controller, which creates a new unsaved record and renders the form.</p>
<p>An HTTP POST to <code>/resources</code> takes the record created as part of the <em>new</em> action and passes it to the <em>create</em> action within the controller, which then attempts to save it to the database.</p> | {
"question_id": 2472393,
"question_date": "2010-03-18T18:29:00.500Z",
"question_score": 215,
"tags": "ruby-on-rails|rest",
"answer_id": 2472489,
"answer_date": "2010-03-18T18:46:46.053Z",
"answer_score": 286
} |
Please answer the following Stack Overflow question:
Title: Is there an Eclipse line-width marker?
<p>I have a specific project where I need to wrap every code line at 65 characters. I have set up the eclipse Java code formatter properly for this. But what I really want is a vertical line to be drawn in the editor showing where the max line width while I am typing, not just when I run the formmater. I know this feature is available in some capacity because it is displayed in the code formatter property page.</p>
<p>I don't see any option in eclipse to turn this on and I didn't see any plug-ins that do it on Eclipse Plugin Central</p> | <p>Look in Windows / Preferences (at least on Windows - IIRC it moves around for different operating systems) then:</p>
<pre><code>General -> Editors -> Text Editors -> Show Print Margin
</code></pre>
<p>Tick this and it should show the line.</p>
<p>As a quick way of finding this, use the search filter in the top and filter on "margin".</p>
<p>Notes from the comments - unverified by me, but I have no reason to doubt them:</p>
<blockquote>
<p>It has changed somehow in 2016: For details see [here] (<a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=495490#c2" rel="noreferrer">https://bugs.eclipse.org/bugs/show_bug.cgi?id=495490#c2</a>) You have to set it in the formatter: From menu [Window]-->[Preferences], select [Java]-->[Code Style]-->[Formatter], and then edit your formatter profile. In the tab page [Line wrapping], you can find a setting named "Maximum line width". Change this setting, and the print margin in Java source editor will be changed too. </p>
</blockquote> | {
"question_id": 1248895,
"question_date": "2009-08-08T13:36:57.813Z",
"question_score": 215,
"tags": "eclipse|editor|eclipse-plugin",
"answer_id": 1248899,
"answer_date": "2009-08-08T13:40:48.450Z",
"answer_score": 367
} |
Please answer the following Stack Overflow question:
Title: How to modify GitHub pull request?
<p>I've opened a pull request to a project. The maintainer has decided to accept it, but told me to modify some contents. </p>
<p>How can I do it? Whether I should keep the commit hash unchanged, how can I do it?</p> | <p>Just push more commits on to the branch the request is for. The pull request will pick this up then.</p>
<h1>Example:</h1>
<p>If you want to have b merged into master</p>
<ol>
<li>You push c1,c2,c3 to b</li>
<li>then you make a new request for b</li>
<li>it gets reviewed and you need more commits</li>
<li>You push c11,c21,c31 to b</li>
<li>The pull request now shows all 6 six commits</li>
</ol> | {
"question_id": 16748115,
"question_date": "2013-05-25T09:18:21.987Z",
"question_score": 215,
"tags": "git|github|pull-request",
"answer_id": 16748236,
"answer_date": "2013-05-25T09:34:56.470Z",
"answer_score": 226
} |
Please answer the following Stack Overflow question:
Title: WPF datagrid empty row at bottom
<p>I bind my datagrid using</p>
<pre><code>//fill datagrid
public DataTable GameData
{
get
{
DataSet ds = new DataSet();
FileStream fs = new FileStream(IMDB.WebPage.Class.Config.XMLPath,
FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(fs, Encoding.Default);
ds.ReadXml(reader);
fs.Close();
DataTable temp = ds.Tables[0];
return ds.Tables[0];
}
}
</code></pre>
<p>For some reason I get an empty row at the bottom. And sometimes after clicking on some buttons and checkboxes in the grid, more empty rows are added.</p>
<p>Why is this? And how do I block this?</p> | <p>Sounds like you probably have <code>CanUserAddRows</code> set to true for the DataGrid. Just add</p>
<pre><code>CanUserAddRows="false"
</code></pre>
<p>to the XAML.</p> | {
"question_id": 1783839,
"question_date": "2009-11-23T15:26:31.283Z",
"question_score": 215,
"tags": "wpf|datagrid",
"answer_id": 1785131,
"answer_date": "2009-11-23T18:44:45.890Z",
"answer_score": 485
} |
Please answer the following Stack Overflow question:
Title: Generic TryParse
<p>I am trying to create a generic extension that uses 'TryParse' to check if a string is a given type:</p>
<pre><code>public static bool Is<T>(this string input)
{
T notUsed;
return T.TryParse(input, out notUsed);
}
</code></pre>
<p>this won't compile as it cannot resolve symbol 'TryParse'</p>
<p>As I understand, 'TryParse' is not part of any interface.</p>
<p>Is this possible to do at all?</p>
<p><strong>Update:</strong></p>
<p>Using the answers below I have come up with:</p>
<pre><code>public static bool Is<T>(this string input)
{
try
{
TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(input);
}
catch
{
return false;
}
return true;
}
</code></pre>
<p>It works quite well but I think using exceptions in that way doesn't feel right to me.</p>
<p><strong>Update2:</strong></p>
<p>Modified to pass type rather than use generics:</p>
<pre><code>public static bool Is(this string input, Type targetType)
{
try
{
TypeDescriptor.GetConverter(targetType).ConvertFromString(input);
return true;
}
catch
{
return false;
}
}
</code></pre> | <p>You should use the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.typedescriptor.aspx" rel="noreferrer">TypeDescriptor</a> class:</p>
<pre><code>public static T Convert<T>(this string input)
{
try
{
var converter = TypeDescriptor.GetConverter(typeof(T));
if(converter != null)
{
// Cast ConvertFromString(string text) : object to (T)
return (T)converter.ConvertFromString(input);
}
return default(T);
}
catch (NotSupportedException)
{
return default(T);
}
}
</code></pre> | {
"question_id": 2961656,
"question_date": "2010-06-02T21:16:30.737Z",
"question_score": 215,
"tags": "c#|generics|tryparse",
"answer_id": 2961702,
"answer_date": "2010-06-02T21:23:48.637Z",
"answer_score": 214
} |
Please answer the following Stack Overflow question:
Title: Where does Android Studio save the ProGuard mapping file?
<p>In Android Studio, where are the ProGuard mapping files generated after compiling a signed APK?</p>
<p>I'm not sure if it isn't working or if I just forgot the file path, and my compulsory Google/Stack Overflow search did not answer this</p> | <p>It should be located at <code>build/outputs/proguard/release/mapping.txt</code> in your application module's directory.</p>
<p>In the latest version of ProGuard and Android Studio, the file is located at <code>build/outputs/mapping/release/mapping.txt</code>.</p> | {
"question_id": 25724645,
"question_date": "2014-09-08T12:47:37.543Z",
"question_score": 215,
"tags": "android|android-studio|apk|proguard",
"answer_id": 25732793,
"answer_date": "2014-09-08T20:37:47.617Z",
"answer_score": 312
} |
Please answer the following Stack Overflow question:
Title: Properly removing an Integer from a List<Integer>
<p>Here's a nice pitfall I just encountered.
Consider a list of integers:</p>
<pre><code>List<Integer> list = new ArrayList<Integer>();
list.add(5);
list.add(6);
list.add(7);
list.add(1);
</code></pre>
<p>Any educated guess on what happens when you execute <code>list.remove(1)</code>? What about <code>list.remove(new Integer(1))</code>? This can cause some nasty bugs.</p>
<p>What is the proper way to differentiate between <a href="http://download.oracle.com/javase/1.5.0/docs/api/java/util/List.html#remove(int)" rel="noreferrer"><code>remove(int index)</code></a>, which removes an element from given index and <a href="http://download.oracle.com/javase/1.5.0/docs/api/java/util/List.html#remove(java.lang.Object)" rel="noreferrer"><code>remove(Object o)</code></a>, which removes an element by reference, when dealing with lists of integers?</p>
<hr>
<p>The main point to consider here is the one <a href="https://stackoverflow.com/questions/4534146/properly-removing-an-integer-from-a-listinteger/4534152#4534152">@Nikita mentioned</a> - exact parameter matching takes precedence over auto-boxing.</p> | <p>Java always calls the method that best suits your argument. Auto boxing and implicit upcasting is only performed if there's no method which can be called without casting / auto boxing.</p>
<p>The List interface specifies two remove methods (please note the naming of the arguments):</p>
<ul>
<li><code>remove(Object o)</code></li>
<li><code>remove(int index)</code></li>
</ul>
<p>That means that <code>list.remove(1)</code> removes the object at position 1 and <code>remove(new Integer(1))</code> removes the first occurrence of the specified element from this list.</p> | {
"question_id": 4534146,
"question_date": "2010-12-26T14:25:35.850Z",
"question_score": 215,
"tags": "java|collections|overloading",
"answer_id": 4534196,
"answer_date": "2010-12-26T14:45:49.103Z",
"answer_score": 243
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.