input_text
stringlengths 115
13.8k
| output_text
stringlengths 24
15k
| metadata
dict |
---|---|---|
Please answer the following Stack Overflow question:
Title: The object 'DF__*' is dependent on column '*' - Changing int to double
<p>Basically I got a table in my EF database with the following properties:</p>
<pre><code>public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Image { get; set; }
public string WatchUrl { get; set; }
public int Year { get; set; }
public string Source { get; set; }
public int Duration { get; set; }
public int Rating { get; set; }
public virtual ICollection<Category> Categories { get; set; }
</code></pre>
<p>It works fine however when I change the int of Rating to be a double I get the following error when updating the database:</p>
<p><strong>The object 'DF_<em>Movies</em>_Rating__48CFD27E' is dependent on column 'Rating'.
ALTER TABLE ALTER COLUMN Rating failed because one or more objects access this column.</strong></p>
<p>What's the issue?</p> | <p>Try this:</p>
<p>Remove the constraint <em>DF_Movies_Rating__48CFD27E</em> before changing your field type.</p>
<p>The constraint is typically created automatically by the DBMS (SQL Server).</p>
<p>To see the constraint associated with the table, expand the table attributes in <strong>Object explorer</strong>, followed by the category <em>Constraints</em> as shown below:</p>
<p><img src="https://i.stack.imgur.com/fYfVn.png" alt="Tree of your table"></p>
<p>You must remove the constraint before changing the field type.</p> | {
"question_id": 19460912,
"question_date": "2013-10-19T00:26:59.570Z",
"question_score": 212,
"tags": "sql|sql-server|database|entity-framework|entity-framework-4",
"answer_id": 19461205,
"answer_date": "2013-10-19T01:10:03.930Z",
"answer_score": 315
} |
Please answer the following Stack Overflow question:
Title: How to increase storage for Android Emulator? (INSTALL_FAILED_INSUFFICIENT_STORAGE)
<p>I get this sometimes(not often) for one of my projects, couple of classes only<br>
<code>Installation error: INSTALL_FAILED_INSUFFICIENT_STORAGE</code></p>
<p>How do I increase emulator's storage?</p> | <h1>Update</h1>
<p>This answer is, as I write this, nearly eight years old, and about five years stale. But it's still (as I write this) the "accepted" answer, because it answered the question <em>when it was asked.</em></p>
<p>The newer answer, that applies to the newer Android Studio tools, can be found here: <a href="https://stackoverflow.com/a/35828035/62">https://stackoverflow.com/a/35828035/62</a> -- it's a great answer with screen shots. If you're using Android Studio, ignore the Eclipse answer below.</p>
<h1>Original Eclipse-based Answer</h1>
<p>I was searching for the answer to this question, and was unsatisfied with the above answers. But then I found the <a href="http://groups.google.com/group/android-developers/browse_thread/thread/41852900bd603070/583943d91dc9f754?lnk=gst&q=insufficient+memory#583943d91dc9f754" rel="noreferrer">answer</a>, so here it is for future reference:</p>
<p>To summarize (and clarify), in Eclipse, go to "Debug Configurations". You can find that in the drop-down under the "debug" icon. Select "target", and select a preferred emulator target to launch. Then under "additional emulator command line options," add this:</p>
<p><strong>-partition-size 1024</strong></p>
<p>Then CLOSE the emulator (and remove any devices), and click the debug icon, which will launch the preferred emulator you selected. This is important: Eclipse needs to launch the debugger, not AVD. </p>
<p>That fixed the problem for me.</p> | {
"question_id": 2239330,
"question_date": "2010-02-10T18:26:26.547Z",
"question_score": 212,
"tags": "android|android-emulator|emulation|avd",
"answer_id": 3945915,
"answer_date": "2010-10-15T20:33:47.273Z",
"answer_score": 139
} |
Please answer the following Stack Overflow question:
Title: Notification bar icon turns white in Android 5 Lollipop
<p>I have an app showing custom notifications. The problem is that when running in Android 5 the small icon in the Notification bar is shown in white. How can I fix this?</p> | <p>The accepted answer is not (entirely) correct. Sure, it makes notification icons show in color, but does so with a BIG drawback - by setting the target SDK to lower than Android Lollipop!</p>
<p>If you solve your white icon problem by setting your target SDK to 20, as suggested, your app will not target Android Lollipop, which means that you cannot use Lollipop-specific features.</p>
<p>Have a look at <a href="http://developer.android.com/design/style/iconography.html">http://developer.android.com/design/style/iconography.html</a>, and you'll see that the white style is how notifications are meant to be displayed in Android Lollipop.</p>
<p>In Lollipop, Google also suggest that you use a color that will be displayed behind the (white) notification icon - <a href="https://developer.android.com/about/versions/android-5.0-changes.html">https://developer.android.com/about/versions/android-5.0-changes.html</a></p>
<p>So, I think that a better solution is to add a silhouette icon to the app and use it if the device is running Android Lollipop.</p>
<p>For instance:</p>
<pre><code>Notification notification = new Notification.Builder(context)
.setAutoCancel(true)
.setContentTitle("My notification")
.setContentText("Look, white in Lollipop, else color!")
.setSmallIcon(getNotificationIcon())
.build();
return notification;
</code></pre>
<p>And, in the getNotificationIcon method:</p>
<pre><code>private int getNotificationIcon() {
boolean useWhiteIcon = (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP);
return useWhiteIcon ? R.drawable.icon_silhouette : R.drawable.ic_launcher;
}
</code></pre> | {
"question_id": 28387602,
"question_date": "2015-02-07T21:29:25.683Z",
"question_score": 212,
"tags": "android|android-notifications|android-5.0-lollipop",
"answer_id": 29207365,
"answer_date": "2015-03-23T10:00:03.627Z",
"answer_score": 272
} |
Please answer the following Stack Overflow question:
Title: How to export specific request to file using postman?
<p>I want to export one specific request from a Postman extension (Chromium) and send it to another developer so that they can import it. How I can do this?</p> | <p>To do that you need to leverage the "Collections" feature of Postman. This link could help you: <a href="https://learning.getpostman.com/docs/postman/collections/creating_collections/" rel="noreferrer">https://learning.getpostman.com/docs/postman/collections/creating_collections/</a></p>
<p>Here is the way to do it:</p>
<ul>
<li>Create a collection (within tab "Collections")</li>
<li>Execute your request</li>
<li>Add the request to a collection</li>
<li>Share your collection as a file</li>
</ul> | {
"question_id": 28965847,
"question_date": "2015-03-10T14:05:29.547Z",
"question_score": 212,
"tags": "rest|postman|webapi",
"answer_id": 28966615,
"answer_date": "2015-03-10T14:39:05.673Z",
"answer_score": 197
} |
Please answer the following Stack Overflow question:
Title: SQL Server: Filter output of sp_who2
<p>Under SQL Server, is there an easy way to filter the output of sp_who2? Say I wanted to just show rows for a certain database, for example.</p> | <p>You could try something like</p>
<pre><code>DECLARE @Table TABLE(
SPID INT,
Status VARCHAR(MAX),
LOGIN VARCHAR(MAX),
HostName VARCHAR(MAX),
BlkBy VARCHAR(MAX),
DBName VARCHAR(MAX),
Command VARCHAR(MAX),
CPUTime INT,
DiskIO INT,
LastBatch VARCHAR(MAX),
ProgramName VARCHAR(MAX),
SPID_1 INT,
REQUESTID INT
)
INSERT INTO @Table EXEC sp_who2
SELECT *
FROM @Table
WHERE ....
</code></pre>
<p>And filter on what you require.</p> | {
"question_id": 2234691,
"question_date": "2010-02-10T05:39:18.720Z",
"question_score": 212,
"tags": "sql-server|sql-server-2016",
"answer_id": 2234713,
"answer_date": "2010-02-10T05:46:46.077Z",
"answer_score": 374
} |
Please answer the following Stack Overflow question:
Title: facebook: permanent Page Access Token?
<p>I work on a project that has facebook pages as one of its data sources. It imports some data from it periodically with no GUI involved. Then we use a web app to show the data we already have.</p>
<p>Not all the information is public. This means I have to get access to the data once and then keep it. However, I don't know the process and I haven't found a good tutorial on that yet. I guess I need an <code>access_token</code>, how can I get it from the user, step by step? The user is an admin of a facebook page, will he have to add some FB app of ours to the page?</p>
<p>EDIT: Thanks @phwd for the tip. I made a tutorial how to get a permanent page access token, even with <code>offline_access</code> no longer existing.</p>
<p>EDIT: I just found out it's answered here: <a href="https://stackoverflow.com/questions/12168452/long-lasting-fb-access-token-for-server-to-pull-fb-page-info">Long-lasting FB access-token for server to pull FB page info</a></p> | <p>Following the instructions laid out in Facebook's <a href="https://developers.facebook.com/docs/facebook-login/access-tokens#extendingpagetokens" rel="noreferrer">extending page tokens documentation</a> I was able to get a page access token that does not expire.</p>
<p>I suggest using the <a href="https://developers.facebook.com/tools/explorer" rel="noreferrer">Graph API Explorer</a> for all of these steps except where otherwise stated.</p>
<h3>0. Create Facebook App</h3>
<p><strong>If you already have an app</strong>, skip to step 1.</p>
<ol>
<li>Go to <a href="https://developers.facebook.com/apps/" rel="noreferrer">My Apps</a>.</li>
<li>Click "+ Add a New App".</li>
<li>Setup a website app.</li>
</ol>
<p>You don't need to change its permissions or anything. You just need an app that wont go away before you're done with your access token.</p>
<h3>1. Get User Short-Lived Access Token</h3>
<ol>
<li>Go to the <a href="https://developers.facebook.com/tools/explorer" rel="noreferrer">Graph API Explorer</a>.</li>
<li>Select the application you want to get the access token for (in the "Application" drop-down menu, not the "My Apps" menu).</li>
<li>Click "Get Token" > "Get User Access Token".</li>
<li>In the pop-up, under the "Extended Permissions" tab, check "manage_pages".</li>
<li>Click "Get Access Token".</li>
<li>Grant access from a Facebook account that has access to manage the target page. Note that if this user loses access the final, never-expiring access token will likely stop working.</li>
</ol>
<p>The token that appears in the "Access Token" field is your short-lived access token.</p>
<h3>2. Generate Long-Lived Access Token</h3>
<p>Following <a href="https://developers.facebook.com/docs/facebook-login/access-tokens#extending" rel="noreferrer">these instructions</a> from the Facebook docs, make a GET request to</p>
<blockquote>
<p><a href="https://graph.facebook.com/v2.10/oauth/access_token?grant_type=fb_exchange_token&client_id=" rel="noreferrer">https://graph.facebook.com/v2.10/oauth/access_token?grant_type=fb_exchange_token&client_id=</a><strong>{app_id}</strong>&client_secret=<strong>{app_secret}</strong>&fb_exchange_token=<strong>{short_lived_token}</strong></p>
</blockquote>
<p>entering in your app's ID and secret and the short-lived token generated in the previous step.</p>
<p>You <strong>cannot use the Graph API Explorer</strong>. For some reason it gets stuck on this request. I think it's because the response isn't JSON, but a query string. Since it's a GET request, you can just go to the URL in your browser.</p>
<p>The response should look like this:</p>
<blockquote>
<p>{"access_token":"<strong>ABC123</strong>","token_type":"bearer","expires_in":5183791}</p>
</blockquote>
<p>"ABC123" will be your long-lived access token. You can put it into the <a href="https://developers.facebook.com/tools/debug/accesstoken" rel="noreferrer">Access Token Debugger</a> to verify. Under "Expires" it should have something like "2 months".</p>
<h3>3. Get User ID</h3>
<p>Using the long-lived access token, make a GET request to </p>
<blockquote>
<p><a href="https://graph.facebook.com/v2.10/me?access_token=" rel="noreferrer">https://graph.facebook.com/v2.10/me?access_token=</a><strong>{long_lived_access_token}</strong></p>
</blockquote>
<p>The <code>id</code> field is your account ID. You'll need it for the next step.</p>
<h3>4. Get Permanent Page Access Token</h3>
<p>Make a GET request to</p>
<blockquote>
<p><a href="https://graph.facebook.com/v2.10/" rel="noreferrer">https://graph.facebook.com/v2.10/</a><strong>{account_id}</strong>/accounts?access_token=<strong>{long_lived_access_token}</strong></p>
</blockquote>
<p>The JSON response should have a <code>data</code> field under which is an array of items the user has access to. Find the item for the page you want the permanent access token from. The <code>access_token</code> field should have your permanent access token. Copy it and test it in the <a href="https://developers.facebook.com/tools/debug/accesstoken" rel="noreferrer">Access Token Debugger</a>. Under "Expires" it should say "Never".</p> | {
"question_id": 17197970,
"question_date": "2013-06-19T17:52:35.160Z",
"question_score": 212,
"tags": "facebook|facebook-graph-api|facebook-access-token",
"answer_id": 28418469,
"answer_date": "2015-02-09T20:14:26.687Z",
"answer_score": 673
} |
Please answer the following Stack Overflow question:
Title: How do I get a background location update every n minutes in my iOS application?
<p>I'm looking for a way to get a background location update every n minutes in my iOS application. I'm using iOS 4.3 and the solution should work for non-jailbroken iPhones.</p>
<p>I tried / considered following options:</p>
<ul>
<li><code>CLLocationManager startUpdatingLocation/startMonitoringSignificantLocationChanges</code>: This works in the background as expected, based on the configured properties, but it seems not possible to force it to update the location every n minutes</li>
<li><code>NSTimer</code>: Does work when the app is running in the foreground but doesn't seem to be designed for background tasks</li>
<li>Local notifications: Local notifications can be scheduled every n minutes, but it's not possible to execute some code to get the current location (without the user having to launch the app via the notification). This approach also doesn't seem to be a clean approach as this is not what notifications should be used for.</li>
<li><code>UIApplication:beginBackgroundTaskWithExpirationHandler</code>: As far as I understand, this should be used to finish some work in the background (also limited in time) when an app is moved to the background rather than implementing "long-running" background processes.</li>
</ul>
<p>How can I implement these regular background location updates?</p> | <p>I found a solution to implement this with the help of the Apple Developer Forums:</p>
<ul>
<li>Specify <code>location background mode</code></li>
<li>Create an <code>NSTimer</code> in the background with <code>UIApplication:beginBackgroundTaskWithExpirationHandler:</code></li>
<li>When <code>n</code> is <strong>smaller</strong> than <code>UIApplication:backgroundTimeRemaining</code> it will work just fine. When <code>n</code> is <strong>larger</strong>, the <code>location manager</code> should be enabled (and disabled) again before there is no time remaining to avoid the background task being killed. </li>
</ul>
<p><em>This works because location is one of the three allowed types of background execution</em>.</p>
<p><strong>Note: I lost some time by testing this in the simulator where it doesn't work. However, it works fine on my phone.</strong></p> | {
"question_id": 6347503,
"question_date": "2011-06-14T17:23:18.867Z",
"question_score": 212,
"tags": "ios|objective-c|core-location|background-process",
"answer_id": 6465280,
"answer_date": "2011-06-24T08:32:56.333Z",
"answer_score": 117
} |
Please answer the following Stack Overflow question:
Title: How to get the ActionBar height?
<p>I am trying to get the height of the <code>ActionBar</code> (using Sherlock) every time an activity is created (specially to handle configuration changes on rotation where the ActionBar height might change).</p>
<p>For this I use the method <code>ActionBar.getHeight()</code> which works only when the <code>ActionBar</code> is shown.</p>
<p>When the first activity is created for the first time, I can call <code>getHeight()</code> in the <code>onCreateOptionsMenu</code> callback. But this method is not called after.</p>
<p>So my question is when can I call getHeight() and be assured that it doesn't return 0?
Or if it is not possible, how can I set the height of the ActionBar ?</p> | <p>While @birdy's answer is an option if you want to explicitly control the ActionBar size, there is a way to pull it up without locking the size that I found in support documentation. It's a little awkward but it's worked for me. You'll need a context, this example would be valid in an Activity.</p>
<pre><code>// Calculate ActionBar height
TypedValue tv = new TypedValue();
if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
{
int actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
}
</code></pre>
<p><strong>Kotlin</strong>:</p>
<pre class="lang-kotlin prettyprint-override"><code>val tv = TypedValue()
if (requireActivity().theme.resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
val actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, resources.displayMetrics)
}
</code></pre> | {
"question_id": 12301510,
"question_date": "2012-09-06T13:45:03.437Z",
"question_score": 212,
"tags": "android|android-actionbar",
"answer_id": 13216807,
"answer_date": "2012-11-04T07:14:26.607Z",
"answer_score": 451
} |
Please answer the following Stack Overflow question:
Title: SQL JOIN vs IN performance?
<p>I have a case where using a JOIN or an IN will give me the correct results... Which typically has better performance and why? How much does it depend on what database server you are running? (FYI I am using MSSQL)</p> | <p>Generally speaking, <code>IN</code> and <code>JOIN</code> are different queries that can yield different results.</p>
<pre><code>SELECT a.*
FROM a
JOIN b
ON a.col = b.col
</code></pre>
<p>is not the same as</p>
<pre><code>SELECT a.*
FROM a
WHERE col IN
(
SELECT col
FROM b
)
</code></pre>
<p>, unless <code>b.col</code> is unique.</p>
<p>However, this is the synonym for the first query:</p>
<pre><code>SELECT a.*
FROM a
JOIN (
SELECT DISTINCT col
FROM b
)
ON b.col = a.col
</code></pre>
<p>If the joining column is <code>UNIQUE</code> and marked as such, both these queries yield the same plan in <code>SQL Server</code>.</p>
<p>If it's not, then <code>IN</code> is faster than <code>JOIN</code> on <code>DISTINCT</code>.</p>
<p>See this article in my blog for performance details:</p>
<ul>
<li><a href="http://explainextended.com/2009/06/16/in-vs-join-vs-exists/" rel="noreferrer"><strong><code>IN</code> vs. <code>JOIN</code> vs. <code>EXISTS</code></strong></a></li>
</ul> | {
"question_id": 1200295,
"question_date": "2009-07-29T13:31:26.897Z",
"question_score": 212,
"tags": "sql|sql-server|performance|tsql",
"answer_id": 1200337,
"answer_date": "2009-07-29T13:36:53.600Z",
"answer_score": 248
} |
Please answer the following Stack Overflow question:
Title: Asynchronous shell exec in PHP
<p>I've got a PHP script that needs to invoke a shell script but doesn't care at all about the output. The shell script makes a number of SOAP calls and is slow to complete, so I don't want to slow down the PHP request while it waits for a reply. In fact, the PHP request should be able to exit without terminating the shell process.</p>
<p>I've looked into the various <code>exec()</code>, <code>shell_exec()</code>, <code>pcntl_fork()</code>, etc. functions, but none of them seem to offer exactly what I want. (Or, if they do, it's not clear to me how.) Any suggestions?</p> | <p>If it "doesn't care about the output", couldn't the exec to the script be called with the <code>&</code> to background the process?</p>
<p><strong>EDIT</strong> - incorporating what @<a href="https://stackoverflow.com/users/1103/adamthehutt">AdamTheHut</a> commented to this post, you can add this to a call to <code>exec</code>:</p>
<pre><code>" > /dev/null 2>/dev/null &"
</code></pre>
<p>That will redirect both <code>stdio</code> (first <code>></code>) and <code>stderr</code> (<code>2></code>) to <code>/dev/null</code> and run in the background.</p>
<p>There are other ways to do the same thing, but this is the simplest to read.</p>
<hr>
<p>An alternative to the above double-redirect:</p>
<pre><code>" &> /dev/null &"
</code></pre> | {
"question_id": 222414,
"question_date": "2008-10-21T16:02:10.003Z",
"question_score": 212,
"tags": "php|asynchronous|shell",
"answer_id": 222445,
"answer_date": "2008-10-21T16:08:03.283Z",
"answer_score": 236
} |
Please answer the following Stack Overflow question:
Title: How do I merge a specific commit from one branch into another in Git?
<p>I have <code>BranchA</code> which is 113 commits ahead of <code>BranchB</code>.</p>
<p>But I only want the last 10 or so commits from <code>BranchA</code> merged into <code>BranchB</code>.</p>
<p>Is there a way to do this?</p> | <p>The <code>git cherry-pick <commit></code> command allows you to take a single commit (from whatever branch) and, essentially, rebase it in your working branch.</p>
<p><a href="https://git-scm.com/book/en/v2/Distributed-Git-Maintaining-a-Project#_rebase_cherry_pick" rel="noreferrer">Chapter 5 of the Pro Git book explains it better than I can</a>, complete with diagrams and such. (<a href="http://git-scm.com/book/en/Git-Branching-Rebasing" rel="noreferrer">The chapter on Rebasing</a> is also good reading.)</p>
<p>Lastly, there are some <a href="https://stackoverflow.com/questions/1241720/git-cherry-pick-vs-merge-workflow">good comments on the cherry-picking vs merging vs rebasing in another SO question</a>.</p> | {
"question_id": 6372044,
"question_date": "2011-06-16T12:46:25.927Z",
"question_score": 212,
"tags": "git|github",
"answer_id": 6372513,
"answer_date": "2011-06-16T13:16:22.597Z",
"answer_score": 316
} |
Please answer the following Stack Overflow question:
Title: Manually map column names with class properties
<p>I am new to the Dapper micro ORM. So far I am able to use it for simple ORM related stuff but I am not able to map the database column names with the class properties.</p>
<p>For example, I have the following database table:</p>
<pre><code>Table Name: Person
person_id int
first_name varchar(50)
last_name varchar(50)
</code></pre>
<p>and I have a class called Person:</p>
<pre><code>public class Person
{
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
</code></pre>
<p>Please note that my column names in the table are different from the property name of the class to which I am trying to map the data which I got from the query result.</p>
<pre><code>var sql = @"select top 1 PersonId,FirstName,LastName from Person";
using (var conn = ConnectionFactory.GetConnection())
{
var person = conn.Query<Person>(sql).ToList();
return person;
}
</code></pre>
<p>The above code won't work as the column names don't match the object's (Person) properties. In this scenario, is there anything i can do in Dapper to manually map (e.g <code>person_id => PersonId</code>) the column names with object properties?</p> | <p>This works fine:</p>
<pre><code>var sql = @"select top 1 person_id PersonId, first_name FirstName, last_name LastName from Person";
using (var conn = ConnectionFactory.GetConnection())
{
var person = conn.Query<Person>(sql).ToList();
return person;
}
</code></pre>
<p>Dapper has no facility that allows you to specify a <a href="http://msdn.microsoft.com/en-us/library/system.data.linq.mapping.columnattribute.aspx" rel="noreferrer">Column Attribute</a>, I am not against adding support for it, providing we do not pull in the dependency. </p> | {
"question_id": 8902674,
"question_date": "2012-01-17T22:35:21.483Z",
"question_score": 212,
"tags": "dapper",
"answer_id": 8904096,
"answer_date": "2012-01-18T01:35:51.383Z",
"answer_score": 116
} |
Please answer the following Stack Overflow question:
Title: Django optional url parameters
<p>I have a Django URL like this:</p>
<pre><code>url(
r'^project_config/(?P<product>\w+)/(?P<project_id>\w+)/$',
'tool.views.ProjectConfig',
name='project_config'
),
</code></pre>
<p><strong>views.py:</strong></p>
<pre><code>def ProjectConfig(request, product, project_id=None, template_name='project.html'):
...
# do stuff
</code></pre>
<p>The problem is that I want the <code>project_id</code> parameter to be optional.</p>
<p>I want <code>/project_config/</code> and <code>/project_config/12345abdce/</code> to be equally valid URL patterns, so that <strong>if</strong> <code>project_id</code> is passed, <strong>then</strong> I can use it.</p>
<p>As it stands at the moment, I get a 404 when I access the URL without the <code>project_id</code> parameter.</p> | <p>There are several approaches.</p>
<p>One is to use a non-capturing group in the regex: <code>(?:/(?P<title>[a-zA-Z]+)/)?</code><br>
<a href="https://stackoverflow.com/questions/2325433/making-a-regex-django-url-token-optional">Making a Regex Django URL Token Optional</a></p>
<p>Another, easier to follow way is to have multiple rules that matches your needs, all pointing to the same view.</p>
<pre><code>urlpatterns = patterns('',
url(r'^project_config/$', views.foo),
url(r'^project_config/(?P<product>\w+)/$', views.foo),
url(r'^project_config/(?P<product>\w+)/(?P<project_id>\w+)/$', views.foo),
)
</code></pre>
<p>Keep in mind that in your view you'll also need to set a default for the optional URL parameter, or you'll get an error:</p>
<pre><code>def foo(request, optional_parameter=''):
# Your code goes here
</code></pre> | {
"question_id": 14351048,
"question_date": "2013-01-16T03:46:35.593Z",
"question_score": 212,
"tags": "python|django|django-views|django-urls",
"answer_id": 14351174,
"answer_date": "2013-01-16T04:03:10.923Z",
"answer_score": 454
} |
Please answer the following Stack Overflow question:
Title: What to put in a python module docstring?
<p>Ok, so I've read both <a href="http://www.python.org/dev/peps/pep-0008/" rel="noreferrer">PEP 8</a> and <a href="http://www.python.org/dev/peps/pep-0257/" rel="noreferrer">PEP 257</a>, and I've written lots of docstrings for functions and classes, but I'm a little unsure about what should go in a module docstring. I figured, at a minimum, it should document the functions and classes that the module exports, but I've also seen a few modules that list author names, copyright information, etc. Does anyone have an example of how a good python docstring should be structured?</p> | <p>Think about somebody doing <code>help(yourmodule)</code> at the interactive interpreter's prompt — what do they <strong>want</strong> to know? (Other methods of extracting and displaying the information are roughly equivalent to <code>help</code> in terms of amount of information). So if you have in <code>x.py</code>:</p>
<pre><code>"""This module does blah blah."""
class Blah(object):
"""This class does blah blah."""
</code></pre>
<p>then:</p>
<pre><code>>>> import x; help(x)
</code></pre>
<p>shows:</p>
<pre><code>Help on module x:
NAME
x - This module does blah blah.
FILE
/tmp/x.py
CLASSES
__builtin__.object
Blah
class Blah(__builtin__.object)
| This class does blah blah.
|
| Data and other attributes defined here:
|
| __dict__ = <dictproxy object>
| dictionary for instance variables (if defined)
|
| __weakref__ = <attribute '__weakref__' of 'Blah' objects>
| list of weak references to the object (if defined)
</code></pre>
<p>As you see, the detailed information on the classes (and functions too, though I'm not showing one here) is already included from those components' docstrings; the module's own docstring should describe them very summarily (if at all) and rather concentrate on a concise summary of what the module as a whole can do for you, ideally with some doctested examples (just like functions and classes ideally should have doctested examples in their docstrings).</p>
<p>I don't see how metadata such as author name and copyright / license helps the module's user — it can rather go in comments, since it could help somebody considering whether or not to reuse or modify the module.</p> | {
"question_id": 2557110,
"question_date": "2010-03-31T23:04:34.843Z",
"question_score": 212,
"tags": "python|documentation|module",
"answer_id": 2557196,
"answer_date": "2010-03-31T23:28:02.957Z",
"answer_score": 237
} |
Please answer the following Stack Overflow question:
Title: Rails: How to reference images in CSS within Rails 4
<p>There's a strange issue with Rails 4 on Heroku. When images are compiled they have hashes added to them, yet the reference to those files from within CSS don't have the proper name adjusted. Here's what I mean. I have a file called logo.png. Yet when it shows up on heroku it is viewed as:</p>
<pre><code>/assets/logo-200a00a193ed5e297bb09ddd96afb953.png
</code></pre>
<p>However the CSS still states:</p>
<pre><code>background-image:url("./logo.png");
</code></pre>
<p>The result: the image doesn't display. Anybody run into this? How can this be resolved?</p> | <p>Sprockets together with Sass has <a href="http://guides.rubyonrails.org/asset_pipeline.html#css-and-sass" rel="noreferrer">some nifty helpers</a> you can use to get the job done. Sprockets will <em>only</em> process these helpers if your stylesheet file extensions are either <code>.css.scss</code> or <code>.css.sass</code>.</p>
<hr>
<p><strong>Image specific helper:</strong></p>
<pre><code>background-image: image-url("logo.png")
</code></pre>
<hr>
<p><strong>Agnostic helper:</strong></p>
<pre><code>background-image: asset-url("logo.png", image)
background-image: asset-url($asset, $asset-type)
</code></pre>
<hr>
<p>Or if you want to embed the image data in the css file:</p>
<pre><code>background-image: asset-data-url("logo.png")
</code></pre> | {
"question_id": 15257555,
"question_date": "2013-03-06T20:40:55.010Z",
"question_score": 212,
"tags": "ruby-on-rails|heroku|ruby-on-rails-4",
"answer_id": 15591726,
"answer_date": "2013-03-23T20:30:32.813Z",
"answer_score": 405
} |
Please answer the following Stack Overflow question:
Title: Track a new remote branch created on GitHub
<p>I have already got a local master branch tracking the remote master branch of a github project. Now, a collaborator of mine has created a new branch in the same project, and I want to do the following accordingly:</p>
<ol>
<li>create a new branch locally</li>
<li>make this new branch track the newly create remote branch.</li>
</ol>
<p>How should I do it properly?</p> | <pre><code>git fetch
git branch --track branch-name origin/branch-name
</code></pre>
<p>First command makes sure you have remote branch in local repository. Second command creates local branch which tracks remote branch. It assumes that your remote name is <code>origin</code> and branch name is <code>branch-name</code>.</p>
<p><code>--track</code> option is enabled by default for remote branches and you can omit it.</p> | {
"question_id": 11262703,
"question_date": "2012-06-29T13:28:57.797Z",
"question_score": 212,
"tags": "git|github|git-branch",
"answer_id": 11262780,
"answer_date": "2012-06-29T13:33:55.530Z",
"answer_score": 288
} |
Please answer the following Stack Overflow question:
Title: How to flatten only some dimensions of a numpy array
<p>Is there a quick way to "sub-flatten" or flatten only some of the first dimensions in a numpy array?</p>
<p>For example, given a numpy array of dimensions <code>(50,100,25)</code>, the resultant dimensions would be <code>(5000,25)</code></p> | <p>Take a look at <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html" rel="noreferrer">numpy.reshape</a> .</p>
<pre><code>>>> arr = numpy.zeros((50,100,25))
>>> arr.shape
# (50, 100, 25)
>>> new_arr = arr.reshape(5000,25)
>>> new_arr.shape
# (5000, 25)
# One shape dimension can be -1.
# In this case, the value is inferred from
# the length of the array and remaining dimensions.
>>> another_arr = arr.reshape(-1, arr.shape[-1])
>>> another_arr.shape
# (5000, 25)
</code></pre> | {
"question_id": 18757742,
"question_date": "2013-09-12T07:12:21.767Z",
"question_score": 212,
"tags": "python|numpy|flatten",
"answer_id": 18758049,
"answer_date": "2013-09-12T07:27:33.007Z",
"answer_score": 195
} |
Please answer the following Stack Overflow question:
Title: "undefined" function declared in another file?
<p>I'm trying to write a basic go program that calls a function on a different file, but a part of the same package. However, it returns:</p>
<pre><code>undefined: NewEmployee
</code></pre>
<p>Here is the source code:</p>
<p><code>main.go</code>:</p>
<pre><code>package main
func main() {
emp := NewEmployee()
}
</code></pre>
<p><code>employee.go</code>:</p>
<pre><code>package main
type Employee struct {
name string
age int
}
func NewEmployee() *Employee {
p := &Employee{}
return p
}
func PrintEmployee (p *Employee) {
return "Hello world!"
}
</code></pre> | <p>Please read <a href="http://golang.org/doc/code.html" rel="noreferrer">"How to Write Go Code"</a>.</p>
<p>Use <code>go build</code> or <code>go install</code> within the package directory, or supply an import path for the package. Do not use file arguments for <code>build</code> or <code>install</code>.</p>
<p>While you can use file arguments for <code>go run</code>, you should build a package instead, usually with <code>go run .</code>, though you should almost always use <code>go install</code>, or <code>go build</code>.</p> | {
"question_id": 28153203,
"question_date": "2015-01-26T15:27:12.027Z",
"question_score": 212,
"tags": "go|undefined|func",
"answer_id": 28153553,
"answer_date": "2015-01-26T15:46:59.587Z",
"answer_score": 255
} |
Please answer the following Stack Overflow question:
Title: How do I merge a list of dicts into a single dict?
<p>How can I turn a list of dicts like <code>[{'a':1}, {'b':2}, {'c':1}, {'d':2}]</code>, into a single dict like <code>{'a':1, 'b':2, 'c':1, 'd':2}</code>?</p>
<hr />
<p><sub>Answers here will <em>overwrite</em> keys that match between two of the input dicts, because a dict cannot have duplicate keys. If you want to <em>collect</em> multiple values from matching keys, see <a href="https://stackoverflow.com/questions/5946236/how-to-merge-dicts-collecting-values-from-matching-keys">How to merge dicts, collecting values from matching keys?</a>.</sub></p> | <p>This works for dictionaries of any length:</p>
<pre><code>>>> result = {}
>>> for d in L:
... result.update(d)
...
>>> result
{'a':1,'c':1,'b':2,'d':2}
</code></pre>
<p>As a <a href="https://www.python.org/dev/peps/pep-0274/" rel="noreferrer">comprehension</a>:</p>
<pre><code># Python >= 2.7
{k: v for d in L for k, v in d.items()}
# Python < 2.7
dict(pair for d in L for pair in d.items())
</code></pre> | {
"question_id": 3494906,
"question_date": "2010-08-16T15:55:58.427Z",
"question_score": 212,
"tags": "python|list|dictionary",
"answer_id": 3495395,
"answer_date": "2010-08-16T16:56:47.640Z",
"answer_score": 265
} |
Please answer the following Stack Overflow question:
Title: How is Perl's @INC constructed? (aka What are all the ways of affecting where Perl modules are searched for?)
<p>What are all the ways of affecting where Perl modules are searched for?
or, <strong>How is Perl's @INC constructed</strong>? </p>
<p>As we know, <a href="https://stackoverflow.com/questions/2526520/how-does-a-perl-program-know-where-to-find-the-file-containing-perl-module-it-use">Perl uses <code>@INC</code> array containing directory names to determine where to search for Perl module files</a>. </p>
<p>There does not seem to be a comprehensive "@INC" FAQ-type post on StackOverflow, so this question is intended as one. </p> | <p>We will look at how the contents of this array are constructed and can be manipulated to affect where the Perl interpreter will find the module files.</p>
<ol>
<li><p>Default <code>@INC</code></p>
<p>Perl interpreter is <a href="http://search.cpan.org/perldoc/INSTALL" rel="noreferrer">compiled with a specific <code>@INC</code> default value</a>. To find out this value, run <code>env -i perl -V</code> command (<code>env -i</code> ignores the <code>PERL5LIB</code> environmental variable - see #2) and in the output you will see something like this:</p>
<blockquote>
<pre><code>$ env -i perl -V
...
@INC:
/usr/lib/perl5/site_perl/5.18.0/x86_64-linux-thread-multi-ld
/usr/lib/perl5/site_perl/5.18.0
/usr/lib/perl5/5.18.0/x86_64-linux-thread-multi-ld
/usr/lib/perl5/5.18.0
.
</code></pre>
</blockquote></li>
</ol>
<p>Note <code>.</code> at the end; this is the current directory (which is not necessarily the same as the script's directory). It is missing in Perl 5.26+, and when Perl runs with <a href="http://perldoc.perl.org/perlrun.html#*-T*" rel="noreferrer"><code>-T</code> (taint checks enabled)</a>.</p>
<p>To change the default path when configuring Perl binary compilation, set the configuration option <a href="http://search.cpan.org/perldoc?INSTALL#otherlibdirs" rel="noreferrer"><code>otherlibdirs</code></a>:</p>
<blockquote>
<p><code>Configure -Dotherlibdirs=/usr/lib/perl5/site_perl/5.16.3</code></p>
</blockquote>
<ol start="2">
<li><p>Environmental variable <code>PERL5LIB</code> (or <code>PERLLIB</code>)</p>
<p>Perl pre-pends <code>@INC</code> with a list of directories (colon-separated) contained in <code>PERL5LIB</code> (if it is not defined, <code>PERLLIB</code> is used) environment variable of your shell. To see the contents of <code>@INC</code> after <code>PERL5LIB</code> and <code>PERLLIB</code> environment variables have taken effect, run <code>perl -V</code>.</p>
<blockquote>
<pre><code>$ perl -V
...
%ENV:
PERL5LIB="/home/myuser/test"
@INC:
/home/myuser/test
/usr/lib/perl5/site_perl/5.18.0/x86_64-linux-thread-multi-ld
/usr/lib/perl5/site_perl/5.18.0
/usr/lib/perl5/5.18.0/x86_64-linux-thread-multi-ld
/usr/lib/perl5/5.18.0
.
</code></pre>
</blockquote></li>
<li><p><code>-I</code> command-line option</p>
<p>Perl pre-pends <code>@INC</code> with a list of directories (colon-separated) passed as value of the <code>-I</code> command-line option. This can be done in three ways, as usual with Perl options:</p>
<ul>
<li><p>Pass it on command line:</p>
<pre><code>perl -I /my/moduledir your_script.pl
</code></pre></li>
<li><p>Pass it via the first line (shebang) of your Perl script:</p>
<pre><code>#!/usr/local/bin/perl -w -I /my/moduledir
</code></pre></li>
<li><p>Pass it as part of <code>PERL5OPT</code> (or <code>PERLOPT</code>) environment variable (see chapter 19.02 in <a href="http://oreilly.com/catalog/9780596004927" rel="noreferrer">Programming Perl</a>)</p></li>
</ul></li>
<li><p>Pass it via the <a href="http://perldoc.perl.org/lib.html" rel="noreferrer"><code>lib</code> pragma</a></p>
<p>Perl pre-pends <code>@INC</code> with a list of directories passed in to it via <code>use lib</code>.</p>
<p>In a program:</p>
<pre><code>use lib ("/dir1", "/dir2");
</code></pre>
<p>On the command line:</p>
<pre><code>perl -Mlib=/dir1,/dir2
</code></pre>
<p>You can also <a href="http://perldoc.perl.org/lib.html#Deleting-directories-from-@INC" rel="noreferrer">remove the directories from <code>@INC</code> via <code>no lib</code></a>.</p></li>
<li><p>You can directly manipulate <code>@INC</code> as a regular Perl array.</p>
<p>Note: Since <code>@INC</code> is used during the compilation phase, this must be done inside of a <code>BEGIN {}</code> block, which precedes the <code>use MyModule</code> statement.</p>
<ul>
<li><p>Add directories to the beginning via <code>unshift @INC, $dir</code>.</p></li>
<li><p>Add directories to the end via <code>push @INC, $dir</code>.</p></li>
<li><p>Do anything else you can do with a Perl array.</p></li>
</ul></li>
</ol>
<p>Note: The directories are <em>unshifted</em> onto <code>@INC</code> in the order listed in this answer, e.g. default <code>@INC</code> is last in the list, preceded by <code>PERL5LIB</code>, preceded by <code>-I</code>, preceded by <code>use lib</code> and direct <code>@INC</code> manipulation, the latter two mixed in whichever order they are in Perl code.</p>
<h3>References:</h3>
<ul>
<li><a href="http://perldoc.perl.org/perlmod.html#Perl-Modules" rel="noreferrer">perldoc perlmod</a></li>
<li><a href="http://perldoc.perl.org/lib.html" rel="noreferrer">perldoc lib</a></li>
<li><a href="http://world.std.com/~swmcd/steven/perl/module_mechanics.html" rel="noreferrer">Perl Module Mechanics - a great guide containing practical HOW-TOs</a></li>
<li><a href="https://stackoverflow.com/questions/185114/how-do-i-use-a-perl-module-in-a-directory-not-in-inc">How do I 'use' a Perl module in a directory not in <code>@INC</code>?</a></li>
<li><a href="https://rads.stackoverflow.com/amzn/click/com/0596000278" rel="noreferrer" rel="nofollow noreferrer">Programming Perl</a> - chapter 31 part 13, ch 7.2.41</li>
<li><a href="https://stackoverflow.com/questions/2526520/how-does-a-perl-program-know-where-to-find-the-file-containing-perl-module-it-use">How does a Perl program know where to find the file containing Perl module it uses?</a></li>
</ul>
<p>There does not seem to be a comprehensive <code>@INC</code> FAQ-type post on Stack Overflow, so this question is intended as one.</p>
<h3>When to use each approach?</h3>
<ul>
<li><p>If the modules in a directory need to be used by many/all scripts on your site, especially run by multiple users, that directory should be included in the default <code>@INC</code> compiled into the Perl binary.</p></li>
<li><p>If the modules in the directory will be used exclusively by a specific user for all the scripts that user runs (or if recompiling Perl is not an option to change default <code>@INC</code> in previous use case), set the users' <code>PERL5LIB</code>, usually during user login.</p>
<p><em>Note: Please be aware of the usual Unix environment variable pitfalls - e.g. in certain cases running the scripts as a particular user does not guarantee running them with that user's environment set up, e.g. via <code>su</code>.</em></p></li>
<li><p>If the modules in the directory need to be used only in specific circumstances (e.g. when the script(s) is executed in development/debug mode, you can either set <code>PERL5LIB</code> manually, or pass the <code>-I</code> option to perl.</p></li>
<li><p>If the modules need to be used only for specific scripts, by <em>all</em> users using them, use <code>use lib</code>/<code>no lib</code> pragmas in the program itself. It also should be used when the directory to be searched needs to be dynamically determined during runtime - e.g. from the script's command line parameters or script's path (see the <a href="http://p3rl.org/FindBin" rel="noreferrer">FindBin</a> module for very nice use case).</p></li>
<li><p>If the directories in <code>@INC</code> need to be manipulated according to some complicated logic, either impossible to too unwieldy to implement by combination of <code>use lib</code>/<code>no lib</code> pragmas, then use direct <code>@INC</code> manipulation inside <code>BEGIN {}</code> block or inside a special purpose library designated for <code>@INC</code> manipulation, which must be used by your script(s) before any other modules are used.</p>
<p>An example of this is automatically switching between libraries in prod/uat/dev directories, with waterfall library pickup in prod if it's missing from dev and/or UAT (the last condition makes the standard "use lib + FindBin" solution fairly complicated.
A detailed illustration of this scenario is in <a href="https://stackoverflow.com/questions/2474588/how-do-i-use-beta-perl-modules-from-beta-perl-scripts"><em>How do I use beta Perl modules from beta Perl scripts?</em></a>.</p></li>
<li><p>An additional use case for directly manipulating <code>@INC</code> is to be able to add subroutine references or object references (yes, Virginia, <code>@INC</code> can contain custom Perl code and not just directory names, as explained in <a href="https://stackoverflow.com/questions/2541119/when-is-a-subroutine-reference-in-inc-called"><em>When is a subroutine reference in @INC called?</em></a>).</p></li>
</ul> | {
"question_id": 2526804,
"question_date": "2010-03-26T21:14:48.710Z",
"question_score": 212,
"tags": "perl|perl-module",
"answer_id": 2526809,
"answer_date": "2010-03-26T21:15:29.393Z",
"answer_score": 266
} |
Please answer the following Stack Overflow question:
Title: AngularJS disable partial caching on dev machine
<p>I have problem with caching partials in AngularJS.</p>
<p>In my HTML page I have:</p>
<pre><code><body>
<div ng-view></div>
<body>
</code></pre>
<p>where my partials are loaded.</p>
<p>When I change HTML code in my partial, browser still load old data.</p>
<p>Is there any workaround?</p> | <p>For Development you can also deactivate the browser cache - In Chrome Dev Tools on the bottom right click on the gear and tick the option </p>
<blockquote>
<p>Disable cache (while DevTools is open)</p>
</blockquote>
<p>Update: In Firefox there is the same option in Debugger -> Settings -> Advanced Section (checked for Version 33)</p>
<p>Update 2: Although this option appears in Firefox some report it doesn't work. I suggest using firebug and following hadaytullah answer.</p> | {
"question_id": 14718826,
"question_date": "2013-02-05T23:20:59.087Z",
"question_score": 212,
"tags": "caching|angularjs|browser-cache",
"answer_id": 19177020,
"answer_date": "2013-10-04T08:49:34.660Z",
"answer_score": 200
} |
Please answer the following Stack Overflow question:
Title: Good way of getting the user's location in Android
<h2>The problem:</h2>
<p>Getting the user's current location within a threshold ASAP and at the same time conserve battery.</p>
<h2>Why the problem is a problem:</h2>
<p>First off, android has two providers; network and GPS. Sometimes network is better and sometimes the GPS is better.</p>
<p>By "better" I mean speed vs. accuracy ratio.<br>
I'm willing to sacrifice a few meters in accuracy if I can get the location almost instant and without turning on the GPS.</p>
<p>Secondly, if you request updates for location changes nothing is sent if the current location is stable.</p>
<p>Google has an example of determining the "best" location here: <a href="http://developer.android.com/guide/topics/location/obtaining-user-location.html#BestEstimate" rel="noreferrer">http://developer.android.com/guide/topics/location/obtaining-user-location.html#BestEstimate</a><br>
But I think it's no where near as good as it should/could be.</p>
<p>I'm kind of confused why google hasn't a normalized API for location, the developer shouldn't have to care where the location is from, you should just specify what you want and the phone should choose for you.</p>
<h2>What I need help with:</h2>
<p>I need to find a good way to determine the "best" location, maybe though some heuristic or maybe through some 3rd party library.</p>
<p><b>This does not mean determine the best provider!</b><br>
I'm probably gonna use all providers and picking the best of them.</p>
<h2>Background of the app:</h2>
<p>The app will collect the user's location at a fixed interval (let say every 10 minutes or so) and send it to a server.<br>
The app should conserve as much battery as possible and the location should have X (50-100?) meters accuracy.</p>
<p>The goal is to later be able to plot the user's path during the day on a map so I need sufficient accuracy for that.</p>
<h2>Misc:</h2>
<p>What do you think are reasonable values on desired and accepted accuracies?<br>
I've been using 100m as accepted and 30m as desired, is this to much to ask?<br>
I'd like to be able to plot the user's path on a map later.<br>
Is 100m for desired and 500m for accepted better?</p>
<p>Also, right now I have the GPS on for a maximum of 60 seconds per location update, is this too short to get a location if you're indoors with an accuracy of maybe 200m?</p>
<hr>
<p>This is my current code, any feedback is appreciated (apart from the lack of error checking which is TODO):</p>
<pre><code>protected void runTask() {
final LocationManager locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
updateBestLocation(locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER));
updateBestLocation(locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER));
if (getLocationQuality(bestLocation) != LocationQuality.GOOD) {
Looper.prepare();
setLooper(Looper.myLooper());
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateBestLocation(location);
if (getLocationQuality(bestLocation) != LocationQuality.GOOD)
return;
// We're done
Looper l = getLooper();
if (l != null) l.quit();
}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
public void onStatusChanged(String provider, int status,
Bundle extras) {
// TODO Auto-generated method stub
Log.i("LocationCollector", "Fail");
Looper l = getLooper();
if (l != null) l.quit();
}
};
// Register the listener with the Location Manager to receive
// location updates
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 1000, 1, locationListener,
Looper.myLooper());
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 1000, 1,
locationListener, Looper.myLooper());
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
Looper l = getLooper();
if (l != null) l.quit();
// Log.i("LocationCollector",
// "Stopping collector due to timeout");
}
}, MAX_POLLING_TIME);
Looper.loop();
t.cancel();
locationManager.removeUpdates(locationListener);
setLooper(null);
}
if (getLocationQuality(bestLocation) != LocationQuality.BAD)
sendUpdate(locationToString(bestLocation));
else Log.w("LocationCollector", "Failed to get a location");
}
private enum LocationQuality {
BAD, ACCEPTED, GOOD;
public String toString() {
if (this == GOOD) return "Good";
else if (this == ACCEPTED) return "Accepted";
else return "Bad";
}
}
private LocationQuality getLocationQuality(Location location) {
if (location == null) return LocationQuality.BAD;
if (!location.hasAccuracy()) return LocationQuality.BAD;
long currentTime = System.currentTimeMillis();
if (currentTime - location.getTime() < MAX_AGE
&& location.getAccuracy() <= GOOD_ACCURACY)
return LocationQuality.GOOD;
if (location.getAccuracy() <= ACCEPTED_ACCURACY)
return LocationQuality.ACCEPTED;
return LocationQuality.BAD;
}
private synchronized void updateBestLocation(Location location) {
bestLocation = getBestLocation(location, bestLocation);
}
// Pretty much an unmodified version of googles example
protected Location getBestLocation(Location location,
Location currentBestLocation) {
if (currentBestLocation == null) {
// A new location is always better than no location
return location;
}
if (location == null) return currentBestLocation;
// Check whether the new location fix is newer or older
long timeDelta = location.getTime() - currentBestLocation.getTime();
boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
boolean isNewer = timeDelta > 0;
// If it's been more than two minutes since the current location, use
// the new location
// because the user has likely moved
if (isSignificantlyNewer) {
return location;
// If the new location is more than two minutes older, it must be
// worse
} else if (isSignificantlyOlder) {
return currentBestLocation;
}
// Check whether the new location fix is more or less accurate
int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation
.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 200;
// Check if the old and new location are from the same provider
boolean isFromSameProvider = isSameProvider(location.getProvider(),
currentBestLocation.getProvider());
// Determine location quality using a combination of timeliness and
// accuracy
if (isMoreAccurate) {
return location;
} else if (isNewer && !isLessAccurate) {
return location;
} else if (isNewer && !isSignificantlyLessAccurate
&& isFromSameProvider) {
return location;
}
return bestLocation;
}
/** Checks whether two providers are the same */
private boolean isSameProvider(String provider1, String provider2) {
if (provider1 == null) {
return provider2 == null;
}
return provider1.equals(provider2);
}
</code></pre> | <p>Looks like we're coding the same application ;-)<br>
Here is my current implementation. I'm still in the beta testing phase of my GPS uploader app, so there might be many possible improvements. but it seems to work pretty well so far.</p>
<pre><code>/**
* try to get the 'best' location selected from all providers
*/
private Location getBestLocation() {
Location gpslocation = getLocationByProvider(LocationManager.GPS_PROVIDER);
Location networkLocation =
getLocationByProvider(LocationManager.NETWORK_PROVIDER);
// if we have only one location available, the choice is easy
if (gpslocation == null) {
Log.d(TAG, "No GPS Location available.");
return networkLocation;
}
if (networkLocation == null) {
Log.d(TAG, "No Network Location available");
return gpslocation;
}
// a locationupdate is considered 'old' if its older than the configured
// update interval. this means, we didn't get a
// update from this provider since the last check
long old = System.currentTimeMillis() - getGPSCheckMilliSecsFromPrefs();
boolean gpsIsOld = (gpslocation.getTime() < old);
boolean networkIsOld = (networkLocation.getTime() < old);
// gps is current and available, gps is better than network
if (!gpsIsOld) {
Log.d(TAG, "Returning current GPS Location");
return gpslocation;
}
// gps is old, we can't trust it. use network location
if (!networkIsOld) {
Log.d(TAG, "GPS is old, Network is current, returning network");
return networkLocation;
}
// both are old return the newer of those two
if (gpslocation.getTime() > networkLocation.getTime()) {
Log.d(TAG, "Both are old, returning gps(newer)");
return gpslocation;
} else {
Log.d(TAG, "Both are old, returning network(newer)");
return networkLocation;
}
}
/**
* get the last known location from a specific provider (network/gps)
*/
private Location getLocationByProvider(String provider) {
Location location = null;
if (!isProviderSupported(provider)) {
return null;
}
LocationManager locationManager = (LocationManager) getApplicationContext()
.getSystemService(Context.LOCATION_SERVICE);
try {
if (locationManager.isProviderEnabled(provider)) {
location = locationManager.getLastKnownLocation(provider);
}
} catch (IllegalArgumentException e) {
Log.d(TAG, "Cannot acces Provider " + provider);
}
return location;
}
</code></pre>
<p><strong>Edit:</strong> here is the part that requests the periodic updates from the location providers:</p>
<pre><code>public void startRecording() {
gpsTimer.cancel();
gpsTimer = new Timer();
long checkInterval = getGPSCheckMilliSecsFromPrefs();
long minDistance = getMinDistanceFromPrefs();
// receive updates
LocationManager locationManager = (LocationManager) getApplicationContext()
.getSystemService(Context.LOCATION_SERVICE);
for (String s : locationManager.getAllProviders()) {
locationManager.requestLocationUpdates(s, checkInterval,
minDistance, new LocationListener() {
@Override
public void onStatusChanged(String provider,
int status, Bundle extras) {}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onProviderDisabled(String provider) {}
@Override
public void onLocationChanged(Location location) {
// if this is a gps location, we can use it
if (location.getProvider().equals(
LocationManager.GPS_PROVIDER)) {
doLocationUpdate(location, true);
}
}
});
// //Toast.makeText(this, "GPS Service STARTED",
// Toast.LENGTH_LONG).show();
gps_recorder_running = true;
}
// start the gps receiver thread
gpsTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
Location location = getBestLocation();
doLocationUpdate(location, false);
}
}, 0, checkInterval);
}
public void doLocationUpdate(Location l, boolean force) {
long minDistance = getMinDistanceFromPrefs();
Log.d(TAG, "update received:" + l);
if (l == null) {
Log.d(TAG, "Empty location");
if (force)
Toast.makeText(this, "Current location not available",
Toast.LENGTH_SHORT).show();
return;
}
if (lastLocation != null) {
float distance = l.distanceTo(lastLocation);
Log.d(TAG, "Distance to last: " + distance);
if (l.distanceTo(lastLocation) < minDistance && !force) {
Log.d(TAG, "Position didn't change");
return;
}
if (l.getAccuracy() >= lastLocation.getAccuracy()
&& l.distanceTo(lastLocation) < l.getAccuracy() && !force) {
Log.d(TAG,
"Accuracy got worse and we are still "
+ "within the accuracy range.. Not updating");
return;
}
if (l.getTime() <= lastprovidertimestamp && !force) {
Log.d(TAG, "Timestamp not never than last");
return;
}
}
// upload/store your location here
}
</code></pre>
<p><strong>Things to consider:</strong></p>
<ul>
<li><p>do not request GPS updates too often, it drains battery power. I currently
use 30 min as default for my application. </p></li>
<li><p>add a 'minimum distance to last known location' check. without this, your points
will "jump around" when GPS is not available and the location is being triangulated
from the cell towers. or you can check if the new location is outside of the accuracy
value from the last known location.</p></li>
</ul> | {
"question_id": 6181704,
"question_date": "2011-05-30T23:57:24.170Z",
"question_score": 212,
"tags": "android|geolocation|android-location",
"answer_id": 6280851,
"answer_date": "2011-06-08T14:56:39.320Z",
"answer_score": 167
} |
Please answer the following Stack Overflow question:
Title: VS 2017 Git Local Commit DB.lock error on every commit
<p>We are getting this error on every local commit:</p>
<blockquote>
<p>Git failed with a fatal error.error:
open(".vs/XXXXXX.Dev.Library/v15/Server/sqlite3/db.lock"): Permission
deniedfatal: Unable to process path
.vs/XXXXXX.Dev.Library/v15/Server/sqlite3/db.lock</p>
</blockquote>
<p>This is a brand new installation of VS 2017 using the local git repository before it can sync to Azure DevOps GIT.</p>
<p>We can manually delete the lock file and then <em>sync</em> fine, but it seriously slows down the development process (having to <em>close</em>, <em>delete</em>, <em>open</em>, <em>commit</em> every time).</p>
<p>Does anyone know a better long-term fix for this issue? </p> | <p>Just add the .vs folder to the <a href="https://git-scm.com/docs/gitignore" rel="noreferrer">.gitignore</a> file.</p>
<p>Here is the template for Visual Studio from GitHub's collection of .gitignore templates, as an example:<br>
<a href="https://github.com/github/gitignore/blob/master/VisualStudio.gitignore" rel="noreferrer">https://github.com/github/gitignore/blob/master/VisualStudio.gitignore</a></p>
<hr>
<p>If you have any trouble adding the .gitignore file, just follow these steps:</p>
<ol>
<li>On the Team Explorer's window, go to Settings.</li>
</ol>
<p><a href="https://i.stack.imgur.com/nJhJI.png" rel="noreferrer"><img src="https://i.stack.imgur.com/nJhJI.png" alt="Team Explorer - Settings"></a></p>
<ol start="2">
<li>Then access Repository Settings.</li>
</ol>
<p><a href="https://i.stack.imgur.com/iHFfb.png" rel="noreferrer"><img src="https://i.stack.imgur.com/iHFfb.png" alt="Repository Settings"></a></p>
<ol start="3">
<li>Finally, click Add in the Ignore File section.</li>
</ol>
<p><a href="https://i.stack.imgur.com/8W1KG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8W1KG.png" alt="enter image description here"></a></p>
<p>Done. ;)<br>
This default file already includes the .vs folder.</p>
<p><a href="https://i.stack.imgur.com/79mAT.png" rel="noreferrer"><img src="https://i.stack.imgur.com/79mAT.png" alt="enter image description here"></a></p> | {
"question_id": 47460039,
"question_date": "2017-11-23T16:38:48.950Z",
"question_score": 212,
"tags": "git|visual-studio",
"answer_id": 47472811,
"answer_date": "2017-11-24T11:55:48.487Z",
"answer_score": 453
} |
Please answer the following Stack Overflow question:
Title: SSH Port forwarding in a ~/.ssh/config file?
<p>So I typically run this command a lot: </p>
<blockquote>
<p>ssh -L 5901:[email protected]:5901</p>
</blockquote>
<p>I use it to do VNC over SSH. </p>
<p>How do I convert that command into something that will work in a ~/.ssh/config file? </p>
<p>ex: </p>
<pre><code>host yam
HostName yam.myHost.edu
User myUserName
</code></pre>
<p>all I want to do is type: </p>
<pre><code>ssh yam
</code></pre>
<p>And have it open a SSH shell with a local listen port, and a remote port forwarded to it. </p>
<p>Suggestions? </p> | <p>You can use the <a href="http://www.manpagez.com/man/5/ssh_config/"><strong><code>LocalForward</code></strong></a> directive in your <code>host yam</code> section of <code>~/.ssh/config</code>:</p>
<pre><code>LocalForward 5901 computer.myHost.edu:5901
</code></pre> | {
"question_id": 9146457,
"question_date": "2012-02-05T02:34:31.940Z",
"question_score": 212,
"tags": "linux|macos|unix|ssh",
"answer_id": 9146502,
"answer_date": "2012-02-05T02:42:05.180Z",
"answer_score": 324
} |
Please answer the following Stack Overflow question:
Title: Truncating long strings with CSS: feasible yet?
<p>Is there any good way of truncating text with plain HTML and CSS, so that dynamic content can fit in a fixed-width-and-height layout?</p>
<p>I've been truncating server-side by <em>logical</em> width (i.e. a blindly-guessed number of characters), but since a 'w' is wider than an 'i' this tends to be suboptimal, and also requires me to re-guess (and keep tweaking) the number of characters for every fixed width. Ideally the truncation would happen in the browser, which knows the <em>physical</em> width of the rendered text.</p>
<p>I've found that IE has a <code>text-overflow: ellipsis</code> property that does exactly what I want, but I need this to be cross-browser. This property <a href="http://www.quirksmode.org/css/textoverflow.html" rel="noreferrer">seems to be (somewhat?) standard</a> but isn't supported by Firefox. I've found <a href="http://www.jide.fr/emulate-text-overflowellipsis-in-firefox-with-css" rel="noreferrer">various</a> <a href="https://stackoverflow.com/questions/480722/how-can-i-set-a-td-width-to-visually-truncate-its-displayed-contents">workarounds</a> based on <code>overflow: hidden</code>, but they either don't display an ellipsis (I want the user to know the content was truncated), or display it all the time (even if the content wasn't truncated).</p>
<p>Does anyone have a good way of fitting dynamic text in a fixed layout, or is server-side truncation by logical width as good as I'm going to get for now?</p> | <p><strong>Update:</strong> <a href="http://hacks.mozilla.org/2011/09/whats-new-for-web-developers-in-firefox-7/" rel="noreferrer"><code>text-overflow: ellipsis</code> is now supported</a> as of Firefox 7 (released September 27th 2011). Yay! My original answer follows as a historical record.</p>
<p>Justin Maxwell has cross browser CSS solution. It does come with the downside however of not allowing the text to be selected in Firefox. Check out <a href="http://mattsnider.com/css/css-string-truncation-with-ellipsis/" rel="noreferrer">his guest post on Matt Snider's blog</a> for the full details on how this works.</p>
<p>Note this technique also prevents updating the content of the node in JavaScript using the <code>innerHTML</code> property in Firefox. See the end of this post for a workaround.</p>
<p><strong>CSS</strong></p>
<pre><code>.ellipsis {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
-o-text-overflow: ellipsis;
-moz-binding: url('assets/xml/ellipsis.xml#ellipsis');
}
</code></pre>
<p><strong><code>ellipsis.xml</code> file contents</strong></p>
<pre><code><?xml version="1.0"?>
<bindings
xmlns="http://www.mozilla.org/xbl"
xmlns:xbl="http://www.mozilla.org/xbl"
xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
>
<binding id="ellipsis">
<content>
<xul:window>
<xul:description crop="end" xbl:inherits="value=xbl:text"><children/></xul:description>
</xul:window>
</content>
</binding>
</bindings>
</code></pre>
<p><strong>Updating node content</strong></p>
<p>To update the content of a node in a way that works in Firefox use the following:</p>
<pre><code>var replaceEllipsis(node, content) {
node.innerHTML = content;
// use your favorite framework to detect the gecko browser
if (YAHOO.env.ua.gecko) {
var pnode = node.parentNode,
newNode = node.cloneNode(true);
pnode.replaceChild(newNode, node);
}
};
</code></pre>
<p>See <a href="http://mattsnider.com/javascript/dynamically-updating-content-of-firefox-ellipsis-hack/" rel="noreferrer">Matt Snider's post for an explanation of how this works</a>.</p> | {
"question_id": 802175,
"question_date": "2009-04-29T12:40:44.560Z",
"question_score": 212,
"tags": "css|text|layout|cross-browser|truncate",
"answer_id": 1101702,
"answer_date": "2009-07-09T03:27:03.677Z",
"answer_score": 189
} |
Please answer the following Stack Overflow question:
Title: SQL Server 2008 can't login with newly created user
<p>I'm using using Windows Vista and I'm having trouble logging in with a newly created user.</p>
<ol>
<li>I open SQL Server Management Studio. </li>
<li>I create a new Login by right-clicking on Security->Logins.<br>
Check: SQL Server Authentication<br>
Login name: tester<br>
Password: test<br>
Click OK </li>
<li>I added this user to User Mapping to my database of choice.</li>
<li>Click File -> Connect Object Explorer, select SQL Server Authentication and enter tester/test and click Connect.</li>
</ol>
<p>I get an error:</p>
<pre><code>Login failed for user 'tester'. (Microsoft SQL Server, Error: 18456"
with Severity = 14 and State = 1.
</code></pre>
<p>What causes this error and how do I login with my user?</p> | <p>SQL Server was not configured to allow mixed authentication. </p>
<p>Here are steps to fix:</p>
<ol>
<li>Right-click on SQL Server instance at root of Object Explorer, click on Properties</li>
<li>Select Security from the left pane.</li>
<li><p>Select the SQL Server and Windows Authentication mode radio button, and click OK. </p>
<p><img src="https://i.stack.imgur.com/EMCX9.png" alt="enter image description here"></p></li>
<li><p>Right-click on the SQL Server instance, select Restart (alternatively, open up Services and restart the SQL Server service).</p></li>
</ol>
<p>This is also incredibly helpful for IBM Connections users, my wizards were not able to connect until I fxed this setting.</p> | {
"question_id": 1719399,
"question_date": "2009-11-12T01:56:34.137Z",
"question_score": 212,
"tags": "sql-server|authentication|ssms",
"answer_id": 1719476,
"answer_date": "2009-11-12T02:13:30.297Z",
"answer_score": 513
} |
Please answer the following Stack Overflow question:
Title: Is std::vector copying the objects with a push_back?
<p>After a lot of investigations with valgrind, I've made the conclusion that std::vector makes a copy of an object you want to push_back.</p>
<p>Is that really true ? A vector cannot keep a reference or a pointer of an object without a copy ?!</p>
<p>Thanks</p> | <p>Yes, <code>std::vector<T>::push_back()</code> creates a copy of the argument and stores it in the vector. If you want to store pointers to objects in your vector, create a <code>std::vector<whatever*></code> instead of <code>std::vector<whatever></code>. </p>
<p>However, you need to make sure that the objects referenced by the pointers remain valid while the vector holds a reference to them (smart pointers utilizing the RAII idiom solve the problem). </p> | {
"question_id": 2275076,
"question_date": "2010-02-16T17:54:45.227Z",
"question_score": 212,
"tags": "c++|stl|stdvector",
"answer_id": 2275095,
"answer_date": "2010-02-16T17:57:45.767Z",
"answer_score": 222
} |
Please answer the following Stack Overflow question:
Title: callback to handle completion of pipe
<p>I am using the following node.js code to download documents from some url and save it in the disk.
I want to be informed about when the document is downloaded. i have not seen any callback with pipe.Or, Is there any 'end' event that can be captured on completion of download ?</p>
<pre><code>request(some_url_doc).pipe(fs.createWriteStream('xyz.doc'));
</code></pre> | <p>Streams are <code>EventEmitter</code>s so you can listen to certain events. As you said there is a <code>finish</code> event for request (previously <code>end</code>).</p>
<pre><code> var stream = request(...).pipe(...);
stream.on('finish', function () { ... });
</code></pre>
<p>For more information about which events are available you can check the <a href="http://nodejs.org/api/stream.html#stream_event_finish">stream documentation page</a>.</p> | {
"question_id": 11447872,
"question_date": "2012-07-12T08:30:03.730Z",
"question_score": 212,
"tags": "node.js",
"answer_id": 11448311,
"answer_date": "2012-07-12T08:59:09.540Z",
"answer_score": 327
} |
Please answer the following Stack Overflow question:
Title: How to tell if an npm package was installed globally or locally
<p>I am installing <a href="https://en.wikipedia.org/wiki/Grunt_(software)" rel="nofollow noreferrer">Grunt</a>, <a href="https://en.wikipedia.org/wiki/Node.js" rel="nofollow noreferrer">Node.js</a>, npm, <a href="https://bower.io/" rel="nofollow noreferrer">Bower</a>, and grunt-cli on <a href="https://en.wikipedia.org/wiki/Windows_7" rel="nofollow noreferrer">Windows 7</a>.</p>
<p>The instructions say I should run the install commands with the <em>-g</em> flag for global.</p>
<p>How can I check if I used the -g flag when I installed? It will take a lot of time to uninstall them and reinstall.</p> | <p>Use the <code>list</code> command with the <code>-g</code> flag to see all packages that are installed globally: </p>
<p><code>npm list -g</code></p>
<p>To check if a specific package is installed globally, you can provide the name of package (<code>grunt</code> in this case) as seen below:</p>
<p><code>npm list -g grunt</code></p>
<p>Or you can use <code>grep</code> to filter on package names:</p>
<p><code>npm list -g | grep grunt</code></p>
<p>Source: <a href="https://docs.npmjs.com/cli/ls">https://docs.npmjs.com/cli/ls</a></p> | {
"question_id": 26104276,
"question_date": "2014-09-29T16:12:35.720Z",
"question_score": 212,
"tags": "node.js|gruntjs|npm",
"answer_id": 26104367,
"answer_date": "2014-09-29T16:16:55.990Z",
"answer_score": 299
} |
Please answer the following Stack Overflow question:
Title: ASP.NET MVC3 - textarea with @Html.EditorFor
<p>I have ASP.NET MVC3 app and I have also form for add news. When VS2010 created default view I have only text inputs for string data, but I want to have textarea for news text. How I can do it with Razor syntax.</p>
<p>Text input look like this:</p>
<pre><code>@Html.EditorFor(model => model.Text)
</code></pre> | <p>You could use the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.datatypeattribute.aspx" rel="noreferrer"><code>[DataType]</code></a> attribute on your view model like this:</p>
<pre><code>public class MyViewModel
{
[DataType(DataType.MultilineText)]
public string Text { get; set; }
}
</code></pre>
<p>and then you could have a controller:</p>
<pre><code>public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel());
}
}
</code></pre>
<p>and a view which does what you want:</p>
<pre><code>@model AppName.Models.MyViewModel
@using (Html.BeginForm())
{
@Html.EditorFor(x => x.Text)
<input type="submit" value="OK" />
}
</code></pre> | {
"question_id": 4927003,
"question_date": "2011-02-07T21:46:36.223Z",
"question_score": 212,
"tags": "asp.net-mvc-3",
"answer_id": 4927032,
"answer_date": "2011-02-07T21:49:15.997Z",
"answer_score": 382
} |
Please answer the following Stack Overflow question:
Title: How can I use a variable inside a Dockerfile CMD?
<p>Inside my Dockerfile:</p>
<pre><code>ENV PROJECTNAME mytestwebsite
CMD ["django-admin", "startproject", "$PROJECTNAME"]
</code></pre>
<p>Error:</p>
<pre><code>CommandError: '$PROJECTNAME' is not a valid project name
</code></pre>
<p>What is the quickest workaround here? Does Docker have any plan to "fix" or introduce this functionality in later versions of Docker?</p>
<p>NOTE: If I remove the CMD line from the Docker file and then run the Docker container, I am able to manually run Django-admin startproject $PROJECTNAME from inside the container and it will create the project...</p> | <p>When you use an execution list, as in...</p>
<pre><code>CMD ["django-admin", "startproject", "$PROJECTNAME"]
</code></pre>
<p>...then Docker will execute the given command <em>directly</em>, without involving a shell. Since there is no shell involved, that means:</p>
<ul>
<li>No variable expansion</li>
<li>No wildcard expansion</li>
<li>No i/o redirection with <code>></code>, <code><</code>, <code>|</code>, etc</li>
<li>No multiple commands via <code>command1; command2</code></li>
<li>And so forth.</li>
</ul>
<p>If you want your <code>CMD</code> to expand variables, you need to arrange for a shell. You can do that like this:</p>
<pre><code>CMD ["sh", "-c", "django-admin startproject $PROJECTNAME"]
</code></pre>
<p>Or you can use a simple string instead of an execution list, which gets you a result largely identical to the previous example:</p>
<pre><code>CMD django-admin startproject $PROJECTNAME
</code></pre> | {
"question_id": 40454470,
"question_date": "2016-11-06T20:59:24.137Z",
"question_score": 212,
"tags": "docker|dockerfile",
"answer_id": 40454758,
"answer_date": "2016-11-06T21:30:30.643Z",
"answer_score": 303
} |
Please answer the following Stack Overflow question:
Title: Java equivalent to C# extension methods
<p>I am looking to implement a functionality in a list of object as I would in C# using an extension method.</p>
<p>Something like this:</p>
<pre><code>List<DataObject> list;
// ... List initialization.
list.getData(id);
</code></pre>
<p>How do I do that in Java?</p> | <p>Java does not support extension methods.</p>
<p>Instead, you can make a regular static method, or write your own class.</p> | {
"question_id": 4359979,
"question_date": "2010-12-05T16:59:26.410Z",
"question_score": 212,
"tags": "java|extension-methods",
"answer_id": 4359990,
"answer_date": "2010-12-05T17:01:33.197Z",
"answer_score": 239
} |
Please answer the following Stack Overflow question:
Title: Git: which is the default configured remote for branch?
<p>I have a remote bare repository <code>hub</code>. I work only in the <code>master</code> branch.
The last sentence of this error message below makes me wonder: How do I find out which is the <em>"default configured remote for your current branch"</em>? And how do I set it?</p>
<pre><code>[myserver]~/progs $ git remote -v
hub ~/sitehub/progs.git/ (fetch)
hub ~/sitehub/progs.git/ (push)
[myserver]~/progs $ git branch -r
hub/master
[myserver]~/progs $ cat .git/HEAD
ref: refs/heads/master
[myserver]~/progs $ git pull hub
You asked to pull from the remote 'hub', but did not specify
a branch. Because this is not the default configured remote
for your current branch, you must specify a branch on the command line.
</code></pre> | <p>Track the remote branch</p>
<p>You can specify the default remote repository for pushing and pulling using git-branch’s track option. You’d normally do this by specifying the --track option when creating your local master branch, but as it already exists we’ll just update the config manually like so:</p>
<p>Edit your <code>.git/config</code></p>
<pre><code>[branch "master"]
remote = origin
merge = refs/heads/master
</code></pre>
<p>Now you can simply git push and git pull.</p>
<p>[<a href="https://gist.github.com/569530" rel="noreferrer">source</a>]</p> | {
"question_id": 4847101,
"question_date": "2011-01-31T02:19:49.197Z",
"question_score": 212,
"tags": "git|git-push|remote-branch",
"answer_id": 4847136,
"answer_date": "2011-01-31T02:28:23.813Z",
"answer_score": 237
} |
Please answer the following Stack Overflow question:
Title: React.useState does not reload state from props
<p>I'm expecting state to reload on props change, but this does not work and <code>user</code> variable is not updated on next <code>useState</code> call, what is wrong?</p>
<pre><code>function Avatar(props) {
const [user, setUser] = React.useState({...props.user});
return user.avatar ?
(<img src={user.avatar}/>)
: (<p>Loading...</p>);
}
</code></pre>
<p><a href="https://codepen.io/vitalyster/pen/LaPMJO" rel="noreferrer">codepen</a></p> | <p>I've seen almost all the answers to this question promoting a bad pattern: <strong>updating state as a result of a <em>prop change</em> inside a <code>useEffect</code> call.</strong> The <code>useEffect</code> hook is used for synchronizing your React components with external systems. Using it for synchronizing <strong>React states</strong> can potentially lead to bugs (because re-renders caused by other effects can lead to unintended state updates). A better solution would be to trigger a <strong>reconciliation</strong> with a <code>key</code> prop change in the <code><Avatar /></code> component from its parent:</p>
<pre><code>// App.jsx
function App() {
// ...logic here
return <Avatar initialUser={user} key={user.id} />
}
// Avatar.jsx
function Avatar({ initialUser }) {
// I suppose you need this component to manage it's own state
// otherwise you can get rid of this useState altogether.
const [user, setUser] = React.useState(initialUser);
return user.avatar ? (
<img src={user.avatar} />
) : (
<p>Loading...</p>
);
}
</code></pre>
<p>You can think of that <code>key</code> prop in this case as the <a href="https://tkdodo.eu/blog/putting-props-to-use-state#react-keys" rel="noreferrer">dependency array of useEffect</a>, but you won't be triggering unintended state changes as a result of unexpected <code>useEffect</code> calls triggered by the component renders.</p>
<p>You can read more about this here:
<a href="https://tkdodo.eu/blog/putting-props-to-use-state" rel="noreferrer">Putting Props To State</a></p>
<p>And more info on how <code>useEffect</code> might be a foot gun, here:</p>
<p><a href="https://beta.reactjs.org/learn/you-might-not-need-an-effect" rel="noreferrer">You Might Not Need an Effect</a></p> | {
"question_id": 54865764,
"question_date": "2019-02-25T12:01:02.657Z",
"question_score": 212,
"tags": "reactjs|react-hooks",
"answer_id": 72914696,
"answer_date": "2022-07-08T17:00:22.557Z",
"answer_score": 15
} |
Please answer the following Stack Overflow question:
Title: Angularjs ng-model doesn't work inside ng-if
<p>Here is the fiddle showing the problem. <a href="http://jsfiddle.net/Erk4V/1/" rel="noreferrer">http://jsfiddle.net/Erk4V/1/</a></p>
<p>It appears if I have an ng-model inside of an ng-if, the model does not work as expected.</p>
<p>I am wondering if this is a bug or if I am misunderstanding the proper usage.</p>
<pre><code><div ng-app >
<div ng-controller="main">
Test A: {{testa}}<br />
Test B: {{testb}}<br />
Test C: {{testc}}<br />
<div>
testa (without ng-if): <input type="checkbox" ng-model="testa" />
</div>
<div ng-if="!testa">
testb (with ng-if): <input type="checkbox" ng-model="testb" />
</div>
<div ng-if="!someothervar">
testc (with ng-if): <input type="checkbox" ng-model="testc" />
</div>
</div>
</div>
</code></pre> | <p>The <code>ng-if</code> directive, like other directives creates a child scope. See the script below (or <a href="http://jsfiddle.net/Erk4V/4/" rel="noreferrer">this jsfiddle</a>)</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><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular.min.js"></script>
<script>
function main($scope) {
$scope.testa = false;
$scope.testb = false;
$scope.testc = false;
$scope.obj = {test: false};
}
</script>
<div ng-app >
<div ng-controller="main">
Test A: {{testa}}<br />
Test B: {{testb}}<br />
Test C: {{testc}}<br />
{{obj.test}}
<div>
testa (without ng-if): <input type="checkbox" ng-model="testa" />
</div>
<div ng-if="!testa">
testb (with ng-if): <input type="checkbox" ng-model="testb" /> {{testb}}
</div>
<div ng-if="!someothervar">
testc (with ng-if): <input type="checkbox" ng-model="testc" />
</div>
<div ng-if="!someothervar">
object (with ng-if): <input type="checkbox" ng-model="obj.test" />
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>So, your checkbox changes the <code>testb</code> inside of the child scope, but not the outer parent scope.</p>
<p>Note, that if you want to modify the data in the parent scope, you'll need to modify the internal properties of an object like in the last div that I added.</p> | {
"question_id": 18342917,
"question_date": "2013-08-20T18:54:14.477Z",
"question_score": 212,
"tags": "angularjs",
"answer_id": 18342974,
"answer_date": "2013-08-20T18:57:26.210Z",
"answer_score": 224
} |
Please answer the following Stack Overflow question:
Title: Convert line-endings for whole directory tree (Git)
<p>Following situation:</p>
<p>I'm working on a Mac running OS X and recently joined a project whose members so far all use Windows. One of my first tasks was to set up the codebase in a Git repository, so I pulled the directory tree from FTP and tried to check it into the Git repo I had prepared locally. When trying to do this, all I got was this</p>
<pre><code>fatal: CRLF would be replaced by LF in blog/license.txt.
</code></pre>
<p>Since this affects all files below the "blog" folder, I'm looking for a way to conveniently convert ALL files in the tree to Unix line-endings. Is there a tool that does that out of the box or do I get scripting something myself?</p>
<p>For reference, my Git config concerning line-endings:</p>
<pre><code>core.safecrlf=true
core.autocrlf=input
</code></pre> | <p><a href="http://linuxcommand.org/man_pages/dos2unix1.html" rel="noreferrer">dos2unix</a> does that for you. Fairly straight forward process.<br>
<code>dos2unix filename</code></p>
<p>Thanks to toolbear, here is a one-liner that recursively replaces line endings and properly handles whitespace, quotes, and shell meta chars.</p>
<p><code>find . -type f -exec dos2unix {} \;</code></p>
<p>If you're using dos2unix 6.0 binary files will be ignored.</p> | {
"question_id": 7068179,
"question_date": "2011-08-15T17:15:20.593Z",
"question_score": 212,
"tags": "git|line-endings",
"answer_id": 7068241,
"answer_date": "2011-08-15T17:20:49.847Z",
"answer_score": 353
} |
Please answer the following Stack Overflow question:
Title: Why is JavaScript called JavaScript, since it has nothing to do with Java?
<p>Since JavaScript is not derived from Java, why does it have "Java" in the name?</p> | <p>JavaScript was originally named Mocha, later it was renamed to LiveScript, and then to JavaScript.</p>
<p>The LiveScript to JavaScript name change came because Netscape and Sun did a license agreement.</p>
<p>The language was then submitted for standarization to the <a href="http://www.ecma-international.org/" rel="noreferrer">ECMA International</a> Organization. By that time, Netscape didn't allow the use of the "JavaScript" name, so the standarized language is named <a href="https://www.ecma-international.org/technical-committees/tc39/" rel="noreferrer">ECMAScript</a>.</p>
<p>JavaScript isn't actually an open name. It is currently a <a href="https://tsdr.uspto.gov/#caseNumber=75026640&caseType=SERIAL_NO&searchType=statusSearch" rel="noreferrer">trademark</a> of Oracle (formerly Sun).</p>
<p>There still a lot of confusion, some people still think that JavaScript, JScript, and ECMAScript are three different languages.</p>
<p>ECMAScript is the "standards" name for the language.</p>
<p>JavaScript is technically a "dialect" of ECMAScript, the Mozilla Foundation can use "JavaScript" as the name of their implementations (currently present on the <a href="https://github.com/mozilla/rhino" rel="noreferrer">Rhino</a> and <a href="https://spidermonkey.dev" rel="noreferrer">SpiderMonkey</a> engines).</p>
<p>In the early days, Microsoft decided also to do what Netscape was doing on their own browser, and they developed <a href="http://msdn.microsoft.com/en-us/library/hbxc2t98%28VS.85%29.aspx" rel="noreferrer">JScript</a>, which is also an ECMAScript dialect, but was named in this way to avoid trademark issues.</p> | {
"question_id": 2018731,
"question_date": "2010-01-07T06:56:13.763Z",
"question_score": 212,
"tags": "java|javascript",
"answer_id": 2475528,
"answer_date": "2010-03-19T07:05:43.283Z",
"answer_score": 136
} |
Please answer the following Stack Overflow question:
Title: How do I override __getattr__ without breaking the default behavior?
<p>How do I override the <a href="https://docs.python.org/3/reference/datamodel.html#object.__getattr__" rel="nofollow noreferrer"><code>__getattr__</code></a> method of a class without breaking the default behavior?</p> | <p>Overriding <code>__getattr__</code> should be fine -- <code>__getattr__</code> is only called as a last resort i.e. if there are no attributes in the instance that match the name. For instance, if you access <code>foo.bar</code>, then <code>__getattr__</code> will only be called if <code>foo</code> has no attribute called <code>bar</code>. If the attribute is one you don't want to handle, raise <code>AttributeError</code>:</p>
<pre><code>class Foo(object):
def __getattr__(self, name):
if some_predicate(name):
# ...
else:
# Default behaviour
raise AttributeError
</code></pre>
<p>However, unlike <code>__getattr__</code>, <code>__getattribute__</code> will be called first (only works for new style classes i.e. those that inherit from object). In this case, you can preserve default behaviour like so:</p>
<pre><code>class Foo(object):
def __getattribute__(self, name):
if some_predicate(name):
# ...
else:
# Default behaviour
return object.__getattribute__(self, name)
</code></pre>
<p>See <a href="http://docs.python.org/reference/datamodel.html#object.__getattr__">the Python docs for more</a>.</p> | {
"question_id": 2405590,
"question_date": "2010-03-08T23:29:32.057Z",
"question_score": 212,
"tags": "python|getattr",
"answer_id": 2405617,
"answer_date": "2010-03-08T23:35:42.623Z",
"answer_score": 304
} |
Please answer the following Stack Overflow question:
Title: Why is IntelliJ 13 IDEA so slow after upgrading from version 12?
<p>While using IntelliJ 13 ultimate edition for a week, it just seems really slow.</p>
<p>First of all, the whole IDE stops for a second or so every once in a while. The Java editor's auto complete is really slow compared to 12 version.</p>
<p>I have not changed anything from the default settings other than using a Dracula theme.</p>
<p>It seems that this is not a problem of my own. Many people suggested setting the heap size higher than default, or clearing the cache, but I have not checked or tested on these suggestion. Do I need to change some setting to improve the new version's performance?</p> | <p>I had the same problem with slowness in IntelliJ 13 after upgrading from 12.
What worked for me was editing the idea64.vmoptions in the bin folder and setting the max heap to 8 GB (was 512 MB) and the Max PermGen to at least 1GB (was 300MB).Example below:</p>
<pre><code>-Xms128m
-Xmx8192m
-XX:MaxPermSize=1024m
</code></pre>
<p>Upon restart it was much faster.</p>
<p>For IntelliJ 2020 going back to 2017 on Mac
<code>/Applications/IntelliJ IDEA.app/Contents/bin/idea.vmoptions</code></p>
<p>On a Mac, this file is located in this path: </p>
<p>For IntelliJ 14 or 15 on Mac
<code>/Applications/IntelliJ IDEA 14.app/Contents/bin/idea.vmoptions</code></p>
<p>For IntelliJ 13 on Mac
<code>/Users/yourusername/Library/Preferences/IntelliJIdea13/idea.vmoptions</code></p>
<p>IntelliJ's updater (since 2017) seems to roll this change back, so you may need to re-apply it after updating.</p>
<p>On Ubuntu Linux, this file is located in this path relative to the install directory:</p>
<pre><code>idea-IU-135.475/bin/idea64.vmoptions
</code></pre>
<p>and for 2016.2:</p>
<pre><code> ~/.IdeaIC2016.2/idea64.vmoptions
</code></pre>
<p>On Windows 10 (Community edition shown here) these files are located in:</p>
<p><code>C:\Program Files (x86)\JetBrains\IntelliJ IDEA Community Edition 2016.1.3\bin\idea64.exe.vmoptions</code></p> | {
"question_id": 20545435,
"question_date": "2013-12-12T13:54:51.537Z",
"question_score": 212,
"tags": "intellij-idea",
"answer_id": 22508853,
"answer_date": "2014-03-19T14:21:27.760Z",
"answer_score": 261
} |
Please answer the following Stack Overflow question:
Title: Why does MYSQL higher LIMIT offset slow the query down?
<p>Scenario in short: A table with more than 16 million records [2GB in size]. The higher LIMIT offset with SELECT, the slower the query becomes, when using ORDER BY *primary_key*</p>
<p>So </p>
<pre><code>SELECT * FROM large ORDER BY `id` LIMIT 0, 30
</code></pre>
<p>takes far less than </p>
<pre><code>SELECT * FROM large ORDER BY `id` LIMIT 10000, 30
</code></pre>
<p>That only orders 30 records and same eitherway. So it's not the overhead from ORDER BY.<br>
Now when fetching the latest 30 rows it takes around 180 seconds. How can I optimize that simple query?</p> | <p>It's normal that higher offsets slow the query down, since the query needs to count off the first <code>OFFSET + LIMIT</code> records (and take only <code>LIMIT</code> of them). The higher is this value, the longer the query runs.</p>
<p>The query cannot go right to <code>OFFSET</code> because, first, the records can be of different length, and, second, there can be gaps from deleted records. It needs to check and count each record on its way.</p>
<p>Assuming that <code>id</code> is the primary key of a MyISAM table, or a unique non-primary key field on an InnoDB table, you can speed it up by using this trick:</p>
<pre><code>SELECT t.*
FROM (
SELECT id
FROM mytable
ORDER BY
id
LIMIT 10000, 30
) q
JOIN mytable t
ON t.id = q.id
</code></pre>
<p>See this article:</p>
<ul>
<li><a href="http://explainextended.com/2009/10/23/mysql-order-by-limit-performance-late-row-lookups/" rel="noreferrer"><strong>MySQL ORDER BY / LIMIT performance: late row lookups</strong></a></li>
</ul> | {
"question_id": 4481388,
"question_date": "2010-12-19T03:01:04.690Z",
"question_score": 212,
"tags": "mysql|performance|sql-order-by|limit",
"answer_id": 4502426,
"answer_date": "2010-12-21T18:06:02.810Z",
"answer_score": 222
} |
Please answer the following Stack Overflow question:
Title: Merging without whitespace conflicts
<p>I've got a problem, where a large commit which changes about a thousand lines of code, removing whitespace from the end of lines and removing spaces before tabs.</p>
<p>There are also about 50 pull requests for this project, in which all will get conflicts, when my commit is merged. Is there any way that git can be set up so that when merging future commits, it ignores conflicts where one of them is just a whitespace change?</p>
<p>Modifying git itself or using a third party tool isn't possible, but using a hook is fine.</p> | <pre><code> git merge -Xignore-all-space
</code></pre>
<p>Or (more precise)</p>
<pre><code> git merge -Xignore-space-change
</code></pre>
<p>should be enough to ignore all space related conflicts during the merge.</p>
<p>See <a href="http://linux.die.net/man/1/git-diff" rel="noreferrer">git diff</a>:</p>
<pre><code>--ignore-space-change
</code></pre>
<blockquote>
<p>Ignore changes in amount of whitespace.<br>
This ignores whitespace at line end, and considers all other sequences of one or more whitespace characters to be equivalent. </p>
</blockquote>
<pre><code>--ignore-all-space
</code></pre>
<blockquote>
<p>Ignore whitespace when comparing lines.<br>
This ignores differences even if one line has whitespace where the other line has none. </p>
</blockquote>
<p><a href="https://stackoverflow.com/users/72178/ks1322"><code>ks1322</code></a> adds in the comments a good advice:</p>
<blockquote>
<p>It is worth to merge with <strong><code>--no-commit</code> and review the merge before actual commit</strong>. </p>
</blockquote>
<hr>
<p>The <a href="https://stackoverflow.com/users/902207/callum-macrae">OP Callum Macrae</a> reports that, in that case, the merge proceed uninterrupted, and the trailing spaces contained in the pull request patches are applied to the local files.<br>
However, the OP uses a pre-commit hook which takes care of said trailing spaces.<br>
(I suppose a bit similar to <a href="https://gist.github.com/1028787" rel="noreferrer">this one</a>, also <a href="https://github.com/LockerProject/Locker/issues/257" rel="noreferrer">referenced here</a>).</p>
<hr>
<p>The OP's pre-commit hook is <a href="https://gist.github.com/2141321" rel="noreferrer">referenced here</a>:</p>
<blockquote>
<p>In addition to removing trailing whitespace, it removes one to three spaces before tabs (I have tab width set to 4), and adds EOLs.<br>
I've had reports that the code that adds the EOL deletes the file in windows, but haven't been able to replicate it.</p>
</blockquote> | {
"question_id": 9776527,
"question_date": "2012-03-19T19:24:41.420Z",
"question_score": 212,
"tags": "git|whitespace|git-merge",
"answer_id": 9784089,
"answer_date": "2012-03-20T09:21:32.787Z",
"answer_score": 290
} |
Please answer the following Stack Overflow question:
Title: How do I structure Cloud Functions for Firebase to deploy multiple functions from multiple files?
<p>I would like to create multiple Cloud Functions for Firebase and deploy them all at the same time from one project. I would also like to separate each function into a separate file. Currently I can create multiple functions if I put them both in index.js such as:</p>
<pre><code>exports.foo = functions.database.ref('/foo').onWrite(event => {
...
});
exports.bar = functions.database.ref('/bar').onWrite(event => {
...
});
</code></pre>
<p>However I would like to put foo and bar in separate files. I tried this:</p>
<pre><code>/functions
|--index.js (blank)
|--foo.js
|--bar.js
|--package.json
</code></pre>
<p>where foo.js is</p>
<pre><code>exports.foo = functions.database.ref('/foo').onWrite(event => {
...
});
</code></pre>
<p>and bar.js is</p>
<pre><code>exports.bar = functions.database.ref('/bar').onWrite(event => {
...
});
</code></pre>
<p>Is there a way to accomplish this without putting all functions in index.js?</p> | <p>Ah, Cloud Functions for Firebase load node modules normally, so this works</p>
<p>structure:</p>
<pre><code>/functions
|--index.js
|--foo.js
|--bar.js
|--package.json
</code></pre>
<p>index.js:</p>
<pre><code>const functions = require('firebase-functions');
const fooModule = require('./foo');
const barModule = require('./bar');
exports.foo = functions.database.ref('/foo').onWrite(fooModule.handler);
exports.bar = functions.database.ref('/bar').onWrite(barModule.handler);
</code></pre>
<p>foo.js:</p>
<pre><code>exports.handler = (event) => {
...
};
</code></pre>
<p>bar.js:</p>
<pre><code>exports.handler = (event) => {
...
};
</code></pre> | {
"question_id": 43486278,
"question_date": "2017-04-19T04:17:57.110Z",
"question_score": 212,
"tags": "javascript|firebase|google-cloud-platform|google-cloud-functions",
"answer_id": 43487001,
"answer_date": "2017-04-19T05:22:35.990Z",
"answer_score": 147
} |
Please answer the following Stack Overflow question:
Title: What is the dependency inversion principle and why is it important?
<p>What is the dependency inversion principle and why is it important?</p> | <p>Check this document out: <a href="https://drive.google.com/file/d/0BwhCYaYDn8EgMjdlMWIzNGUtZTQ0NC00ZjQ5LTkwYzQtZjRhMDRlNTQ3ZGMz/view" rel="noreferrer">The Dependency Inversion Principle</a>.</p>
<p>It basically says:</p>
<ul>
<li>High level modules should not depend upon low-level modules. Both should depend upon abstractions.</li>
<li>Abstractions should never depend upon details. Details should depend upon abstractions.</li>
</ul>
<p>As to why it is important, in short: changes are risky, and by depending on a concept instead of on an implementation, you reduce the need for change at call sites.</p>
<p>Effectively, the DIP reduces coupling between different pieces of code. The idea is that although there are many ways of implementing, say, a logging facility, the way you would use it should be relatively stable in time. If you can extract an interface that represents the concept of logging, this interface should be much more stable in time than its implementation, and call sites should be much less affected by changes you could make while maintaining or extending that logging mechanism.</p>
<p>By also making the implementation depend on an interface, you get the possibility to choose at run-time which implementation is better suited for your particular environment. Depending on the cases, this may be interesting too.</p> | {
"question_id": 62539,
"question_date": "2008-09-15T12:53:20.030Z",
"question_score": 212,
"tags": "oop|solid-principles|glossary|principles|dependency-inversion",
"answer_id": 62577,
"answer_date": "2008-09-15T12:57:45.667Z",
"answer_score": 120
} |
Please answer the following Stack Overflow question:
Title: Unresolved specs during Gem::Specification.reset:
<p>When launching Guard, I'm getting this output:</p>
<pre class="lang-none prettyprint-override"><code>$ guard
WARN: Unresolved specs during Gem::Specification.reset:
lumberjack (>= 1.0.2)
ffi (>= 0.5.0)
WARN: Clearing out unresolved specs.
Please report a bug if this causes problems.
</code></pre>
<p>What does this mean, and how do I fix it?</p>
<p>Contents of Guardfile:</p>
<pre><code>guard 'livereload' do
watch(%r{.+\.(css|js|html)$})
end
guard 'sass', :input => 'css', :style => :compressed, :extension => '.min.css'
</code></pre> | <p>I was seeing this issue by just running <strong>RSpec</strong> on its own. From what I understand, this means that you have more than one version of the listed gems installed on your system, and RSpec is unsure which one to use. After uninstalling older version of the gems, the warnings went away.</p>
<p>You can try:</p>
<pre><code>gem cleanup lumberjack
</code></pre>
<p>Or:</p>
<pre><code>gem list lumberjack
gem uninstall lumberjack
</code></pre>
<p>If you're using Bundler, you can try <code>bundle exec guard</code> (or in my case <code>bundle exec rspec</code>).</p> | {
"question_id": 17936340,
"question_date": "2013-07-30T00:15:20.983Z",
"question_score": 212,
"tags": "ruby|rubygems|guard",
"answer_id": 18127613,
"answer_date": "2013-08-08T13:41:30.407Z",
"answer_score": 287
} |
Please answer the following Stack Overflow question:
Title: Keyword for the outer class from an anonymous inner class
<p>In the following snippet:</p>
<pre><code>public class a {
public void otherMethod(){}
public void doStuff(String str, InnerClass b){}
public void method(a){
doStuff("asd",
new InnerClass(){
public void innerMethod(){
otherMethod();
}
}
);
}
}
</code></pre>
<p>Is there a keyword to refer to the outer class from the inner class? Basically what I want to do is <code>outer.otherMethod()</code>, or something of the like, but can't seem to find anything.</p> | <p>In general you use <code>OuterClassName.this</code> to refer to the enclosing instance of the outer class.</p>
<p>In your example that would be <code>a.this.otherMethod()</code></p> | {
"question_id": 56974,
"question_date": "2008-09-11T15:58:55.030Z",
"question_score": 212,
"tags": "java|anonymous-inner-class",
"answer_id": 56987,
"answer_date": "2008-09-11T16:03:27.127Z",
"answer_score": 359
} |
Please answer the following Stack Overflow question:
Title: Why use sprintf function in PHP?
<p>I am trying to learn more about the PHP function sprintf() but php.net did not help me much as I am still confused, why would you want to use it? </p>
<p>Take a look at my example below.</p>
<p>Why use this: </p>
<pre><code>$output = sprintf("Here is the result: %s for this date %s", $result, $date);
</code></pre>
<p>When this does the same and is easier to write IMO:</p>
<pre><code>$output = 'Here is the result: ' .$result. ' for this date ' .$date;
</code></pre>
<p>Am I missing something here?</p> | <p><code>sprintf</code> has all the formatting capabilities of the original printf which means you can do much more than just inserting variable values in strings.</p>
<p>For instance, specify number format (hex, decimal, octal), number of decimals, padding and more. Google for printf and you'll find plenty of examples. The <a href="http://en.wikipedia.org/wiki/Printf#printf_format_placeholders" rel="noreferrer">wikipedia article on printf</a> should get you started.</p> | {
"question_id": 1386593,
"question_date": "2009-09-06T20:09:37.707Z",
"question_score": 212,
"tags": "php|printf",
"answer_id": 1386607,
"answer_date": "2009-09-06T20:13:37.117Z",
"answer_score": 142
} |
Please answer the following Stack Overflow question:
Title: How can I determine what font a browser is actually using to render some text?
<p>My CSS specifies "<code>font-family: Helvetica, Arial, sans-serif;</code>" for the whole page. It looks like Verdana is being used instead on some parts. I would like to be able to verify this.</p>
<p>I've tried copying and pasting from my browser into Word, but it's not preserving the font.</p>
<p>Is there some way to determine which font is actually being used for a section of text?</p>
<p>Firebug will give me the list of fonts as above[1], but I don't see a way to determine which one of the fonts is being used.</p>
<ol>
<li>It turns out the wrong list was being used, which solved my original Verdana problem. But I'm still curious if there's a way to identify the actual rendering font.</li>
</ol> | <p>Per <a href="https://stackoverflow.com/a/16794295/82124">Wilfred Hughes' answer</a>, Firefox now supports this natively. <a href="https://hacks.mozilla.org/2013/04/developer-tools-update-firefox-22/" rel="noreferrer">This article has more details</a>. </p>
<p>This answer original referenced the "Font Finder" plugin, but only because it was from 4 years ago. The fact that old answers linger like this and the community cannot update them is one of the few remaining failures of Stack Overflow. </p> | {
"question_id": 884177,
"question_date": "2009-05-19T17:53:05.530Z",
"question_score": 212,
"tags": "css|browser|fonts",
"answer_id": 3258993,
"answer_date": "2010-07-15T19:02:35.650Z",
"answer_score": 53
} |
Please answer the following Stack Overflow question:
Title: Do I need a Global.asax.cs file at all if I'm using an OWIN Startup.cs class and move all configuration there?
<p>Let's say for example in a brand new ASP.NET MVC 5 application made from the MVC with Individual Accounts template, if I delete the <code>Global.asax.cs</code> class and move it's configuration code to <code>Startup.cs</code> <code>Configuration()</code> method as follow, what are the downsides?</p>
<pre><code>public partial class Startup
{
public void Configuration(IAppBuilder app)
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
ConfigureAuth(app);
}
}
</code></pre>
<p>The upsides for me is that when upgrading ASP.NET 4 applications to ASP.NET 5 and using pieces that now must be configured in the Startup.cs class, I'm not doing dependency injection and other configuration in two different classes that seem related to starting up, and configuration.</p> | <p>Startup.Configuration gets called slightly later than Application_Start, but I don't think the difference will matter much in most cases.</p>
<p>I believe the major reasons we kept the other code in Global.asax are:</p>
<ol>
<li>Consistency with previous versions of MVC. (That's where everybody currently expects to find this code.)</li>
<li>Ability to add other event handlers. In Global.asax, you can handle other methods like Session_Start and Application_Error.</li>
<li>Correctness in a variety of authentication scenarios. The Startup.Configuration method is only called if you have Microsoft.Owin.Host.SystemWeb.dll in your bin directory. If you remove this DLL, it will silently stop calling Startup.Configuration, which could be hard to understand.</li>
</ol>
<p>I think the third reason is the most important one we didn't take this approach by default, since some scenarios don't include having this DLL, and it's nice to be able to change authentication approaches without invalidating the location where unrelated code (like route registration) is placed.</p>
<p>But if none of those reasons apply in your scenario, I think you'd be fine using this approach.</p> | {
"question_id": 20168978,
"question_date": "2013-11-23T22:58:56.643Z",
"question_score": 212,
"tags": "c#|asp.net|asp.net-mvc|asp.net-mvc-5|owin",
"answer_id": 20200895,
"answer_date": "2013-11-25T18:51:59.837Z",
"answer_score": 179
} |
Please answer the following Stack Overflow question:
Title: Unable to find testhost.dll. Please publish your test project and retry
<p>I have a simple dotnet core class library with a single XUnit test method:</p>
<pre><code>TestLib.csproj:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.SDK" Version="15.9.0" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.console" Version="2.4.1">
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.1">
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="xunit.runners" Version="2.0.0" />
</ItemGroup>
</Project>
BasicTest.cs:
using Xunit;
namespace TestLib
{
public class BasicTest
{
[Fact(DisplayName = "Basic unit test")]
[Trait("Category", "unit")]
public void TestStringHelper()
{
var sut = "sut";
var verify = "sut";
Assert.Equal(sut, verify);
}
}
}
</code></pre>
<p>If I enter the project on the CLI and type <code>dotnet build</code> the project builds. If I type <code>dotnet test</code> I get this:</p>
<pre><code>C:\git\Testing\TestLib> dotnet test
C:\git\Testing\TestLib\TestLib.csproj : warning NU1701: Package 'xunit.runner.visualstudio 2.4.1' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETStandard,Version=v2.0'. This package may not be fully compatible with your project.
Build started, please wait...
C:\git\Testing\TestLib\TestLib.csproj : warning NU1701: Package 'xunit.runner.visualstudio 2.4.1' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETStandard,Version=v2.0'. This package may not be fully compatible with your project.
Build completed.
Test run for C:\git\Testing\TestLib\bin\Debug\netstandard2.0\TestLib.dll(.NETStandard,Version=v2.0)
Microsoft (R) Test Execution Command Line Tool Version 16.0.0-preview-20181205-02
Copyright (c) Microsoft Corporation. All rights reserved.
Starting test execution, please wait...
Unable to find C:\git\Testing\TestLib\bin\Debug\netstandard2.0\testhost.dll. Please publish your test project and retry.
Test Run Aborted.
</code></pre>
<p>What do I need to change to get the test to run?</p>
<p>If it helps, VS Code is not displaying the tests in its test explorer, either.</p> | <p>In my case, the problem was that I was targeting .NET Core 2.0 and switching to .NET Core 2.1 solved the problem. However I was using Microsoft.NET.Test.SDK v16.4.0 instead of 15.9.0.</p> | {
"question_id": 54770830,
"question_date": "2019-02-19T16:26:20.020Z",
"question_score": 212,
"tags": "c#|unit-testing|.net-core|xunit.net",
"answer_id": 59199795,
"answer_date": "2019-12-05T16:49:39.927Z",
"answer_score": 39
} |
Please answer the following Stack Overflow question:
Title: dyld: Library not loaded: @rpath/libswift_stdlib_core.dylib
<p>I get this error after adding a Swift class to an old Xcode project.</p>
<p><code>dyld: Library not loaded: @rpath/libswift_stdlib_core.dylib</code></p>
<p>How can I make the project run again?</p> | <p>For me none of the previous solutions worked. We discovered that there is a flag <code>ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES</code> (in earlier versions: "Embedded Content Contains Swift Code") in the Build Settings that needs to be set to YES. It was NO by default!</p> | {
"question_id": 24002836,
"question_date": "2014-06-02T20:36:18.630Z",
"question_score": 212,
"tags": "swift|dyld",
"answer_id": 25772532,
"answer_date": "2014-09-10T18:28:36.147Z",
"answer_score": 157
} |
Please answer the following Stack Overflow question:
Title: Can you use reflection to find the name of the currently executing method?
<p>Like the title says: Can reflection give you the name of the currently executing method.</p>
<p>I'm inclined to guess not, because of the Heisenberg problem. How do you call a method that will tell you the current method without changing what the current method is? But I'm hoping someone can prove me wrong there.</p>
<p><strong>Update:</strong> </p>
<ul>
<li>Part 2: Could this be used to look inside code for a property as well? </li>
<li>Part 3: What would the performance be like?</li>
</ul>
<p><strong>Final Result</strong><br>
I learned about MethodBase.GetCurrentMethod(). I also learned that not only can I create a stack trace, I can create only the exact frame I need if I want. </p>
<p>To use this inside a property, just take a .Substring(4) to remove the 'set_' or 'get_'.</p> | <p>As of .NET 4.5, you can also use <a href="https://docs.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callermembernameattribute" rel="noreferrer">[CallerMemberName]</a>.</p>
<p>Example: a property setter (to answer part 2):</p>
<pre><code>protected void SetProperty<T>(T value, [CallerMemberName] string property = null)
{
this.propertyValues[property] = value;
OnPropertyChanged(property);
}
public string SomeProperty
{
set { SetProperty(value); }
}
</code></pre>
<p>The compiler will supply matching string literals at call sites, so there is basically no performance overhead.</p> | {
"question_id": 44153,
"question_date": "2008-09-04T16:45:35.870Z",
"question_score": 212,
"tags": ".net|reflection",
"answer_id": 15310053,
"answer_date": "2013-03-09T11:18:17.030Z",
"answer_score": 132
} |
Please answer the following Stack Overflow question:
Title: Mercurial: Can I rename a branch?
<p>We now have a "stiging" branch, where "staging" seems to be a far better semantic fit. What's a good strategy for handling this?</p> | <p>Update to the <code>stiging</code> branch and create a new branch off of it. Then close the old branch.</p>
<p>In summary:</p>
<pre><code>hg update stiging
hg branch staging
hg commit -m"Changing stiging branch to staging."
hg update stiging
hg commit --close-branch -m"This was a typo; use staging instead."
hg push --new-branch
</code></pre> | {
"question_id": 4378684,
"question_date": "2010-12-07T15:59:59.570Z",
"question_score": 212,
"tags": "mercurial|branch|dvcs",
"answer_id": 7245187,
"answer_date": "2011-08-30T14:54:07.360Z",
"answer_score": 227
} |
Please answer the following Stack Overflow question:
Title: When should I choose Vector in Scala?
<p>It seems that <code>Vector</code> was late to the Scala collections party, and all the influential blog posts had already left.</p>
<p>In Java <code>ArrayList</code> is the default collection - I might use <code>LinkedList</code> but only when I've thought through an algorithm and care enough to optimise. In Scala should I be using <code>Vector</code> as my default <code>Seq</code>, or trying to work out when <code>List</code> is actually more appropriate?</p> | <p>As a general rule, default to using <code>Vector</code>. It’s faster than <code>List</code> for <em>almost</em> everything and more memory-efficient for larger-than-trivial sized sequences. See this <a href="http://docs.scala-lang.org/overviews/collections/performance-characteristics.html" rel="noreferrer">documentation</a> of the relative performance of Vector compared to the other collections. There are some downsides to going with <code>Vector</code>. Specifically:</p>
<ul>
<li>Updates at the head are slower than <code>List</code> (though not by as much as you might think)</li>
</ul>
<p>Another downside before Scala 2.10 was that pattern matching support was better for <code>List</code>, but this was rectified in 2.10 with generalized <code>+:</code> and <code>:+</code> extractors.</p>
<p>There is also a more abstract, algebraic way of approaching this question: what sort of sequence do you <em>conceptually</em> have? Also, what are you <em>conceptually</em> doing with it? If I see a function that returns an <code>Option[A]</code>, I know that function has some holes in its domain (and is thus partial). We can apply this same logic to collections.</p>
<p>If I have a sequence of type <code>List[A]</code>, I am effectively asserting two things. First, my algorithm (and data) is entirely stack-structured. Second, I am asserting that the only things I’m going to do with this collection are full, O(n) traversals. These two really go hand-in-hand. Conversely, if I have something of type <code>Vector[A]</code>, the <em>only</em> thing I am asserting is that my data has a well defined order and a finite length. Thus, the assertions are weaker with <code>Vector</code>, and this leads to its greater flexibility.</p> | {
"question_id": 6928327,
"question_date": "2011-08-03T14:45:07.723Z",
"question_score": 212,
"tags": "scala|vector|scala-collections",
"answer_id": 6934116,
"answer_date": "2011-08-03T22:35:26.930Z",
"answer_score": 297
} |
Please answer the following Stack Overflow question:
Title: What is the relationship between virtualenv and pyenv?
<p>I recently learned how to use virtualenv and virtualenvwrapper in my workflow but I've seen pyenv mentioned in a few guides but I can't seem to get an understanding of what pyenv is and how it is different/similar to virtualenv. Is pyenv a better/newer replacement for virtualenv or a complimentary tool? If the latter what does it do differently and how do the two (and virtualenvwrapper if applicable) work together? </p> | <p><strong>Pyenv</strong> and <strong>virtualenv</strong> are very different tools that work in different ways to do different things:</p>
<ul>
<li><p><strong>Pyenv</strong> is a bash extension - will not work on Windows - that intercepts your calls to python, pip, etc., to direct them to one of several of the system python tool-chains. So you always have all the libraries that you have installed in the selected python version available - as such it is good for users who have to switch between different versions of python.</p></li>
<li><p><strong>VirtualEnv</strong>, is pure python so works everywhere, it makes a copy of, <em>optionally a specific version of,</em> python and pip local to the activate environment which may or may not include links to the current system tool-chain, if it does not you can install just a known subset of libraries into that environment. As such it is almost certainly much better for testing and deployment as you know <strong>exactly</strong> which libraries, at which versions, are used and a global change will not impact your module. </p></li>
</ul>
<h2>venv <em>python > 3.3</em></h2>
<p>Note that from Python 3.3 onward there is a built in implementation of VirtualEnv called venv (with, on some installations a wrapper called pyvenv - this wrapper is <a href="https://docs.python.org/dev/whatsnew/3.6.html#id8" rel="noreferrer">deprecated in Python 3.6</a>), which should probably be used in preference. To avoid possible issues with the wrapper it is often a good idea to use it directly by using <code>/path/to/python3 -m venv desired/env/path</code> or you can use the excellent <code>py</code> python selector on windows with <code>py -3 -m venv desired/env/path</code>. It will create the directory specified with <code>desired/env/path</code> configure and populate it appropriately. In general it is very much like using VirtualEnv.</p>
<h2>Additional Tools</h2>
<p>There are a number of tools that it is worth mentioning, and considering, as they can help with the use of one or more of the above:</p>
<ul>
<li><a href="https://pypi.python.org/pypi/virtualenvwrapper" rel="noreferrer">VirtualEnvWrapper</a> Manage and simplify the use and management of VirtualEnv - <strong>Cross Platform</strong>.</li>
<li><a href="https://github.com/yyuu/pyenv-virtualenv" rel="noreferrer">pyenv-virtualenv</a>, <em>installed by <a href="https://github.com/yyuu/pyenv-installer" rel="noreferrer">pyenv-installer</a></em>, which gives PyEnv tools for managing and interfacing to VirtualEnv - with this you can have a base installation that includes more than one version of python and create isolated environments within each of them - <em>Linux/OS-X</em>. <em>Suggested by Johann Visagie</em></li>
<li><a href="http://www.pyinstaller.org/" rel="noreferrer">PyInstaller</a> can take your python code, possibly developed & tested under VirtualEnv, and bundle it up so that it can run one platforms that do not have <em>your version of</em> python installed - Note that it is not a cross compiler you will need a Windows (virtual-)machine to build Windows installs, etc., but it can be handy even where you can be sure that python will be installed but cannot be sure that the version of python and all the libraries will be compatible with your code.</li>
</ul> | {
"question_id": 29950300,
"question_date": "2015-04-29T17:13:23.360Z",
"question_score": 212,
"tags": "python|virtualenv|virtualenvwrapper|pyenv",
"answer_id": 29950604,
"answer_date": "2015-04-29T17:30:11.473Z",
"answer_score": 191
} |
Please answer the following Stack Overflow question:
Title: Lowercase JSON key names with JSON Marshal in Go
<p>I wish to use the <code>"encoding/json"</code> package to marshal a struct declared in one of the imported packages of my application.</p>
<p>Eg.:</p>
<pre><code>type T struct {
Foo int
}
</code></pre>
<p>Because it is imported, all available (exported) fields in the struct begins with an upper case letter. But I wish to have lower case key names:</p>
<pre><code>out, err := json.Marshal(&T{Foo: 42})
</code></pre>
<p>will result in</p>
<blockquote>
<p>{"Foo":42}</p>
</blockquote>
<p>but I wish to get</p>
<blockquote>
<p>{"foo":42}</p>
</blockquote>
<p>Is it possible to get around the problem in some easy way?</p> | <p>Have a look at the docs for <a href="http://golang.org/pkg/encoding/json/#Marshal" rel="noreferrer">encoding/json.Marshal</a>.
It discusses using struct field tags to determine how the generated json is formatted.</p>
<p>For example:</p>
<pre><code>type T struct {
FieldA int `json:"field_a"`
FieldB string `json:"field_b,omitempty"`
}
</code></pre>
<p>This will generate JSON as follows:</p>
<pre><code>{
"field_a": 1234,
"field_b": "foobar"
}
</code></pre> | {
"question_id": 11693865,
"question_date": "2012-07-27T18:46:19.290Z",
"question_score": 212,
"tags": "json|go|serialization|tags|marshalling",
"answer_id": 11694255,
"answer_date": "2012-07-27T19:14:25.923Z",
"answer_score": 321
} |
Please answer the following Stack Overflow question:
Title: How to remove convexity defects in a Sudoku square?
<p>I was doing a fun project: Solving a Sudoku from an input image using OpenCV (as in Google goggles etc). And I have completed the task, but at the end I found a little problem for which I came here.</p>
<p>I did the programming using Python API of OpenCV 2.3.1.</p>
<p>Below is what I did :</p>
<ol>
<li>Read the image</li>
<li>Find the contours </li>
<li>Select the one with maximum area, ( and also somewhat equivalent to square).</li>
<li><p>Find the corner points.</p>
<p>e.g. given below:</p>
<p><img src="https://i.stack.imgur.com/h1yKg.png" alt="enter image description here"></p>
<p>(<strong>Notice here that the green line correctly coincides with the true boundary of the Sudoku, so the Sudoku can be correctly warped</strong>. Check next image)</p></li>
<li><p>warp the image to a perfect square</p>
<p>eg image:</p>
<p><img src="https://i.stack.imgur.com/i4D9o.png" alt="enter image description here"></p></li>
<li><p>Perform OCR ( for which I used the method I have given in <a href="https://stackoverflow.com/questions/9413216/simple-digit-recognition-ocr-in-opencv-python">Simple Digit Recognition OCR in OpenCV-Python</a> )</p></li>
</ol>
<p>And the method worked well.</p>
<p><strong>Problem:</strong></p>
<p>Check out <a href="http://web.archive.org/web/20140601100441/http://davemark.com/images/sudoku.jpg" rel="noreferrer">this image.</a></p>
<p>Performing the step 4 on this image gives the result below:</p>
<p><img src="https://i.stack.imgur.com/YTiOC.jpg" alt="enter image description here"></p>
<p>The red line drawn is the original contour which is the true outline of sudoku boundary.</p>
<p>The green line drawn is approximated contour which will be the outline of warped image.</p>
<p>Which of course, there is difference between green line and red line at the top edge of sudoku. So while warping, I am not getting the original boundary of the Sudoku.</p>
<p><strong>My Question :</strong> </p>
<p>How can I warp the image on the correct boundary of the Sudoku, i.e. the red line OR how can I remove the difference between red line and green line? Is there any method for this in OpenCV?</p> | <p>I have a solution that works, but you'll have to translate it to OpenCV yourself. It's written in Mathematica.</p>
<p>The first step is to adjust the brightness in the image, by dividing each pixel with the result of a closing operation:</p>
<pre><code>src = ColorConvert[Import["http://davemark.com/images/sudoku.jpg"], "Grayscale"];
white = Closing[src, DiskMatrix[5]];
srcAdjusted = Image[ImageData[src]/ImageData[white]]
</code></pre>
<p><img src="https://i.stack.imgur.com/DLMIA.png" alt="enter image description here"></p>
<p>The next step is to find the sudoku area, so I can ignore (mask out) the background. For that, I use connected component analysis, and select the component that's got the largest convex area:</p>
<pre><code>components =
ComponentMeasurements[
ColorNegate@Binarize[srcAdjusted], {"ConvexArea", "Mask"}][[All,
2]];
largestComponent = Image[SortBy[components, First][[-1, 2]]]
</code></pre>
<p><img src="https://i.stack.imgur.com/lGUIe.png" alt="enter image description here"></p>
<p>By filling this image, I get a mask for the sudoku grid:</p>
<pre><code>mask = FillingTransform[largestComponent]
</code></pre>
<p><img src="https://i.stack.imgur.com/jXwoT.png" alt="enter image description here"></p>
<p>Now, I can use a 2nd order derivative filter to find the vertical and horizontal lines in two separate images:</p>
<pre><code>lY = ImageMultiply[MorphologicalBinarize[GaussianFilter[srcAdjusted, 3, {2, 0}], {0.02, 0.05}], mask];
lX = ImageMultiply[MorphologicalBinarize[GaussianFilter[srcAdjusted, 3, {0, 2}], {0.02, 0.05}], mask];
</code></pre>
<p><img src="https://i.stack.imgur.com/ptwTi.png" alt="enter image description here"></p>
<p>I use connected component analysis again to extract the grid lines from these images. The grid lines are much longer than the digits, so I can use caliper length to select only the grid lines-connected components. Sorting them by position, I get 2x10 mask images for each of the vertical/horizontal grid lines in the image:</p>
<pre><code>verticalGridLineMasks =
SortBy[ComponentMeasurements[
lX, {"CaliperLength", "Centroid", "Mask"}, # > 100 &][[All,
2]], #[[2, 1]] &][[All, 3]];
horizontalGridLineMasks =
SortBy[ComponentMeasurements[
lY, {"CaliperLength", "Centroid", "Mask"}, # > 100 &][[All,
2]], #[[2, 2]] &][[All, 3]];
</code></pre>
<p><img src="https://i.stack.imgur.com/WKhhF.png" alt="enter image description here"></p>
<p>Next I take each pair of vertical/horizontal grid lines, dilate them, calculate the pixel-by-pixel intersection, and calculate the center of the result. These points are the grid line intersections:</p>
<pre><code>centerOfGravity[l_] :=
ComponentMeasurements[Image[l], "Centroid"][[1, 2]]
gridCenters =
Table[centerOfGravity[
ImageData[Dilation[Image[h], DiskMatrix[2]]]*
ImageData[Dilation[Image[v], DiskMatrix[2]]]], {h,
horizontalGridLineMasks}, {v, verticalGridLineMasks}];
</code></pre>
<p><img src="https://i.stack.imgur.com/26GOU.png" alt="enter image description here"></p>
<p>The last step is to define two interpolation functions for X/Y mapping through these points, and transform the image using these functions:</p>
<pre><code>fnX = ListInterpolation[gridCenters[[All, All, 1]]];
fnY = ListInterpolation[gridCenters[[All, All, 2]]];
transformed =
ImageTransformation[
srcAdjusted, {fnX @@ Reverse[#], fnY @@ Reverse[#]} &, {9*50, 9*50},
PlotRange -> {{1, 10}, {1, 10}}, DataRange -> Full]
</code></pre>
<p><img src="https://i.stack.imgur.com/cLncR.png" alt="enter image description here"></p>
<p>All of the operations are basic image processing function, so this should be possible in OpenCV, too. The spline-based image transformation might be harder, but I don't think you really need it. Probably using the perspective transformation you use now on each individual cell will give good enough results.</p> | {
"question_id": 10196198,
"question_date": "2012-04-17T17:39:18.617Z",
"question_score": 212,
"tags": "python|opencv|computer-vision|sudoku",
"answer_id": 10226971,
"answer_date": "2012-04-19T11:22:54.750Z",
"answer_score": 270
} |
Please answer the following Stack Overflow question:
Title: Can someone explain this 'double negative' trick?
<p>I am by no means an expert at Javascript, but I have been reading Mark Pilgrim's <a href="http://diveintohtml5.info/" rel="noreferrer">"Dive into HTML5"</a> webpage and he mentioned something that I would like a better understanding of.</p>
<p>He states:</p>
<blockquote>
<p>Finally, you use the double-negative trick to force the result to a Boolean value (true or false).</p>
</blockquote>
<pre><code>function supports_canvas() {
return !!document.createElement('canvas').getContext;
}
</code></pre>
<p>If anyone can explain this a little better I would appreciate it!</p> | <p>A logical NOT operator <code>!</code> converts a value to a boolean that is the opposite of its logical value. </p>
<p>The second <code>!</code> converts the previous boolean result back to the boolean representation of its original logical value.</p>
<p><a href="https://developer.mozilla.org/en/JavaScript/Reference/Operators/Logical_Operators" rel="noreferrer">From these docs</a> for the Logical NOT operator:</p>
<blockquote>
<p>Returns false if its single operand can be converted to true; otherwise, returns true.</p>
</blockquote>
<p>So if <code>getContext</code> gives you a "falsey" value, the <code>!!</code> will make it return the boolean value <code>false</code>. Otherwise it will return <code>true</code>.</p>
<p>The "falsey" values are:</p>
<ul>
<li><code>false</code></li>
<li><code>NaN</code></li>
<li><code>undefined</code></li>
<li><code>null</code></li>
<li><code>""</code> (empty string)</li>
<li><code>0</code></li>
</ul> | {
"question_id": 4686583,
"question_date": "2011-01-13T23:39:06.373Z",
"question_score": 212,
"tags": "javascript|html",
"answer_id": 4686608,
"answer_date": "2011-01-13T23:44:04.333Z",
"answer_score": 255
} |
Please answer the following Stack Overflow question:
Title: What is the best way to stop people hacking the PHP-based highscore table of a Flash game
<p>I'm talking about an action game with no upper score limit and no way to verify the score on the server by replaying moves etc. </p>
<p>What I really need is the strongest encryption possible in Flash/PHP, and a way to prevent people calling the PHP page other than through my Flash file. I have tried some simple methods in the past of making multiple calls for a single score and completing a checksum / fibonacci sequence etc, and also obfuscating the SWF with Amayeta SWF Encrypt, but they were all hacked eventually.</p>
<p>Thanks to StackOverflow responses I have now found some more info from Adobe - <a href="http://www.adobe.com/devnet/flashplayer/articles/secure_swf_apps_12.html" rel="noreferrer">http://www.adobe.com/devnet/flashplayer/articles/secure_swf_apps_12.html</a> and <a href="https://github.com/mikechambers/as3corelib" rel="noreferrer">https://github.com/mikechambers/as3corelib</a> - which I think I can use for the encryption. Not sure this will get me around CheatEngine though.</p>
<p>I need to know the best solutions for both AS2 and AS3, if they are different.</p>
<p>The main problems seem to be things like TamperData and LiveHTTP headers, but I understand there are more advanced hacking tools as well - like CheatEngine (thanks Mark Webster)</p> | <p>This is a classic problem with Internet games and contests. Your Flash code works with users to decide a score for a game. But users aren't trusted, and the Flash code runs on the user's computer. You're SOL. There is nothing you can do to prevent an attacker from forging high scores:</p>
<ul>
<li><p>Flash is even easier to reverse engineer than you might think it is, since the bytecodes are well documented and describe a high-level language (Actionscript) --- when you publish a Flash game, you're publishing your source code, whether you know it or not.</p></li>
<li><p>Attackers control the runtime memory of the Flash interpreter, so that anyone who knows how to use a programmable debugger can alter any variable (including the current score) at any time, or alter the program itself.</p></li>
</ul>
<p>The simplest possible attack against your system is to run the HTTP traffic for the game through a proxy, catch the high-score save, and replay it with a higher score.</p>
<p>You can try to block this attack by binding each high score save to a single instance of the game, for instance by sending an encrypted token to the client at game startup, which might look like:</p>
<pre><code>hex-encoding( AES(secret-key-stored-only-on-server, timestamp, user-id, random-number))
</code></pre>
<p>(You could also use a session cookie to the same effect).</p>
<p>The game code echoes this token back to the server with the high-score save. But an attacker can still just launch the game again, get a token, and then immediately paste that token into a replayed high-score save. </p>
<p>So next you feed not only a token or session cookie, but also a high-score-encrypting session key. This will be a 128 bit AES key, itself encrypted with a key hardcoded into the Flash game:</p>
<pre><code>hex-encoding( AES(key-hardcoded-in-flash-game, random-128-bit-key))
</code></pre>
<p>Now before the game posts the high score, it decrypts the high-score-encrypting-session key, which it can do because you hardcoded the high-score-encrypting-session-key-decrypting-key into the Flash binary. You encrypt the high score with this decrypted key, along with the SHA1 hash of the high score:</p>
<pre><code>hex-encoding( AES(random-128-bit-key-from-above, high-score, SHA1(high-score)))
</code></pre>
<p>The PHP code on the server checks the token to make sure the request came from a valid game instance, then decrypts the encrypted high score, checking to make sure the high-score matches the SHA1 of the high-score (if you skip this step, decryption will simply produce random, likely very high, high scores). </p>
<p>So now the attacker decompiles your Flash code and quickly finds the AES code, which sticks out like a sore thumb, although even if it didn't it'd be tracked down in 15 minutes with a memory search and a tracer ("I know my score for this game is 666, so let's find 666 in memory, then catch any operation that touches that value --- oh look, the high score encryption code!"). With the session key, the attacker doesn't even have to run the Flash code; she grabs a game launch token and a session key and can send back an arbitrary high score.</p>
<p>You're now at the point where most developers just give up --- give or take a couple months of messing with attackers by:</p>
<ul>
<li><p>Scrambling the AES keys with XOR operations</p></li>
<li><p>Replacing key byte arrays with functions that calculate the key</p></li>
<li><p>Scattering fake key encryptions and high score postings throughout the binary.</p></li>
</ul>
<p>This is all mostly a waste of time. It goes without saying, SSL isn't going to help you either; SSL can't protect you when one of the two SSL endpoints is evil.</p>
<p>Here are some things that can actually reduce high score fraud:</p>
<ul>
<li><p>Require a login to play the game, have the login produce a session cookie, and don't allow multiple outstanding game launches on the same session, or multiple concurrent sessions for the same user.</p></li>
<li><p>Reject high scores from game sessions that last less than the shortest real games ever played (for a more sophisticated approach, try "quarantining" high scores for game sessions that last less than 2 standard deviations below the mean game duration). Make sure you're tracking game durations serverside.</p></li>
<li><p>Reject or quarantine high scores from logins that have only played the game once or twice, so that attackers have to produce a "paper trail" of reasonable looking game play for each login they create.</p></li>
<li><p>"Heartbeat" scores during game play, so that your server sees the score growth over the lifetime of one game play. Reject high scores that don't follow reasonable score curves (for instance, jumping from 0 to 999999). </p></li>
<li><p>"Snapshot" game state during game play (for instance, amount of ammunition, position in the level, etc), which you can later reconcile against recorded interim scores. You don't even have to have a way to detect anomalies in this data to start with; you just have to collect it, and then you can go back and analyze it if things look fishy.</p></li>
<li><p>Disable the account of any user who fails one of your security checks (for instance, by ever submitting an encrypted high score that fails validation). </p></li>
</ul>
<p>Remember though that you're only deterring high score fraud here. There's <em>nothing</em> you can do to prevent if. If there's money on the line in your game, someone is going to defeat any system you come up with. The objective isn't to <em>stop</em> this attack; it's to make the attack more expensive than just getting really good at the game and beating it.</p> | {
"question_id": 73947,
"question_date": "2008-09-16T16:01:27.887Z",
"question_score": 212,
"tags": "php|actionscript-3|security|actionscript|actionscript-2",
"answer_id": 74841,
"answer_date": "2008-09-16T17:32:22.097Z",
"answer_score": 415
} |
Please answer the following Stack Overflow question:
Title: Why does the MongoDB Java driver use a random number generator in a conditional?
<p>I saw the following code in <a href="https://github.com/mongodb/mongo-java-driver/blob/1d2e6faa80aeb5287a26d0348f18f4b51d566759/src/main/com/mongodb/ConnectionStatus.java#L213">this commit</a> for <a href="https://github.com/mongodb/mongo-java-driver">MongoDB's Java Connection driver</a>, and it appears at first to be a joke of some sort. What does the following code do?</p>
<pre><code>if (!((_ok) ? true : (Math.random() > 0.1))) {
return res;
}
</code></pre>
<p>(EDIT: the code <a href="https://github.com/mongodb/mongo-java-driver/commit/8e02cd006d79acd1d0ae6604c2ee7537b250c044#diff-08d4a794472cb22d6bf2c4bb0615aa49L212">has been updated since</a> posting this question)</p> | <p>After inspecting the history of that line, my main conclusion is that there has been some incompetent programming at work.</p>
<ol>
<li><p>That line is gratuitously convoluted. The general form</p>
<pre><code>a? true : b
</code></pre>
<p>for <code>boolean a, b</code> is equivalent to the simple</p>
<pre><code>a || b
</code></pre></li>
<li><p>The surrounding negation and excessive parentheses convolute things further. Keeping in mind <a href="http://en.wikipedia.org/wiki/De_Morgan%27s_laws">De Morgan's laws</a> it is a trivial observation that this piece of code amounts to</p>
<pre><code>if (!_ok && Math.random() <= 0.1)
return res;
</code></pre></li>
<li><p>The commit that <a href="https://github.com/mongodb/mongo-java-driver/commit/ee7543a4f7cc26618cf78eab2a18bd33b3e101cc">originally introduced this logic</a> had</p>
<pre><code>if (_ok == true) {
_logger.log( Level.WARNING , "Server seen down: " + _addr, e );
} else if (Math.random() < 0.1) {
_logger.log( Level.WARNING , "Server seen down: " + _addr );
}
</code></pre>
<p>—another example of incompetent coding, but notice the <em>reversed logic</em>: here the event is logged if either <code>_ok</code> or in 10% of other cases, whereas the code in 2. <em>returns</em> 10% of the times and logs 90% of the times. So the later commit ruined not only clarity, but correctness itself. </p>
<p>I think in the code you have posted we can actually see how the author intended to transform the original <code>if-then</code> somehow literally into its negation required for the early <code>return</code> condition. But then he messed up and inserted an effective "double negative" by reversing the inequality sign.</p></li>
<li><p>Coding style issues aside, stochastic logging is quite a dubious practice all by itself, especially since the log entry does not document its own peculiar behavior. The intention is, obviously, reducing restatements of the same fact: that the server is currently down. The appropriate solution is to log only <em>changes</em> of the server state, and not each its observation, let alone a random selection of 10% such observations. Yes, that takes just a little bit more effort, so let's see some.</p></li>
</ol>
<p>I can only hope that all this evidence of incompetence, accumulated from inspecting <em>just three lines of code</em>, does not speak fairly of the project as a whole, and that this piece of work will be cleaned up ASAP.</p> | {
"question_id": 16833100,
"question_date": "2013-05-30T09:56:29.027Z",
"question_score": 212,
"tags": "java|mongodb|obfuscation",
"answer_id": 16833798,
"answer_date": "2013-05-30T10:30:06.627Z",
"answer_score": 281
} |
Please answer the following Stack Overflow question:
Title: Why are Standard iterator ranges [begin, end) instead of [begin, end]?
<p>Why does the Standard define <code>end()</code> as one past the end, instead of at the actual end?</p> | <p>The best argument easily is the one made by <a href="http://www.cs.utexas.edu/~EWD/transcriptions/EWD08xx/EWD831.html" rel="noreferrer">Dijkstra himself</a>:</p>
<ul>
<li><p>You want the size of the range to be a simple difference <em>end</em> − <em>begin</em>;</p></li>
<li><p>including the lower bound is more "natural" when sequences degenerate to empty ones, and also because the alternative (<em>excluding</em> the lower bound) would require the existence of a "one-before-the-beginning" sentinel value.</p></li>
</ul>
<p>You still need to justify why you start counting at zero rather than one, but that wasn't part of your question.</p>
<p>The wisdom behind the [begin, end) convention pays off time and again when you have any sort of algorithm that deals with multiple nested or iterated calls to range-based constructions, which chain naturally. By contrast, using a doubly-closed range would incur off-by-ones and extremely unpleasant and noisy code. For example, consider a partition [<em>n</em><sub>0</sub>, <em>n</em><sub>1</sub>)[<em>n</em><sub>1</sub>, <em>n</em><sub>2</sub>)[<em>n</em><sub>2</sub>,<em>n</em><sub>3</sub>). Another example is the standard iteration loop <code>for (it = begin; it != end; ++it)</code>, which runs <code>end - begin</code> times. The corresponding code would be much less readable if both ends were inclusive – and imagine how you'd handle empty ranges.</p>
<p>Finally, we can also make a nice argument why counting should start at zero: With the half-open convention for ranges that we just established, if you are given a range of <em>N</em> elements (say to enumerate the members of an array), then 0 is the natural "beginning" so that you can write the range as [0, <em>N</em>), without any awkward offsets or corrections.</p>
<p>In a nutshell: the fact that we don't see the number <code>1</code> everywhere in range-based algorithms is a direct consequence of, and motivation for, the [begin, end) convention.</p> | {
"question_id": 9963401,
"question_date": "2012-04-01T09:40:24.887Z",
"question_score": 212,
"tags": "c++|stl|iterator|standards",
"answer_id": 9963438,
"answer_date": "2012-04-01T09:45:23.820Z",
"answer_score": 295
} |
Please answer the following Stack Overflow question:
Title: javascript function leading bang ! syntax
<p>I've been seeing this syntax on a few libraries now and I'm wondering what the benefit is. (note i'm well aware of closures and what the code is doing, I'm only concerned about the syntactical differences)</p>
<pre><code>!function(){
// do stuff
}();
</code></pre>
<p>As an alternative to the more common</p>
<pre><code>(function(){
// do stuff
})();
</code></pre>
<p>for self invoking anonymous functions.</p>
<p>I'm wondering a few things. First off, what is allowing the top example to actually work? Why is the bang necessary in order to make this statement syntactically correct? I'm told also that <code>+</code> works, and I'm sure some others, in place of <code>!</code></p>
<p>Second, what is the benefit? All I can tell is that it saves a single character, but I can't imagine that's such a huge benefit to attract numerous adopters. Is there some other benefit I"m missing? </p>
<p>The only other difference I can see would be the return value of the self invoking function, but in both of these examples, we don't really care about the return value of the function since it's used only to create a closure. So can someone tell me why one might use the first syntax?</p> | <p>Ideally you should be able to do all this simply as:</p>
<pre><code>function(){
// do stuff
}();
</code></pre>
<p>That means declare anonymous function and execute it. But that will not work due to specifics of JS grammar.</p>
<p>So shortest form of achieving this is to use some expression e.g. UnaryExpression (and so CallExpression):</p>
<pre><code>!function(){
// do stuff
}();
</code></pre>
<p>Or for the fun: </p>
<pre><code>-function(){
// do stuff
}();
</code></pre>
<p>Or: </p>
<pre><code>+function(){
// do stuff
}();
</code></pre>
<p>Or even:</p>
<pre><code>~function(){
// do stuff
return 0;
}( );
</code></pre> | {
"question_id": 5827290,
"question_date": "2011-04-29T02:41:29.793Z",
"question_score": 212,
"tags": "javascript|syntax",
"answer_id": 5827420,
"answer_date": "2011-04-29T03:08:23.890Z",
"answer_score": 104
} |
Please answer the following Stack Overflow question:
Title: Why is x == (x = y) not the same as (x = y) == x?
<p>Consider the following example:</p>
<pre><code>class Quirky {
public static void main(String[] args) {
int x = 1;
int y = 3;
System.out.println(x == (x = y)); // false
x = 1; // reset
System.out.println((x = y) == x); // true
}
}
</code></pre>
<p>I'm not sure if there is an item in the Java Language Specification that dictates loading the previous value of a variable for comparison with the right side (<code>x = y</code>) which, by the order implied by brackets, should be calculated first.</p>
<p>Why does the first expression evaluate to <code>false</code>, but the second evaluate to <code>true</code>? I would have expected <code>(x = y)</code> to be evaluated first, and then it would compare <code>x</code> with itself (<code>3</code>) and return <code>true</code>.</p>
<hr>
<p>This question is different from <a href="https://stackoverflow.com/questions/32755655/order-of-evaluation-of-subexpressions-in-a-java-expression">order of evaluation of subexpressions in a Java expression</a> in that <code>x</code> is definitely not a 'subexpression' here. It needs to be <strong>loaded</strong> for the comparison rather than to be 'evaluated'. The question is Java-specific and the expression <code>x == (x = y)</code>, unlike far-fetched impractical constructs commonly crafted for tricky interview questions, came from a real project. It was supposed to be a one-line replacement for the compare-and-replace idiom</p>
<pre><code>int oldX = x;
x = y;
return oldX == y;
</code></pre>
<p>which, being even simpler than x86 CMPXCHG instruction, deserved a shorter expression in Java.</p> | <blockquote>
<p>which, by the order implied by brackets, should be calculated first</p>
</blockquote>
<p>No. It is a common misconception that parentheses have any (general) effect on calculation or evaluation order. They only coerce the parts of your expression into a particular tree, binding the right operands to the right operations for the job.</p>
<p>(And, if you don't use them, this information comes from the "precedence" and associativity of the operators, something that's a result of how the language's syntax tree is defined. In fact, this is still exactly how it works when you use parentheses, but we simplify and say that we're not relying on any precedence rules then.)</p>
<p>Once that's done (i.e. once your code has been parsed into a program) those operands still need to be evaluated, and there are separate rules about how that is done: said rules (as Andrew has shown us) state that the LHS of each operation is evaluated first in Java.</p>
<p>Note that this is not the case in all languages; for example, in C++, unless you're using a short-circuiting operator like <code>&&</code> or <code>||</code>, the evaluation order of operands is generally unspecified and you shouldn't rely on it either way.</p>
<p>Teachers need to stop explaining operator precedence using misleading phrases like "this makes the addition happen first". Given an expression <code>x * y + z</code> the proper explanation would be "operator precedence makes the addition happen between <code>x * y</code> and <code>z</code>, rather than between <code>y</code> and <code>z</code>", with no mention of any "order".</p> | {
"question_id": 53749841,
"question_date": "2018-12-12T19:11:49.207Z",
"question_score": 212,
"tags": "java|variable-assignment|equality|operator-precedence|jls",
"answer_id": 53760490,
"answer_date": "2018-12-13T11:08:13.353Z",
"answer_score": 98
} |
Please answer the following Stack Overflow question:
Title: How does a language expand itself?
<p>I am learning C++ and I've just started learning about some of <a href="https://en.wikipedia.org/wiki/Qt_(software)">Qt</a>'s capabilities to code GUI programs. I asked myself the following question:</p>
<p>How does C++, which previously had no syntax capable of asking the OS for a window or a way to communicate through networks (with APIs which I don't completely understand either, I admit) suddenly get such capabilities <strong>through libraries written in C++ themselves?</strong> It all seems terribly circular to me. What C++ instructions could you possibly come up with in those libraries?</p>
<p>I realize this question might seem trivial to an experienced software developer but I've been researching for hours without finding any direct response. It's gotten to the point where I can't follow the tutorial about Qt because the existence of libraries is incomprehensible to me.</p> | <p>A computer is like an onion, it has many <em>many</em> layers, from the inner core of pure hardware to the outermost application layer. Each layer exposes parts of itself to the next outer layer, so that the outer layer may use some of the inner layers functionality.</p>
<p>In the case of e.g. Windows the operating system exposes the so-called WIN32 API for applications running on Windows. The Qt library uses that API to provide applications using Qt to its own API. You use Qt, Qt uses WIN32, WIN32 uses lower levels of the Windows operating system, and so on until it's electrical signals in the hardware.</p> | {
"question_id": 24993282,
"question_date": "2014-07-28T10:30:02.823Z",
"question_score": 212,
"tags": "c++|libraries|bootstrapping",
"answer_id": 24993453,
"answer_date": "2014-07-28T10:39:52.800Z",
"answer_score": 196
} |
Please answer the following Stack Overflow question:
Title: Setting different color for each series in scatter plot on matplotlib
<p>Suppose I have three data sets:</p>
<pre><code>X = [1,2,3,4]
Y1 = [4,8,12,16]
Y2 = [1,4,9,16]
</code></pre>
<p>I can scatter plot this:</p>
<pre><code>from matplotlib import pyplot as plt
plt.scatter(X,Y1,color='red')
plt.scatter(X,Y2,color='blue')
plt.show()
</code></pre>
<p>How can I do this with 10 sets? </p>
<p>I searched for this and could find any reference to what I'm asking.</p>
<p><strong>Edit: clarifying (hopefully) my question</strong> </p>
<p>If I call scatter multiple times, I can only set the same color on each scatter. Also, I know I can set a color array manually but I'm sure there is a better way to do this.
My question is then, "How can I automatically scatter-plot my several data sets, each with a different color. </p>
<p>If that helps, I can easily assign a unique number to each data set. </p> | <p>I don't know what you mean by 'manually'. You can choose a colourmap and make a colour array easily enough:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
x = np.arange(10)
ys = [i+x+(i*x)**2 for i in range(10)]
colors = cm.rainbow(np.linspace(0, 1, len(ys)))
for y, c in zip(ys, colors):
plt.scatter(x, y, color=c)
</code></pre>
<p><a href="https://i.stack.imgur.com/XwKlk.png" rel="noreferrer"><img src="https://i.stack.imgur.com/XwKlk.png" alt="Matplotlib graph with different colors" /></a></p>
<p>Or you can make your own colour cycler using <code>itertools.cycle</code> and specifying the colours you want to loop over, using <code>next</code> to get the one you want. For example, with 3 colours:</p>
<pre><code>import itertools
colors = itertools.cycle(["r", "b", "g"])
for y in ys:
plt.scatter(x, y, color=next(colors))
</code></pre>
<p><a href="https://i.stack.imgur.com/z6UAN.png" rel="noreferrer"><img src="https://i.stack.imgur.com/z6UAN.png" alt="Matplotlib graph with only 3 colors" /></a></p>
<p>Come to think of it, maybe it's cleaner not to use <code>zip</code> with the first one neither:</p>
<pre><code>colors = iter(cm.rainbow(np.linspace(0, 1, len(ys))))
for y in ys:
plt.scatter(x, y, color=next(colors))
</code></pre> | {
"question_id": 12236566,
"question_date": "2012-09-02T14:02:12.673Z",
"question_score": 211,
"tags": "python|matplotlib|scatter-plot",
"answer_id": 12236808,
"answer_date": "2012-09-02T14:39:07.303Z",
"answer_score": 332
} |
Please answer the following Stack Overflow question:
Title: Check if option is selected with jQuery, if not select a default
<p>Using jQuery, how do you check if there is an option selected in a select menu, and if not, assign one of the options as selected.</p>
<p>(The select is generated with a maze of PHP functions in an app I just inherited, so this is a quick fix while I get my head around those :)</p> | <p>While I'm not sure about exactly what you want to accomplish, this bit of code worked for me.</p>
<pre><code><select id="mySelect" multiple="multiple">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
<option value="4">Fourth</option>
</select>
<script type="text/javascript">
$(document).ready(function() {
if (!$("#mySelect option:selected").length) {
$("#mySelect option[value='3']").attr('selected', 'selected');
}
});
</script>
</code></pre> | {
"question_id": 149573,
"question_date": "2008-09-29T16:47:31.610Z",
"question_score": 211,
"tags": "javascript|jquery|forms|dom|html-select",
"answer_id": 149820,
"answer_date": "2008-09-29T17:42:11.273Z",
"answer_score": 273
} |
Please answer the following Stack Overflow question:
Title: A table name as a variable
<p>I am trying to execute this query:</p>
<pre><code>declare @tablename varchar(50)
set @tablename = 'test'
select * from @tablename
</code></pre>
<p>This produces the following error:</p>
<blockquote>
<p>Msg 1087, Level 16, State 1, Line 5</p>
<p>Must declare the table variable "@tablename".</p>
</blockquote>
<p>What's the right way to have the table name populated dynamically?</p> | <p>For static queries, like the one in your question, table names and column names need to be static.</p>
<p>For dynamic queries, you should generate the full SQL dynamically, and use sp_executesql to execute it.</p>
<p>Here is an example of a script used to compare data between the same tables of different databases:</p>
<p>Static query:</p>
<pre><code>SELECT * FROM [DB_ONE].[dbo].[ACTY]
EXCEPT
SELECT * FROM [DB_TWO].[dbo].[ACTY]
</code></pre>
<p>Since I want to easily change the name of <code>table</code> and <code>schema</code>, I have created this dynamic query:</p>
<pre><code>declare @schema sysname;
declare @table sysname;
declare @query nvarchar(max);
set @schema = 'dbo'
set @table = 'ACTY'
set @query = '
SELECT * FROM [DB_ONE].' + QUOTENAME(@schema) + '.' + QUOTENAME(@table) + '
EXCEPT
SELECT * FROM [DB_TWO].' + QUOTENAME(@schema) + '.' + QUOTENAME(@table);
EXEC sp_executesql @query
</code></pre>
<p>Since dynamic queries have many details that need to be considered and they are hard to maintain, I recommend that you read: <a href="http://www.sommarskog.se/dynamic_sql.html" rel="noreferrer">The curse and blessings of dynamic SQL</a></p> | {
"question_id": 2838490,
"question_date": "2010-05-15T01:07:17.497Z",
"question_score": 211,
"tags": "sql|sql-server|tsql|variable-names|tablename",
"answer_id": 2838507,
"answer_date": "2010-05-15T01:14:49.247Z",
"answer_score": 164
} |
Please answer the following Stack Overflow question:
Title: How to stop mysqld
<p>To find out the start command for mysqld (using a mac) I can do:</p>
<pre><code>ps aux|grep mysql
</code></pre>
<p>I get the following output, which allows me to start mysql server.</p>
<pre><code>/usr/local/mysql/bin/mysqld --basedir=/usr/local/mysql --datadir=...
</code></pre>
<p>How would I find the necessary command to stop mysql from the command line?</p> | <p>Try:</p>
<pre><code>/usr/local/mysql/bin/mysqladmin -u root -p shutdown
</code></pre>
<p>Or:</p>
<pre><code>sudo mysqld stop
</code></pre>
<p>Or:</p>
<pre><code>sudo /usr/local/mysql/bin/mysqld stop
</code></pre>
<p>Or:</p>
<pre><code>sudo mysql.server stop
</code></pre>
<p>If you install the <strong>Launchctl in OSX</strong> you can try:</p>
<h2>MacPorts</h2>
<pre><code>sudo launchctl unload -w /Library/LaunchDaemons/org.macports.mysql.plist
sudo launchctl load -w /Library/LaunchDaemons/org.macports.mysql.plist
</code></pre>
<p>Note: this is persistent after reboot.</p>
<h2>Homebrew</h2>
<pre><code>launchctl unload -w ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist
launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist
</code></pre>
<h2>Binary installer</h2>
<pre><code>sudo /Library/StartupItems/MySQLCOM/MySQLCOM stop
sudo /Library/StartupItems/MySQLCOM/MySQLCOM start
sudo /Library/StartupItems/MySQLCOM/MySQLCOM restart
</code></pre>
<p>I found that in: <a href="https://stackoverflow.com/a/102094/58768">https://stackoverflow.com/a/102094/58768</a></p> | {
"question_id": 11091414,
"question_date": "2012-06-18T21:33:17.673Z",
"question_score": 211,
"tags": "mysql|macos",
"answer_id": 11091462,
"answer_date": "2012-06-18T21:36:57.033Z",
"answer_score": 347
} |
Please answer the following Stack Overflow question:
Title: How to download Visual Studio Community Edition 2015 (not 2017)
<p>I have a Resharper 9x license and it is only compatible up to MS VS Community 2015 edition. I tried to download the 2015 version from Microsoft but their website stubbornly wants me to have 2017, only. Can someone please provide me a url to the 2015 edition? Or, explain how to navigate Microsoft's site to obtain the 2015 edition?</p>
<p><strong>Update on solution</strong></p>
<p>1) vs_community.exe is the download filename for any version, 2015, 2017, etc. You will not know which version it is until you click the .exe. You will then see the version in the title of the installer.</p>
<p>2) There is a url trick to get the version that you want.</p>
<p><s><a href="https://www.visualstudio.com/thank-you-downloading-visual-studio/?sku=Community&rel=15" rel="noreferrer">https://www.visualstudio.com/thank-you-downloading-visual-studio/?sku=Community&rel=15</a></s></p>
<p>...change the rel=15 to rel=17 etc</p>
<p>Or use the links provided in the answer below</p> | <p>You can use these links to download Visual Studio 2015</p>
<p><strong>Community Edition:</strong></p>
<ul>
<li><a href="https://go.microsoft.com/fwlink/?LinkId=532606&clcid=0x409" rel="noreferrer">Web Installer</a></li>
<li><a href="https://go.microsoft.com/fwlink/?LinkId=615448&clcid=0x409" rel="noreferrer">ISO Image</a></li>
</ul>
<p>And for anyone in the future who might be looking for the other editions here are the links for them as well:</p>
<p><strong>Professional Edition:</strong></p>
<ul>
<li><a href="https://go.microsoft.com/fwlink/?LinkId=615435&clcid=0x409" rel="noreferrer">Web Installer</a></li>
<li><a href="https://go.microsoft.com/fwlink/?LinkId=615434&clcid=0x409" rel="noreferrer">ISO Image</a></li>
</ul>
<p><strong>Enterprise Edition:</strong></p>
<ul>
<li><a href="https://go.microsoft.com/fwlink/?LinkId=615437&clcid=0x409" rel="noreferrer">Web Installer</a></li>
<li><a href="https://go.microsoft.com/fwlink/?LinkId=615436&clcid=0x409" rel="noreferrer">ISO Image</a></li>
</ul> | {
"question_id": 44290672,
"question_date": "2017-05-31T16:58:00.817Z",
"question_score": 211,
"tags": "visual-studio|visual-studio-2015",
"answer_id": 44290942,
"answer_date": "2017-05-31T17:12:31.680Z",
"answer_score": 630
} |
Please answer the following Stack Overflow question:
Title: Python data structure sort list alphabetically
<p>I am a bit confused regarding data structure in python; <code>()</code>,<code>[]</code>, and <code>{}</code>. I am trying to sort a simple list, probably since I cannot identify the type of data I am failing to sort it.</p>
<p>My list is simple: <code>['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue']</code> </p>
<p>My question is what type of data this is, and how to sort the words alphabetically?</p> | <p><code>[]</code> denotes a <a href="http://docs.python.org/3/tutorial/introduction.html#lists" rel="noreferrer">list</a>, <code>()</code> denotes a <a href="http://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences" rel="noreferrer">tuple</a> and <code>{}</code> denotes a <a href="http://docs.python.org/3/tutorial/datastructures.html#dictionaries" rel="noreferrer">dictionary</a>. You should take a look at the <a href="http://docs.python.org/3/tutorial/index.html" rel="noreferrer">official Python tutorial</a> as these are the very basics of programming in Python.</p>
<p>What you have is a list of strings. You can sort it like this:</p>
<pre><code>In [1]: lst = ['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue']
In [2]: sorted(lst)
Out[2]: ['Eflux', 'Intrigue', 'Sedge', 'Stem', 'Whim', 'constitute']
</code></pre>
<p>As you can see, words that start with an uppercase letter get preference over those starting with a lowercase letter. If you want to sort them independently, do this:</p>
<pre><code>In [4]: sorted(lst, key=str.lower)
Out[4]: ['constitute', 'Eflux', 'Intrigue', 'Sedge', 'Stem', 'Whim']
</code></pre>
<p>You can also sort the list in reverse order by doing this:</p>
<pre><code>In [12]: sorted(lst, reverse=True)
Out[12]: ['constitute', 'Whim', 'Stem', 'Sedge', 'Intrigue', 'Eflux']
In [13]: sorted(lst, key=str.lower, reverse=True)
Out[13]: ['Whim', 'Stem', 'Sedge', 'Intrigue', 'Eflux', 'constitute']
</code></pre>
<p><strong>Please note:</strong> If you work with Python 3, then <code>str</code> is the correct data type for every string that contains human-readable text. However, if you still need to work with Python 2, then you might deal with unicode strings which have the data type <code>unicode</code> in Python 2, and not <code>str</code>. In such a case, if you have a list of unicode strings, you must write <code>key=unicode.lower</code> instead of <code>key=str.lower</code>.</p> | {
"question_id": 14032521,
"question_date": "2012-12-25T17:04:55.777Z",
"question_score": 211,
"tags": "python|list|sorting|alphabetical",
"answer_id": 14032557,
"answer_date": "2012-12-25T17:10:51.413Z",
"answer_score": 309
} |
Please answer the following Stack Overflow question:
Title: How to check if a JSON key exists?
<p>So, I get some JSON values from the server but I don't know if there will be a particular field or not.</p>
<p>So like:</p>
<pre><code>{ "regatta_name":"ProbaRegatta",
"country":"Congo",
"status":"invited"
}
</code></pre>
<p>And sometimes, there will be an extra field like:</p>
<pre><code>{ "regatta_name":"ProbaRegatta",
"country":"Congo",
"status":"invited",
"club":"somevalue"
}
</code></pre>
<p>I would like to check if the field named "club" exists so that at parsing I won't get</p>
<blockquote>
<p>org.json.JSONException: No value for club</p>
</blockquote> | <p>JSONObject class has a method named "has":</p>
<p><a href="http://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)">http://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)</a></p>
<blockquote>
<p>Returns true if this object has a mapping for name. The mapping may be NULL.</p>
</blockquote> | {
"question_id": 17487205,
"question_date": "2013-07-05T10:54:37.937Z",
"question_score": 211,
"tags": "java|android|json",
"answer_id": 17487273,
"answer_date": "2013-07-05T10:57:31.733Z",
"answer_score": 328
} |
Please answer the following Stack Overflow question:
Title: Linq select objects in list where exists IN (A,B,C)
<p>I have a list of <code>orders</code>.<br>
I want to select <code>orders</code> based on a set of order statuses.</p>
<p>So essentially <code>select orders where order.StatusCode in ("A", "B", "C")</code></p>
<pre><code>// Filter the orders based on the order status
var filteredOrders = from order in orders.Order
where order.StatusCode.????????("A", "B", "C")
select order;
</code></pre> | <p>Your status-codes are also a collection, so use <a href="http://msdn.microsoft.com/en-us/library/bb352880.aspx" rel="noreferrer"><code>Contains</code></a>:</p>
<pre><code>var allowedStatus = new[]{ "A", "B", "C" };
var filteredOrders = orders.Order.Where(o => allowedStatus.Contains(o.StatusCode));
</code></pre>
<p>or in query syntax:</p>
<pre><code>var filteredOrders = from order in orders.Order
where allowedStatus.Contains(order.StatusCode)
select order;
</code></pre> | {
"question_id": 14257360,
"question_date": "2013-01-10T11:53:33.117Z",
"question_score": 211,
"tags": "c#|linq|list|linq-to-objects|exists",
"answer_id": 14257379,
"answer_date": "2013-01-10T11:55:06.150Z",
"answer_score": 348
} |
Please answer the following Stack Overflow question:
Title: How can I apply a border only inside a table?
<p>I am trying to figure out how to add border only inside the table. When I do:</p>
<pre><code>table {
border: 0;
}
table td, table th {
border: 1px solid black;
}
</code></pre>
<p>The border is around the whole table and also between table cells. What I want to achieve is to have border only inside the table around table cells (without outer border around the table).</p>
<p>Here is markup I'm using for tables (even though I think that is not important):</p>
<pre><code><table>
<tr>
<th>Heading 1</th>
<th>Heading 2</th>
</tr>
<tr>
<td>Cell (1,1)</td>
<td>Cell (1,2)</td>
</tr>
<tr>
<td>Cell (2,1)</td>
<td>Cell (2,2)</td>
</tr>
<tr>
<td>Cell (3,1)</td>
<td>Cell (3,2)</td>
</tr>
</table>
</code></pre>
<p>And here are some basic styles I apply to most of my tables:</p>
<pre><code>table {
border-collapse: collapse;
border-spacing: 0;
}
</code></pre> | <p>If you are doing what I believe you are trying to do, you'll need something a little more like this:</p>
<pre><code>table {
border-collapse: collapse;
}
table td, table th {
border: 1px solid black;
}
table tr:first-child th {
border-top: 0;
}
table tr:last-child td {
border-bottom: 0;
}
table tr td:first-child,
table tr th:first-child {
border-left: 0;
}
table tr td:last-child,
table tr th:last-child {
border-right: 0;
}
</code></pre>
<p><a href="http://jsfiddle.net/Daniel_Hug/8M2wp" rel="noreferrer">jsFiddle Demo</a></p>
<p>The problem is that you are setting a 'full border' around all the cells, which make it appear as if you have a border around the entire table.</p>
<p>Cheers.</p>
<p>EDIT: A little more info on those pseudo-classes can be found on <a href="http://www.quirksmode.org/css/firstchild.html" rel="noreferrer">quirksmode</a>, and, as to be expected, you are pretty much S.O.L. in terms of IE support.</p> | {
"question_id": 1257430,
"question_date": "2009-08-10T21:52:34.267Z",
"question_score": 211,
"tags": "html|css|html-table|border",
"answer_id": 1257487,
"answer_date": "2009-08-10T22:05:49.793Z",
"answer_score": 214
} |
Please answer the following Stack Overflow question:
Title: Parsing Command Line Arguments in C++?
<p>What is the best way of parsing command-line arguments in C++ if the program is specified to be run like this:</p>
<pre><code>prog [-abc] [input [output]]
</code></pre>
<p>Is there some way of doing this built into the standard library, or do I need to write my own code?</p>
<hr />
<p>Related:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/332849/parsing-command-line-arguments-in-a-unicode-c-application">Parsing command line arguments in a unicode C++ application</a></li>
</ul> | <p><a href="http://www.boost.org/doc/libs/release/libs/program_options/" rel="noreferrer">Boost.Program_options</a> should do the trick</p> | {
"question_id": 865668,
"question_date": "2009-05-14T20:46:44.643Z",
"question_score": 211,
"tags": "c++|command-line-arguments",
"answer_id": 865687,
"answer_date": "2009-05-14T20:49:37.383Z",
"answer_score": 90
} |
Please answer the following Stack Overflow question:
Title: How can I define an interface for an array of objects?
<p>I have the following interface and code. I thought I was doing the definitions correctly but I am getting an error:</p>
<pre><code>interface IenumServiceGetOrderBy { id: number; label: string; key: any }[];
</code></pre>
<p>and:</p>
<pre><code>getOrderBy = (entity): IenumServiceGetOrderBy => {
var result: IenumServiceGetOrderBy;
switch (entity) {
case "content":
result =
[
{ id: 0, label: 'CId', key: 'contentId' },
{ id: 1, label: 'Modified By', key: 'modifiedBy' },
{ id: 2, label: 'Modified Date', key: 'modified' },
{ id: 3, label: 'Status', key: 'contentStatusId' },
{ id: 4, label: 'Status > Type', key: ['contentStatusId', 'contentTypeId'] },
{ id: 5, label: 'Title', key: 'title' },
{ id: 6, label: 'Type', key: 'contentTypeId' },
{ id: 7, label: 'Type > Status', key: ['contentTypeId', 'contentStatusId'] }
];
break;
}
return result;
};
</code></pre>
<p>Error:</p>
<pre><code>Error 190 Cannot convert '{}[]' to 'IenumServiceGetOrderBy':
Type '{}[]' is missing property 'id' from type 'IenumServiceGetOrderBy'
</code></pre> | <p>You can define an interface with an <a href="https://www.typescriptlang.org/docs/handbook/interfaces.html#indexable-types" rel="noreferrer">indexer</a>:</p>
<pre><code>interface EnumServiceGetOrderBy {
[index: number]: { id: number; label: string; key: any };
}
</code></pre> | {
"question_id": 25469244,
"question_date": "2014-08-24T06:53:30.950Z",
"question_score": 211,
"tags": "typescript",
"answer_id": 25469668,
"answer_date": "2014-08-24T07:53:49.513Z",
"answer_score": 155
} |
Please answer the following Stack Overflow question:
Title: DropDownList's SelectedIndexChanged event not firing
<p>I have a DropDownList object in my web page. When I click on it and select a different value, nothing happens, even though I have a function wired up to the <code>SelectedIndexChanged</code> event.</p>
<p>First, the actual object's HTML code:</p>
<pre><code><asp:DropDownList ID="logList" runat="server"
onselectedindexchanged="itemSelected">
</asp:DropDownList>
</code></pre>
<p>And this is that function, <code>itemSelected</code>:</p>
<pre><code>protected void itemSelected(object sender, EventArgs e)
{
Response.Write("Getting clicked; " + sender.GetType().ToString());
FileInfo selectedfile;
Response.Write("<script>alert('Hello')</script>");
foreach (FileInfo file in logs)
{
if (file.Name == logList.Items[logList.SelectedIndex].Text)
{
Response.Write("<script>alert('Hello')</script>");
}
}
}
</code></pre>
<p>None of the Responses appear, and that portion of JavaScript is never run. I've tried this on the latest 3.6 version of Firefox, as well as Internet Explorer 8. This is being served from a Windows Server 2003 R2 machine, running ASP.NET with the .NET Framework version 4.</p> | <p>Set DropDownList <code>AutoPostBack</code> property to true.</p>
<p>Eg:</p>
<pre><code><asp:DropDownList ID="logList" runat="server" AutoPostBack="True"
onselectedindexchanged="itemSelected">
</asp:DropDownList>
</code></pre> | {
"question_id": 4905406,
"question_date": "2011-02-05T06:01:14.253Z",
"question_score": 211,
"tags": "asp.net|drop-down-menu|selectedindexchanged",
"answer_id": 4905428,
"answer_date": "2011-02-05T06:06:51.460Z",
"answer_score": 434
} |
Please answer the following Stack Overflow question:
Title: convert string array to string
<p>I would like to convert a string array to a single string.</p>
<pre><code>string[] test = new string[2];
test[0] = "Hello ";
test[1] = "World!";
</code></pre>
<p>I would like to have something like "Hello World!"</p> | <pre><code>string[] test = new string[2];
test[0] = "Hello ";
test[1] = "World!";
string.Join("", test);
</code></pre> | {
"question_id": 4841401,
"question_date": "2011-01-30T05:51:37.773Z",
"question_score": 211,
"tags": "c#|arrays|string",
"answer_id": 4841409,
"answer_date": "2011-01-30T05:54:04.240Z",
"answer_score": 375
} |
Please answer the following Stack Overflow question:
Title: Installing SciPy with pip
<p>It is possible to install <a href="http://en.wikipedia.org/wiki/NumPy" rel="noreferrer">NumPy</a> with <a href="https://en.wikipedia.org/wiki/Pip_%28package_manager%29" rel="noreferrer">pip</a> using <code>pip install numpy</code>. </p>
<p>Is there a similar possibility with <a href="http://en.wikipedia.org/wiki/SciPy" rel="noreferrer">SciPy</a>? (Doing <code>pip install scipy</code> does not work.)</p>
<hr>
<p><strong>Update</strong></p>
<p>The package SciPy is now available to be installed with <code>pip</code>!</p> | <p>An attempt to <code>easy_install</code> indicates a problem with their <a href="http://pypi.python.org/pypi/scipy/0.7.0" rel="noreferrer">listing</a> in the <a href="http://pypi.python.org/pypi" rel="noreferrer">Python Package Index</a>, which pip searches.</p>
<pre><code>easy_install scipy
Searching for scipy
Reading http://pypi.python.org/simple/scipy/
Reading http://www.scipy.org
Reading http://sourceforge.net/project/showfiles.php?group_id=27747&package_id=19531
Reading http://new.scipy.org/Wiki/Download
</code></pre>
<p>All is not lost, however; <code>pip</code> can install from <a href="http://en.wikipedia.org/wiki/Apache_Subversion" rel="noreferrer">Subversion</a> (SVN), <a href="http://en.wikipedia.org/wiki/Git_%28software%29" rel="noreferrer">Git</a>, <a href="http://en.wikipedia.org/wiki/Mercurial" rel="noreferrer">Mercurial</a>, and <a href="http://en.wikipedia.org/wiki/Bazaar_%28software%29" rel="noreferrer">Bazaar</a> repositories. SciPy uses SVN:</p>
<pre><code>pip install svn+http://svn.scipy.org/svn/scipy/trunk/#egg=scipy
</code></pre>
<p>Update (12-2012):</p>
<pre><code>pip install git+https://github.com/scipy/scipy.git
</code></pre>
<p>Since NumPy is a dependency, it should be installed as well.</p> | {
"question_id": 2213551,
"question_date": "2010-02-06T15:13:55.820Z",
"question_score": 211,
"tags": "python|installation|scipy|pip",
"answer_id": 2214018,
"answer_date": "2010-02-06T17:48:20.537Z",
"answer_score": 107
} |
Please answer the following Stack Overflow question:
Title: Excel: last character/string match in a string
<p>Is there an efficient way to identify the last character/string match in a string using base functions? I.e. not the last character/string <strong>of</strong> the string, but the position of a character/string's last occurrence <strong>in</strong> a string. <code>Search</code> and <code>find</code> both work left-to-right so I can't think how to apply without lengthy recursive algorithm. And <a href="http://www.mrexcel.com/archive/General/30895.html">this solution</a> now seems obsolete.</p> | <p><strong>New Answer</strong> | 31-3-2022:</p>
<p>With even newer functions come even shorter answers. At time of writing in BETA, but probably widely available in the near future, we can use <a href="https://support.microsoft.com/en-us/office/textbefore-function-d099c28a-dba8-448e-ac6c-f086d0fa1b29" rel="nofollow noreferrer"><code>TEXTBEFORE()</code></a>:</p>
<pre><code>=LEN(TEXTBEFORE(A2,B2,-1))+1
</code></pre>
<p>The trick here is that the 3rd parameter tells the function to retrieve the last occurence of the substring we give in the 2nd parameter. At time of writing this function is still case-sensitive by default which could be handeld by the optional 4th parameter.</p>
<hr />
<p><strong>Original Answer</strong> | 17-6-2020:</p>
<p>With newer versions of excel come new functions and thus new methods. Though it's replicable in older versions (yet I have not seen it before), when one has Excel O365 one can use:</p>
<pre><code>=MATCH(2,1/(MID(A1,SEQUENCE(LEN(A1)),1)="Y"))
</code></pre>
<p>This can also be used to retrieve the last position of (overlapping) substrings:</p>
<pre><code>=MATCH(2,1/(MID(A1,SEQUENCE(LEN(A1)),2)="YY"))
</code></pre>
<hr />
<pre><code>| Value | Pattern | Formula | Position |
|--------|---------|------------------------------------------------|----------|
| XYYZ | Y | =MATCH(2,1/(MID(A2,SEQUENCE(LEN(A2)),1)="Y")) | 3 |
| XYYYZ | YY | =MATCH(2,1/(MID(A3,SEQUENCE(LEN(A3)),2)="YY")) | 3 |
| XYYYYZ | YY | =MATCH(2,1/(MID(A4,SEQUENCE(LEN(A4)),2)="YY")) | 4 |
</code></pre>
<hr />
<p>Whilst this both allows us to no longer use an arbitrary replacement character and it allows overlapping patterns, the "downside" is the useage of an array.</p>
<hr />
<p><em><strong>Note:</strong> You can force the same behaviour in older Excel versions through either</em></p>
<pre><code>=MATCH(2,1/(MID(A2,ROW(A1:INDEX(A:A,LEN(A2))),1)="Y"))
</code></pre>
<p><em>Entered through <kbd>Ctrl</kbd><kbd>Shift</kbd><kbd>Enter</kbd>, or using an inline <code>INDEX</code> to get rid of implicit intersection:</em></p>
<pre><code>=MATCH(2,INDEX(1/(MID(A2,ROW(A1:INDEX(A:A,LEN(A2))),1)="Y"),))
</code></pre> | {
"question_id": 18617349,
"question_date": "2013-09-04T15:02:04.983Z",
"question_score": 211,
"tags": "excel|excel-formula",
"answer_id": 62439299,
"answer_date": "2020-06-17T22:21:45.167Z",
"answer_score": 12
} |
Please answer the following Stack Overflow question:
Title: How to loop through files matching wildcard in batch file
<p>I have a set of base filenames, for each name 'f' there are exactly two files, 'f.in' and 'f.out'. I want to write a batch file (in Windows XP) which goes through all the filenames, for each one it should:</p>
<ul>
<li>Display the base name 'f'</li>
<li>Perform an action on 'f.in'</li>
<li>Perform another action on 'f.out'</li>
</ul>
<p>I don't have any way to list the set of base filenames, other than to search for *.in (or *.out) for example.</p> | <p>Assuming you have two programs that process the two files, process_in.exe and process_out.exe:</p>
<pre><code>for %%f in (*.in) do (
echo %%~nf
process_in "%%~nf.in"
process_out "%%~nf.out"
)
</code></pre>
<p>%%~nf is a substitution modifier, that expands %f to a file name only.
See other modifiers in <a href="https://technet.microsoft.com/en-us/library/bb490909.aspx" rel="noreferrer">https://technet.microsoft.com/en-us/library/bb490909.aspx</a> (midway down the page) or just in the next answer.</p> | {
"question_id": 39615,
"question_date": "2008-09-02T14:12:02.527Z",
"question_score": 211,
"tags": "command-line|windows-xp|batch-file",
"answer_id": 39664,
"answer_date": "2008-09-02T14:28:51.457Z",
"answer_score": 316
} |
Please answer the following Stack Overflow question:
Title: PowerShell equivalent to grep -f
<p>I'm looking for the PowerShell equivalent to <code>grep --file=filename</code>. If you don't know <code>grep</code>, filename is a text file where each line has a regular expression pattern you want to match.</p>
<p>Maybe I'm missing something obvious, but <code>Select-String</code> doesn't seem to have this option.</p> | <p>The <code>-Pattern</code> parameter in <code>Select-String</code> supports an array of patterns. So the one you're looking for is:</p>
<pre><code>Get-Content .\doc.txt | Select-String -Pattern (Get-Content .\regex.txt)
</code></pre>
<p>This searches through the textfile <code>doc.txt</code> by using every regex(one per line) in <code>regex.txt</code></p> | {
"question_id": 15199321,
"question_date": "2013-03-04T10:24:17.170Z",
"question_score": 211,
"tags": "powershell|grep",
"answer_id": 15201215,
"answer_date": "2013-03-04T12:06:58.253Z",
"answer_score": 227
} |
Please answer the following Stack Overflow question:
Title: Bulk Insertion in Laravel using eloquent ORM
<p>How can we perform bulk database insertions in Laravel using Eloquent ORM?</p>
<p>I am working with an XML document, looping through its elements. I want to accomplish something like this in Laravel:</p>
<pre class="lang-php prettyprint-override"><code>$sXML = download_page('http://remotepage.php&function=getItems&count=100&page=1');
$oXML = new SimpleXMLElement($sXML);
$query = "INSERT INTO tbl_item (first_name, last_name, date_added) VALUES";
foreach($oXML->results->item->item as $oEntry){
$query .= "('" . $oEntry->firstname . "', '" . $oEntry->lastname . "', '" . date("Y-m-d H:i:s") . "'),";
}
mysql_query($query);
</code></pre>
<p>but I am getting the following error.</p>
<blockquote>
<p>SQLSTATE[HY093]: Invalid parameter number: mixed named and positional parameters.</p>
</blockquote> | <p>You can just use <code>Eloquent::insert()</code>.</p>
<p>For example:</p>
<pre><code>$data = [
['name'=>'Coder 1', 'rep'=>'4096'],
['name'=>'Coder 2', 'rep'=>'2048'],
//...
];
Coder::insert($data);
</code></pre> | {
"question_id": 12702812,
"question_date": "2012-10-03T06:16:16.933Z",
"question_score": 211,
"tags": "php|laravel|eloquent",
"answer_id": 13595393,
"answer_date": "2012-11-27T23:54:16.433Z",
"answer_score": 398
} |
Please answer the following Stack Overflow question:
Title: How to plot multiple dataframes in subplots
<p>I have a few Pandas DataFrames sharing the same value scale, but having different columns and indices. When invoking <code>df.plot()</code>, I get separate plot images. what I really want is to have them all in the same plot as subplots, but I'm unfortunately failing to come up with a solution to how and would highly appreciate some help. </p> | <p>You can manually create the subplots with matplotlib, and then plot the dataframes on a specific subplot using the <code>ax</code> keyword. For example for 4 subplots (2x2):</p>
<pre><code>import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=2, ncols=2)
df1.plot(ax=axes[0,0])
df2.plot(ax=axes[0,1])
...
</code></pre>
<p>Here <code>axes</code> is an array which holds the different subplot axes, and you can access one just by indexing <code>axes</code>.<br>
If you want a shared x-axis, then you can provide <code>sharex=True</code> to <code>plt.subplots</code>.</p> | {
"question_id": 22483588,
"question_date": "2014-03-18T15:18:11.250Z",
"question_score": 211,
"tags": "python|pandas|matplotlib|seaborn|subplot",
"answer_id": 22484249,
"answer_date": "2014-03-18T15:45:26.467Z",
"answer_score": 368
} |
Please answer the following Stack Overflow question:
Title: Can Selenium WebDriver open browser windows silently in the background?
<p>I have a Selenium test suite that runs many tests and on each new test it opens a browser window on top of any other windows I have open. Very jarring while working in a local environment. Is there a way to tell Selenium or the OS (Mac) to open the windows in the background?</p> | <p>There are a few ways, but it isn't a simple "set a configuration value". Unless you invest in a headless browser, which doesn't suit everyone's requirements, it is a little bit of a hack:</p>
<p><em><a href="https://stackoverflow.com/questions/5370762/how-to-hide-firefox-window-firefox-webdriver">How to hide Firefox window (Selenium WebDriver)?</a></em></p>
<p>and</p>
<p><em><a href="https://stackoverflow.com/questions/1418082/is-it-possible-to-hide-the-browser-in-selenium-rc">Is it possible to hide the browser in Selenium RC?</a></em></p>
<p>You can 'supposedly', pass in some parameters into Chrome, specifically: <code>--no-startup-window</code></p>
<p>Note that for some browsers, especially Internet Explorer, it will hurt your tests to not have it run in focus.</p>
<p>You can also hack about a bit with <a href="https://en.wikipedia.org/wiki/AutoIt" rel="noreferrer">AutoIt</a>, to hide the window once it's opened.</p> | {
"question_id": 16180428,
"question_date": "2013-04-23T22:46:50.160Z",
"question_score": 211,
"tags": "selenium|selenium-webdriver|webdriver|selenium-grid",
"answer_id": 16196050,
"answer_date": "2013-04-24T15:28:32.310Z",
"answer_score": 74
} |
Please answer the following Stack Overflow question:
Title: Google MAP API Uncaught TypeError: Cannot read property 'offsetWidth' of null
<p>I'm trying to use Google MAP API v3 with the following code.</p>
<pre><code><h2>Topology</h2>
<script src="https://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="{% url css_media 'tooltip.topology.css' %}" />
<link rel="stylesheet" type="text/css" href="{% url css_media 'tooltip.css' %}" />
<style type="text/css" >
#map_canvas {
width:300px;
height:300px;
}
</style>
<script type="text/javascript">
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
</script>
<div id="map_canvas"> </div>
</code></pre>
<p>When I run this code, the browser says this. </p>
<blockquote>
<p>Uncaught TypeError: Cannot read property 'offsetWidth' of null</p>
</blockquote>
<p>I have no idea, since I follow the direction given in <a href="https://developers.google.com/maps/documentation/javascript/tutorial">this tutorial</a>.</p>
<p>Do you have any clue?</p> | <p>This problem is usually due to the map div not being rendered before the javascript runs that needs to access it.</p>
<p>You should put your initialization code inside an onload function or at the bottom of your HTML file, just before the tag, so the DOM is completely rendered before it executes (note that the second option is more sensitive to invalid HTML).</p>
<p>Note, as pointed out by <a href="https://stackoverflow.com/users/1963978/matthewsheets">matthewsheets</a> this also could be cause by the div with that id not existing at all in your HTML (the pathological case of the div not being rendered) </p>
<p>Adding code sample from <a href="https://stackoverflow.com/users/697856/wf9a5m75">wf9a5m75</a>'s post to put everything in one place:</p>
<pre><code><script type="text/javascript">
function initialize() {
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
}
google.maps.event.addDomListener(window, "load", initialize);
</script>
</code></pre> | {
"question_id": 11740663,
"question_date": "2012-07-31T12:58:43.900Z",
"question_score": 211,
"tags": "javascript|google-maps-api-3",
"answer_id": 11743096,
"answer_date": "2012-07-31T15:03:34.150Z",
"answer_score": 324
} |
Please answer the following Stack Overflow question:
Title: Call int() function on every list element?
<p>I have a list with numeric strings, like so:</p>
<pre><code>numbers = ['1', '5', '10', '8'];
</code></pre>
<p>I would like to convert every list element to integer, so it would look like this:</p>
<pre><code>numbers = [1, 5, 10, 8];
</code></pre>
<p>I could do it using a loop, like so:</p>
<pre><code>new_numbers = [];
for n in numbers:
new_numbers.append(int(n));
numbers = new_numbers;
</code></pre>
<p>Does it have to be so ugly? I'm sure there is a more pythonic way to do this in a one line of code. Please help me out.</p> | <p>This is what <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="noreferrer">list comprehensions</a> are for:</p>
<pre><code>numbers = [ int(x) for x in numbers ]
</code></pre> | {
"question_id": 3371269,
"question_date": "2010-07-30T12:12:58.193Z",
"question_score": 211,
"tags": "python|list|type-conversion|integer",
"answer_id": 3371274,
"answer_date": "2010-07-30T12:13:33.587Z",
"answer_score": 402
} |
Please answer the following Stack Overflow question:
Title: Uncaught TypeError: (intermediate value)(...) is not a function
<p>Everything works fine when I wrote the js logic in a closure as a single js file, as:</p>
<pre><code>(function(win){
//main logic here
win.expose1 = ....
win.expose2 = ....
})(window)
</code></pre>
<p>but when I try to insert a logging alternative function before that closure in the same js file, </p>
<pre><code> window.Glog = function(msg){
console.log(msg)
}
// this was added before the main closure.
(function(win){
//the former closure that contains the main javascript logic;
})(window)
</code></pre>
<p>it complains that there is a TypeError:</p>
<pre><code>Uncaught TypeError: (intermediate value)(...) is not a function
</code></pre>
<p>What did I do wrong?</p> | <p>The error is a result of the missing semicolon on the third line:</p>
<pre><code>window.Glog = function(msg) {
console.log(msg);
}; // <--- Add this semicolon
(function(win) {
// ...
})(window);
</code></pre>
<p>The ECMAScript specification has <a href="https://www.ecma-international.org/ecma-262/5.1/#sec-7.9" rel="noreferrer">specific rules for automatic semicolon insertion</a>, however in this case a semicolon isn't automatically inserted because the parenthesised expression that begins on the next line can be interpreted as an argument list for a function call.</p>
<p>This means that without that semicolon, the anonymous <code>window.Glog</code> function was being invoked with a function as the <code>msg</code> parameter, followed by <code>(window)</code> which was subsequently attempting to invoke whatever was returned.</p>
<p>This is how the code was being interpreted:</p>
<pre><code>window.Glog = function(msg) {
console.log(msg);
}(function(win) {
// ...
})(window);
</code></pre> | {
"question_id": 42036349,
"question_date": "2017-02-04T04:05:23.793Z",
"question_score": 211,
"tags": "javascript|typeerror",
"answer_id": 42036382,
"answer_date": "2017-02-04T04:12:15.960Z",
"answer_score": 407
} |
Please answer the following Stack Overflow question:
Title: Cell spacing in UICollectionView
<p>How do I set cell spacing in a section of <code>UICollectionView</code>? I know there is a property <code>minimumInteritemSpacing</code> I have set it to 5.0 still the spacing is not appearing 5.0. I have implemented the flowout delegate method.</p>
<pre><code>- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
return 5.0;
}
</code></pre>
<p>still I am not getting the desired result. I think its the minimum spacing . Isn't there any way by which I can set the maximum spacing?</p>
<p><img src="https://i.stack.imgur.com/bm6Ggm.png" alt="simulator sc"></p> | <p>I know that the topic is old, but in case anyone still needs correct answer here what you need:</p>
<ol>
<li>Override standard flow layout.</li>
<li><p>Add implementation like that:</p>
<pre><code>- (NSArray *) layoutAttributesForElementsInRect:(CGRect)rect {
NSArray *answer = [super layoutAttributesForElementsInRect:rect];
for(int i = 1; i < [answer count]; ++i) {
UICollectionViewLayoutAttributes *currentLayoutAttributes = answer[i];
UICollectionViewLayoutAttributes *prevLayoutAttributes = answer[i - 1];
NSInteger maximumSpacing = 4;
NSInteger origin = CGRectGetMaxX(prevLayoutAttributes.frame);
if(origin + maximumSpacing + currentLayoutAttributes.frame.size.width < self.collectionViewContentSize.width) {
CGRect frame = currentLayoutAttributes.frame;
frame.origin.x = origin + maximumSpacing;
currentLayoutAttributes.frame = frame;
}
}
return answer;
}
</code></pre></li>
</ol>
<p>where maximumSpacing could be set to any value you prefer. This trick guarantees that the space between cells would be EXACTLY equal to maximumSpacing!!</p> | {
"question_id": 17229350,
"question_date": "2013-06-21T06:55:09.743Z",
"question_score": 211,
"tags": "ios|objective-c|uicollectionview",
"answer_id": 19429189,
"answer_date": "2013-10-17T14:16:01.937Z",
"answer_score": 151
} |
Please answer the following Stack Overflow question:
Title: How do I run a docker instance from a DockerFile?
<p>I finally figured out how to get docker up and running. </p>
<pre><code>docker run --name my-forum-nodebb --link my-forum-redis:redis -p 80:80 -p 443:443 -p 4567:4567 -P -t -i nodebb/docker:ubuntu
</code></pre>
<p>I linked it to a redis instance, cool. </p>
<p>This is from scratch and I assume that when I created the redis instance </p>
<pre><code>docker run --name my-forum-redis -d -p 6379:6379 nodebb/docker:ubuntu-redis
</code></pre>
<p>it pulls the image from a remote repo?</p>
<p>NodeBB offers a <code>Dockerfile</code> <a href="https://github.com/NodeBB/NodeBB/blob/master/Dockerfile" rel="noreferrer">https://github.com/NodeBB/NodeBB/blob/master/Dockerfile</a> I am not really quite sure how to use it. I am assuming that I can somehow create a local environment by calling this Dockerfile on my remote.</p>
<p>Is this correct? If so how can I create the local instance pointing to the remote?</p> | <p>Download the file and from the same directory run <code>docker build -t nodebb .</code></p>
<p>This will give you an image on your local machine that's named nodebb that you can launch an container from with <code>docker run -d nodebb</code> (you can change <strong>nodebb</strong> to your own name).</p> | {
"question_id": 36075525,
"question_date": "2016-03-18T03:19:47.063Z",
"question_score": 211,
"tags": "docker|docker-machine",
"answer_id": 36076856,
"answer_date": "2016-03-18T05:33:42.493Z",
"answer_score": 242
} |
Please answer the following Stack Overflow question:
Title: Generate random numbers with a given (numerical) distribution
<p>I have a file with some probabilities for different values e.g.:</p>
<pre><code>1 0.1
2 0.05
3 0.05
4 0.2
5 0.4
6 0.2
</code></pre>
<p>I would like to generate random numbers using this distribution. Does an existing module that handles this exist? It's fairly simple to code on your own (build the cumulative density function, generate a random value [0,1] and pick the corresponding value) but it seems like this should be a common problem and probably someone has created a function/module for it.</p>
<p>I need this because I want to generate a list of birthdays (which do not follow any distribution in the standard <code>random</code> module).</p> | <p><a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.rv_discrete.html" rel="noreferrer"><code>scipy.stats.rv_discrete</code></a> might be what you want. You can supply your probabilities via the <code>values</code> parameter. You can then use the <code>rvs()</code> method of the distribution object to generate random numbers.</p>
<p>As pointed out by Eugene Pakhomov in the comments, you can also pass a <code>p</code> keyword parameter to <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.choice.html" rel="noreferrer"><code>numpy.random.choice()</code></a>, e.g.</p>
<pre><code>numpy.random.choice(numpy.arange(1, 7), p=[0.1, 0.05, 0.05, 0.2, 0.4, 0.2])
</code></pre>
<p>If you are using Python 3.6 or above, you can use <code>random.choices()</code> from the standard library – see the <a href="https://stackoverflow.com/a/41852266/5987">answer by Mark Dickinson</a>.</p> | {
"question_id": 4265988,
"question_date": "2010-11-24T10:56:51.943Z",
"question_score": 211,
"tags": "python|module|random",
"answer_id": 4266645,
"answer_date": "2010-11-24T12:15:50.883Z",
"answer_score": 188
} |
Please answer the following Stack Overflow question:
Title: How to alter a column's data type in a PostgreSQL table?
<p>Entering the following command into a PostgreSQL interactive terminal results in an error:</p>
<pre><code>ALTER TABLE tbl_name ALTER COLUMN col_name varchar (11);
</code></pre>
<p>What is the correct command to alter the data type of a column?</p> | <p>See documentation here: <a href="http://www.postgresql.org/docs/current/interactive/sql-altertable.html" rel="noreferrer">http://www.postgresql.org/docs/current/interactive/sql-altertable.html</a></p>
<pre><code>ALTER TABLE tbl_name ALTER COLUMN col_name TYPE varchar (11);
</code></pre> | {
"question_id": 7162903,
"question_date": "2011-08-23T14:45:19.190Z",
"question_score": 211,
"tags": "sql|postgresql|psql|alter-table|alter-column",
"answer_id": 7162961,
"answer_date": "2011-08-23T14:49:41.823Z",
"answer_score": 322
} |
Please answer the following Stack Overflow question:
Title: /bin/sh: apt-get: not found
<p>I am trying to change a dockerFile to work with aspell. I have a bash script that I want to wrap in a dock</p>
<blockquote>
<p>Step 4: Wrap the script in a Docker container.</p>
<p>The sample SDK we downloaded earlier contains an example of an action wrapped in a Docker container. In particular, the sample SDK includes a Dockerfile that builds the C program in client/example.c and installs the binary as /blackbox/client/action .</p>
<p>The key line in the sample Dockerfile is:</p>
<pre><code>RUN cd /blackbox/client; gcc -o action example.c
</code></pre>
<p>Instead of compiling example.c and installing the binary as an action, we’ll change the Dockerfile to install aspell into the Linux environment, and then install our action.sh script as the executable action command.</p>
<p>To do so, we delete the RUN command above, and insert the following commands into the Dockerfile:</p>
<pre><code>RUN apt-get install -y aspell
RUN rm -f /blackbox/client/action
ADD action.sh /blackbox/client/action
</code></pre>
</blockquote>
<p>I am trying to do this on the dockerfile below</p>
<pre><code># Dockerfile for example whisk docker action
FROM openwhisk/dockerskeleton
ENV FLASK_PROXY_PORT 8080
### Add source file(s)
ADD example.c /action/example.c
RUN sudo apt-get install -y aspell
RUN rm -f /blackbox/client/action
ADD action.sh /blackbox/client/action
CMD ["/home/huseyin/bin", "-c", "cd actionProxy && python -u actionproxy.py"]
</code></pre>
<p>The tutorial is outdated so I can't figure out how to make it work. What am I doing wrong?</p> | <p>The <a href="https://hub.docker.com/r/openwhisk/dockerskeleton/~/dockerfile/" rel="noreferrer">image you're using</a> is <a href="https://alpinelinux.org" rel="noreferrer">Alpine based</a>, so you can't use <code>apt-get</code> because it's Ubuntu's package manager.</p>
<p>To fix this just use: </p>
<p><code>apk update</code> and <code>apk add</code></p> | {
"question_id": 45142855,
"question_date": "2017-07-17T11:18:39.070Z",
"question_score": 211,
"tags": "bash|docker|dockerfile|aspell",
"answer_id": 45143116,
"answer_date": "2017-07-17T11:29:43.630Z",
"answer_score": 550
} |
Please answer the following Stack Overflow question:
Title: How can I debug "ImagePullBackOff"?
<p>All of a sudden, I cannot deploy some images which could be deployed before. I got the following pod status:</p>
<pre><code>[root@webdev2 origin]# oc get pods
NAME READY STATUS RESTARTS AGE
arix-3-yjq9w 0/1 ImagePullBackOff 0 10m
docker-registry-2-vqstm 1/1 Running 0 2d
router-1-kvjxq 1/1 Running 0 2d
</code></pre>
<p>The application just won't start. The pod is not trying to run the container. From the Event page, I have got <code>Back-off pulling image "172.30.84.25:5000/default/arix@sha256:d326</code>. I have verified that I can pull the image with the tag with <code>docker pull</code>.</p>
<p>I have also checked the log of the last container. It was closed for some reason. I think the pod should at least try to restart it.</p>
<p>I have run out of ideas to debug the issues. What can I check more?</p> | <p>You can use the '<em><strong>describe pod</strong></em>' syntax</p>
<p><strong>For OpenShift use:</strong></p>
<pre><code>oc describe pod <pod-id>
</code></pre>
<p><strong>For vanilla Kubernetes:</strong></p>
<pre><code>kubectl describe pod <pod-id>
</code></pre>
<p>Examine the events of the output.
In my case it shows <code>Back-off pulling image unreachableserver/nginx:1.14.22222</code></p>
<p>In this case the image <code>unreachableserver/nginx:1.14.22222</code> can not be pulled from the Internet because there is no Docker registry unreachableserver and the image <code>nginx:1.14.22222</code> does not exist.</p>
<p><strong>NB: If you do not see any events of interest and the pod has been in the 'ImagePullBackOff' status for a while (seems like more than 60 minutes), you need to delete the pod and look at the events from the new pod.</strong></p>
<p><strong>For OpenShift use:</strong></p>
<pre><code>oc delete pod <pod-id>
oc get pods
oc get pod <new-pod-id>
</code></pre>
<p><strong>For vanilla Kubernetes:</strong></p>
<pre><code>kubectl delete pod <pod-id>
kubectl get pods
kubectl get pod <new-pod-id>
</code></pre>
<p>Sample output:</p>
<pre><code> Type Reason Age From Message
---- ------ ---- ---- -------
Normal Scheduled 32s default-scheduler Successfully assigned rk/nginx-deployment-6c879b5f64-2xrmt to aks-agentpool-x
Normal Pulling 17s (x2 over 30s) kubelet Pulling image "unreachableserver/nginx:1.14.22222"
Warning Failed 16s (x2 over 29s) kubelet Failed to pull image "unreachableserver/nginx:1.14.22222": rpc error: code = Unknown desc = Error response from daemon: pull access denied for unreachableserver/nginx, repository does not exist or may require 'docker login': denied: requested access to the resource is denied
Warning Failed 16s (x2 over 29s) kubelet Error: ErrImagePull
Normal BackOff 5s (x2 over 28s) kubelet Back-off pulling image "unreachableserver/nginx:1.14.22222"
Warning Failed 5s (x2 over 28s) kubelet Error: ImagePullBackOff
</code></pre>
<p><strong>Additional debugging steps</strong></p>
<ol>
<li>try to pull the docker image and tag manually on your computer</li>
<li>Identify the node by doing a 'kubectl/oc get pods -o wide'</li>
<li>ssh into the node (if you can) that can not pull the docker image</li>
<li>check that the node can resolve the DNS of the docker registry by performing a ping.</li>
<li>try to pull the docker image manually on the node</li>
<li>If you are using a private registry, check that your <a href="https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/" rel="noreferrer">secret</a> exists and the secret is correct. Your secret should also be in the same namespace. Thanks <a href="https://stackoverflow.com/users/2677943/swenzel">swenzel</a></li>
<li>Some registries have firewalls that limit ip address access. The firewall may block the pull</li>
<li>Some CIs create deployments with temporary docker secrets. So the secret expires after a few days (You are asking for production failures...)</li>
</ol> | {
"question_id": 34848422,
"question_date": "2016-01-18T06:24:30.987Z",
"question_score": 211,
"tags": "kubernetes|openshift|openshift-origin",
"answer_id": 44150759,
"answer_date": "2017-05-24T06:40:15.343Z",
"answer_score": 219
} |
Please answer the following Stack Overflow question:
Title: Equivalent of varchar(max) in MySQL?
<p>What is the equivalent of varchar(max) in MySQL?</p> | <p>The max length of a varchar is subject to the max row size in MySQL, which is 64KB (not counting BLOBs):</p>
<pre><code>VARCHAR(65535)
</code></pre>
<p>However, note that the limit is lower if you use a multi-byte character set:</p>
<pre><code>VARCHAR(21844) CHARACTER SET utf8
</code></pre>
<hr>
<p>Here are some examples:</p>
<p>The maximum row size is 65535, but a varchar also includes a byte or two to encode the length of a given string. So you actually can't declare a varchar of the maximum row size, even if it's the only column in the table.</p>
<pre><code>mysql> CREATE TABLE foo ( v VARCHAR(65534) );
ERROR 1118 (42000): Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs
</code></pre>
<p>But if we try decreasing lengths, we find the greatest length that works:</p>
<pre><code>mysql> CREATE TABLE foo ( v VARCHAR(65532) );
Query OK, 0 rows affected (0.01 sec)
</code></pre>
<p>Now if we try to use a multibyte charset at the table level, we find that it counts each character as multiple bytes. UTF8 strings don't <em>necessarily</em> use multiple bytes per string, but MySQL can't assume you'll restrict all your future inserts to single-byte characters.</p>
<pre><code>mysql> CREATE TABLE foo ( v VARCHAR(65532) ) CHARSET=utf8;
ERROR 1074 (42000): Column length too big for column 'v' (max = 21845); use BLOB or TEXT instead
</code></pre>
<p>In spite of what the last error told us, InnoDB still doesn't like a length of 21845.</p>
<pre><code>mysql> CREATE TABLE foo ( v VARCHAR(21845) ) CHARSET=utf8;
ERROR 1118 (42000): Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs
</code></pre>
<p>This makes perfect sense, if you calculate that 21845*3 = 65535, which wouldn't have worked anyway. Whereas 21844*3 = 65532, which does work.</p>
<pre><code>mysql> CREATE TABLE foo ( v VARCHAR(21844) ) CHARSET=utf8;
Query OK, 0 rows affected (0.32 sec)
</code></pre> | {
"question_id": 332798,
"question_date": "2008-12-02T01:49:36.760Z",
"question_score": 211,
"tags": "mysql|varchar",
"answer_id": 332805,
"answer_date": "2008-12-02T01:55:28.930Z",
"answer_score": 227
} |
Please answer the following Stack Overflow question:
Title: Requests -- how to tell if you're getting a 404
<p>I'm using the Requests library and accessing a website to gather data from it with the following code: </p>
<pre><code>r = requests.get(url)
</code></pre>
<p>I want to add error testing for when an improper URL is entered and a 404 error is returned. If I intentionally enter an invalid URL, when I do this:</p>
<pre><code>print r
</code></pre>
<p>I get this:</p>
<pre><code><Response [404]>
</code></pre>
<p>EDIT:</p>
<p>I want to know how to test for that. The object type is still the same. When I do <code>r.content</code> or <code>r.text</code>, I simply get the HTML of a custom 404 page. </p> | <p>Look at the <a href="https://requests.readthedocs.io/en/latest/user/quickstart/#response-status-codes" rel="noreferrer"><code>r.status_code</code> attribute</a>:</p>
<pre><code>if r.status_code == 404:
# A 404 was issued.
</code></pre>
<p>Demo:</p>
<pre><code>>>> import requests
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.status_code
404
</code></pre>
<p>If you want <code>requests</code> to raise an exception for error codes (4xx or 5xx), call <code>r.raise_for_status()</code>:</p>
<pre><code>>>> r = requests.get('http://httpbin.org/status/404')
>>> r.raise_for_status()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "requests/models.py", line 664, in raise_for_status
raise http_error
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
>>> r = requests.get('http://httpbin.org/status/200')
>>> r.raise_for_status()
>>> # no exception raised.
</code></pre>
<p>You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:</p>
<pre><code>if r:
# successful response
</code></pre>
<p>If you want to be more explicit, use <code>if r.ok:</code>. </p> | {
"question_id": 15258728,
"question_date": "2013-03-06T21:46:37.613Z",
"question_score": 211,
"tags": "python|python-requests",
"answer_id": 15258759,
"answer_date": "2013-03-06T21:48:50.033Z",
"answer_score": 433
} |
Please answer the following Stack Overflow question:
Title: Git says "Warning: Permanently added to the list of known hosts"
<p>Every time I use git to interact with a remote, such as when pulling or pushing, I am shown the following message:</p>
<blockquote>
<p>Warning: Permanently added '...' (RSA) to the list of known hosts.</p>
</blockquote>
<p>How can I prevent this annoying message from displaying? It is only an annoyance—everything functions properly.</p> | <p>Create a <code>~/.ssh/config</code> file and insert the line:</p>
<pre><code>UserKnownHostsFile ~/.ssh/known_hosts
</code></pre>
<p>You will then see the message the next time you access Github, but after that you'll not see it anymore because the host is added to the <code>known_hosts</code> file. This fixes the issue, rather than just hiding the log message.</p>
<p>This problem was bugging me for quite some time. The problem occurs because the OpenSSH client compiled for Windows doesn't check the known_hosts file in <code>~/.ssh/known_hosts</code></p>
<p>ssh -vvv [email protected]</p>
<pre><code>debug3: check_host_in_hostfile: filename /dev/null
debug3: check_host_in_hostfile: filename /etc/ssh/ssh_known_hosts
debug3: check_host_in_hostfile: filename /dev/null
debug3: check_host_in_hostfile: filename /etc/ssh/ssh_known_hosts
Warning: Permanently added 'github.com,207.97.227.239' (RSA) to the list of known hosts.
</code></pre> | {
"question_id": 9299651,
"question_date": "2012-02-15T19:09:10.500Z",
"question_score": 211,
"tags": "git|shell|command-line|ssh|terminal",
"answer_id": 15578473,
"answer_date": "2013-03-22T19:34:53.830Z",
"answer_score": 260
} |
Please answer the following Stack Overflow question:
Title: What is {this.props.children} and when you should use it?
<p>Being a beginner to React world, I want to understand in depth what happens when I use <code>{this.props.children}</code> and what are the situations to use the same. What is the relevance of it in below code snippet?</p>
<pre><code>render() {
if (this.props.appLoaded) {
return (
<div>
<Header
appName={this.props.appName}
currentUser={this.props.currentUser}
/>
{this.props.children}
</div>
);
}
}
</code></pre> | <blockquote>
<p><strong>What even is ‘children’?</strong></p>
<p>The React docs say that you can use <code>props.children</code> on components that represent ‘generic boxes’ and that don’t know their children ahead of time. For me, that didn’t really clear things up. I’m sure for some, that definition makes perfect sense but it didn’t for me.</p>
<p>My simple explanation of what <code>this.props.children</code> does is that <em>it is used to display whatever you include between the opening and closing tags when invoking a component.</em></p>
<p><strong>A simple example:</strong></p>
<p>Here’s an example of a stateless function that is used to create a component. Again, since this is a function, there is no <code>this</code> keyword so just use <code>props.children</code></p>
</blockquote>
<pre><code>const Picture = (props) => {
return (
<div>
<img src={props.src}/>
{props.children}
</div>
)
}
</code></pre>
<blockquote>
<p>This component contains an <code><img></code> that is receiving some <code>props</code> and then it is displaying <code>{props.children}</code>.</p>
<p>Whenever this component is invoked <code>{props.children}</code> will also be displayed and this is just a reference to what is between the opening and closing tags of the component.</p>
</blockquote>
<pre><code>//App.js
render () {
return (
<div className='container'>
<Picture key={picture.id} src={picture.src}>
//what is placed here is passed as props.children
</Picture>
</div>
)
}
</code></pre>
<blockquote>
<p>Instead of invoking the component with a self-closing tag <code><Picture /></code> if you invoke it will full opening and closing tags <code><Picture> </Picture></code> you can then place more code between it.</p>
<p>This de-couples the <code><Picture></code> component from its content and makes it more reusable.</p>
</blockquote>
<p>Reference: <a href="https://codeburst.io/a-quick-intro-to-reacts-props-children-cb3d2fce4891" rel="noreferrer">A quick intro to React’s props.children</a></p> | {
"question_id": 49706823,
"question_date": "2018-04-07T11:18:04.453Z",
"question_score": 211,
"tags": "javascript|reactjs|react-redux",
"answer_id": 49706920,
"answer_date": "2018-04-07T11:32:11.133Z",
"answer_score": 318
} |
Please answer the following Stack Overflow question:
Title: How do I add more members to my ENUM-type column in MySQL?
<p>The MySQL reference manual does not provide a clearcut example on how to do this.</p>
<p>I have an ENUM-type column of country names that I need to add more countries to. What is the correct MySQL syntax to achieve this?</p>
<p>Here's my attempt:</p>
<pre><code>ALTER TABLE carmake CHANGE country country ENUM('Sweden','Malaysia');
</code></pre>
<p>The error I get is: <code>ERROR 1265 (01000): Data truncated for column 'country' at row 1.</code></p>
<p>The <code>country</code> column is the ENUM-type column in the above-statement.</p>
<p><b>SHOW CREATE TABLE</b> OUTPUT:</p>
<pre><code>mysql> SHOW CREATE TABLE carmake;
+---------+---------------------------------------------------------------------+
| Table | Create Table
+---------+---------------------------------------------------------------------+
| carmake | CREATE TABLE `carmake` (
`carmake_id` tinyint(4) NOT NULL AUTO_INCREMENT,
`name` tinytext,
`country` enum('Japan','USA','England','Australia','Germany','France','Italy','Spain','Czech Republic','China','South Korea','India') DEFAULT NULL,
PRIMARY KEY (`carmake_id`),
KEY `name` (`name`(3))
) ENGINE=InnoDB AUTO_INCREMENT=49 DEFAULT CHARSET=latin1 |
+---------+---------------------------------------------------------------------+
1 row in set (0.00 sec)
</code></pre>
<p><b> SELECT DISTINCT country FROM carmake</b> OUTPUT:</p>
<pre><code>+----------------+
| country |
+----------------+
| Italy |
| Germany |
| England |
| USA |
| France |
| South Korea |
| NULL |
| Australia |
| Spain |
| Czech Republic |
+----------------+
</code></pre> | <pre><code>ALTER TABLE
`table_name`
MODIFY COLUMN
`column_name2` enum(
'existing_value1',
'existing_value2',
'new_value1',
'new_value2'
)
NOT NULL AFTER `column_name1`;
</code></pre> | {
"question_id": 1501958,
"question_date": "2009-10-01T04:55:50.167Z",
"question_score": 211,
"tags": "mysql|enums|alter-table",
"answer_id": 40551734,
"answer_date": "2016-11-11T16:00:00.370Z",
"answer_score": 200
} |
Please answer the following Stack Overflow question:
Title: Why binary_crossentropy and categorical_crossentropy give different performances for the same problem?
<p>I'm trying to train a CNN to categorize text by topic. When I use binary cross-entropy I get ~80% accuracy, with categorical cross-entropy I get ~50% accuracy.</p>
<p>I don't understand why this is. It's a multiclass problem, doesn't that mean that I have to use categorical cross-entropy and that the results with binary cross-entropy are meaningless?</p>
<pre class="lang-python prettyprint-override"><code>model.add(embedding_layer)
model.add(Dropout(0.25))
# convolution layers
model.add(Conv1D(nb_filter=32,
filter_length=4,
border_mode='valid',
activation='relu'))
model.add(MaxPooling1D(pool_length=2))
# dense layers
model.add(Flatten())
model.add(Dense(256))
model.add(Dropout(0.25))
model.add(Activation('relu'))
# output layer
model.add(Dense(len(class_id_index)))
model.add(Activation('softmax'))
</code></pre>
<p>Then I compile it either it like this using <code>categorical_crossentropy</code> as the loss function:</p>
<pre class="lang-python prettyprint-override"><code>model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
</code></pre>
<p>or </p>
<pre class="lang-python prettyprint-override"><code>model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
</code></pre>
<p>Intuitively it makes sense why I'd want to use categorical cross-entropy, I don't understand why I get good results with binary, and poor results with categorical.</p> | <p>The reason for this apparent performance discrepancy between categorical & binary cross entropy is what user xtof54 has already reported in <a href="https://stackoverflow.com/a/44498955/4685471">his answer below</a>, i.e.:</p>
<blockquote>
<p>the accuracy computed with the Keras method <code>evaluate</code> is just plain
wrong when using binary_crossentropy with more than 2 labels</p>
</blockquote>
<p>I would like to elaborate more on this, demonstrate the actual underlying issue, explain it, and offer a remedy.</p>
<p>This behavior is not a bug; the underlying reason is a rather subtle & undocumented issue at how Keras actually <em>guesses</em> which accuracy to use, depending on the loss function you have selected, when you include simply <code>metrics=['accuracy']</code> in your model compilation. In other words, while your first compilation option</p>
<pre class="lang-python prettyprint-override"><code>model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
</code></pre>
<p>is valid, your second one:</p>
<pre class="lang-python prettyprint-override"><code>model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
</code></pre>
<p>will not produce what you expect, but the reason is not the use of binary cross entropy (which, at least in principle, is an absolutely valid loss function).</p>
<p>Why is that? If you check the <a href="https://github.com/fchollet/keras/blob/master/keras/metrics.py" rel="noreferrer">metrics source code</a>, Keras does not define a single accuracy metric, but several different ones, among them <code>binary_accuracy</code> and <code>categorical_accuracy</code>. What happens <a href="https://github.com/keras-team/keras/blob/master/keras/engine/training.py#L876" rel="noreferrer">under the hood</a> is that, since you have selected binary cross entropy as your loss function and have not specified a particular accuracy metric, Keras (wrongly...) infers that you are interested in the <code>binary_accuracy</code>, and this is what it returns - while in fact you are interested in the <code>categorical_accuracy</code>.</p>
<p>Let's verify that this is the case, using the <a href="https://github.com/fchollet/keras/blob/master/examples/mnist_cnn.py" rel="noreferrer">MNIST CNN example</a> in Keras, with the following modification:</p>
<pre class="lang-python prettyprint-override"><code>model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # WRONG way
model.fit(x_train, y_train,
batch_size=batch_size,
epochs=2, # only 2 epochs, for demonstration purposes
verbose=1,
validation_data=(x_test, y_test))
# Keras reported accuracy:
score = model.evaluate(x_test, y_test, verbose=0)
score[1]
# 0.9975801164627075
# Actual accuracy calculated manually:
import numpy as np
y_pred = model.predict(x_test)
acc = sum([np.argmax(y_test[i])==np.argmax(y_pred[i]) for i in range(10000)])/10000
acc
# 0.98780000000000001
score[1]==acc
# False
</code></pre>
<p>To remedy this, i.e. to use indeed binary cross entropy as your loss function (as I said, nothing wrong with this, at least in principle) while still getting the <strong>categorical</strong> accuracy required by the problem at hand, you should ask explicitly for <code>categorical_accuracy</code> in the model compilation as follows:</p>
<pre class="lang-python prettyprint-override"><code>from keras.metrics import categorical_accuracy
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=[categorical_accuracy])
</code></pre>
<p>In the MNIST example, after training, scoring, and predicting the test set as I show above, the two metrics now are the same, as they should be:</p>
<pre class="lang-python prettyprint-override"><code># Keras reported accuracy:
score = model.evaluate(x_test, y_test, verbose=0)
score[1]
# 0.98580000000000001
# Actual accuracy calculated manually:
y_pred = model.predict(x_test)
acc = sum([np.argmax(y_test[i])==np.argmax(y_pred[i]) for i in range(10000)])/10000
acc
# 0.98580000000000001
score[1]==acc
# True
</code></pre>
<p>System setup:</p>
<pre class="lang-python prettyprint-override"><code>Python version 3.5.3
Tensorflow version 1.2.1
Keras version 2.0.4
</code></pre>
<p><strong>UPDATE</strong>: After my post, I discovered that this issue had already been identified in <a href="https://stackoverflow.com/questions/45799474/keras-model-evaluate-vs-model-predict-accuracy-difference-in-multi-class-nlp-ta/45834857#45834857">this answer</a>.</p> | {
"question_id": 42081257,
"question_date": "2017-02-07T03:34:55.963Z",
"question_score": 211,
"tags": "machine-learning|keras|neural-network|deep-learning|conv-neural-network",
"answer_id": 46038271,
"answer_date": "2017-09-04T13:34:45.440Z",
"answer_score": 257
} |
Please answer the following Stack Overflow question:
Title: Using varchar(MAX) vs TEXT on SQL Server
<p>I just read that the <code>VARCHAR(MAX)</code> datatype (which can store close to 2GB of char data) is the recommended replacement for the <code>TEXT</code> datatype in SQL Server 2005 and Next SQL SERVER versions. </p>
<p>If I want to search inside a column for any string, which operation is quicker?</p>
<ol>
<li><p>Using a the <code>LIKE</code> clause against a <code>VARCHAR(MAX)</code> column?</p>
<p><code>WHERE COL1 LIKE '%search string%'</code></p></li>
<li><p>Using the <code>TEXT</code> column and put a <em>Full Text Index</em>/<em>Catalog</em> on this column, and then search using the <code>CONTAINS</code> clause?</p>
<p><code>WHERE CONTAINS (Col1, 'MyToken')</code></p></li>
</ol> | <p>The <code>VARCHAR(MAX)</code> type is a replacement for <code>TEXT</code>. The basic difference is that a <code>TEXT</code> type will always store the data in a blob whereas the <code>VARCHAR(MAX)</code> type will attempt to store the data directly in the row unless it exceeds the 8k limitation and at that point it stores it in a blob.</p>
<p>Using the LIKE statement is identical between the two datatypes. The additional functionality <code>VARCHAR(MAX)</code> gives you is that it is also can be used with <code>=</code> and <code>GROUP BY</code> as any other <code>VARCHAR</code> column can be. However, if you do have a lot of data you will have a huge performance issue using these methods.</p>
<p>In regard to if you should use <code>LIKE</code> to search, or if you should use <em>Full Text Indexing</em> and <code>CONTAINS</code>. This question is the same regardless of <code>VARCHAR(MAX)</code> or <code>TEXT</code>.</p>
<p>If you are searching large amounts of text and performance is key then you should use a <em>Full Text Index</em>.</p>
<p><code>LIKE</code> is simpler to implement and is often suitable for small amounts of data, but it has extremely poor performance with large data due to its inability to use an index.</p> | {
"question_id": 834788,
"question_date": "2009-05-07T13:56:35.277Z",
"question_score": 211,
"tags": "sql-server|performance|text|varchar|sql-types",
"answer_id": 834863,
"answer_date": "2009-05-07T14:10:28.130Z",
"answer_score": 341
} |
Please answer the following Stack Overflow question:
Title: Effects of the extern keyword on C functions
<p>In C, I did not notice any effect of the <code>extern</code> keyword used before function declaration.
At first, I thought that when defining <code>extern int f();</code> in a single file <strong>forces</strong> you to implement it outside of the file's scope. However I found out that both:</p>
<pre><code>extern int f();
int f() {return 0;}
</code></pre>
<p>and</p>
<pre><code>extern int f() {return 0;}
</code></pre>
<p>compile just fine, with no warnings from gcc. I used <code>gcc -Wall -ansi</code>; it wouldn't even accept <code>//</code> comments.</p>
<p>Are there any effects for using <code>extern</code> <strong>before function definitions</strong>? Or is it just an optional keyword with no side effects for functions.</p>
<p>In the latter case I don't understand why did the standard designers chose to litter the grammar with superfluous keywords.</p>
<p><strong>EDIT:</strong> To clarify, I know there's usage for <code>extern</code> in variables, but I'm only asking about <code>extern</code> in <strong>functions</strong>.</p> | <p>We have two files, foo.c and bar.c.</p>
<p>Here is foo.c</p>
<pre><code>#include <stdio.h>
volatile unsigned int stop_now = 0;
extern void bar_function(void);
int main(void)
{
while (1) {
bar_function();
stop_now = 1;
}
return 0;
}
</code></pre>
<p>Now, here is bar.c</p>
<pre><code>#include <stdio.h>
extern volatile unsigned int stop_now;
void bar_function(void)
{
if (! stop_now) {
printf("Hello, world!\n");
sleep(30);
}
}
</code></pre>
<p>As you can see, we have no shared header between foo.c and bar.c , however bar.c needs something declared in foo.c when it's linked, and foo.c needs a function from bar.c when it's linked.</p>
<p><em><strong>By using 'extern', you are telling the compiler that whatever follows it will be found (non-static) at link time; don't reserve anything for it in the current pass since it will be encountered later. Functions and variables are treated equally in this regard.</strong></em></p>
<p>It's very useful if you need to share some global between modules and don't want to put / initialize it in a header.</p>
<p>Technically, every function in a library public header is 'extern', however labeling them as such has very little to no benefit, depending on the compiler. Most compilers can figure that out on their own. As you see, those functions are actually defined somewhere else.</p>
<p>In the above example, main() would print hello world only once, but continue to enter bar_function(). Also note, bar_function() is not going to return in this example (since it's just a simple example). Just imagine stop_now being modified when a signal is serviced (hence, volatile) if this doesn't seem practical enough.</p>
<p>Externs are very useful for things like signal handlers, a mutex that you don't want to put in a header or structure, etc. Most compilers will optimize to ensure that they don't reserve any memory for external objects, since they know they'll be reserving it in the module where the object is defined. However, again, there's little point in specifying it with modern compilers when prototyping public functions.</p>
<p>Hope that helps :)</p> | {
"question_id": 856636,
"question_date": "2009-05-13T07:51:53.073Z",
"question_score": 211,
"tags": "c|syntax|standards",
"answer_id": 856736,
"answer_date": "2009-05-13T08:19:37.537Z",
"answer_score": 173
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.