input_text
stringlengths 115
13.8k
| output_text
stringlengths 24
15k
| metadata
dict |
---|---|---|
Please answer the following Stack Overflow question:
Title: YAML Multi-Line Arrays
<p>In <a href="http://yaml.org/spec" rel="noreferrer">YAML</a>, you can easily create <a href="https://stackoverflow.com/questions/3790454/in-yaml-how-do-i-break-a-string-over-multiple-lines">multi-line strings</a>. However, I would like the ability to create a multi-line array (mainly for readibility within config files) using the <code>|</code> character.</p>
<p>A YAML <strong>array</strong> can be represented as: <code>['key1', 'key2', 'key3']</code>.</p>
<p>A YAML <strong>sequence</strong> uses a dash followed by a space and then a string:</p>
<pre><code>- String1
- String2
- String3
</code></pre>
<p>This would evaluate to: <code>['string1', 'string2', 'string3']</code>.</p>
<p>A YAML <strong>mapping</strong> is an array of key and value pairs that we see all the time in YAML:</p>
<pre><code>Key1: string1
Key2: string2
Key3: string3
</code></pre>
<p>This is all well and good, but I can't for the life of me see how to do a multi-line array. Something like this:</p>
<pre><code>|
['string1', 'string2', 'string3']
['string4', 'string5', 'string6']
</code></pre>
<p>Short of creating multiple array mappings in YAML and merging them in my programming language of choice, is there any way to achieve multi-line arrays, maybe with <code>{ }</code> like Python has but in YAML?</p> | <p>A YAML <strong>sequence</strong> <em>is</em> an <strong>array</strong>. So this is the right way to express it:</p>
<pre><code>key:
- string1
- string2
- string3
- string4
- string5
- string6
</code></pre>
<p>That's identical in meaning to:</p>
<pre><code>key: ['string1', 'string2', 'string3', 'string4', 'string5', 'string6']
</code></pre>
<p>It's also legal to split a single-line array over several lines:</p>
<pre><code>key: ['string1', 'string2', 'string3',
'string4', 'string5',
'string6']
</code></pre>
<p>and even have multi-line strings in single-line arrays:</p>
<pre><code>key: ['string1', 'long
string', 'string3', 'string4', 'string5', 'string6']
</code></pre> | {
"question_id": 23657086,
"question_date": "2014-05-14T14:09:29.293Z",
"question_score": 206,
"tags": "yaml",
"answer_id": 33136212,
"answer_date": "2015-10-14T21:51:57.820Z",
"answer_score": 370
} |
Please answer the following Stack Overflow question:
Title: MySQL Delete all rows from table and reset ID to zero
<p>I need to delete all rows from a table but when I add a new row, I want the primary key ID, which has an auto increment, to start again from 0 respectively from 1.</p> | <p>Do not delete, use truncate:</p>
<pre><code>Truncate table XXX
</code></pre>
<blockquote>
<p>The table handler does not remember the last used AUTO_INCREMENT value, but starts counting from the beginning. This is true even for MyISAM and InnoDB, which normally do not reuse sequence values.</p>
</blockquote>
<p><a href="http://dev.mysql.com/doc/refman/5.7/en/truncate-table.html" rel="noreferrer">Source</a>.</p> | {
"question_id": 12651867,
"question_date": "2012-09-29T10:18:44.597Z",
"question_score": 206,
"tags": "mysql",
"answer_id": 12651878,
"answer_date": "2012-09-29T10:20:18.193Z",
"answer_score": 340
} |
Please answer the following Stack Overflow question:
Title: Mutex example / tutorial?
<p>I'm new to multithreading, and was trying to understand how mutexes work. Did a lot of Googling but it still left some doubts of how it works because I created my own program in which locking didn't work.</p>
<p>One absolutely non-intuitive syntax of the mutex is <code>pthread_mutex_lock( &mutex1 );</code>, where it looks like the mutex is being locked, when what I really want to lock is some other variable. Does this syntax mean that locking a mutex locks a region of code until the mutex is unlocked? Then how do threads know that the region is locked? [<em>UPDATE: Threads know that the region is locked, by</em> <a href="http://en.wikipedia.org/wiki/Memory_barrier#Multithreaded_programming_and_memory_visibility" rel="noreferrer">Memory Fencing</a> ]. And isn't such a phenomenon supposed to be called critical section? [<em>UPDATE: Critical section objects are available in Windows only, where the objects are faster than mutexes and are visible only to the thread which implements it. Otherwise, critical section just refers to the area of code protected by a mutex</em>]</p>
<p>In short, could you please help with the simplest possible mutex <strong>example program</strong> and the simplest possible <strong>explanation</strong> on the logic of how it works? I'm sure this will help <em><strong>plenty</strong></em> of other newbies.</p> | <p><em>Here goes my humble attempt to explain the concept to newbies around the world: (a <a href="http://nrecursions.blogspot.com/2014/08/mutex-tutorial-and-example.html" rel="noreferrer">color coded version</a> on my blog too)</em> </p>
<p>A lot of people run to a lone phone booth (they don't have mobile phones) to talk to their loved ones. The first person to catch the door-handle of the booth, is the one who is allowed to use the phone. He has to keep holding on to the handle of the door as long as he uses the phone, otherwise someone else will catch hold of the handle, throw him out and talk to his wife :) There's no queue system as such. When the person finishes his call, comes out of the booth and leaves the door handle, the next person to get hold of the door handle will be allowed to use the phone. </p>
<p>A <strong>thread</strong> is : Each person<br>
The <strong>mutex</strong> is : The door handle<br>
The <strong>lock</strong> is : The person's hand<br>
The <strong>resource</strong> is : The phone </p>
<p>Any thread which has to execute some lines of code which should not be modified by other threads at the same time (using the phone to talk to his wife), has to first acquire a lock on a mutex (clutching the door handle of the booth). Only then will a thread be able to run those lines of code (making the phone call). </p>
<p>Once the thread has executed that code, it should release the lock on the mutex so that another thread can acquire a lock on the mutex (other people being able to access the phone booth).</p>
<p>[<em>The concept of having a mutex is a bit absurd when considering real-world exclusive access, but in the programming world I guess there was no other way to let the other threads 'see' that a thread was already executing some lines of code. There are concepts of recursive mutexes etc, but this example was only meant to show you the basic concept. Hope the example gives you a clear picture of the concept.</em>] </p>
<p><strong>With C++11 threading:</strong></p>
<pre><code>#include <iostream>
#include <thread>
#include <mutex>
std::mutex m;//you can use std::lock_guard if you want to be exception safe
int i = 0;
void makeACallFromPhoneBooth()
{
m.lock();//man gets a hold of the phone booth door and locks it. The other men wait outside
//man happily talks to his wife from now....
std::cout << i << " Hello Wife" << std::endl;
i++;//no other thread can access variable i until m.unlock() is called
//...until now, with no interruption from other men
m.unlock();//man lets go of the door handle and unlocks the door
}
int main()
{
//This is the main crowd of people uninterested in making a phone call
//man1 leaves the crowd to go to the phone booth
std::thread man1(makeACallFromPhoneBooth);
//Although man2 appears to start second, there's a good chance he might
//reach the phone booth before man1
std::thread man2(makeACallFromPhoneBooth);
//And hey, man3 also joined the race to the booth
std::thread man3(makeACallFromPhoneBooth);
man1.join();//man1 finished his phone call and joins the crowd
man2.join();//man2 finished his phone call and joins the crowd
man3.join();//man3 finished his phone call and joins the crowd
return 0;
}
</code></pre>
<p>Compile and run using <code>g++ -std=c++0x -pthread -o thread thread.cpp;./thread</code></p>
<p>Instead of explicitly using <code>lock</code> and <code>unlock</code>, you can use brackets <a href="https://software.intel.com/en-us/node/527509" rel="noreferrer">as shown here</a>, if you are using a scoped lock <a href="https://stackoverflow.com/questions/15179553/boost-scoped-lock-vs-plain-lock-unlock">for the advantage it provides</a>. Scoped locks have a slight performance overhead though. </p> | {
"question_id": 4989451,
"question_date": "2011-02-14T06:33:46.673Z",
"question_score": 206,
"tags": "c++|c|multithreading|synchronization|mutex",
"answer_id": 5154174,
"answer_date": "2011-03-01T11:55:21.353Z",
"answer_score": 342
} |
Please answer the following Stack Overflow question:
Title: Asynchronous method call in Python?
<p>I was wondering if there's any library for asynchronous method calls in <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29" rel="noreferrer">Python</a>. It would be great if you could do something like</p>
<pre><code>@async
def longComputation():
<code>
token = longComputation()
token.registerCallback(callback_function)
# alternative, polling
while not token.finished():
doSomethingElse()
if token.finished():
result = token.result()
</code></pre>
<p>Or to call a non-async routine asynchronously</p>
<pre><code>def longComputation()
<code>
token = asynccall(longComputation())
</code></pre>
<p>It would be great to have a more refined strategy as native in the language core. Was this considered?</p> | <p>You can use the <a href="http://docs.python.org/library/multiprocessing.html#module-multiprocessing" rel="noreferrer">multiprocessing module</a> added in Python 2.6. You can use pools of processes and then get results asynchronously with: </p>
<pre><code>apply_async(func[, args[, kwds[, callback]]])
</code></pre>
<p>E.g.:</p>
<pre><code>from multiprocessing import Pool
def f(x):
return x*x
if __name__ == '__main__':
pool = Pool(processes=1) # Start a worker processes.
result = pool.apply_async(f, [10], callback) # Evaluate "f(10)" asynchronously calling callback when finished.
</code></pre>
<p>This is only one alternative. This module provides lots of facilities to achieve what you want. Also it will be really easy to make a decorator from this.</p> | {
"question_id": 1239035,
"question_date": "2009-08-06T13:55:35.350Z",
"question_score": 206,
"tags": "python|asynchronous|python-asyncio|coroutine",
"answer_id": 1239252,
"answer_date": "2009-08-06T14:28:14.697Z",
"answer_score": 151
} |
Please answer the following Stack Overflow question:
Title: Custom header to HttpClient request
<p>How do I add a custom header to a <code>HttpClient</code> request? I am using <code>PostAsJsonAsync</code> method to post the JSON. The custom header that I would need to be added is </p>
<pre><code>"X-Version: 1"
</code></pre>
<p>This is what I have done so far:</p>
<pre><code>using (var client = new HttpClient()) {
client.BaseAddress = new Uri("https://api.clickatell.com/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "xxxxxxxxxxxxxxxxxxxx");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.PostAsJsonAsync("rest/message", svm).Result;
}
</code></pre> | <pre><code>var request = new HttpRequestMessage {
RequestUri = new Uri("[your request url string]"),
Method = HttpMethod.Post,
Headers = {
{ "X-Version", "1" } // HERE IS HOW TO ADD HEADERS,
{ HttpRequestHeader.Authorization.ToString(), "[your authorization token]" },
{ HttpRequestHeader.ContentType.ToString(), "multipart/mixed" },//use this content type if you want to send more than one content type
},
Content = new MultipartContent { // Just example of request sending multipart request
new ObjectContent<[YOUR JSON OBJECT TYPE]>(
new [YOUR JSON OBJECT TYPE INSTANCE](...){...},
new JsonMediaTypeFormatter(),
"application/json"), // this will add 'Content-Type' header for the first part of request
new ByteArrayContent([BINARY DATA]) {
Headers = { // this will add headers for the second part of request
{ "Content-Type", "application/Executable" },
{ "Content-Disposition", "form-data; filename=\"test.pdf\"" },
},
},
},
};
</code></pre> | {
"question_id": 35907642,
"question_date": "2016-03-10T04:32:18.777Z",
"question_score": 206,
"tags": "c#|asp.net|http-headers|dotnet-httpclient",
"answer_id": 43780538,
"answer_date": "2017-05-04T10:37:11.547Z",
"answer_score": 83
} |
Please answer the following Stack Overflow question:
Title: How to get changes from another branch
<p>I am currently working on <code>featurex</code> branch. Our master branch is named <code>our-team</code>. Since I started working on <code>featurex</code>, more changes have been made to branch <code>our-team</code>.</p>
<p>I have done this locally to get all the latest changes from <code>our-team</code>:</p>
<pre><code>git checkout our-team
git pull
</code></pre>
<p>Before I push <code>featurex</code> for merging, I would locally like to get all changes from <code>our-team</code> branch into <code>featurex</code> so that I can ensure everything works as expected.</p>
<p>How can I do that?</p> | <p>You can use <a href="https://git-scm.com/docs/git-rebase" rel="noreferrer">rebase</a>, for instance, <code>git rebase our-team</code> when you are on your branch <code>featurex</code>.</p>
<p>It will move the start point of the branch at the end of your <code>our-team</code> branch, merging all changes in your <code>featurex</code> branch.</p> | {
"question_id": 37709298,
"question_date": "2016-06-08T17:39:01.270Z",
"question_score": 206,
"tags": "git",
"answer_id": 37709368,
"answer_date": "2016-06-08T17:42:41.620Z",
"answer_score": 106
} |
Please answer the following Stack Overflow question:
Title: Better way to check variable for null or empty string?
<p>Since PHP is a dynamic language what's the best way of checking to see if a provided field is empty? </p>
<p>I want to ensure that:</p>
<ol>
<li>null is considered an empty string</li>
<li>a white space only string is considered empty</li>
<li>that "0" is not considered empty</li>
</ol>
<p>This is what I've got so far:</p>
<pre><code>$question = trim($_POST['question']);
if ("" === "$question") {
// Handle error here
}
</code></pre>
<p>There must be a simpler way of doing this?</p> | <pre><code>// Function for basic field validation (present and neither empty nor only white space
function IsNullOrEmptyString($str){
return ($str === null || trim($str) === '');
}
</code></pre> | {
"question_id": 381265,
"question_date": "2008-12-19T15:24:37.677Z",
"question_score": 206,
"tags": "php|validation",
"answer_id": 381275,
"answer_date": "2008-12-19T15:27:32.430Z",
"answer_score": 335
} |
Please answer the following Stack Overflow question:
Title: What is the difference between a schema and a table and a database?
<p>This is probably a n00blike (or worse) question. But I've always viewed a schema as a table definition in a database. This is wrong or not entirely correct. I don't remember much from my database courses. </p> | <p><strong>schema</strong> -> floor plan</p>
<p><strong>database</strong> -> house</p>
<p><strong>table</strong> -> room</p> | {
"question_id": 298739,
"question_date": "2008-11-18T13:41:27.667Z",
"question_score": 206,
"tags": "database|schema|definition|database-table",
"answer_id": 298751,
"answer_date": "2008-11-18T13:45:13.447Z",
"answer_score": 290
} |
Please answer the following Stack Overflow question:
Title: Avoid browser popup blockers
<p>I'm developing an OAuth authentication flow purely in JavaScript and I want to show the user the "grant access" window in a popup, but it gets blocked.</p>
<p>How can I prevent pop up windows created by either <code>window.open</code> or <code>window.showModalDialog</code> from being blocked by the different browsers' pop-up blockers?</p> | <p>The general rule is that popup blockers will engage if <code>window.open</code> or similar is invoked from javascript that is not invoked by <strong>direct user action</strong>. That is, you can call <code>window.open</code> in response to a button click without getting hit by the popup blocker, but if you put the same code in a timer event it will be blocked. Depth of call chain is also a factor - some older browsers only look at the immediate caller, newer browsers can backtrack a little to see if the caller's caller was a mouse click etc. Keep it as shallow as you can to avoid the popup blockers.</p> | {
"question_id": 2587677,
"question_date": "2010-04-06T19:29:26.187Z",
"question_score": 206,
"tags": "javascript|popup|modal-dialog|popup-blocker",
"answer_id": 2587692,
"answer_date": "2010-04-06T19:32:15.640Z",
"answer_score": 329
} |
Please answer the following Stack Overflow question:
Title: VSCode single to double quote automatic replace
<p>When I execute a <code>Format Document</code> command on a Vue Component.vue file VSCode replace all single quoted string with double quoted string.</p>
<p>In my specific case this rule conflicts with electron-vue lint configuration that require singlequote.</p>
<p>I don't have prettier extensions installed (no <code>prettier.singleQuote</code> in my setting)</p>
<p>How to customize VSCode to avoid this? </p> | <p>I dont have <code>prettier</code> extension installed, but after reading the <a href="https://stackoverflow.com/questions/47091719/vs-code-auto-indent-code-formatting-changes-single-quotation-marks-to-double">possible duplicate</a> answer I've added from scratch in my User Setting (<code>UserSetting.json</code>, Ctrl+, shortcut):</p>
<pre><code>"prettier.singleQuote": true
</code></pre>
<p>A part a green warning (<code>Unknown configuration setting</code>) the single quotes are no more replaced.</p>
<p>I suspect that the prettier extension is not visible but is embedded inside the <a href="https://marketplace.visualstudio.com/items?itemName=octref.vetur" rel="noreferrer">Vetur</a> extension.</p> | {
"question_id": 48864985,
"question_date": "2018-02-19T11:16:25.793Z",
"question_score": 206,
"tags": "visual-studio-code|vscode-settings",
"answer_id": 48866406,
"answer_date": "2018-02-19T12:37:13.033Z",
"answer_score": 216
} |
Please answer the following Stack Overflow question:
Title: What is the difference between XSD and WSDL?
<p>What is the difference between an <code>XML Schema</code> and <code>WSDL</code>?</p>
<p>The difference I noticed is that <code>WSDL</code> contains <code>XSD</code> and in <code>WSDL</code> we can declare operations, but not in <code>XSD</code>. Is that correct?</p> | <p>XSD defines a schema which is a definition of how an XML document can be structured. You can use it to check that a given XML document is valid and follows the rules you've laid out in the schema.</p>
<p>WSDL is a XML document that describes a web service. It shows which operations are available and how data should be structured to send to those operations.</p>
<p>WSDL documents have an associated XSD that show what is valid to put in a WSDL document.</p> | {
"question_id": 1952015,
"question_date": "2009-12-23T10:36:05.783Z",
"question_score": 206,
"tags": "web-services|wsdl|xsd",
"answer_id": 1952034,
"answer_date": "2009-12-23T10:41:13.183Z",
"answer_score": 194
} |
Please answer the following Stack Overflow question:
Title: Is it possible to specify the schema when connecting to postgres with JDBC?
<p>Is it possible? Can i specify it on the connection URL? How to do that?</p> | <p>I know this was answered already, but I just ran into the same issue trying to specify the schema to use for the liquibase command line. </p>
<p><strong>Update</strong>
As of JDBC v<a href="https://jdbc.postgresql.org/documentation/94/connect.html#connection-parameters" rel="noreferrer">9.4</a> you can specify the url with the new currentSchema parameter like so:</p>
<pre class="lang-none prettyprint-override"><code>jdbc:postgresql://localhost:5432/mydatabase?currentSchema=myschema
</code></pre>
<p>Appears based on an earlier patch:</p>
<p><a href="http://web.archive.org/web/20141025044151/http://postgresql.1045698.n5.nabble.com/Patch-to-allow-setting-schema-search-path-in-the-connectionURL-td2174512.html" rel="noreferrer">http://web.archive.org/web/20141025044151/http://postgresql.1045698.n5.nabble.com/Patch-to-allow-setting-schema-search-path-in-the-connectionURL-td2174512.html</a></p>
<p>Which proposed url's like so:
</p>
<pre><code>jdbc:postgresql://localhost:5432/mydatabase?searchpath=myschema
</code></pre> | {
"question_id": 4168689,
"question_date": "2010-11-12T20:15:23.713Z",
"question_score": 206,
"tags": "java|database|postgresql|jdbc|database-schema",
"answer_id": 4820666,
"answer_date": "2011-01-27T19:07:50.690Z",
"answer_score": 279
} |
Please answer the following Stack Overflow question:
Title: Dynamically changing font size of UILabel
<p>I currently have a <code>UILabel</code>:</p>
<pre><code>factLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 100, 280, 100)];
factLabel.text = @"some text some text some text some text";
factLabel.backgroundColor = [UIColor clearColor];
factLabel.lineBreakMode = UILineBreakModeWordWrap;
factLabel.numberOfLines = 10;
[self.view addSubview:factLabel];
</code></pre>
<p>Throughout the life of my iOS application, <code>factLabel</code> gets a bunch of different values. Some with multiple sentences, others with just 5 or 6 words. </p>
<p>How can I set up the <code>UILabel</code> so that the font size changes so that the text always fits in the bounds I defined?</p> | <p><em>Single line:</em></p>
<pre><code>factLabel.numberOfLines = 1;
factLabel.minimumFontSize = 8;
factLabel.adjustsFontSizeToFitWidth = YES;
</code></pre>
<p>The above code will adjust your text's font size down to (for example) <code>8</code> trying to fit your text within the label.
<code>numberOfLines = 1</code> is mandatory.</p>
<p><em>Multiple lines:</em></p>
<p>For <code>numberOfLines > 1</code> there is a method to figure out the size of final text through <a href="https://developer.apple.com/documentation/foundation/nsstring?language=objc" rel="noreferrer">NSString's sizeWithFont:... UIKit addition</a> methods, for example:</p>
<pre><code>CGSize lLabelSize = [yourText sizeWithFont:factLabel.font
forWidth:factLabel.frame.size.width
lineBreakMode:factLabel.lineBreakMode];
</code></pre>
<p>After that you can just resize your label using resulting <code>lLabelSize</code>, for example (assuming that you will change only label's height):</p>
<pre><code>factLabel.frame = CGRectMake(factLabel.frame.origin.x, factLabel.frame.origin.y, factLabel.frame.size.width, lLabelSize.height);
</code></pre>
<p><strong>iOS6</strong></p>
<p><em>Single line:</em></p>
<p>Starting with iOS6, <code>minimumFontSize</code> has been deprecated. The line</p>
<pre><code>factLabel.minimumFontSize = 8.;
</code></pre>
<p>can be changed to:</p>
<pre><code>factLabel.minimumScaleFactor = 8./factLabel.font.pointSize;
</code></pre>
<p><strong>iOS7</strong></p>
<p><em>Multiple lines:</em></p>
<p>Starting with iOS7, <code>sizeWithFont</code> becomes deprecated.
Multiline case is reduced to:</p>
<pre><code>factLabel.numberOfLines = 0;
factLabel.lineBreakMode = NSLineBreakByWordWrapping;
CGSize maximumLabelSize = CGSizeMake(factLabel.frame.size.width, CGFLOAT_MAX);
CGSize expectSize = [factLabel sizeThatFits:maximumLabelSize];
factLabel.frame = CGRectMake(factLabel.frame.origin.x, factLabel.frame.origin.y, expectSize.width, expectSize.height);
</code></pre>
<p><strong>iOS 13 (Swift 5):</strong> </p>
<pre><code>label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.5
</code></pre> | {
"question_id": 4865458,
"question_date": "2011-02-01T16:53:13.807Z",
"question_score": 206,
"tags": "ios|objective-c|fonts|uilabel",
"answer_id": 4865577,
"answer_date": "2011-02-01T17:03:46.493Z",
"answer_score": 399
} |
Please answer the following Stack Overflow question:
Title: In Git, how do I figure out what my current revision is?
<p>I just want to know what my current version number is.</p> | <p>What do you mean by "version number"? It is quite common to tag a commit with a version number and then use</p>
<pre><code>$ git describe --tags
</code></pre>
<p>to identify the current HEAD w.r.t. any tags. If you mean you want to know the hash of the current HEAD, you probably want:</p>
<pre><code>$ git rev-parse HEAD
</code></pre>
<p>or for the short revision hash:</p>
<pre><code>$ git rev-parse --short HEAD
</code></pre>
<p>It is often sufficient to do:</p>
<pre><code>$ cat .git/refs/heads/${branch-main}
</code></pre>
<p>but this is not reliable as the ref may be packed.</p> | {
"question_id": 5724513,
"question_date": "2011-04-20T01:10:52.090Z",
"question_score": 206,
"tags": "git",
"answer_id": 5724755,
"answer_date": "2011-04-20T01:59:40.377Z",
"answer_score": 281
} |
Please answer the following Stack Overflow question:
Title: What is the canonical way to trim a string in Ruby without creating a new string?
<p>This is what I have now - which looks too verbose for the work it is doing.</p>
<pre><code>@title = tokens[Title].strip! || tokens[Title] if !tokens[Title].nil?
</code></pre>
<p>Assume tokens is a array obtained by splitting a CSV line.
now the functions like strip! chomp! et. all return nil if the string was not modified</p>
<pre><code>"abc".strip! # => nil
" abc ".strip! # => "abc"
</code></pre>
<p>What is the Ruby way to say trim it if it contains extra leading or trailing spaces without creating copies?</p>
<p>Gets uglier if I want to do <code>tokens[Title].chomp!.strip!</code></p> | <p>I guess what you want is:</p>
<pre><code>@title = tokens[Title]
@title.strip!
</code></pre>
<p>The <a href="http://ruby-doc.org/core-2.1.5/String.html#method-i-strip" rel="noreferrer"><code>#strip!</code></a> method will return <code>nil</code> if it didn't strip anything, and the variable itself if it was stripped.</p>
<p>According to Ruby standards, a method suffixed with an exclamation mark changes the variable in place.</p>
<p>Hope this helps.</p>
<p><strong>Update:</strong> This is output from <code>irb</code> to demonstrate:</p>
<pre><code>>> @title = "abc"
=> "abc"
>> @title.strip!
=> nil
>> @title
=> "abc"
>> @title = " abc "
=> " abc "
>> @title.strip!
=> "abc"
>> @title
=> "abc"
</code></pre> | {
"question_id": 1000688,
"question_date": "2009-06-16T10:30:34.347Z",
"question_score": 206,
"tags": "ruby|string",
"answer_id": 1000896,
"answer_date": "2009-06-16T11:29:51.017Z",
"answer_score": 303
} |
Please answer the following Stack Overflow question:
Title: Add unique constraint to combination of two columns
<p>I have a table and, somehow, the same person got into my <code>Person</code> table twice. Right now, the primary key is just an autonumber but there are two other fields that exist that I want to force to be unique.</p>
<p>For example, the fields are:</p>
<pre><code>ID
Name
Active
PersonNumber
</code></pre>
<p><strong>I only want 1 record with a unique PersonNumber and Active = 1.</strong><br>
(So the combination of the two fields needs to be unique)</p>
<p>What is the best way on an existing table in SQL server I can make it so if anyone else does an insert with the same value as an existing value, it fails so I don't have to worry about this in my application code.</p> | <p>Once you have removed your duplicate(s):</p>
<pre><code>ALTER TABLE dbo.yourtablename
ADD CONSTRAINT uq_yourtablename UNIQUE(column1, column2);
</code></pre>
<p>or</p>
<pre><code>CREATE UNIQUE INDEX uq_yourtablename
ON dbo.yourtablename(column1, column2);
</code></pre>
<p>Of course, it can often be better to check for this violation first, before just letting SQL Server try to insert the row and returning an exception (exceptions are expensive).</p>
<ul>
<li><p><a href="http://www.sqlperformance.com/2012/08/t-sql-queries/error-handling" rel="noreferrer">Performance impact of different error handling techniques</a></p>
</li>
<li><p><a href="http://www.mssqltips.com/sqlservertip/2632/checking-for-potential-constraint-violations-before-entering-sql-server-try-and-catch-logic/?utm_source=AaronBertrand" rel="noreferrer">Checking for potential constraint violations before entering TRY/CATCH</a></p>
</li>
</ul>
<p>If you want to prevent exceptions from bubbling up to the application, without making changes to the application, you can use an <code>INSTEAD OF</code> trigger:</p>
<pre><code>CREATE TRIGGER dbo.BlockDuplicatesYourTable
ON dbo.YourTable
INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON;
IF NOT EXISTS (SELECT 1 FROM inserted AS i
INNER JOIN dbo.YourTable AS t
ON i.column1 = t.column1
AND i.column2 = t.column2
)
BEGIN
INSERT dbo.YourTable(column1, column2, ...)
SELECT column1, column2, ... FROM inserted;
END
ELSE
BEGIN
PRINT 'Did nothing.';
END
END
GO
</code></pre>
<p>But if you don't tell the user they didn't perform the insert, they're going to wonder why the data isn't there and no exception was reported.</p>
<hr />
<p><strong>EDIT</strong> here is an example that does exactly what you're asking for, even using the same names as your question, and proves it. You should try it out before assuming the above ideas only treat one column or the other as opposed to the combination...</p>
<pre><code>USE tempdb;
GO
CREATE TABLE dbo.Person
(
ID INT IDENTITY(1,1) PRIMARY KEY,
Name NVARCHAR(32),
Active BIT,
PersonNumber INT
);
GO
ALTER TABLE dbo.Person
ADD CONSTRAINT uq_Person UNIQUE(PersonNumber, Active);
GO
-- succeeds:
INSERT dbo.Person(Name, Active, PersonNumber)
VALUES(N'foo', 1, 22);
GO
-- succeeds:
INSERT dbo.Person(Name, Active, PersonNumber)
VALUES(N'foo', 0, 22);
GO
-- fails:
INSERT dbo.Person(Name, Active, PersonNumber)
VALUES(N'foo', 1, 22);
GO
</code></pre>
<p>Data in the table after all of this:</p>
<pre><code>ID Name Active PersonNumber
---- ------ ------ ------------
1 foo 1 22
2 foo 0 22
</code></pre>
<p>Error message on the last insert:</p>
<blockquote>
<p>Msg 2627, Level 14, State 1, Line 3
Violation of UNIQUE KEY constraint 'uq_Person'. Cannot insert duplicate key in object 'dbo.Person'.
The statement has been terminated.</p>
</blockquote>
<p>Also I blogged more recently about a solution to applying a unique constraint to two columns <em>in either order</em>:</p>
<ul>
<li><a href="https://www.mssqltips.com/sqlservertip/6737/sql-unique-constraint-where-order-does-not-matter/?utm_source=AaronBertrand" rel="noreferrer">Enforce a Unique Constraint Where Order Does Not Matter</a></li>
</ul> | {
"question_id": 15800250,
"question_date": "2013-04-03T23:52:48.780Z",
"question_score": 206,
"tags": "sql|sql-server",
"answer_id": 15800279,
"answer_date": "2013-04-03T23:56:18.293Z",
"answer_score": 304
} |
Please answer the following Stack Overflow question:
Title: How do I get the information from a meta tag with JavaScript?
<p>The information I need is in a meta tag. How can I access the <code>"content"</code> data of the meta tag when <code>property="video"</code>?</p>
<p><strong>HTML:</strong></p>
<pre><code><meta property="video" content="http://video.com/video33353.mp4" />
</code></pre> | <p>You can use this:</p>
<pre><code>function getMeta(metaName) {
const metas = document.getElementsByTagName('meta');
for (let i = 0; i < metas.length; i++) {
if (metas[i].getAttribute('name') === metaName) {
return metas[i].getAttribute('content');
}
}
return '';
}
console.log(getMeta('video'));
</code></pre> | {
"question_id": 7524585,
"question_date": "2011-09-23T05:20:53.633Z",
"question_score": 206,
"tags": "javascript|html|greasemonkey|meta-tags",
"answer_id": 7524621,
"answer_date": "2011-09-23T05:25:15.153Z",
"answer_score": 150
} |
Please answer the following Stack Overflow question:
Title: html5 - canvas element - Multiple layers
<p>Without any extension library, is it possible to have multiple layers in the same canvas element?</p>
<p>So if I do a clearRect on the top layer, it will not erase the bottom one?</p>
<p>Thanks.</p> | <p>No, however, you could layer multiple <code><canvas></code> elements on top of each other and accomplish something similar.</p>
<pre><code><div style="position: relative;">
<canvas id="layer1" width="100" height="100"
style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
<canvas id="layer2" width="100" height="100"
style="position: absolute; left: 0; top: 0; z-index: 1;"></canvas>
</div>
</code></pre>
<p>Draw your first layer on the <code>layer1</code> canvas, and the second layer on the <code>layer2</code> canvas. Then when you <code>clearRect</code> on the top layer, whatever's on the lower canvas will show through.</p> | {
"question_id": 3008635,
"question_date": "2010-06-09T18:17:45.853Z",
"question_score": 206,
"tags": "html|canvas|layer",
"answer_id": 3008863,
"answer_date": "2010-06-09T18:48:17.540Z",
"answer_score": 294
} |
Please answer the following Stack Overflow question:
Title: Rails: How do I create a default value for attributes in Rails activerecord's model?
<p>I want to create a default value for an attribute by defining it in ActiveRecord. By default everytime the record is created, I want to have a default value for attribute <code>:status</code>. I tried to do this:</p>
<pre><code>class Task < ActiveRecord::Base
def status=(status)
status = 'P'
write_attribute(:status, status)
end
end
</code></pre>
<p>But upon creation I still retrieve this error from the database:</p>
<pre><code>ActiveRecord::StatementInvalid: Mysql::Error: Column 'status' cannot be null
</code></pre>
<p>Therefore I presume the value was not applied to the attribute. </p>
<p>What would be the elegant way to do this in Rails?</p>
<p>Many thanks.</p> | <p>You can set a default option for the column in the migration</p>
<pre><code>....
add_column :status, :string, :default => "P"
....
</code></pre>
<p>OR</p>
<p>You can use a callback, <code>before_save</code></p>
<pre><code>class Task < ActiveRecord::Base
before_save :default_values
def default_values
self.status ||= 'P' # note self.status = 'P' if self.status.nil? might better for boolean fields (per @frontendbeauty)
end
end
</code></pre> | {
"question_id": 1550688,
"question_date": "2009-10-11T13:24:11.957Z",
"question_score": 206,
"tags": "ruby-on-rails|activerecord",
"answer_id": 1551430,
"answer_date": "2009-10-11T18:48:42.257Z",
"answer_score": 306
} |
Please answer the following Stack Overflow question:
Title: Proxy with express.js
<p>To avoid same-domain AJAX issues, I want my node.js web server to forward all requests from URL <code>/api/BLABLA</code> to another server, for example <code>other_domain.com:3000/BLABLA</code>, and return to user the same thing that this remote server returned, transparently. </p>
<p>All other URLs (beside <code>/api/*</code>) are to be served directly, no proxying.</p>
<p>How do I achieve this with node.js + express.js? Can you give a simple code example?</p>
<p>(both the web server and the remote <code>3000</code> server are under my control, both running node.js with express.js)</p>
<hr>
<p>So far I found this <a href="https://github.com/http-party/node-http-proxy" rel="noreferrer">https://github.com/http-party/node-http-proxy</a> , but reading the documentation there didn't make me any wiser. I ended up with</p>
<pre><code>var proxy = new httpProxy.RoutingProxy();
app.all("/api/*", function(req, res) {
console.log("old request url " + req.url)
req.url = '/' + req.url.split('/').slice(2).join('/'); // remove the '/api' part
console.log("new request url " + req.url)
proxy.proxyRequest(req, res, {
host: "other_domain.com",
port: 3000
});
});
</code></pre>
<p>but nothing is returned to the original web server (or to the end user), so no luck.</p> | <p>You want to use <a href="http://nodejs.org/api/http.html#http_http_request_options_callback" rel="noreferrer"><code>http.request</code></a> to create a similar request to the remote API and return its response.</p>
<p>Something like this:</p>
<pre class="lang-js prettyprint-override"><code>const http = require('http');
// or use import http from 'http';
/* your app config here */
app.post('/api/BLABLA', (oreq, ores) => {
const options = {
// host to forward to
host: 'www.google.com',
// port to forward to
port: 80,
// path to forward to
path: '/api/BLABLA',
// request method
method: 'POST',
// headers to send
headers: oreq.headers,
};
const creq = http
.request(options, pres => {
// set encoding
pres.setEncoding('utf8');
// set http status code based on proxied response
ores.writeHead(pres.statusCode);
// wait for data
pres.on('data', chunk => {
ores.write(chunk);
});
pres.on('close', () => {
// closed, let's end client request as well
ores.end();
});
pres.on('end', () => {
// finished, let's finish client request as well
ores.end();
});
})
.on('error', e => {
// we got an error
console.log(e.message);
try {
// attempt to set error message and http status
ores.writeHead(500);
ores.write(e.message);
} catch (e) {
// ignore
}
ores.end();
});
creq.end();
});
</code></pre>
<p><em>Notice: I haven't really tried the above, so it might contain parse errors hopefully this will give you a hint as to how to get it to work.</em></p> | {
"question_id": 10435407,
"question_date": "2012-05-03T16:20:44.890Z",
"question_score": 206,
"tags": "node.js|proxy|express|reverse-proxy",
"answer_id": 10435819,
"answer_date": "2012-05-03T16:47:48.633Z",
"answer_score": 66
} |
Please answer the following Stack Overflow question:
Title: What is the difference between printf() and puts() in C?
<p>I know you can print with <code>printf()</code> and <code>puts()</code>. I can also see that <code>printf()</code> allows you to interpolate variables and do formatting.</p>
<p>Is <code>puts()</code> merely a primitive version of <code>printf()</code>. Should it be used for every possible <code>printf()</code> without string interpolation?</p> | <p><code>puts</code> is simpler than <code>printf</code> but be aware that the former automatically appends a newline. If that's not what you want, you can <code>fputs</code> your string to stdout or use <code>printf</code>.</p> | {
"question_id": 2454474,
"question_date": "2010-03-16T13:03:28.590Z",
"question_score": 206,
"tags": "c|string|output|printf|puts",
"answer_id": 2454491,
"answer_date": "2010-03-16T13:06:06.430Z",
"answer_score": 166
} |
Please answer the following Stack Overflow question:
Title: How can I use multiple refs for an array of elements with hooks?
<p>As far as I understood I can use refs for a single element like this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const { useRef, useState, useEffect } = React;
const App = () => {
const elRef = useRef();
const [elWidth, setElWidth] = useState();
useEffect(() => {
setElWidth(elRef.current.offsetWidth);
}, []);
return (
<div>
<div ref={elRef} style={{ width: "100px" }}>
Width is: {elWidth}
</div>
</div>
);
};
ReactDOM.render(
<App />,
document.getElementById("root")
);</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<div id="root"></div></code></pre>
</div>
</div>
</p>
<p>How can I implement this for an array of elements? Obviously not like that: (I knew it even I did not try it:)</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const { useRef, useState, useEffect } = React;
const App = () => {
const elRef = useRef();
const [elWidth, setElWidth] = useState();
useEffect(() => {
setElWidth(elRef.current.offsetWidth);
}, []);
return (
<div>
{[1, 2, 3].map(el => (
<div ref={elRef} style={{ width: `${el * 100}px` }}>
Width is: {elWidth}
</div>
))}
</div>
);
};
ReactDOM.render(
<App />,
document.getElementById("root")
);</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<div id="root"></div></code></pre>
</div>
</div>
</p>
<p>I have seen <a href="https://github.com/facebook/react/issues/14072" rel="noreferrer">this</a> and hence <a href="https://github.com/facebook/react/issues/14490#issuecomment-454973512" rel="noreferrer">this</a>. But, I'm still confused about how to implement that suggestion for this simple case. </p> | <p>A ref is initially just <code>{ current: null }</code> object. <code>useRef</code> keeps the reference to this object between component renders. <code>current</code> value is primarily intended for component refs but can hold anything.</p>
<p>There should be an array of refs at some point. In case the array length may vary between renders, an array should scale accordingly:</p>
<pre class="lang-js prettyprint-override"><code>const arrLength = arr.length;
const [elRefs, setElRefs] = React.useState([]);
React.useEffect(() => {
// add or remove refs
setElRefs((elRefs) =>
Array(arrLength)
.fill()
.map((_, i) => elRefs[i] || createRef()),
);
}, [arrLength]);
return (
<div>
{arr.map((el, i) => (
<div ref={elRefs[i]} style={...}>
...
</div>
))}
</div>
);
</code></pre>
<p>This piece of code can be optimized by unwrapping <code>useEffect</code> and replacing <code>useState</code> with <code>useRef</code> but it should be noted that doing side effects in render function is generally considered a bad practice:</p>
<pre class="lang-js prettyprint-override"><code>const arrLength = arr.length;
const elRefs = React.useRef([]);
if (elRefs.current.length !== arrLength) {
// add or remove refs
elRefs.current = Array(arrLength)
.fill()
.map((_, i) => elRefs.current[i] || createRef());
}
return (
<div>
{arr.map((el, i) => (
<div ref={elRefs.current[i]} style={...}>
...
</div>
))}
</div>
);
</code></pre> | {
"question_id": 54633690,
"question_date": "2019-02-11T15:18:46.603Z",
"question_score": 206,
"tags": "javascript|reactjs|react-hooks",
"answer_id": 54633947,
"answer_date": "2019-02-11T15:32:27.603Z",
"answer_score": 147
} |
Please answer the following Stack Overflow question:
Title: How to refer environment variable in POM.xml?
<p>I am using maven as build tool. I have set an environment variable called <code>env</code>. How can I get access to this environment variable's value in the <code>pom.xml</code> file?</p> | <p>Check out the <a href="http://books.sonatype.com/mvnref-book/reference/resource-filtering-sect-properties.html" rel="noreferrer">Maven Properties Guide</a>...</p>
<p>As Seshagiri pointed out in the comments, <code>${env.VARIABLE_NAME}</code> will do what you want.</p>
<p>I will add a word of warning and say that a <code>pom.xml</code> should completely describe your project so please use environment variables judiciously. If you make your builds dependent on your environment, they are harder to reproduce</p> | {
"question_id": 10463077,
"question_date": "2012-05-05T15:05:27.573Z",
"question_score": 206,
"tags": "java|maven|environment-variables|pom.xml",
"answer_id": 10463133,
"answer_date": "2012-05-05T15:11:32.433Z",
"answer_score": 249
} |
Please answer the following Stack Overflow question:
Title: event.preventDefault() function not working in IE
<p>Following is my JavaScript (mootools) code:</p>
<pre class="lang-js prettyprint-override"><code>$('orderNowForm').addEvent('submit', function (event) {
event.preventDefault();
allFilled = false;
$$(".required").each(function (inp) {
if (inp.getValue() != '') {
allFilled = true;
}
});
if (!allFilled) {
$$(".errormsg").setStyle('display', '');
return;
} else {
$$('.defaultText').each(function (input) {
if (input.getValue() == input.getAttribute('title')) {
input.setAttribute('value', '');
}
});
}
this.send({
onSuccess: function () {
$('page_1_table').setStyle('display', 'none');
$('page_2_table').setStyle('display', 'none');
$('page_3_table').setStyle('display', '');
}
});
});
</code></pre>
<p>In all browsers except IE, this works fine. But in IE, this causes an error. I have IE8 so while using its JavaScript debugger, I found out that the <code>event</code> object does not have a <code>preventDefault</code> method which is causing the error and so the form is getting submitted. The method is supported in case of Firefox (which I found out using Firebug).</p>
<p>Any Help?</p> | <p>in IE, you can use</p>
<pre><code>event.returnValue = false;
</code></pre>
<p>to achieve the same result.</p>
<p>And in order not to get an error, you can test for the existence of preventDefault:</p>
<pre><code>if(event.preventDefault) event.preventDefault();
</code></pre>
<p>You can combine the two with:</p>
<pre><code>event.preventDefault ? event.preventDefault() : (event.returnValue = false);
</code></pre> | {
"question_id": 1000597,
"question_date": "2009-06-16T10:09:03.923Z",
"question_score": 206,
"tags": "javascript|internet-explorer|events|mootools|preventdefault",
"answer_id": 1000606,
"answer_date": "2009-06-16T10:10:20.707Z",
"answer_score": 480
} |
Please answer the following Stack Overflow question:
Title: Where to install Android SDK on Mac OS X?
<p>Where should the Android SDK be installed on Mac OS X?</p> | <p>In <a href="https://brew.sh/" rel="nofollow noreferrer">homebrew</a> the <code>android-sdk</code> has migrated from <code>homebrew/core</code> to <code>homebrew/cask</code>.</p>
<pre><code>brew tap homebrew/cask
</code></pre>
<p>and install <code>android-sdk</code> using</p>
<pre><code>brew install android-sdk --cask
</code></pre>
<p>You will have to add the <code>ANDROID_HOME</code> to profile (.zshrc or .bashrc)</p>
<pre><code>export ANDROID_HOME=/usr/local/share/android-sdk
</code></pre>
<p>If you prefer otherwise, copy the package to</p>
<pre><code>~/opt/local/android-sdk-mac
</code></pre> | {
"question_id": 2677431,
"question_date": "2010-04-20T17:52:28.453Z",
"question_score": 206,
"tags": "android|configuration|macos",
"answer_id": 43797501,
"answer_date": "2017-05-05T05:56:45.337Z",
"answer_score": 91
} |
Please answer the following Stack Overflow question:
Title: Pick a random value from an enum?
<p>If I have an enum like this:</p>
<pre><code>public enum Letter {
A,
B,
C,
//...
}
</code></pre>
<p>What is the best way to pick one randomly? It doesn't need to be production quality bulletproof, but a fairly even distribution would be nice.</p>
<p>I could do something like this</p>
<pre><code>private Letter randomLetter() {
int pick = new Random().nextInt(Letter.values().length);
return Letter.values()[pick];
}
</code></pre>
<p>But is there a better way? I feel like this is something that's been solved before.</p> | <p>The only thing I would suggest is caching the result of <code>values()</code> because each call copies an array. Also, don't create a <code>Random</code> every time. Keep one. Other than that what you're doing is fine. So:</p>
<pre><code>public enum Letter {
A,
B,
C,
//...
private static final List<Letter> VALUES =
Collections.unmodifiableList(Arrays.asList(values()));
private static final int SIZE = VALUES.size();
private static final Random RANDOM = new Random();
public static Letter randomLetter() {
return VALUES.get(RANDOM.nextInt(SIZE));
}
}
</code></pre> | {
"question_id": 1972392,
"question_date": "2009-12-29T00:54:29.203Z",
"question_score": 206,
"tags": "java|random|enums",
"answer_id": 1972399,
"answer_date": "2009-12-29T00:56:55.063Z",
"answer_score": 175
} |
Please answer the following Stack Overflow question:
Title: How do I create a datetime in Python from milliseconds?
<p>How do I create a datetime in Python from milliseconds? I can create a similar <code>Date</code> object in Java by <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Date.html" rel="noreferrer"><code>java.util.Date(milliseconds)</code></a>.</p>
<blockquote>
<p>Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.</p>
</blockquote> | <p>Just convert it to timestamp</p>
<pre><code>datetime.datetime.fromtimestamp(ms/1000.0)
</code></pre> | {
"question_id": 748491,
"question_date": "2009-04-14T17:01:03.047Z",
"question_score": 206,
"tags": "python|datetime",
"answer_id": 748534,
"answer_date": "2009-04-14T17:12:51.707Z",
"answer_score": 331
} |
Please answer the following Stack Overflow question:
Title: Path to MSBuild
<p>How can I programatically get the path to MSBuild from a machine where my .exe is running?</p>
<p>I can get the .NET version from the Environment but is there a way of getting the correct folder for a .NET version?</p> | <p>Poking around the registry, it looks like</p>
<pre><code>HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\2.0
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\3.5
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\4.0
</code></pre>
<p>may be what you're after; fire up regedit.exe and have a look.</p>
<h3>Query via command line (per <a href="https://stackoverflow.com/a/15446618/712526">Nikolay Botev</a>)</h3>
<pre><code>reg.exe query "HKLM\SOFTWARE\Microsoft\MSBuild\ToolsVersions\4.0" /v MSBuildToolsPath
</code></pre>
<h3>Query via PowerShell (per <a href="https://stackoverflow.com/a/31404176/712526">MovGP0</a>)</h3>
<pre><code>dir HKLM:\SOFTWARE\Microsoft\MSBuild\ToolsVersions\
</code></pre> | {
"question_id": 328017,
"question_date": "2008-11-29T21:12:51.857Z",
"question_score": 206,
"tags": ".net|msbuild",
"answer_id": 328133,
"answer_date": "2008-11-29T22:59:05.590Z",
"answer_score": 152
} |
Please answer the following Stack Overflow question:
Title: Export multiple classes in ES6 modules
<p>I'm trying to create a module that exports multiple ES6 classes. Let's say I have the following directory structure:</p>
<pre><code>my/
└── module/
├── Foo.js
├── Bar.js
└── index.js
</code></pre>
<p><code>Foo.js</code> and <code>Bar.js</code> each export a default ES6 class:</p>
<pre><code>// Foo.js
export default class Foo {
// class definition
}
// Bar.js
export default class Bar {
// class definition
}
</code></pre>
<p>I currently have my <code>index.js</code> set up like this:</p>
<pre><code>import Foo from './Foo';
import Bar from './Bar';
export default {
Foo,
Bar,
}
</code></pre>
<p>However, I am unable to import. I want to be able to do this, but the classes aren't found:</p>
<pre><code>import {Foo, Bar} from 'my/module';
</code></pre>
<p>What is the correct way to export multiple classes in an ES6 module?</p> | <p>Try this in your code:</p>
<pre><code>import Foo from './Foo';
import Bar from './Bar';
// without default
export {
Foo,
Bar,
}
</code></pre>
<p>Btw, you can also do it this way:</p>
<pre><code>// bundle.js
export { default as Foo } from './Foo'
export { default as Bar } from './Bar'
export { default } from './Baz'
// and import somewhere..
import Baz, { Foo, Bar } from './bundle'
</code></pre>
<p>Using <code>export</code> </p>
<pre><code>export const MyFunction = () => {}
export const MyFunction2 = () => {}
const Var = 1;
const Var2 = 2;
export {
Var,
Var2,
}
// Then import it this way
import {
MyFunction,
MyFunction2,
Var,
Var2,
} from './foo-bar-baz';
</code></pre>
<p>The difference with <code>export default</code> is that you can export something, and apply the name where you import it:</p>
<pre><code>// export default
export default class UserClass {
constructor() {}
};
// import it
import User from './user'
</code></pre> | {
"question_id": 38340500,
"question_date": "2016-07-12T23:43:21.513Z",
"question_score": 206,
"tags": "javascript|module|export|ecmascript-6|babeljs",
"answer_id": 38340590,
"answer_date": "2016-07-12T23:55:25.920Z",
"answer_score": 356
} |
Please answer the following Stack Overflow question:
Title: How do you see recent SVN log entries?
<p>Typing <code>svn log</code> spits out an incredibly long, useless list on a command line. I have no idea why that is the default. If I wanted to read (or even could read) 300 entries on the terminal, I wouldn't mind typing <code>svn log --full</code> or something similar. </p>
<p>Perhaps the SVN guys are thinking I wanted to feed that output to another program. However, if that is the case, it would make more sense to have the more verbose call for the program - not the terminal user.</p>
<p>Anyway, how do I see just some recent activity like the last 5 or 10 entries to see what changed?</p> | <p><code>limit</code> option, e.g.:</p>
<pre><code>svn log --limit 4
svn log -l 4
</code></pre>
<p>Only the last 4 entries</p> | {
"question_id": 4881129,
"question_date": "2011-02-02T23:23:04.593Z",
"question_score": 206,
"tags": "svn",
"answer_id": 4881167,
"answer_date": "2011-02-02T23:30:44.500Z",
"answer_score": 274
} |
Please answer the following Stack Overflow question:
Title: What is the difference between synchronous and asynchronous programming (in node.js)
<p>I've been reading <a href="http://www.nodebeginner.org/" rel="noreferrer">nodebeginner</a>
And I came across the following two pieces of code.</p>
<p>The first one:</p>
<pre><code> var result = database.query("SELECT * FROM hugetable");
console.log("Hello World");
</code></pre>
<p>The second one:</p>
<pre><code> database.query("SELECT * FROM hugetable", function(rows) {
var result = rows;
});
console.log("Hello World");
</code></pre>
<p>I get what they're supposed to do, they query the database to retrieve the answer to the query. And then <code>console.log('Hello world')</code>.</p>
<p>The first one is supposedly synchronous code.
And the second one is asynchronous code.</p>
<p>The difference between the two pieces is very vague to me. What would the output be?</p>
<p>Googling on asynchronous programming didn't help me either. </p> | <p>The difference is that in the <strong>first example</strong>, the program will block in the first line. The next line (<code>console.log</code>) will have to wait.</p>
<p>In the <strong>second example</strong>, the <code>console.log</code> will be executed WHILE the query is being processed. That is, the query will be processed in the background, while your program is doing other things, and once the query data is ready, you will do whatever you want with it.</p>
<p>So, in a nutshell: The first example will block, while the second won't.</p>
<p>The output of the following two examples:</p>
<pre><code>// Example 1 - Synchronous (blocks)
var result = database.query("SELECT * FROM hugetable");
console.log("Query finished");
console.log("Next line");
// Example 2 - Asynchronous (doesn't block)
database.query("SELECT * FROM hugetable", function(result) {
console.log("Query finished");
});
console.log("Next line");
</code></pre>
<p>Would be:</p>
<ol>
<li><code>Query finished</code><br>
<code>Next line</code></li>
<li><code>Next line</code><br>
<code>Query finished</code></li>
</ol>
<p><em>Note</em><br>
While Node itself is <strong>single threaded</strong>, there are some task that can run in parallel. For example, File System operations occur in a different process. </p>
<p>That's why Node can do async operations: one thread is doing file system operations, while the main Node thread keeps executing your javascript code. In an event-driven server like Node, the file system thread notifies the main Node thread of certain events such as completion, failure, or progress, along with any data associated with that event (such as the result of a database query or an error message) and the main Node thread decides what to do with that data. </p>
<p>You can read more about this here: <a href="https://stackoverflow.com/a/14797359/920173">How the single threaded non blocking IO model works in Node.js</a></p> | {
"question_id": 16336367,
"question_date": "2013-05-02T11:00:47.053Z",
"question_score": 206,
"tags": "javascript|node.js|asynchronous|synchronous",
"answer_id": 16336405,
"answer_date": "2013-05-02T11:03:00.373Z",
"answer_score": 241
} |
Please answer the following Stack Overflow question:
Title: What's the difference between lists enclosed by square brackets and parentheses in Python?
<pre><code>>>> x=[1,2]
>>> x[1]
2
>>> x=(1,2)
>>> x[1]
2
</code></pre>
<p>Are they both valid? Is one preferred for some reason?</p> | <p>Square brackets are <a href="http://docs.python.org/tutorial/datastructures.html#more-on-lists" rel="noreferrer">lists</a> while parentheses are <a href="https://docs.python.org/tutorial/datastructures.html#tuples-and-sequences" rel="noreferrer">tuples</a>.</p>
<p>A list is mutable, meaning you can change its contents:</p>
<pre><code>>>> x = [1,2]
>>> x.append(3)
>>> x
[1, 2, 3]
</code></pre>
<p>while tuples are not:</p>
<pre><code>>>> x = (1,2)
>>> x
(1, 2)
>>> x.append(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'
</code></pre>
<p>The other main difference is that a tuple is hashable, meaning that you can use it as a key to a dictionary, among other things. For example:</p>
<pre><code>>>> x = (1,2)
>>> y = [1,2]
>>> z = {}
>>> z[x] = 3
>>> z
{(1, 2): 3}
>>> z[y] = 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
</code></pre>
<hr>
<p>Note that, as many people have pointed out, you can add tuples together. For example:</p>
<pre><code>>>> x = (1,2)
>>> x += (3,)
>>> x
(1, 2, 3)
</code></pre>
<p>However, <strong>this does not mean tuples are mutable</strong>. In the example above, a <em>new</em> tuple is constructed by adding together the two tuples as arguments. The original tuple is not modified. To demonstrate this, consider the following:</p>
<pre><code>>>> x = (1,2)
>>> y = x
>>> x += (3,)
>>> x
(1, 2, 3)
>>> y
(1, 2)
</code></pre>
<p>Whereas, if you were to construct this same example with a list, <code>y</code> would also be updated:</p>
<pre><code>>>> x = [1, 2]
>>> y = x
>>> x += [3]
>>> x
[1, 2, 3]
>>> y
[1, 2, 3]
</code></pre> | {
"question_id": 8900166,
"question_date": "2012-01-17T19:02:34.433Z",
"question_score": 206,
"tags": "python|list|tuples",
"answer_id": 8900189,
"answer_date": "2012-01-17T19:04:21.717Z",
"answer_score": 315
} |
Please answer the following Stack Overflow question:
Title: Setting HttpContext.Current.Session in a unit test
<p>I have a web service I am trying to unit test. In the service it pulls several values from the <code>HttpContext</code> like so:</p>
<pre><code> m_password = (string)HttpContext.Current.Session["CustomerId"];
m_userID = (string)HttpContext.Current.Session["CustomerUrl"];
</code></pre>
<p>in the unit test I am creating the context using a simple worker request, like so:</p>
<pre><code>SimpleWorkerRequest request = new SimpleWorkerRequest("", "", "", null, new StringWriter());
HttpContext context = new HttpContext(request);
HttpContext.Current = context;
</code></pre>
<p>However, whenever I try to set the values of <code>HttpContext.Current.Session</code></p>
<pre><code>HttpContext.Current.Session["CustomerId"] = "customer1";
HttpContext.Current.Session["CustomerUrl"] = "customer1Url";
</code></pre>
<p>I get null reference exception that says <code>HttpContext.Current.Session</code> is null. </p>
<p>Is there any way to initialize the current session within the unit test?</p> | <p>We had to mock <code>HttpContext</code> by using a <code>HttpContextManager</code> and calling the factory from within our application as well as the Unit Tests</p>
<pre><code>public class HttpContextManager
{
private static HttpContextBase m_context;
public static HttpContextBase Current
{
get
{
if (m_context != null)
return m_context;
if (HttpContext.Current == null)
throw new InvalidOperationException("HttpContext not available");
return new HttpContextWrapper(HttpContext.Current);
}
}
public static void SetCurrentContext(HttpContextBase context)
{
m_context = context;
}
}
</code></pre>
<p>You would then replace any calls to <code>HttpContext.Current</code> with <code>HttpContextManager.Current</code> and have access to the same methods. Then when you're testing, you can also access the <code>HttpContextManager</code> and mock your expectations</p>
<p>This is an example using <a href="https://www.nuget.org/packages/Moq/" rel="noreferrer">Moq</a>:</p>
<pre><code>private HttpContextBase GetMockedHttpContext()
{
var context = new Mock<HttpContextBase>();
var request = new Mock<HttpRequestBase>();
var response = new Mock<HttpResponseBase>();
var session = new Mock<HttpSessionStateBase>();
var server = new Mock<HttpServerUtilityBase>();
var user = new Mock<IPrincipal>();
var identity = new Mock<IIdentity>();
var urlHelper = new Mock<UrlHelper>();
var routes = new RouteCollection();
MvcApplication.RegisterRoutes(routes);
var requestContext = new Mock<RequestContext>();
requestContext.Setup(x => x.HttpContext).Returns(context.Object);
context.Setup(ctx => ctx.Request).Returns(request.Object);
context.Setup(ctx => ctx.Response).Returns(response.Object);
context.Setup(ctx => ctx.Session).Returns(session.Object);
context.Setup(ctx => ctx.Server).Returns(server.Object);
context.Setup(ctx => ctx.User).Returns(user.Object);
user.Setup(ctx => ctx.Identity).Returns(identity.Object);
identity.Setup(id => id.IsAuthenticated).Returns(true);
identity.Setup(id => id.Name).Returns("test");
request.Setup(req => req.Url).Returns(new Uri("http://www.google.com"));
request.Setup(req => req.RequestContext).Returns(requestContext.Object);
requestContext.Setup(x => x.RouteData).Returns(new RouteData());
request.SetupGet(req => req.Headers).Returns(new NameValueCollection());
return context.Object;
}
</code></pre>
<p>and then to use it within your unit tests, I call this within my Test Init method</p>
<pre><code>HttpContextManager.SetCurrentContext(GetMockedHttpContext());
</code></pre>
<p>you can then, in the above method add the expected results from Session that you're expecting to be available to your web service.</p> | {
"question_id": 9624242,
"question_date": "2012-03-08T20:15:31.473Z",
"question_score": 206,
"tags": "c#|web-services|unit-testing|httpcontext",
"answer_id": 9624433,
"answer_date": "2012-03-08T20:28:31.323Z",
"answer_score": 111
} |
Please answer the following Stack Overflow question:
Title: View more than one project/solution in Visual Studio
<p>I am new to visual studio and I am experimenting around with some Windows Services. I have created two solutions and I would like to view both of them at once. Without having to click file->recent projects to switch back and forth.</p>
<p>Ideally this could take place in the solution explorer and just nest the projects, but I am only able to view one solution/project at a time there.</p>
<p>Is there anyway to view multiple solutions/projects in Visual Studio?</p> | <p>This is the way Visual Studio is designed: One solution, one Visual Studio (VS) instance.</p>
<p>Besides switching between solutions in one VS instance, you can also open another VS instance and open your other solution with that one. Next to solutions there are as you said "projects". You can have multiple projects within one solution and therefore view many projects at the same time.</p> | {
"question_id": 4079278,
"question_date": "2010-11-02T15:35:57.353Z",
"question_score": 206,
"tags": "visual-studio",
"answer_id": 4079330,
"answer_date": "2010-11-02T15:40:09.877Z",
"answer_score": 217
} |
Please answer the following Stack Overflow question:
Title: How to get a unique device ID in Swift?
<p>How can I get a device's unique ID in Swift?</p>
<p>I need an ID to use in the database and as the API-key for my web service in my social app. Something to keep track of this devices daily use and limit its queries to the database.</p> | <p>You can use this (Swift 3):</p>
<pre><code>UIDevice.current.identifierForVendor!.uuidString
</code></pre>
<p>For older versions:</p>
<pre><code>UIDevice.currentDevice().identifierForVendor
</code></pre>
<p>or if you want a string:</p>
<pre><code>UIDevice.currentDevice().identifierForVendor!.UUIDString
</code></pre>
<p><br>
There is no longer a way to uniquely identify a device after the user uninstalled the app(s). The documentation says:</p>
<blockquote>
<p>The value in this property remains the same while the app (or another app from the same vendor) is installed on the iOS device. The value changes when the user deletes all of that vendor’s apps from the device and subsequently reinstalls one or more of them.</p>
</blockquote>
<p><br>
You may also want to read this article by Mattt Thompson for more details: <br>
<a href="http://nshipster.com/uuid-udid-unique-identifier/" rel="noreferrer">http://nshipster.com/uuid-udid-unique-identifier/</a></p>
<p><strong>Update for Swift 4.1</strong>, you will need to use:</p>
<pre><code>UIDevice.current.identifierForVendor?.uuidString
</code></pre> | {
"question_id": 25925481,
"question_date": "2014-09-19T02:30:50.047Z",
"question_score": 206,
"tags": "ios|swift|uuid|uniqueidentifier",
"answer_id": 25929324,
"answer_date": "2014-09-19T08:15:42.210Z",
"answer_score": 450
} |
Please answer the following Stack Overflow question:
Title: What is the difference between atan and atan2 in C++?
<p>What is the difference between <code>atan</code> and <code>atan2</code> in C++?</p> | <p><a href="http://en.cppreference.com/w/cpp/numeric/math/atan2" rel="noreferrer"><code>std::atan2</code></a> allows calculating the arctangent of all four quadrants. <a href="http://en.cppreference.com/w/cpp/numeric/math/atan" rel="noreferrer"><code>std::atan</code></a> only allows calculating from quadrants 1 and 4.</p> | {
"question_id": 283406,
"question_date": "2008-11-12T09:20:28.700Z",
"question_score": 206,
"tags": "c++|math.h",
"answer_id": 283408,
"answer_date": "2008-11-12T09:22:19.523Z",
"answer_score": 164
} |
Please answer the following Stack Overflow question:
Title: Stopping Docker containers by image name - Ubuntu
<p>On Ubuntu 14.04 (Trusty Tahr) I'm looking for a way to stop a running container and the only information I have is the image name that was used in the Docker run command. </p>
<p>Is there a command to find all the matching running containers that match that image name and stop them?</p> | <h2>If you know the <code>image:tag</code> exact container version</h2>
<p>Following <a href="https://github.com/docker/docker/issues/8959" rel="noreferrer">issue 8959</a>, a good start would be:</p>
<pre><code>docker ps -a -q --filter="name=<containerName>"
</code></pre>
<p>Since <code>name</code> refers to the <em>container</em> and not the image name, you would need to use the more recent <a href="https://github.com/docker/docker/commit/b1cb1b1df493b3e0b739b9f374b6c82e306dede8" rel="noreferrer">Docker 1.9 filter ancestor</a>, mentioned in <a href="https://stackoverflow.com/users/158288/koekiebox">koekiebox</a>'s <a href="https://stackoverflow.com/a/34899613/6309">answer</a>.</p>
<pre><code>docker ps -a -q --filter ancestor=<image-name>
</code></pre>
<hr />
<p>As commented below by <a href="https://stackoverflow.com/users/1919237/kiril">kiril</a>, to remove those containers:</p>
<blockquote>
<p><code>stop</code> returns the containers as well.</p>
</blockquote>
<p>So chaining <code>stop</code> and <code>rm</code> will do the job:</p>
<pre><code>docker rm $(docker stop $(docker ps -a -q --filter ancestor=<image-name> --format="{{.ID}}"))
</code></pre>
<hr />
<h2>If you know only the image name (not <code>image:tag</code>)</h2>
<p>As <a href="https://stackoverflow.com/users/986696/alex-jansen">Alex Jansen</a> points out in <a href="https://stackoverflow.com/questions/32073971/stopping-docker-containers-by-image-name-ubuntu/32074098#comment121207874_32074098">the comments</a>:</p>
<blockquote>
<p>The <a href="https://docs.docker.com/engine/reference/commandline/ps/#filtering" rel="noreferrer">ancestor option</a> does not support wildcard matching.</p>
</blockquote>
<p>Alex <a href="https://stackoverflow.com/a/68584752/6309">proposes a solution</a>, but the one I managed to run, when you have <em>multiple</em> containers running from the same image is (in your <code>~/.bashrc</code> for instance):</p>
<pre><code>dsi() { docker stop $(docker ps -a | awk -v i="^$1.*" '{if($2~i){print$1}}'); }
</code></pre>
<p>Then I just call in my bash session (after sourcing <code>~/.bashrc</code>):</p>
<pre><code>dsi alpine
</code></pre>
<p>And any container running from <code>alpine.*:xxx</code> would stop.</p>
<p>Meaning: any image whose name is <em>starting</em> with <code>alpine</code>.<br />
You might need to tweak the <code>awk -v i="^$1.*"</code> if you want <code>^$1.*</code> to be more precise.</p>
<p>From there, of course:</p>
<pre><code>drmi() { docker rm $(dsi $1 | tr '\n' ' '); }
</code></pre>
<p>And a <code>drmi alpine</code> would stop <em>and remove</em> any <code>alpine:xxx</code> container.</p> | {
"question_id": 32073971,
"question_date": "2015-08-18T13:35:17.657Z",
"question_score": 206,
"tags": "docker|ubuntu|docker-image",
"answer_id": 32074098,
"answer_date": "2015-08-18T13:40:17.423Z",
"answer_score": 289
} |
Please answer the following Stack Overflow question:
Title: Chart.js v2 - hiding grid lines
<p>I am using Chart.js v2 to draw a simple line chart. Everything looks fine, except there are grid lines that I don't want:</p>
<p><a href="https://i.stack.imgur.com/ir7Ll.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/ir7Ll.jpg" alt="Grid Lines I don't want"></a></p>
<p>The documentation for Line Chart is here: <a href="https://nnnick.github.io/Chart.js/docs-v2/#line-chart" rel="noreferrer">https://nnnick.github.io/Chart.js/docs-v2/#line-chart</a>, but I can't find anything about hiding those "Grid Lines".</p>
<p>How can I remove the grid lines?</p> | <p>I found a solution that works for hiding the grid lines in a Line chart.</p>
<p>Set the <code>gridLines</code> color to be the same as the div's background color.</p>
<pre><code>var options = {
scales: {
xAxes: [{
gridLines: {
color: "rgba(0, 0, 0, 0)",
}
}],
yAxes: [{
gridLines: {
color: "rgba(0, 0, 0, 0)",
}
}]
}
}
</code></pre>
<p>or use </p>
<pre><code>var options = {
scales: {
xAxes: [{
gridLines: {
display:false
}
}],
yAxes: [{
gridLines: {
display:false
}
}]
}
}
</code></pre> | {
"question_id": 36676263,
"question_date": "2016-04-17T12:06:47.763Z",
"question_score": 206,
"tags": "javascript|chart.js2",
"answer_id": 36692545,
"answer_date": "2016-04-18T11:22:37.390Z",
"answer_score": 449
} |
Please answer the following Stack Overflow question:
Title: How do I get AWS_ACCESS_KEY_ID for Amazon?
<p>I'm totally new to AWS.</p>
<p>I downloaded some sample code from Amazon and I need to set a number of constants:</p>
<ul>
<li><code>AWS_ACCESS_KEY_ID</code></li>
<li><code>AWS_SECRET_ACCESS_KEY</code></li>
<li><code>MERCHANT_ID</code></li>
<li><code>MARKETPLACE_ID</code> </li>
</ul>
<p>I just created an AWS account. I want some type of sandbox account so I can try out the code samples.</p>
<p>What are the exact steps I have to take to:</p>
<ol>
<li>Create a sandbox account</li>
<li>Get these credentials</li>
</ol> | <ol>
<li>Go to: <a href="http://aws.amazon.com/">http://aws.amazon.com/</a></li>
<li>Sign Up & create a new account (they'll give you the option for 1 year trial or similar)</li>
<li>Go to your <a href="https://console.aws.amazon.com">AWS account overview</a></li>
<li>Account menu in the upper-right (has your name on it)</li>
<li>sub-menu: Security Credentials</li>
</ol> | {
"question_id": 21440709,
"question_date": "2014-01-29T19:28:15.160Z",
"question_score": 206,
"tags": "amazon-web-services|access-keys",
"answer_id": 21443349,
"answer_date": "2014-01-29T21:46:59.223Z",
"answer_score": 240
} |
Please answer the following Stack Overflow question:
Title: jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON
<p>I’m making requests to my server using <code>jQuery.post()</code> and my server is returning JSON objects (like <code>{ "var": "value", ... }</code>). However, if any of the values contains a single quote (properly escaped like <code>\'</code>), jQuery fails to parse an otherwise valid JSON string. Here’s an example of what I mean (<a href="https://i.stack.imgur.com/jKAtL.png" rel="noreferrer">done in Chrome’s console</a>):</p>
<pre><code>data = "{ \"status\": \"success\", \"newHtml\": \"Hello \\\'x\" }";
eval("x = " + data); // { newHtml: "Hello 'x", status: "success" }
$.parseJSON(data); // Invalid JSON: { "status": "success", "newHtml": "Hello \'x" }
</code></pre>
<p>Is this normal? Is there no way to properly pass a single quote via JSON?</p> | <p>According to the state machine diagram on the <a href="http://www.json.org/" rel="noreferrer">JSON website</a>, only escaped double-quote characters are allowed, not single-quotes. Single quote characters do not need to be escaped:</p>
<p><img src="https://i.stack.imgur.com/15Kqv.gif" alt="http://www.json.org/string.gif"></p>
<p><br />
<b>Update</b> - More information for those that are interested:</p>
<hr />
<p>Douglas Crockford does not specifically say why the JSON specification does not allow escaped single quotes within strings. However, during his discussion of JSON in <a href="http://oreilly.com/javascript/excerpts/javascript-good-parts/json.html" rel="noreferrer">Appendix E of JavaScript: The Good Parts</a>, he writes:</p>
<blockquote>
<p>JSON's design goals were to be minimal, portable, textual, and a subset of JavaScript. The less we need to agree on in order to interoperate, the more easily we can interoperate.</p>
</blockquote>
<p>So perhaps he decided to only allow strings to be defined using double-quotes since this is one less rule that all JSON implementations must agree on. As a result, it is impossible for a single quote character within a string to accidentally terminate the string, because by definition a string can only be terminated by a double-quote character. Hence there is no need to allow escaping of a single quote character in the formal specification.</p>
<p><hr />
Digging a little bit deeper, Crockford's <a href="http://www.json.org/java/index.html" rel="noreferrer">org.json</a> implementation of JSON for Java is more permissible and <em>does</em> allow single quote characters:</p>
<blockquote>
<p>The texts produced by the toString methods strictly conform to the JSON syntax rules. The constructors are more forgiving in the texts they will accept:</p>
<p>...</p>
<ul>
<li>Strings may be quoted with ' (single quote).</li>
</ul>
</blockquote>
<p>This is confirmed by the <a href="https://github.com/douglascrockford/JSON-java/blob/master/JSONTokener.java" rel="noreferrer">JSONTokener</a> source code. The <code>nextString</code> method accepts escaped single quote characters and treats them just like double-quote characters:</p>
<pre><code>public String nextString(char quote) throws JSONException {
char c;
StringBuffer sb = new StringBuffer();
for (;;) {
c = next();
switch (c) {
...
case '\\':
c = this.next();
switch (c) {
...
case '"':
case '\'':
case '\\':
case '/':
sb.append(c);
break;
...
</code></pre>
<p>At the top of the method is an informative comment:</p>
<blockquote>
<p>The formal JSON format does not allow strings in single quotes, but an implementation is allowed to accept them.</p>
</blockquote>
<p>So some implementations will accept single quotes - but you should not rely on this. Many popular implementations are quite restrictive in this regard and will reject JSON that contains single quoted strings and/or escaped single quotes.</p>
<hr />
<p>Finally to tie this back to the original question, <a href="http://code.jquery.com/jquery-latest.js" rel="noreferrer"><code>jQuery.parseJSON</code></a> first attempts to use the browser's native JSON parser or a loaded library such as <a href="https://github.com/douglascrockford/JSON-js/blob/master/json2.js" rel="noreferrer">json2.js</a> where applicable (which on a side note is the library the jQuery logic is based on if <code>JSON</code> is not defined). Thus jQuery can only be as permissive as that underlying implementation:</p>
<pre><code>parseJSON: function( data ) {
...
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
...
jQuery.error( "Invalid JSON: " + data );
},
</code></pre>
<p>As far as I know these implementations only adhere to the official JSON specification and do not accept single quotes, hence neither does jQuery.</p> | {
"question_id": 2275359,
"question_date": "2010-02-16T18:39:18.383Z",
"question_score": 206,
"tags": "javascript|jquery|json",
"answer_id": 2275428,
"answer_date": "2010-02-16T18:49:16.693Z",
"answer_score": 327
} |
Please answer the following Stack Overflow question:
Title: Are table names in MySQL case sensitive?
<p>Are table names in MySQL case sensitive?</p>
<p>On my Windows development machine the code I have is able to query my tables which appear to be all lowercase. When I deploy to the test server in our datacenter the table names appear to start with an uppercase letter.</p>
<p>The servers we use are all on Ubuntu.</p> | <p>In general:</p>
<p><strong>Database and table names are not case sensitive in Windows, and case sensitive in most varieties of Unix.</strong></p>
<blockquote>
<p>In MySQL, databases correspond to directories within the data
directory. Each table within a database corresponds to at least one
file within the database directory. Consequently, the case sensitivity of the
underlying operating system plays a part in the case sensitivity of
database and table names.</p>
</blockquote>
<p>One can configure how tables names are stored on the disk using the system variable <code>lower_case_table_names</code> (in the <strong>my.cnf</strong> configuration file under [mysqld]).</p>
<p>Read the section: <a href="http://dev.mysql.com/doc/refman/5.0/en/identifier-case-sensitivity.html" rel="noreferrer">10.2.2 Identifier Case Sensitivity</a> for more information.</p> | {
"question_id": 6134006,
"question_date": "2011-05-26T05:17:18.497Z",
"question_score": 206,
"tags": "mysql|case-sensitive|mysql5",
"answer_id": 6134059,
"answer_date": "2011-05-26T05:25:51.080Z",
"answer_score": 253
} |
Please answer the following Stack Overflow question:
Title: Wait for a void async method
<p>How can I wait for a <code>void async</code> method to finish its job?</p>
<p>for example, I have a function like below:</p>
<pre><code>async void LoadBlahBlah()
{
await blah();
...
}
</code></pre>
<p>now I want to make sure that everything has been loaded before continuing somewhere else.</p> | <p>Best practice is to mark function <code>async void</code> only if it is fire and forget method, if you want to await on, you should mark it as <code>async Task</code>.</p>
<p>In case if you still want to await, then wrap it like so <code>await Task.Run(() => blah())</code></p> | {
"question_id": 13636648,
"question_date": "2012-11-29T23:25:35.257Z",
"question_score": 206,
"tags": "c#|asynchronous",
"answer_id": 13638087,
"answer_date": "2012-11-30T02:17:28.257Z",
"answer_score": 322
} |
Please answer the following Stack Overflow question:
Title: Request failed: unacceptable content-type: text/html using AFNetworking 2.0
<p>I'm trying out the new version 2.0 of AFNetworking and I'm getting the error above. Any idea why this is happening? Here's my code:</p>
<pre><code> NSURL *URL = [NSURL URLWithString:kJSONlink];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
[[NSOperationQueue mainQueue] addOperation:op];
</code></pre>
<p>I'm using Xcode 5.0.</p>
<p>Also, here's the error message:</p>
<pre><code>Error: Error Domain=AFNetworkingErrorDomain Code=-1016 "Request failed: unacceptable content-type: text/html" UserInfo=0xda2e670 {NSErrorFailingURLKey=kJSONlink, AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0xda35180> { URL: kJSONlink } { status code: 200, headers {
Connection = "Keep-Alive";
"Content-Encoding" = gzip;
"Content-Length" = 2898;
"Content-Type" = "text/html";
Date = "Tue, 01 Oct 2013 10:59:45 GMT";
"Keep-Alive" = "timeout=5, max=100";
Server = Apache;
Vary = "Accept-Encoding";
} }, NSLocalizedDescription=Request failed: unacceptable content-type: text/html}
</code></pre>
<p>I just hid the JSON using kJSONlink. This should return a JSON.</p> | <p>This means that your server is sending <code>"text/html"</code> instead of the already supported types.
My solution was to add <code>"text/html"</code> to <code>acceptableContentTypes</code> set in <code>AFURLResponseSerialization</code> class. Just search for "acceptableContentTypes" and add <code>@"text/html"</code> to the set manually.</p>
<p>Of course, the ideal solution is to change the type sent from the server, but for that you will have to talk with the server team.</p> | {
"question_id": 19114623,
"question_date": "2013-10-01T11:09:16.413Z",
"question_score": 206,
"tags": "ios|afnetworking|afnetworking-2",
"answer_id": 19121229,
"answer_date": "2013-10-01T16:21:35.260Z",
"answer_score": 363
} |
Please answer the following Stack Overflow question:
Title: How to form tuple column from two columns in Pandas
<p>I've got a Pandas DataFrame and I want to combine the 'lat' and 'long' columns to form a tuple.</p>
<pre><code><class 'pandas.core.frame.DataFrame'>
Int64Index: 205482 entries, 0 to 209018
Data columns:
Month 205482 non-null values
Reported by 205482 non-null values
Falls within 205482 non-null values
Easting 205482 non-null values
Northing 205482 non-null values
Location 205482 non-null values
Crime type 205482 non-null values
long 205482 non-null values
lat 205482 non-null values
dtypes: float64(4), object(5)
</code></pre>
<p>The code I tried to use was:</p>
<pre><code>def merge_two_cols(series):
return (series['lat'], series['long'])
sample['lat_long'] = sample.apply(merge_two_cols, axis=1)
</code></pre>
<p>However, this returned the following error:</p>
<pre><code>---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-261-e752e52a96e6> in <module>()
2 return (series['lat'], series['long'])
3
----> 4 sample['lat_long'] = sample.apply(merge_two_cols, axis=1)
5
</code></pre>
<p>...</p>
<pre><code>AssertionError: Block shape incompatible with manager
</code></pre>
<p>How can I solve this problem?</p> | <p>Get comfortable with <code>zip</code>. It comes in handy when dealing with column data. </p>
<pre><code>df['new_col'] = list(zip(df.lat, df.long))
</code></pre>
<p>It's less complicated and faster than using <code>apply</code> or <code>map</code>. Something like <code>np.dstack</code> is twice as fast as <code>zip</code>, but wouldn't give you tuples.</p> | {
"question_id": 16031056,
"question_date": "2013-04-16T07:21:52.430Z",
"question_score": 206,
"tags": "python|dataframe|pandas|tuples",
"answer_id": 16068497,
"answer_date": "2013-04-17T19:24:48.227Z",
"answer_score": 319
} |
Please answer the following Stack Overflow question:
Title: Regex Named Groups in Java
<p>It is my understanding that the <code>java.regex</code> package does not have support for named groups (<a href="http://www.regular-expressions.info/named.html" rel="noreferrer">http://www.regular-expressions.info/named.html</a>) so can anyone point me towards a third-party library that does?</p>
<p>I've looked at <a href="http://jregex.sourceforge.net/" rel="noreferrer">jregex</a> but its last release was in 2002 and it didn't work for me (admittedly I only tried briefly) under java5.</p> | <p>(<strong>Update</strong>: <strong>August 2011</strong>)</p>
<p>As <a href="https://stackoverflow.com/users/50260/geofflane">geofflane</a> mentions in <a href="https://stackoverflow.com/questions/415580/regex-named-groups-in-java/7033467#7033467">his answer</a>, <a href="http://download.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#group%28java.lang.String%29" rel="noreferrer">Java 7 now support named groups</a>.<br>
<a href="https://stackoverflow.com/users/471272/tchrist">tchrist</a> points out in the comment that the support is limited.<br>
He <strong>details the limitations in his great answer "<a href="https://stackoverflow.com/questions/5767627/java-regex-helper/5771326#5771326">Java Regex Helper</a>"</strong> </p>
<p>Java 7 regex named group support was presented back in <a href="http://blogs.oracle.com/xuemingshen/entry/named_capturing_group_in_jdk7" rel="noreferrer"><strong>September 2010</strong> in Oracle's blog</a>.</p>
<p>In the official release of Java 7, the constructs to support the named capturing group are:</p>
<blockquote>
<ul>
<li><code>(?<name>capturing text)</code> to define a named group "name"</li>
<li><code>\k<name></code> to backreference a named group "name"</li>
<li><code>${name}</code> to reference to captured group in Matcher's replacement string</li>
<li><a href="http://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#group%28java.lang.String%29" rel="noreferrer"><code>Matcher.group(String name)</code></a> to return the captured input subsequence by the given "named group".</li>
</ul>
</blockquote>
<hr>
<p><strong>Other alternatives for pre-Java 7</strong> were:</p>
<ul>
<li><a href="http://code.google.com/p/named-regexp/" rel="noreferrer">Google named-regex</a> (see <a href="https://stackoverflow.com/users/134642/john-hardy">John Hardy</a>'s <a href="https://stackoverflow.com/questions/415580/regex-named-groups-in-java/1095737#1095737">answer</a>)<br>
<a href="https://stackoverflow.com/users/337621/gabor-liptak">Gábor Lipták</a> mentions (November 2012) that this project might not be active (with <a href="http://code.google.com/p/named-regexp/issues/list" rel="noreferrer">several outstanding bugs</a>), and its <a href="https://github.com/tony19/named-regexp" rel="noreferrer">GitHub fork</a> could be considered instead.</li>
<li><a href="http://jregex.sourceforge.net/" rel="noreferrer">jregex</a> (See <a href="https://stackoverflow.com/users/22982/brian-clozel">Brian Clozel</a>'s <a href="https://stackoverflow.com/questions/415580/regex-named-groups-in-java/3782345#3782345">answer</a>)</li>
</ul>
<hr>
<p>(<strong>Original answer</strong>: <strong>Jan 2009</strong>, with the next two links now broken)</p>
<p>You can not refer to named group, unless you code your own version of Regex...</p>
<p>That is precisely what <a href="http://x86.sun.com/thread.jspa?threadID=785370&messageID=4463652" rel="noreferrer">Gorbush2 did in this thread</a>.</p>
<p><a href="http://gorbush.narod.ru/files/regex2.zip" rel="noreferrer"><strong>Regex2</strong></a></p>
<p>(limited implementation, as pointed out again by <a href="https://stackoverflow.com/users/471272/tchrist">tchrist</a>, as it looks only for ASCII identifiers. tchrist details the limitation as:</p>
<blockquote>
<p>only being able to have one named group per same name (which you don’t always have control over!) and not being able to use them for in-regex recursion.</p>
</blockquote>
<p>Note: You can find true regex recursion examples in Perl and PCRE regexes, as mentioned in <a href="http://www.perl.com/pub/2003/06/06/regexps.html" rel="noreferrer">Regexp Power</a>, <a href="http://www.pcre.org/pcre.txt" rel="noreferrer">PCRE specs</a> and <a href="http://perl.plover.com/yak/regex/samples/slide083.html" rel="noreferrer">Matching Strings with Balanced Parentheses</a> slide)</p>
<p>Example:</p>
<p>String:</p>
<pre><code>"TEST 123"
</code></pre>
<p>RegExp:</p>
<pre><code>"(?<login>\\w+) (?<id>\\d+)"
</code></pre>
<p>Access</p>
<pre><code>matcher.group(1) ==> TEST
matcher.group("login") ==> TEST
matcher.name(1) ==> login
</code></pre>
<p>Replace</p>
<pre><code>matcher.replaceAll("aaaaa_$1_sssss_$2____") ==> aaaaa_TEST_sssss_123____
matcher.replaceAll("aaaaa_${login}_sssss_${id}____") ==> aaaaa_TEST_sssss_123____
</code></pre>
<hr>
<p>(extract from the implementation)</p>
<pre><code>public final class Pattern
implements java.io.Serializable
{
[...]
/**
* Parses a group and returns the head node of a set of nodes that process
* the group. Sometimes a double return system is used where the tail is
* returned in root.
*/
private Node group0() {
boolean capturingGroup = false;
Node head = null;
Node tail = null;
int save = flags;
root = null;
int ch = next();
if (ch == '?') {
ch = skip();
switch (ch) {
case '<': // (?<xxx) look behind or group name
ch = read();
int start = cursor;
[...]
// test forGroupName
int startChar = ch;
while(ASCII.isWord(ch) && ch != '>') ch=read();
if(ch == '>'){
// valid group name
int len = cursor-start;
int[] newtemp = new int[2*(len) + 2];
//System.arraycopy(temp, start, newtemp, 0, len);
StringBuilder name = new StringBuilder();
for(int i = start; i< cursor; i++){
name.append((char)temp[i-1]);
}
// create Named group
head = createGroup(false);
((GroupTail)root).name = name.toString();
capturingGroup = true;
tail = root;
head.next = expr(tail);
break;
}
</code></pre> | {
"question_id": 415580,
"question_date": "2009-01-06T05:45:36.373Z",
"question_score": 206,
"tags": "java|regex",
"answer_id": 415635,
"answer_date": "2009-01-06T06:36:42.027Z",
"answer_score": 331
} |
Please answer the following Stack Overflow question:
Title: blur vs focusout -- any real differences?
<p>Is there any difference between JS events <strong>blur</strong> vs <strong>focusout</strong>?</p>
<p>I have two textboxes: <code>password</code> and <code>confirm_password</code>.</p>
<p>I want to check password match when user tabs out of the confirm pwd textbox, for example.</p>
<p>In this case which event should I use or does it matter?</p> | <p>The documentation for <a href="http://api.jquery.com/focusout/" rel="noreferrer">focusout</a> says (<em>emphasis</em> mine):</p>
<blockquote>
<p>The <code>focusout</code> event is sent to an element when it, <em>or any element
inside of it</em>, loses focus. This is distinct from the <code>blur</code> event in
that <em>it supports detecting the loss of focus on descendant elements</em> (in
other words, it supports event bubbling).</p>
</blockquote>
<p>The same distinction exists between the <a href="http://api.jquery.com/focusin/" rel="noreferrer">focusin</a> and <a href="http://api.jquery.com/focus" rel="noreferrer">focus</a> events.</p> | {
"question_id": 8973532,
"question_date": "2012-01-23T14:53:09.873Z",
"question_score": 206,
"tags": "javascript|jquery",
"answer_id": 8973560,
"answer_date": "2012-01-23T14:55:00.427Z",
"answer_score": 276
} |
Please answer the following Stack Overflow question:
Title: How to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field?
<p>To illustrate, assume that I have two tables as follows:</p>
<pre><code>VehicleID Name
1 Chuck
2 Larry
LocationID VehicleID City
1 1 New York
2 1 Seattle
3 1 Vancouver
4 2 Los Angeles
5 2 Houston
</code></pre>
<p>I want to write a query to return the following results:</p>
<pre><code>VehicleID Name Locations
1 Chuck New York, Seattle, Vancouver
2 Larry Los Angeles, Houston
</code></pre>
<p>I know that this can be done using server side cursors, ie:</p>
<pre><code>DECLARE @VehicleID int
DECLARE @VehicleName varchar(100)
DECLARE @LocationCity varchar(100)
DECLARE @Locations varchar(4000)
DECLARE @Results TABLE
(
VehicleID int
Name varchar(100)
Locations varchar(4000)
)
DECLARE VehiclesCursor CURSOR FOR
SELECT
[VehicleID]
, [Name]
FROM [Vehicles]
OPEN VehiclesCursor
FETCH NEXT FROM VehiclesCursor INTO
@VehicleID
, @VehicleName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @Locations = ''
DECLARE LocationsCursor CURSOR FOR
SELECT
[City]
FROM [Locations]
WHERE [VehicleID] = @VehicleID
OPEN LocationsCursor
FETCH NEXT FROM LocationsCursor INTO
@LocationCity
WHILE @@FETCH_STATUS = 0
BEGIN
SET @Locations = @Locations + @LocationCity
FETCH NEXT FROM LocationsCursor INTO
@LocationCity
END
CLOSE LocationsCursor
DEALLOCATE LocationsCursor
INSERT INTO @Results (VehicleID, Name, Locations) SELECT @VehicleID, @Name, @Locations
END
CLOSE VehiclesCursor
DEALLOCATE VehiclesCursor
SELECT * FROM @Results
</code></pre>
<p>However, as you can see, this requires a great deal of code. What I would like is a generic function that would allow me to do something like this:</p>
<pre><code>SELECT VehicleID
, Name
, JOIN(SELECT City FROM Locations WHERE VehicleID = Vehicles.VehicleID, ', ') AS Locations
FROM Vehicles
</code></pre>
<p>Is this possible? Or something similar?</p> | <p>If you're using SQL Server 2005, you could use the FOR XML PATH command.</p>
<pre><code>SELECT [VehicleID]
, [Name]
, (STUFF((SELECT CAST(', ' + [City] AS VARCHAR(MAX))
FROM [Location]
WHERE (VehicleID = Vehicle.VehicleID)
FOR XML PATH ('')), 1, 2, '')) AS Locations
FROM [Vehicle]
</code></pre>
<p>It's a lot easier than using a cursor, and seems to work fairly well.</p>
<p><strong>Update</strong></p>
<p>For anyone still using this method with newer versions of SQL Server, there is another way of doing it which is a bit easier and more performant using the
<a href="https://docs.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-ver15" rel="noreferrer"><code>STRING_AGG</code></a> method that has been available since SQL Server 2017.</p>
<pre><code>SELECT [VehicleID]
,[Name]
,(SELECT STRING_AGG([City], ', ')
FROM [Location]
WHERE VehicleID = V.VehicleID) AS Locations
FROM [Vehicle] V
</code></pre>
<p>This also allows a different separator to be specified as the second parameter, providing a little more flexibility over the former method.</p> | {
"question_id": 6899,
"question_date": "2008-08-09T20:11:18.467Z",
"question_score": 206,
"tags": "sql|sql-server|string-concatenation",
"answer_id": 6980,
"answer_date": "2008-08-10T01:05:00.980Z",
"answer_score": 274
} |
Please answer the following Stack Overflow question:
Title: Changing Locale within the app itself
<p>My users can change the Locale within the app (they may want to keep their phone settings in English but read the content of my app in French, Dutch or any other language ...)</p>
<p>Why is this working perfectly fine in 1.5/1.6 but NOT in 2.0 anymore ???</p>
<pre><code>@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case 201:
Locale locale2 = new Locale("fr");
Locale.setDefault(locale2);
Configuration config2 = new Configuration();
config2.locale = locale2;
getBaseContext().getResources().updateConfiguration(
config2, getBaseContext().getResources().getDisplayMetrics());
// loading data ...
refresh();
// refresh the tabs and their content
refresh_Tab ();
break;
case 201: etc...
</code></pre>
<p>The problem is that the MENU "shrinks" more and more everytime the user is going through the lines of code above ... </p>
<p>This is the Menu that gets shrunk:</p>
<pre><code>@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 100, 1, "REFRESH").setIcon(android.R.drawable.ic_menu_compass);
SubMenu langMenu = menu.addSubMenu(0, 200, 2, "NL-FR").setIcon(android.R.drawable.ic_menu_rotate);
langMenu.add(1, 201, 0, "Nederlands");
langMenu.add(1, 202, 0, "Français");
menu.add(0, 250, 4, R.string.OptionMenu2).setIcon(android.R.drawable.ic_menu_send);
menu.add(0, 300, 5, R.string.OptionMenu3).setIcon(android.R.drawable.ic_menu_preferences);
menu.add(0, 350, 3, R.string.OptionMenu4).setIcon(android.R.drawable.ic_menu_more);
menu.add(0, 400, 6, "Exit").setIcon(android.R.drawable.ic_menu_delete);
return super.onCreateOptionsMenu(menu);
}
</code></pre>
<p>What should I do in API Level 5 to make this work again ?</p>
<p>HERE IS THE FULL CODE IF YOU WANT TO TEST THIS :</p>
<pre><code>import java.util.Locale;
import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.widget.Toast;
public class Main extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
SubMenu langMenu = menu.addSubMenu(0, 200, 2, "NL-FR").setIcon(android.R.drawable.ic_menu_rotate);
langMenu.add(1, 201, 0, "Nederlands");
langMenu.add(1, 202, 0, "Français");
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case 201:
Locale locale = new Locale("nl");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
Toast.makeText(this, "Locale in Nederlands !", Toast.LENGTH_LONG).show();
break;
case 202:
Locale locale2 = new Locale("fr");
Locale.setDefault(locale2);
Configuration config2 = new Configuration();
config2.locale = locale2;
getBaseContext().getResources().updateConfiguration(config2, getBaseContext().getResources().getDisplayMetrics());
Toast.makeText(this, "Locale en Français !", Toast.LENGTH_LONG).show();
break;
}
return super.onOptionsItemSelected(item);
}
}
</code></pre>
<p>AND HERE IS THE MANIFEST :</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cousinHub.ChangeLocale"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".Main"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="3" />
</manifest>
</code></pre>
<p><strong>THIS IS WHAT I FOUND :</strong></p>
<pre><code><uses-sdk android:minSdkVersion="5" />
</code></pre>
<p>=> IT WORKS JUST FINE ...</p>
<pre><code><uses-sdk android:minSdkVersion="3" />
</code></pre>
<p>=> Menu shrinks every time you change the locale !!!</p>
<p>as I want to keep my application accessible for users on 1.5, what should I do ??</p> | <p>After a good night of sleep, I found the answer on the Web (a simple Google search on the following line "<code>getBaseContext().getResources().updateConfiguration(mConfig, getBaseContext().getResources().getDisplayMetrics());</code>"), here it is :</p>
<p><a href="http://adrianvintu.com/blogengine/post/Force-Locale-on-Android.aspx" rel="noreferrer" title="Take a look">link text</a>
=> this link also shows <code>screenshots</code> of what is happening ! </p>
<p><strong>Density was the issue here</strong>, I needed to have this in the AndroidManifest.xml</p>
<pre><code><supports-screens
android:smallScreens="true"
android:normalScreens="true"
android:largeScreens="true"
android:anyDensity="true"
/>
</code></pre>
<p>The most important is the <strong>android:anyDensity =" true "</strong>. </p>
<p>Don't forget to add the following in the <code>AndroidManifest.xml</code> for every activity (for Android 4.1 and below):</p>
<pre><code>android:configChanges="locale"
</code></pre>
<p>This version is needed when you build for Android 4.2 (API level 17) <a href="https://stackoverflow.com/questions/13856229/onconfigurationchanged-is-not-called-over-jellybean4-2-1">explanation here</a>:</p>
<pre><code>android:configChanges="locale|layoutDirection"
</code></pre> | {
"question_id": 2264874,
"question_date": "2010-02-15T09:13:56.610Z",
"question_score": 206,
"tags": "android|menu|locale",
"answer_id": 2271141,
"answer_date": "2010-02-16T07:05:05.957Z",
"answer_score": 63
} |
Please answer the following Stack Overflow question:
Title: Can I invoke an instance method on a Ruby module without including it?
<h3>Background:</h3>
<p>I have a module which declares a number of instance methods</p>
<pre><code>module UsefulThings
def get_file; ...
def delete_file; ...
def format_text(x); ...
end
</code></pre>
<p>And I want to call some of these methods from within a class. How you normally do this in ruby is like this:</p>
<pre><code>class UsefulWorker
include UsefulThings
def do_work
format_text("abc")
...
end
end
</code></pre>
<h3>Problem</h3>
<p><code>include UsefulThings</code> brings in <em>all</em> of the methods from <code>UsefulThings</code>. In this case I only want <code>format_text</code> and explicitly do not want <code>get_file</code> and <code>delete_file</code>.</p>
<p>I can see several possible solutions to this: </p>
<ol>
<li>Somehow invoke the method directly on the module without including it anywhere
<ul>
<li>I don't know how/if this can be done. (Hence this question)</li>
</ul></li>
<li>Somehow include <code>Usefulthings</code> and only bring in some of it's methods
<ul>
<li>I also don't know how/if this can be done</li>
</ul></li>
<li>Create a proxy class, include <code>UsefulThings</code> in that, then delegate <code>format_text</code> to that proxy instance
<ul>
<li>This would work, but anonymous proxy classes are a hack. Yuck.</li>
</ul></li>
<li>Split up the module into 2 or more smaller modules
<ul>
<li>This would also work, and is probably the best solution I can think of, but I'd prefer to avoid it as I'd end up with a proliferation of dozens and dozens of modules - managing this would be burdensome</li>
</ul></li>
</ol>
<p>Why are there lots of unrelated functions in a single module? It's <code>ApplicationHelper</code> from a rails app, which our team has de-facto decided on as the dumping ground for anything not specific enough to belong anywhere else. Mostly standalone utility methods that get used everywhere. I could break it up into seperate helpers, but there'd be 30 of them, all with 1 method each... this seems unproductive</p> | <p>If a method on a module is turned into a module function you can simply call it off of Mods as if it had been declared as</p>
<pre><code>module Mods
def self.foo
puts "Mods.foo(self)"
end
end
</code></pre>
<p>The module_function approach below will avoid breaking any classes which include all of Mods.</p>
<pre><code>module Mods
def foo
puts "Mods.foo"
end
end
class Includer
include Mods
end
Includer.new.foo
Mods.module_eval do
module_function(:foo)
public :foo
end
Includer.new.foo # this would break without public :foo above
class Thing
def bar
Mods.foo
end
end
Thing.new.bar
</code></pre>
<p>However, I'm curious why a set of unrelated functions are all contained within the same module in the first place? </p>
<p><em>Edited</em> to show that includes still work if <code>public :foo</code> is called after <code>module_function :foo</code></p> | {
"question_id": 322470,
"question_date": "2008-11-26T23:03:37.793Z",
"question_score": 206,
"tags": "ruby|module|methods",
"answer_id": 322526,
"answer_date": "2008-11-26T23:27:24.890Z",
"answer_score": 148
} |
Please answer the following Stack Overflow question:
Title: Automatically hard wrap lines at column in VSCode
<p>How can I automatically hard wrap lines in VSCode? By that I mean if a line reaches a specified column, automatically insert a newline at the word boundary closest to that column without going over. Vim has a setting called <a href="http://vim.wikia.com/wiki/Automatic_word_wrapping" rel="noreferrer">textwidth</a> that does this that I like to use when editing Markdown. It doesn't seem like VSCode does, as far as I can tell. It just has ways to control softwrapping.</p> | <p>VSCode doesn't support this out of the box. But you can install the <code>Rewrap</code> extension, which allows you to format the block that your cursor is currently in by pressing <kbd>Alt</kbd> + <kbd>Q</kbd>.</p>
<p><code>Rewrap</code> requires no further settings, since it reads VSCode's settings to obtain the column at which to break.</p>
<p><code>Rewrap</code> also supports automatic wrapping (off by default): <a href="https://github.com/stkb/Rewrap/wiki/Auto-wrap" rel="noreferrer">https://github.com/stkb/Rewrap/wiki/Auto-wrap</a> </p> | {
"question_id": 43122175,
"question_date": "2017-03-30T15:29:12.357Z",
"question_score": 206,
"tags": "visual-studio-code|vscode-settings",
"answer_id": 45839079,
"answer_date": "2017-08-23T11:57:11.623Z",
"answer_score": 258
} |
Please answer the following Stack Overflow question:
Title: How to set timeout in Retrofit library?
<p>I am using <a href="http://square.github.io/retrofit/">Retrofit</a> library in my app, and I'd like to set a timeout of 60 seconds. Does Retrofit have some way to do this? </p>
<p>I set Retrofit this way:</p>
<pre><code>RestAdapter restAdapter = new RestAdapter.Builder()
.setServer(BuildConfig.BASE_URL)
.setConverter(new GsonConverter(gson))
.build();
</code></pre>
<p>How can I set the timeout?</p> | <p>You can set timeouts on the underlying HTTP client. If you don't specify a client, Retrofit will create one with default connect and read timeouts. To set your own timeouts, you need to configure your own client and supply it to the <code>RestAdapter.Builder</code>.</p>
<p>An option is to use the <a href="http://square.github.io/okhttp/" rel="noreferrer">OkHttp</a> client, also from Square.</p>
<p><strong>1. Add the library dependency</strong></p>
<p>In the build.gradle, include this line:</p>
<pre><code>compile 'com.squareup.okhttp:okhttp:x.x.x'
</code></pre>
<p><em>Where <code>x.x.x</code> is the desired library version.</em></p>
<p><strong>2. Set the client</strong> </p>
<p>For example, if you want to set a timeout of 60 seconds, do this way for Retrofit before version 2 and Okhttp before version 3 (<strong><em>FOR THE NEWER VERSIONS, SEE THE EDITS</em></strong>):</p>
<pre><code>public RestAdapter providesRestAdapter(Gson gson) {
final OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setReadTimeout(60, TimeUnit.SECONDS);
okHttpClient.setConnectTimeout(60, TimeUnit.SECONDS);
return new RestAdapter.Builder()
.setEndpoint(BuildConfig.BASE_URL)
.setConverter(new GsonConverter(gson))
.setClient(new OkClient(okHttpClient))
.build();
}
</code></pre>
<hr>
<p><strong>EDIT 1</strong></p>
<p>For okhttp versions since <code>3.x.x</code>, you have to set the dependency this way:</p>
<pre><code>compile 'com.squareup.okhttp3:okhttp:x.x.x'
</code></pre>
<p>And set the client using the builder pattern:</p>
<pre><code>final OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
.build();
</code></pre>
<p>More info in <a href="https://square.github.io/okhttp/recipes/#timeouts-kt-java" rel="noreferrer">Timeouts</a></p>
<hr>
<p><strong>EDIT 2</strong></p>
<p>Retrofit versions since <code>2.x.x</code> also uses the builder pattern, so change the return block above to this:</p>
<pre><code>return new Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();
</code></pre>
<p>If using a code like my <code>providesRestAdapter</code> method, then change the method return type to <a href="https://square.github.io/retrofit/2.x/retrofit/" rel="noreferrer">Retrofit</a>.</p>
<p>More info in <a href="https://futurestud.io/blog/retrofit-2-upgrade-guide-from-1-9" rel="noreferrer">Retrofit 2 — Upgrade Guide from 1.9
</a></p>
<hr>
<p>ps: If your minSdkVersion is greater than 8, you can use <code>TimeUnit.MINUTES</code>:</p>
<pre><code>okHttpClient.setReadTimeout(1, TimeUnit.MINUTES);
okHttpClient.setConnectTimeout(1, TimeUnit.MINUTES);
</code></pre>
<p>For more details about the units, see <a href="http://developer.android.com/reference/java/util/concurrent/TimeUnit.html" rel="noreferrer">TimeUnit</a>.</p> | {
"question_id": 29380844,
"question_date": "2015-04-01T00:26:12.033Z",
"question_score": 206,
"tags": "java|android|timeout|retrofit",
"answer_id": 29380845,
"answer_date": "2015-04-01T00:26:12.033Z",
"answer_score": 360
} |
Please answer the following Stack Overflow question:
Title: How to use C++ in Go
<p>In the new <a href="http://golang.org/" rel="noreferrer">Go</a> language, how do I call C++ code? In other words, how can I wrap my C++ classes and use them in Go?</p> | <p><strong>Update:</strong> I've succeeded in linking a small test C++ class with Go</p>
<p>If you wrap you C++ code with a C interface you should be able to call your library with cgo (see the example of gmp in <code>$GOROOT/misc/cgo/gmp</code>). </p>
<p>I'm not sure if the idea of a class in C++ is really expressible in Go, as it doesn't have inheritance.</p>
<p>Here's an example:</p>
<p>I have a C++ class defined as:</p>
<pre><code>// foo.hpp
class cxxFoo {
public:
int a;
cxxFoo(int _a):a(_a){};
~cxxFoo(){};
void Bar();
};
// foo.cpp
#include <iostream>
#include "foo.hpp"
void
cxxFoo::Bar(void){
std::cout<<this->a<<std::endl;
}
</code></pre>
<p>which I want to use in Go. I'll use the C interface</p>
<pre><code>// foo.h
#ifdef __cplusplus
extern "C" {
#endif
typedef void* Foo;
Foo FooInit(void);
void FooFree(Foo);
void FooBar(Foo);
#ifdef __cplusplus
}
#endif
</code></pre>
<p>(I use a <code>void*</code> instead of a C struct so the compiler knows the size of Foo)</p>
<p>The implementation is:</p>
<pre><code>//cfoo.cpp
#include "foo.hpp"
#include "foo.h"
Foo FooInit()
{
cxxFoo * ret = new cxxFoo(1);
return (void*)ret;
}
void FooFree(Foo f)
{
cxxFoo * foo = (cxxFoo*)f;
delete foo;
}
void FooBar(Foo f)
{
cxxFoo * foo = (cxxFoo*)f;
foo->Bar();
}
</code></pre>
<p>with all that done, the Go file is:</p>
<pre><code>// foo.go
package foo
// #include "foo.h"
import "C"
import "unsafe"
type GoFoo struct {
foo C.Foo;
}
func New()(GoFoo){
var ret GoFoo;
ret.foo = C.FooInit();
return ret;
}
func (f GoFoo)Free(){
C.FooFree(unsafe.Pointer(f.foo));
}
func (f GoFoo)Bar(){
C.FooBar(unsafe.Pointer(f.foo));
}
</code></pre>
<p>The makefile I used to compile this was:</p>
<pre><code>// makefile
TARG=foo
CGOFILES=foo.go
include $(GOROOT)/src/Make.$(GOARCH)
include $(GOROOT)/src/Make.pkg
foo.o:foo.cpp
g++ $(_CGO_CFLAGS_$(GOARCH)) -fPIC -O2 -o $@ -c $(CGO_CFLAGS) $<
cfoo.o:cfoo.cpp
g++ $(_CGO_CFLAGS_$(GOARCH)) -fPIC -O2 -o $@ -c $(CGO_CFLAGS) $<
CGO_LDFLAGS+=-lstdc++
$(elem)_foo.so: foo.cgo4.o foo.o cfoo.o
gcc $(_CGO_CFLAGS_$(GOARCH)) $(_CGO_LDFLAGS_$(GOOS)) -o $@ $^ $(CGO_LDFLAGS)
</code></pre>
<p>Try testing it with:</p>
<pre><code>// foo_test.go
package foo
import "testing"
func TestFoo(t *testing.T){
foo := New();
foo.Bar();
foo.Free();
}
</code></pre>
<p>You'll need to install the shared library with make install, then run make test. Expected output is:</p>
<pre><code>gotest
rm -f _test/foo.a _gotest_.6
6g -o _gotest_.6 foo.cgo1.go foo.cgo2.go foo_test.go
rm -f _test/foo.a
gopack grc _test/foo.a _gotest_.6 foo.cgo3.6
1
PASS
</code></pre> | {
"question_id": 1713214,
"question_date": "2009-11-11T05:25:13.433Z",
"question_score": 206,
"tags": "c++|wrapper|go",
"answer_id": 1721230,
"answer_date": "2009-11-12T10:12:05.653Z",
"answer_score": 184
} |
Please answer the following Stack Overflow question:
Title: What's the difference between KeyDown and KeyPress in .NET?
<p>What is the difference between the <code>KeyDown</code> and <code>KeyPress</code> events in .NET?</p> | <p>There is apparently <em>a lot</em> of misunderstanding about this!</p>
<p>The only practical difference between <code>KeyDown</code> and <code>KeyPress</code> is that <code>KeyPress</code> relays the character resulting from a keypress, and is only called if there is one.</p>
<p>In other words, if you press <kbd>A</kbd> on your keyboard, you'll get this sequence of events:</p>
<ol>
<li>KeyDown: KeyCode=Keys.A, KeyData=Keys.A, Modifiers=Keys.None</li>
<li>KeyPress: KeyChar='a'</li>
<li>KeyUp: KeyCode=Keys.A</li>
</ol>
<p>But if you press <kbd>Shift</kbd>+<kbd>A</kbd>, you'll get:</p>
<ol>
<li>KeyDown: KeyCode=Keys.ShiftKey, KeyData=Keys.ShiftKey, Shift, Modifiers=Keys.Shift</li>
<li>KeyDown: KeyCode=Keys.A, KeyData=Keys.A | Keys.Shift, Modifiers=Keys.Shift</li>
<li>KeyPress: KeyChar='A'</li>
<li>KeyUp: KeyCode=Keys.A</li>
<li>KeyUp: KeyCode=Keys.ShiftKey</li>
</ol>
<p>If you hold down the keys for a while, you'll get something like:</p>
<ol>
<li>KeyDown: KeyCode=Keys.ShiftKey, KeyData=Keys.ShiftKey, Shift, Modifiers=Keys.Shift</li>
<li>KeyDown: KeyCode=Keys.ShiftKey, KeyData=Keys.ShiftKey, Shift, Modifiers=Keys.Shift</li>
<li>KeyDown: KeyCode=Keys.ShiftKey, KeyData=Keys.ShiftKey, Shift, Modifiers=Keys.Shift</li>
<li>KeyDown: KeyCode=Keys.ShiftKey, KeyData=Keys.ShiftKey, Shift, Modifiers=Keys.Shift</li>
<li>KeyDown: KeyCode=Keys.ShiftKey, KeyData=Keys.ShiftKey, Shift, Modifiers=Keys.Shift</li>
<li>KeyDown: KeyCode=Keys.A, KeyData=Keys.A | Keys.Shift, Modifiers=Keys.Shift</li>
<li>KeyPress: KeyChar='A'</li>
<li>KeyDown: KeyCode=Keys.A, KeyData=Keys.A | Keys.Shift, Modifiers=Keys.Shift</li>
<li>KeyPress: KeyChar='A'</li>
<li>KeyDown: KeyCode=Keys.A, KeyData=Keys.A | Keys.Shift, Modifiers=Keys.Shift</li>
<li>KeyPress: KeyChar='A'</li>
<li>KeyDown: KeyCode=Keys.A, KeyData=Keys.A | Keys.Shift, Modifiers=Keys.Shift</li>
<li>KeyPress: KeyChar='A'</li>
<li>KeyDown: KeyCode=Keys.A, KeyData=Keys.A | Keys.Shift, Modifiers=Keys.Shift</li>
<li>KeyPress: KeyChar='A'</li>
<li>KeyUp: KeyCode=Keys.A</li>
<li>KeyUp: KeyCode=Keys.ShiftKey</li>
</ol>
<p>Notice that <code>KeyPress</code> occurs <em>in between</em> <code>KeyDown</code> and <code>KeyUp</code>, <strong>not</strong> after <code>KeyUp</code>, as many of the other answers have stated, that <code>KeyPress</code> is not called when a character isn't generated, and that <code>KeyDown</code> is repeated while the key is held down, also contrary to many of the other answers.</p>
<p>Examples of keys that do <strong>not</strong> directly result in calls to <code>KeyPress</code>:</p>
<ul>
<li><kbd>Shift</kbd>, <kbd>Ctrl</kbd>, <kbd>Alt</kbd></li>
<li><kbd>F1</kbd> through <kbd>F12</kbd></li>
<li>Arrow keys</li>
</ul>
<p>Examples of keys that <strong>do</strong> result in calls to <code>KeyPress</code>:</p>
<ul>
<li><kbd>A</kbd> through <kbd>Z</kbd>, <kbd>0</kbd> through <kbd>9</kbd>, etc.</li>
<li><kbd>Spacebar</kbd></li>
<li><kbd>Tab</kbd> (KeyChar='\t', ASCII 9)</li>
<li><kbd>Enter</kbd> (KeyChar='\r', ASCII 13)</li>
<li><kbd>Esc</kbd> (KeyChar='\x1b', ASCII 27)</li>
<li><kbd>Backspace</kbd> (KeyChar='\b', ASCII 8)</li>
</ul>
<p>For the curious, <code>KeyDown</code> roughly correlates to <code>WM_KEYDOWN</code>, <code>KeyPress</code> to <code>WM_CHAR</code>, and <code>KeyUp</code> to <code>WM_KEYUP</code>. <code>WM_KEYDOWN</code> <em>can</em> be called fewer than the the number of key repeats, but it sends a repeat count, which, IIRC, WinForms uses to generate exactly one KeyDown per repeat.</p> | {
"question_id": 1367700,
"question_date": "2009-09-02T13:30:55.550Z",
"question_score": 206,
"tags": ".net",
"answer_id": 1367865,
"answer_date": "2009-09-02T13:58:31.270Z",
"answer_score": 342
} |
Please answer the following Stack Overflow question:
Title: Disable EditText blinking cursor
<p>Does anyone know how to disable the blinking cursor in an <code>EditText</code> view?</p> | <p>You can use either the xml attribute <code>android:cursorVisible="false"</code> or programatically:</p>
<ul>
<li>java: <code>view.setCursorVisible(false)</code></li>
<li>kotlin: <code>view.isCursorVisible = false</code></li>
</ul> | {
"question_id": 5582702,
"question_date": "2011-04-07T14:27:29.900Z",
"question_score": 206,
"tags": "android|android-edittext",
"answer_id": 5837078,
"answer_date": "2011-04-29T20:29:34.563Z",
"answer_score": 388
} |
Please answer the following Stack Overflow question:
Title: How can I publish an npm package with distribution files?
<p>I would like to publish a npm package that contains my source as well as distribution files. My GitHub repository contains <code>src</code> folder which contains JavaScript source files. The build process generates <code>dist</code> folder that contains the distribution files. Of course, the <code>dist</code> folder is not checked into the GitHub repository.</p>
<p>How do I publish a npm package in a way that when someone does <code>npm install</code>, they get <code>src</code> as well as <code>dist</code> folder? Currently when I run <code>npm publish</code> from my Git repository, it results in only the <code>src</code> folder being published.</p>
<p>My <em>package.json</em> file looks like this:</p>
<pre><code>{
"name": "join-js",
"version": "0.0.1",
"homepage": "https://github.com/archfirst/joinjs",
"repository": {
"type": "git",
"url": "https://github.com/archfirst/joinjs.git"
},
"main": "dist/index.js",
"scripts": {
"test": "gulp",
"build": "gulp build",
"prepublish": "npm run build"
},
"dependencies": {
...
},
"devDependencies": {
...
}
}
</code></pre> | <p>Take a look at the "files" field of package.json file:
<em><a href="https://docs.npmjs.com/cli/v8/configuring-npm/package-json/#files" rel="nofollow noreferrer">package.json, files</a></em></p>
<p>From the documentation:</p>
<blockquote>
<p>The "files" field is an array of files to include in your project. If you name a folder in the array, then it will also include the files inside that folder. (Unless they would be ignored by another rule.)</p>
</blockquote> | {
"question_id": 31642477,
"question_date": "2015-07-26T22:14:10.617Z",
"question_score": 206,
"tags": "node.js|git|github|npm",
"answer_id": 31642620,
"answer_date": "2015-07-26T22:33:47.830Z",
"answer_score": 154
} |
Please answer the following Stack Overflow question:
Title: Breadth First Vs Depth First
<p>When Traversing a Tree/Graph what is the difference between Breadth First and Depth first? Any coding or pseudocode examples would be great.</p> | <p>These two terms differentiate between two different ways of walking a tree.</p>
<p>It is probably easiest just to exhibit the difference. Consider the tree:</p>
<pre><code> A
/ \
B C
/ / \
D E F
</code></pre>
<p>A <strong>depth</strong> first traversal would visit the nodes in this order</p>
<pre><code>A, B, D, C, E, F
</code></pre>
<p>Notice that you go all the way <strong>down</strong> one leg before moving on.</p>
<p>A <strong>breadth</strong> first traversal would visit the node in this order</p>
<pre><code>A, B, C, D, E, F
</code></pre>
<p>Here we work all the way <strong>across</strong> each level before going down.</p>
<p>(Note that there is some ambiguity in the traversal orders, and I've cheated to maintain the "reading" order at each level of the tree. In either case I could get to B before or after C, and likewise I could get to E before or after F. This may or may not matter, depends on you application...)</p>
<hr>
<p>Both kinds of traversal can be achieved with the pseudocode:</p>
<pre><code>Store the root node in Container
While (there are nodes in Container)
N = Get the "next" node from Container
Store all the children of N in Container
Do some work on N
</code></pre>
<p>The difference between the two traversal orders lies in the choice of <code>Container</code>. </p>
<ul>
<li>For <strong>depth first</strong> use a stack. (The recursive implementation uses the call-stack...)</li>
<li>For <strong>breadth-first</strong> use a queue.</li>
</ul>
<hr>
<p>The recursive implementation looks like</p>
<pre><code>ProcessNode(Node)
Work on the payload Node
Foreach child of Node
ProcessNode(child)
/* Alternate time to work on the payload Node (see below) */
</code></pre>
<p>The recursion ends when you reach a node that has no children, so it is guaranteed to end for
finite, acyclic graphs.</p>
<hr>
<p>At this point, I've still cheated a little. With a little cleverness you can also <em>work-on</em> the nodes in this order:</p>
<pre><code>D, B, E, F, C, A
</code></pre>
<p>which is a variation of depth-first, where I don't do the work at each node until I'm walking back up the tree. I have however <em>visited</em> the higher nodes on the way down to find their children.</p>
<p>This traversal is fairly natural in the recursive implementation (use the "Alternate time" line above instead of the first "Work" line), and not <em>too</em> hard if you use a explicit stack, but I'll leave it as an exercise.</p> | {
"question_id": 687731,
"question_date": "2009-03-26T21:59:16.060Z",
"question_score": 206,
"tags": "algorithm|recursion|depth-first-search|breadth-first-search|tree-traversal",
"answer_id": 687752,
"answer_date": "2009-03-26T22:08:12.123Z",
"answer_score": 339
} |
Please answer the following Stack Overflow question:
Title: Where and how is the _ViewStart.cshtml layout file linked?
<p>Here's the About.cshtml from the default MVC 3 template:</p>
<pre><code>@{
ViewBag.Title = "About Us";
}
<h2>About</h2>
<p>
Put content here.
</p>
</code></pre>
<p>I would expect that a reference to the _ViewStart file would be found in the <code>About.cshtml</code>, but clearly it's not.</p>
<p>I've looked in <code>global.asax</code> and <code>web.config</code>, but I can't find out how the <code>About.cshtml</code> file is "linked" with the layout from the _ViewStart file. </p>
<p>Everything works as expected, I'd just like to know what's going on under the hood...</p> | <p>From <a href="http://weblogs.asp.net/scottgu/archive/2010/10/22/asp-net-mvc-3-layouts.aspx" rel="noreferrer">ScottGu's blog</a>:</p>
<blockquote>
<p>Starting with the ASP.NET MVC 3 Beta release, you can now add a file
called _ViewStart.cshtml (or _ViewStart.vbhtml for VB) underneath the
\Views folder of your project:</p>
<p>The _ViewStart file can be used to define common view code that you
want to execute at the start of each View’s rendering. For example,
we could write code within our _ViewStart.cshtml file to
programmatically set the Layout property for each View to be the
SiteLayout.cshtml file by default:</p>
<p>Because this code executes at the start of each View, we no longer
need to explicitly set the Layout in any of our individual view files
(except if we wanted to override the default value above).</p>
<p>Important: Because the _ViewStart.cshtml allows us to write code, we
can optionally make our Layout selection logic richer than just a
basic property set. For example: we could vary the Layout template
that we use depending on what type of device is accessing the site –
and have a phone or tablet optimized layout for those devices, and a
desktop optimized layout for PCs/Laptops. Or if we were building a
CMS system or common shared app that is used across multiple customers
we could select different layouts to use depending on the customer (or
their role) when accessing the site.</p>
<p>This enables a lot of UI flexibility. It also allows you to more
easily write view logic once, and avoid repeating it in multiple
places.</p>
</blockquote>
<p>Also see <a href="http://weblogs.asp.net/gunnarpeipman/archive/2010/10/10/asp-net-mvc-3-beta-view-start-files-for-razor-view-engine.aspx" rel="noreferrer">this</a>.</p> | {
"question_id": 9300410,
"question_date": "2012-02-15T19:59:07.763Z",
"question_score": 206,
"tags": ".net|asp.net-mvc|asp.net-mvc-3|razor",
"answer_id": 9300466,
"answer_date": "2012-02-15T20:03:38.373Z",
"answer_score": 246
} |
Please answer the following Stack Overflow question:
Title: Annotating text on individual facet in ggplot2
<p>I want to annotate some text on last facet of the plot with the following code:</p>
<pre><code>library(ggplot2)
p <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
p <- p + facet_grid(. ~ cyl)
p <- p + annotate("text", label = "Test", size = 4, x = 15, y = 5)
print(p)
</code></pre>
<p><img src="https://i.stack.imgur.com/KBsmL.png" alt="enter image description here" /></p>
<p>But this code annotates the text on every facet. How can I get the annotated text on only one facet?</p> | <p>Function <code>annotate()</code> adds the same label to all panels in a plot with facets. If the intention is to add different annotations to each panel, or annotations to only some panels, a <em>geometry</em> has to be used instead of <code>annotate()</code>. To use a geometry, such as <code>geom_text()</code> we need to assemble a data frame containing the text of the labels in one column and columns for the variables to be mapped to other aesthetics, as well as the variable(s) used for faceting.</p>
<p>Typically you'd do something like this:</p>
<pre><code>ann_text <- data.frame(mpg = 15,wt = 5,lab = "Text",
cyl = factor(8,levels = c("4","6","8")))
p + geom_text(data = ann_text,label = "Text")
</code></pre>
<p>It should work without specifying the factor variable completely, but will probably throw some warnings:</p>
<p><img src="https://i.stack.imgur.com/FNWuB.png" alt="enter image description here" /></p> | {
"question_id": 11889625,
"question_date": "2012-08-09T18:21:29.203Z",
"question_score": 206,
"tags": "r|ggplot2|facet|facet-wrap|facet-grid",
"answer_id": 11889798,
"answer_date": "2012-08-09T18:34:30.997Z",
"answer_score": 184
} |
Please answer the following Stack Overflow question:
Title: How does interfaces with construct signatures work?
<p>I am having some trouble working out how defining constructors in interfaces work. I might be totally misunderstanding something. But I have searched for answers for a good while and I can not find anything related to this. </p>
<p>How do I implement the following interface in a TypeScript class: </p>
<pre><code>interface MyInterface {
new ( ... ) : MyInterface;
}
</code></pre>
<p>Anders Hejlsberg creates an interface containing something similar to this in this <a href="http://media.ch9.ms/ch9/c3e5/e5e02f2e-5962-48db-9ddd-85e27a4fc3e5/IntroducingTSAndersH_mid.mp4">video</a> (at around 14 minutes). But for the life of me I can not implement this in a class.</p>
<p>I am probably misunderstanding something, what am I not getting? </p>
<p>EDIT: </p>
<p>To clarify. With "new ( ... )" I meant "anything". My problem is that I can not get even the most basic version of this working: </p>
<pre><code>interface MyInterface {
new () : MyInterface;
}
class test implements MyInterface {
constructor () { }
}
</code></pre>
<p>This is not compiling for me I get "Class 'test' declares interface 'MyInterface' but does not implement it: Type 'MyInterface' requires a construct signature, but Type 'test' lacks one" when trying to compile it.</p>
<p>EDIT: </p>
<p>So after researching this a bit more given the feedback. </p>
<pre><code>interface MyInterface {
new () : MyInterface;
}
class test implements MyInterface {
constructor () => test { return this; }
}
</code></pre>
<p>Is not valid TypeScript and this does not solve the problem. You can not define the return type of the constructor. It will return "test". The signature of the following:
class test {
constructor () { }
}
Seems to be "new () => test" (obtained by hovering over "class" in the online editor with just that code pasted in). And this is what we would want and what i thought it would be. </p>
<p>Can anyone provide an example of this or something similar where it is actually compiling? </p>
<p>EDIT (again...):</p>
<p>So I might have come up with an idea as to why it is possible to define this in an interface but not possible to implement in a TypeScript class.The following works: </p>
<pre><code>var MyClass = (function () {
function MyClass() { }
return MyClass;
})();
interface MyInterface {
new () : MyInterface;
}
var testFunction = (foo: MyInterface) : void => { }
var bar = new MyClass();
testFunction(bar);
</code></pre>
<p>So is this only a feature of TypeScript that lets you interface javascript? Or is it possible to implement it in TypeScript without having to implement the class using javascript? </p> | <p>
Construct signatures in interfaces are not implementable in classes; they're only for defining existing JS APIs that define a 'new'-able function. Here's an example involving interfaces <code>new</code> signatures that does work:</p>
<pre class="lang-js prettyprint-override"><code>interface ComesFromString {
name: string;
}
interface StringConstructable {
new(n: string): ComesFromString;
}
class MadeFromString implements ComesFromString {
constructor (public name: string) {
console.log('ctor invoked');
}
}
function makeObj(n: StringConstructable) {
return new n('hello!');
}
console.log(makeObj(MadeFromString).name);
</code></pre>
<p>This creates an actual constraint for what you can invoke <code>makeObj</code> with:</p>
<pre class="lang-js prettyprint-override"><code>class Other implements ComesFromString {
constructor (public name: string, count: number) {
}
}
makeObj(Other); // Error! Other's constructor doesn't match StringConstructable
</code></pre> | {
"question_id": 13407036,
"question_date": "2012-11-15T22:03:36.570Z",
"question_score": 206,
"tags": "typescript|constructor|interface",
"answer_id": 13408029,
"answer_date": "2012-11-15T23:26:41.107Z",
"answer_score": 199
} |
Please answer the following Stack Overflow question:
Title: Disable webkit's spin buttons on input type="number"?
<p>I have a site which is primarily for mobile users but desktop too.</p>
<p>On Mobile Safari, using <code><input type="number"></code> works great because it brings up the numerical keyboard on input fields which should only contain numbers.</p>
<p>In Chrome and Safari however, using number inputs displays spin buttons at the right side of the field, which looks like crap in my design. I really don't need the buttons, because they are useless when you need to write something like a 6-digit number anyway.</p>
<p>Is it possible to disable this with <code>-webkit-appearance</code> or some other CSS trick? I have tried without much luck.</p> | <p>The below css works for both Chrome and Firefox</p>
<pre><code>input[type=number]::-webkit-outer-spin-button,
input[type=number]::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
input[type=number] {
-moz-appearance:textfield;
}
</code></pre> | {
"question_id": 3975769,
"question_date": "2010-10-20T07:53:35.347Z",
"question_score": 206,
"tags": "css|html|webkit",
"answer_id": 26379166,
"answer_date": "2014-10-15T09:36:59.053Z",
"answer_score": 118
} |
Please answer the following Stack Overflow question:
Title: What would a "frozen dict" be?
<ul>
<li>A frozen set is a frozenset. </li>
<li>A frozen list could be a tuple. </li>
<li>What would a frozen dict be? An immutable, hashable dict. </li>
</ul>
<p>I guess it could be something like <code>collections.namedtuple</code>, but that is more like a frozen-keys dict (a half-frozen dict). Isn't it?</p>
<p>A "frozendict" should be a frozen dictionary, it should have <code>keys</code>, <code>values</code>, <code>get</code>, etc., and support <code>in</code>, <code>for</code>, etc.</p>
<p>update :<br>
* there it is : <a href="https://www.python.org/dev/peps/pep-0603" rel="noreferrer">https://www.python.org/dev/peps/pep-0603</a></p> | <p>Python doesn't have a builtin frozendict type. It turns out this wouldn't be useful too often (though it would still probably be useful more often than <code>frozenset</code> is).</p>
<p>The most common reason to want such a type is when memoizing function calls for functions with unknown arguments. The most common solution to store a hashable equivalent of a dict (where the values are hashable) is something like <code>tuple(sorted(kwargs.items()))</code>.</p>
<p>This depends on the sorting not being a bit insane. Python cannot positively promise sorting will result in something reasonable here. (But it can't promise much else, so don't sweat it too much.)</p>
<hr />
<p>You could easily enough make some sort of wrapper that works much like a dict. It might look something like</p>
<pre><code>import collections
class FrozenDict(collections.Mapping):
"""Don't forget the docstrings!!"""
def __init__(self, *args, **kwargs):
self._d = dict(*args, **kwargs)
self._hash = None
def __iter__(self):
return iter(self._d)
def __len__(self):
return len(self._d)
def __getitem__(self, key):
return self._d[key]
def __hash__(self):
# It would have been simpler and maybe more obvious to
# use hash(tuple(sorted(self._d.iteritems()))) from this discussion
# so far, but this solution is O(n). I don't know what kind of
# n we are going to run into, but sometimes it's hard to resist the
# urge to optimize when it will gain improved algorithmic performance.
if self._hash is None:
hash_ = 0
for pair in self.items():
hash_ ^= hash(pair)
self._hash = hash_
return self._hash
</code></pre>
<p>It should work great:</p>
<pre><code>>>> x = FrozenDict(a=1, b=2)
>>> y = FrozenDict(a=1, b=2)
>>> x is y
False
>>> x == y
True
>>> x == {'a': 1, 'b': 2}
True
>>> d = {x: 'foo'}
>>> d[y]
'foo'
</code></pre> | {
"question_id": 2703599,
"question_date": "2010-04-24T07:19:50.867Z",
"question_score": 206,
"tags": "python|dictionary|data-structures|immutability",
"answer_id": 2704866,
"answer_date": "2010-04-24T14:52:17.727Z",
"answer_score": 141
} |
Please answer the following Stack Overflow question:
Title: Show current state of Jenkins build on GitHub repo
<p>Is there a way to show the Jenkins build status on my project's GitHub Readme.md? </p>
<p>I use Jenkins to run continuous integration builds. After each commit it ensures that everything compiles, as well as executes unit and integration tests, before finally producing documentation and release bundles. </p>
<p>There's still a risk of inadvertently committing something that breaks the build. It would be good for users visiting the GitHub project page to know the current master is in that state. </p> | <p>Ok, here's how you can set up Jenkins to set GitHub build statuses. This assumes you've already got Jenkins with the GitHub plugin configured to do builds on every push.</p>
<ol>
<li><p>Go to GitHub, log in, go to <strong>Settings</strong>, <strong>Developer Settings</strong>, <strong>Personal access tokens</strong> and click on <strong>Generate new token</strong>.</p>
<p><img src="https://i.stack.imgur.com/ecNwN.png" alt="screenshot of generate new token" /></p>
</li>
<li><p>Check <strong>repo:status</strong> (I'm not sure this is necessary, but I did it, and it worked for me).</p>
<p><img src="https://i.stack.imgur.com/0tXw9.png" alt="screenshot of generate new token" /></p>
</li>
<li><p>Generate the token, copy it.</p>
</li>
<li><p>Make sure the GitHub user you're going to use is a repository collaborator (for private repos) or is a member of a team with push and pull access (for organization repos) to the repositories you want to build.</p>
</li>
<li><p>Go to your Jenkins server, log in.</p>
</li>
<li><p><strong>Manage Jenkins</strong> → <strong>Configure System</strong></p>
</li>
<li><p>Under <strong>GitHub Web Hook</strong> select <strong>Let Jenkins auto-manage hook URLs</strong>, then specify your GitHub <strong>username</strong> and the <strong>OAuth token</strong> you got in step 3.</p>
<p><img src="https://i.stack.imgur.com/Wshl8.png" alt="screenshot of Jenkins global settings" /></p>
</li>
<li><p>Verify that it works with the <strong>Test Credential</strong> button. <strong>Save</strong> the settings.</p>
</li>
<li><p>Find the Jenkins job and add <strong>Set build status on GitHub commit</strong> to the post-build steps</p>
<p><img src="https://i.stack.imgur.com/3LaMZ.png" alt="screenshot of Jenkins job configuration" /></p>
</li>
</ol>
<p>That's it. Now do a test build and go to GitHub repository to see if it worked. Click on <strong>Branches</strong> in the main repository page to see build statuses.</p>
<p><img src="https://i.stack.imgur.com/m9N0U.png" alt="sceenshot of the main page where you click on 'branches'" /></p>
<p>You should see green checkmarks:</p>
<p><img src="https://i.stack.imgur.com/0gFo6.png" alt="screenshot of GitHub branches with build status" /></p> | {
"question_id": 14274293,
"question_date": "2013-01-11T08:31:04.223Z",
"question_score": 206,
"tags": "github|jenkins",
"answer_id": 26910986,
"answer_date": "2014-11-13T14:19:21.810Z",
"answer_score": 175
} |
Please answer the following Stack Overflow question:
Title: How to commit no change and new message?
<p>How can I make a new <code>commit</code> and create a new message if no changes are made to files?</p>
<p>Is this not possible since the commit's code (SHA ?) will be the same?</p> | <p>There's rarely a good reason to do this, but the parameter is <code>--allow-empty</code> for empty commits (no files changed), in contrast to <code>--allow-empty-message</code> for empty commit messages. You can also read more by typing <code>git help commit</code> or visiting <a href="http://www.kernel.org/pub/software/scm/git/docs/git-commit.html" rel="noreferrer">the online documentation</a>.</p>
<p>While the tree object (which has a hash of its own) will be identical, the commit will actually have a different hash, because it will presumably have a different timestamp and message, and will definitely have a different parent commit. All three of those factors are integrated into <code>git</code>'s object hash algorithm.</p>
<hr />
<p>There <em>are</em> a few reasons you might want an empty commit (incorporating some of the comments):</p>
<ul>
<li>As a "declarative commit", to add narration or documentation (via <a href="https://stackoverflow.com/users/640243/davidneiss">DavidNeiss</a>) including after-the-fact data about passing tests or lint (via <a href="https://stackoverflow.com/users/2338813/robert-balicki">Robert Balicki</a>).</li>
<li>To test <code>git</code> commands without generating arbitrary changes (via <a href="https://stackoverflow.com/users/2640937/vaelus">Vaelus</a>).</li>
<li>To re-create a deleted bare repository using <code>gitolite</code> (via <a href="https://stackoverflow.com/users/374110/tatsh">Tatsh</a>).</li>
<li>To arbitrarily create a new commit, such as for re-triggering build tooling (via <a href="https://stackoverflow.com/users/3287927/mattlummus">mattLummus</a>) or for the sake of personal logging or metrics (via <a href="https://stackoverflow.com/users/457586/dynamitereed">DynamiteReed</a>). However, think twice: depending on your branch/merge structure, commits may live for a very long time, so a "just commit nothing" strategy may be inadvertently pollute your team's repository with temporary workflow artifacts and make it hard to separate code revisions from ephemeral cruft.</li>
</ul>
<p>Other strategies to add metadata to a commit tree include:</p>
<ul>
<li>Separate branches or lightweight tags that always point to a commit of a particular status (e.g. "last accepted commit" or "current staging commit").</li>
<li><a href="https://git-scm.com/book/en/v2/Git-Basics-Tagging" rel="noreferrer">Annotated Tags</a> for a way to record timestamp, committer, and message, pointing to an existing commit without adding an entry in the commit tree itself.</li>
<li><a href="http://git-scm.com/docs/git-notes" rel="noreferrer"><code>git notes</code></a> to associate a mutable note on top of an existing immutable commit.</li>
</ul> | {
"question_id": 12470029,
"question_date": "2012-09-18T03:33:57.637Z",
"question_score": 206,
"tags": "git|commit",
"answer_id": 12470056,
"answer_date": "2012-09-18T03:38:07.303Z",
"answer_score": 262
} |
Please answer the following Stack Overflow question:
Title: How to efficiently compare two unordered lists (not sets)?
<pre><code>a = [1, 2, 3, 1, 2, 3]
b = [3, 2, 1, 3, 2, 1]
</code></pre>
<p>a & b should be considered equal, because they have exactly the same elements, only in different order.</p>
<p>The thing is, my actual lists will consist of objects (my class instances), not integers.</p> | <p><strong>O(n)</strong>: The <em><a href="https://docs.python.org/3.5/library/collections.html#collections.Counter" rel="noreferrer">Counter()</a></em> method is best (if your objects are hashable):</p>
<pre><code>def compare(s, t):
return Counter(s) == Counter(t)
</code></pre>
<p><strong>O(n log n)</strong>: The <em><a href="https://docs.python.org/3.5/library/functions.html#sorted" rel="noreferrer">sorted()</a></em> method is next best (if your objects are orderable):</p>
<pre><code>def compare(s, t):
return sorted(s) == sorted(t)
</code></pre>
<p><strong>O(n * n)</strong>: If the objects are neither hashable, nor orderable, you can use equality:</p>
<pre><code>def compare(s, t):
t = list(t) # make a mutable copy
try:
for elem in s:
t.remove(elem)
except ValueError:
return False
return not t
</code></pre> | {
"question_id": 7828867,
"question_date": "2011-10-19T22:13:02.587Z",
"question_score": 206,
"tags": "python|algorithm|list|comparison",
"answer_id": 7829388,
"answer_date": "2011-10-19T23:20:37.200Z",
"answer_score": 336
} |
Please answer the following Stack Overflow question:
Title: getMonth in javascript gives previous month
<p>I am using a datepicker which gives a date in the format Sun Jul 7 00:00:00 EDT 2013.
Even though the month says July, if I do a getMonth, it gives me the previous month.</p>
<pre><code>var d1 = new Date("Sun Jul 7 00:00:00 EDT 2013");
d1.getMonth());//gives 6 instead of 7
</code></pre>
<p>What am I doing wrong?</p> | <p>Because <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMonth">getmonth()</a> start from 0. You may want to have <code>d1.getMonth() + 1</code> to achieve what you want.</p> | {
"question_id": 18624326,
"question_date": "2013-09-04T21:46:32.013Z",
"question_score": 206,
"tags": "javascript|date",
"answer_id": 18624336,
"answer_date": "2013-09-04T21:47:17.580Z",
"answer_score": 400
} |
Please answer the following Stack Overflow question:
Title: Adding information to an exception?
<p>I want to achieve something like this:</p>
<pre><code>def foo():
try:
raise IOError('Stuff ')
except:
raise
def bar(arg1):
try:
foo()
except Exception as e:
e.message = e.message + 'happens at %s' % arg1
raise
bar('arg1')
</code></pre>
<pre class="lang-none prettyprint-override"><code>Traceback...
IOError('Stuff Happens at arg1')
</code></pre>
<p>But what I get is:</p>
<pre class="lang-none prettyprint-override"><code>Traceback..
IOError('Stuff')
</code></pre>
<p>Any clues as to how to achieve this? How to do it both in Python 2 and 3?</p> | <p>I'd do it like this so changing its type in <code>foo()</code> won't require also changing it in <code>bar()</code>.</p>
<pre><code>def foo():
try:
raise IOError('Stuff')
except:
raise
def bar(arg1):
try:
foo()
except Exception as e:
raise type(e)(e.message + ' happens at %s' % arg1)
bar('arg1')
</code></pre>
<hr>
<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
File "test.py", line 13, in <module>
bar('arg1')
File "test.py", line 11, in bar
raise type(e)(e.message + ' happens at %s' % arg1)
IOError: Stuff happens at arg1
</code></pre>
<p><strong>Update 1</strong></p>
<p>Here's a slight modification that preserves the original traceback:</p>
<pre><code>...
def bar(arg1):
try:
foo()
except Exception as e:
import sys
raise type(e), type(e)(e.message +
' happens at %s' % arg1), sys.exc_info()[2]
bar('arg1')
</code></pre>
<hr>
<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
File "test.py", line 16, in <module>
bar('arg1')
File "test.py", line 11, in bar
foo()
File "test.py", line 5, in foo
raise IOError('Stuff')
IOError: Stuff happens at arg1
</code></pre>
<p><strong>Update 2</strong></p>
<p>For Python 3.x, the code in my first update is syntactically incorrect plus the idea of having a <code>message</code> attribute on <code>BaseException</code> was <a href="http://www.python.org/dev/peps/pep-0352/#retracted-ideas" rel="noreferrer">retracted in a change to PEP 352</a> on 2012-05-16 (my first update was posted on 2012-03-12). So currently, in Python 3.5.2 anyway, you'd need to do something along these lines to preserve the traceback and not hardcode the type of exception in function <code>bar()</code>. Also note that there will be the line:</p>
<pre class="lang-none prettyprint-override"><code>During handling of the above exception, another exception occurred:
</code></pre>
<p>in the traceback messages displayed.</p>
<pre><code># for Python 3.x
...
def bar(arg1):
try:
foo()
except Exception as e:
import sys
raise type(e)(str(e) +
' happens at %s' % arg1).with_traceback(sys.exc_info()[2])
bar('arg1')
</code></pre>
<p><strong>Update 3</strong></p>
<p>A commenter asked if there was a way that would work in both Python 2 and 3. Although the answer might seem to be "No" due to the syntax differences, there <em>is</em> a way around that by using a helper function like <a href="http://pythonhosted.org/six/index.html#six.reraise" rel="noreferrer"><code>reraise()</code></a> in the <a href="https://pypi.python.org/pypi/six/" rel="noreferrer"><code>six</code></a> add-on module. So, if you'd rather not use the library for some reason, below is a simplified standalone version.</p>
<p>Note too, that since the exception is reraised within the <code>reraise()</code> function, that will appear in whatever traceback is raised, but the final result is what you want.</p>
<pre><code>import sys
if sys.version_info.major < 3: # Python 2?
# Using exec avoids a SyntaxError in Python 3.
exec("""def reraise(exc_type, exc_value, exc_traceback=None):
raise exc_type, exc_value, exc_traceback""")
else:
def reraise(exc_type, exc_value, exc_traceback=None):
if exc_value is None:
exc_value = exc_type()
if exc_value.__traceback__ is not exc_traceback:
raise exc_value.with_traceback(exc_traceback)
raise exc_value
def foo():
try:
raise IOError('Stuff')
except:
raise
def bar(arg1):
try:
foo()
except Exception as e:
reraise(type(e), type(e)(str(e) +
' happens at %s' % arg1), sys.exc_info()[2])
bar('arg1')
</code></pre> | {
"question_id": 6062576,
"question_date": "2011-05-19T17:34:35.387Z",
"question_score": 206,
"tags": "python|exception",
"answer_id": 6062799,
"answer_date": "2011-05-19T17:53:45.157Z",
"answer_score": 150
} |
Please answer the following Stack Overflow question:
Title: How to get hosting Activity from a view?
<p>I have an <code>Activity</code> with 3 <code>EditText</code>s and a custom view which acts a specialised keyboard to add information into the <code>EditText</code>s. </p>
<p>Currently I'm passing the <code>Activity</code> into the view so that I can get the currently focused edit text and update the contents from the custom keyboard. </p>
<p>Is there a way of referencing the parent activity and getting the currently focused <code>EditText</code> without passing the activity into the view? </p> | <p>I just pulled that source code from the MediaRouter in the <a href="https://android.googlesource.com/platform/frameworks/support/+/refs/heads/marshmallow-release/v7/mediarouter/src/android/support/v7/app/MediaRouteButton.java#262" rel="noreferrer">official support library</a> and so far it works fine:</p>
<pre><code>private Activity getActivity() {
Context context = getContext();
while (context instanceof ContextWrapper) {
if (context instanceof Activity) {
return (Activity)context;
}
context = ((ContextWrapper)context).getBaseContext();
}
return null;
}
</code></pre> | {
"question_id": 8276634,
"question_date": "2011-11-26T05:58:00.143Z",
"question_score": 206,
"tags": "android|android-activity|android-edittext|android-view",
"answer_id": 32973351,
"answer_date": "2015-10-06T15:04:39.477Z",
"answer_score": 334
} |
Please answer the following Stack Overflow question:
Title: Which is faster/best? SELECT * or SELECT column1, colum2, column3, etc
<p>I've heard that <code>SELECT *</code> is generally bad practice to use when writing SQL commands because it is more efficient to <code>SELECT</code> columns you specifically need.</p>
<p>If I need to <code>SELECT</code> every column in a table, should I use </p>
<pre><code>SELECT * FROM TABLE
</code></pre>
<p>or </p>
<pre><code>SELECT column1, colum2, column3, etc. FROM TABLE
</code></pre>
<p>Does the efficiency really matter in this case? I'd think <code>SELECT *</code> would be more optimal internally if you really need all of the data, but I'm saying this with no real understanding of database.</p>
<p>I'm curious to know what the best practice is in this case.</p>
<p><strong>UPDATE:</strong> I probably should specify that the only situation where I would really <em>want</em> to do a <code>SELECT *</code> is when I'm selecting data from one table where I know all columns will always need to be retrieved, even when new columns are added. </p>
<p>Given the responses I've seen however, this still seems like a bad idea and <code>SELECT *</code> should never be used for a lot more technical reasons that I ever though about.</p> | <p>One reason that selecting specific columns is better is that it raises the probability that SQL Server can access the data from indexes rather than querying the table data. </p>
<p>Here's a post I wrote about it: <a href="http://weblogs.asp.net/jgalloway/archive/2007/07/18/the-real-reason-select-queries-are-bad-index-coverage.aspx" rel="noreferrer"><strong>The real reason select queries are bad index coverage</strong></a> </p>
<p>It's also less fragile to change, since any code that consumes the data will be getting the same data structure regardless of changes you make to the table schema in the future.</p> | {
"question_id": 65512,
"question_date": "2008-09-15T18:38:49.450Z",
"question_score": 206,
"tags": "sql|database",
"answer_id": 65532,
"answer_date": "2008-09-15T18:41:23.110Z",
"answer_score": 194
} |
Please answer the following Stack Overflow question:
Title: Sort a list from another list IDs
<p>I have a list with some identifiers like this:</p>
<pre><code>List<long> docIds = new List<long>() { 6, 1, 4, 7, 2 };
</code></pre>
<p>Morover, I have another list of <code><T></code> items, which are represented by the ids described above.</p>
<pre><code>List<T> docs = GetDocsFromDb(...)
</code></pre>
<p>I need to keep the same order in both collections, so that the items in <code>List<T></code> must be in the same position than in the first one (due to search engine scoring reasons). And this process cannot be done in the <code>GetDocsFromDb()</code> function. </p>
<p>If necessary, it's possible to change the second list into some other structure (<code>Dictionary<long, T></code> for example), but I'd prefer not to change it.</p>
<p>Is there any simple and efficient way to do this "ordenation depending on some IDs" with LINQ?</p> | <pre><code>docs = docs.OrderBy(d => docsIds.IndexOf(d.Id)).ToList();
</code></pre> | {
"question_id": 15275269,
"question_date": "2013-03-07T15:36:35.583Z",
"question_score": 206,
"tags": "c#|linq|sorting|collections",
"answer_id": 15275394,
"answer_date": "2013-03-07T15:42:22.663Z",
"answer_score": 435
} |
Please answer the following Stack Overflow question:
Title: Should "node_modules" folder be included in the git repository
<p>I'm wondering if we should be tracking node_modules in our repo or doing an npm install when checking out the code?</p> | <p>The answer is not as easy as <a href="https://stackoverflow.com/a/18129049/7487335">Alberto Zaccagni suggests</a>. If you develop applications (especially enterprise applications), including node_modules in your git repo is a viable choice and which alternative you choose depends on your project.</p>
<p>Because he argued very well against node_modules I will concentrate on arguments for them.</p>
<p>Imagine that you have just finished enterprise app and you will have to support it for 3-5 years. You definitely don't want to depend on someone's npm module which can tomorrow disappear and you can't update your app anymore.</p>
<p>Or you have your private modules which are not accessible from the internet and you can't build your app on the internet. Or maybe you don't want to depend on your final build on npm service for some reason.</p>
<p>You can find pros and cons <a href="http://addyosmani.com/blog/checking-in-front-end-dependencies/#more-5510" rel="noreferrer">in this Addy Osmani article</a> (although it is about Bower, it is almost the same situation). And I will end with a quote from Bower homepage and Addy's article:</p>
<blockquote>
<p>“If you aren’t authoring a package that is intended to be consumed by others (e.g., you’re building a web app), you should always check installed packages into source control.”</p>
</blockquote> | {
"question_id": 18128863,
"question_date": "2013-08-08T14:37:08.090Z",
"question_score": 206,
"tags": "git|node.js|version-control|npm",
"answer_id": 18131970,
"answer_date": "2013-08-08T17:10:17.507Z",
"answer_score": 203
} |
Please answer the following Stack Overflow question:
Title: Difference between single and double square brackets in Bash
<p>I'm reading bash examples about <code>if</code> but some examples are written with single square brackets:</p>
<pre><code>if [ -f $param ]
then
#...
fi
</code></pre>
<p>others with double square brackets:</p>
<pre><code>if [[ $? -ne 0 ]]
then
start looking for errors in yourlog
fi
</code></pre>
<p>What is the difference?</p> | <p>Single <code>[]</code> are posix shell compliant condition tests.</p>
<p>Double <code>[[]]</code> are an extension to the standard <code>[]</code> and are supported by bash and other shells (e.g. zsh, ksh). They support extra operations (as well as the standard posix operations). For example: <code>||</code> instead of <code>-o</code> and regex matching with <code>=~</code>. A fuller list of differences can be found in the <a href="http://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs" rel="noreferrer">bash manual section on conditional constructs</a>.</p>
<p>Use <code>[]</code> whenever you want your script to be portable across shells. Use <code>[[]]</code> if you want conditional expressions not supported by <code>[]</code> and don't need to be portable.</p> | {
"question_id": 13542832,
"question_date": "2012-11-24T15:56:58.103Z",
"question_score": 206,
"tags": "bash|if-statement",
"answer_id": 13542854,
"answer_date": "2012-11-24T15:59:25.173Z",
"answer_score": 245
} |
Please answer the following Stack Overflow question:
Title: How can I use optional chaining with arrays and functions?
<p>I'm trying to use optional chaining with an array instead of an object but not sure how to do that:</p>
<p>Here's what I'm trying to do <code>myArray.filter(x => x.testKey === myTestKey)?[0]</code>.
Also trying similar thing with a function:</p>
<pre><code>let x = {a: () => {}, b: null}
console.log(x?b());
</code></pre>
<p>But it's giving a similar error - how can I use optional chaining with an array or a function?</p> | <p>You need to put a <code>.</code> after the <code>?</code> to use optional chaining:</p>
<pre><code>myArray.filter(x => x.testKey === myTestKey)?.[0]
</code></pre>
<p><a href="https://www.typescriptlang.org/play/#code/MYewdgzgLgBAtgTwCoFNoGkUJgXhgcgCMBDAJ3wG4BYAKFElkQEFTTjs8BtAbxijSiYEALgIAzECHwwAvgBoYvfhiyiiZaTIC61OuGgxSaAK4AbWHmat2AOjEBLcylIAKAB64AfDDc3lgrFwcS2QBIQBKAH4bTgAGHVp6CBBTFBtTEABzFyMIMyhwiiA" rel="noreferrer">Playground link</a></p>
<p>Using just the <code>?</code> alone makes the compiler think you're trying to use the conditional operator (and then it throws an error since it doesn't see a <code>:</code> later)</p>
<p>Optional chaining isn't just a TypeScript thing - it is a finished proposal <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining" rel="noreferrer">in plain JavaScript</a> too.</p>
<p>It can be used with bracket notation like above, but it can also be used with dot notation property access:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const obj = {
prop2: {
nested2: 'val2'
}
};
console.log(
obj.prop1?.nested1,
obj.prop2?.nested2
);</code></pre>
</div>
</div>
</p>
<p>And with function calls:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const obj = {
fn2: () => console.log('fn2 running')
};
obj.fn1?.();
obj.fn2?.();</code></pre>
</div>
</div>
</p> | {
"question_id": 59623674,
"question_date": "2020-01-07T07:05:02.703Z",
"question_score": 206,
"tags": "javascript|arrays|typescript|function|optional-chaining",
"answer_id": 59623717,
"answer_date": "2020-01-07T07:08:39.090Z",
"answer_score": 384
} |
Please answer the following Stack Overflow question:
Title: Understanding :source option of has_one/has_many through of Rails
<p>Please help me in understanding the <code>:source</code> option of <code>has_one/has_many :through</code> association. The Rails API explanation makes very little sense to me.</p>
<blockquote>
<p>"Specifies the source association name used by <code>has_many</code> <code>:through =>
:queries</code>. Only use it if the name cannot be inferred from the
association. <code>has_many :subscribers, :through => :subscriptions</code> will
look for either <code>:subscribers</code> or <code>:subscriber</code> on <code>Subscription</code>,
unless a <code>:source</code> is given. "</p>
</blockquote> | <p>Sometimes, you want to use different names for different associations. If the name you want to use for an association on the model isn't the same as the assocation on the <code>:through</code> model, you can use <code>:source</code> to specify it.</p>
<p>I don't think the above paragraph is <em>much</em> clearer than the one in the docs, so here's an example. Let's assume we have three models, <code>Pet</code>, <code>Dog</code> and <code>Dog::Breed</code>.</p>
<pre><code>class Pet < ActiveRecord::Base
has_many :dogs
end
class Dog < ActiveRecord::Base
belongs_to :pet
has_many :breeds
end
class Dog::Breed < ActiveRecord::Base
belongs_to :dog
end
</code></pre>
<p>In this case, we've chosen to namespace the <code>Dog::Breed</code>, because we want to access <code>Dog.find(123).breeds</code> as a nice and convenient association.</p>
<p>Now, if we now want to create a <code>has_many :dog_breeds, :through => :dogs</code> association on <code>Pet</code>, we suddenly have a problem. Rails won't be able to find a <code>:dog_breeds</code> association on <code>Dog</code>, so Rails can't possibly know <em>which</em> <code>Dog</code> association you want to use. Enter <code>:source</code>:</p>
<pre><code>class Pet < ActiveRecord::Base
has_many :dogs
has_many :dog_breeds, :through => :dogs, :source => :breeds
end
</code></pre>
<p>With <code>:source</code>, we're telling Rails to <strong>look for an association called <code>:breeds</code> on the <code>Dog</code> model</strong> (as that's the model used for <code>:dogs</code>), and use that.</p> | {
"question_id": 4632408,
"question_date": "2011-01-08T04:51:29.290Z",
"question_score": 206,
"tags": "ruby-on-rails-3|rails-activerecord",
"answer_id": 4632472,
"answer_date": "2011-01-08T05:12:17.397Z",
"answer_score": 273
} |
Please answer the following Stack Overflow question:
Title: Disable the interactive dismissal of presented view controller
<p><strong>iOS 13</strong> introduces a new design of <code>modalPresentationStyle</code> <code>.pageSheet</code> (and its sibling <code>.formSheet</code>) for modally presented view controllers…</p>
<p><a href="https://i.stack.imgur.com/IIoCCm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/IIoCCm.png" alt="The new sliding modal presentation in iOS 13"></a></p>
<p>…and we can dismiss these sheets by sliding the presented view controller down <em>(interactive dismissal)</em>. Although the new "pull-to-dismiss" feature is pretty useful, it may not always be desirable. </p>
<p><strong>THE QUESTION:</strong> How can we turn the interactive dismissal off?
<em>- Bear in mind we keep the presentation style the same.</em></p> | <h3>Option 1:</h3>
<pre><code>viewController.isModalInPresentation = true
</code></pre>
<p><a href="https://i.stack.imgur.com/Eas3G.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Eas3G.gif" alt="Disabled interactive dismissal" /></a></p>
<p><em>(Disabled interactive <code>.pageSheet</code> dismissal acts like this.)</em></p>
<ul>
<li>Since the iOS 13, <code>UIViewController</code> contains a new property called <code>isModalInPresentation</code> which must be set to <code>true</code> to prevent the interactive dismissal.</li>
<li>It basically ignores events outside the view controller's bounds. Bear that in mind if you are using not only the automatic style but also presentation styles like <code>.popover</code> etc.</li>
<li>This property is <code>false</code> by default.</li>
</ul>
<blockquote>
<p><strong>From the <a href="https://developer.apple.com/documentation/uikit/uiviewcontroller/3229894-modalinpresentation?language=objc" rel="nofollow noreferrer">official docs</a></strong>: If <code>true</code>, UIKit ignores events outside the view controller's bounds and prevents the interactive dismissal of the view controller while it is onscreen.</p>
</blockquote>
<hr />
<h3>Option 2:</h3>
<pre><code>func presentationControllerShouldDismiss(_ presentationController: UIPresentationController) -> Bool {
return false
}
</code></pre>
<ul>
<li>Since the iOS 13, <code>UIAdaptivePresentationControllerDelegate</code> contains a new method called <code>presentationControllerShouldDismiss</code>.</li>
<li>This method is called only if the presented view controller is not dismissed programmatically and its <code>isModalInPresentation</code> property is set to <code>false</code>.</li>
</ul>
<blockquote>
<p><strong>Tip:</strong> Don't forget to assign <code>presentationController</code>'s delegate. But be aware, it is known that even just accessing the <code>presentationController</code> can cause a memory leak.</p>
</blockquote> | {
"question_id": 56459329,
"question_date": "2019-06-05T11:11:34.223Z",
"question_score": 206,
"tags": "ios|uiviewcontroller|uikit|modalviewcontroller|ios13",
"answer_id": 56459330,
"answer_date": "2019-06-05T11:11:34.223Z",
"answer_score": 391
} |
Please answer the following Stack Overflow question:
Title: When should I use Struct vs. OpenStruct?
<p>In general, what are the advantages and disadvantages of using an OpenStruct as compared to a Struct? What type of general use-cases would fit each of these?</p> | <p>With an <code>OpenStruct</code>, you can arbitrarily create attributes. A <code>Struct</code>, on the other hand, must have its attributes defined when you create it. The choice of one over the other should be based primarily on whether you need to be able to add attributes later. </p>
<p>The way to think about them is as the middle ground of the spectrum between Hashes on one side and classes on the other. They imply a more concrete relationship amongst the data than does a <code>Hash</code>, but they don't have the instance methods as would a class. A bunch of options for a function, for example, make sense in a hash; they're only loosely related. A name, email, and phone number needed by a function could be packaged together in a <code>Struct</code> or <code>OpenStruct</code>. If that name, email, and phone number needed methods to provide the name in both "First Last" and "Last, First" formats, then you should create a class to handle it.</p> | {
"question_id": 1177594,
"question_date": "2009-07-24T13:18:34.980Z",
"question_score": 206,
"tags": "ruby|struct",
"answer_id": 1177759,
"answer_date": "2009-07-24T13:43:30.847Z",
"answer_score": 194
} |
Please answer the following Stack Overflow question:
Title: Are database triggers necessary?
<p>In my experience, they are not a good idea because they can result in surprising side effects, and are difficult to debug (especially when one trigger fires another). Often developers do not even think of looking if there is a trigger.</p>
<p>On the other hand, if you have logic that must occur every time a new <code>FOO</code> is created in the database, then it may be the most foolproof place to put it is an insert trigger on the <code>FOO</code> table.</p>
<p>The only time we're using triggers is for really simple things like setting the modified date field of a row.</p>
<p>I'm struggling to figure out whether triggers are necessary and would appreciate any input. If they are necessary, what are the most important issues to consider when implementing them?</p> | <p>The main problems with triggers are </p>
<ul>
<li>They are completely Global - they apply no matter what the context of the table activity; </li>
<li>They are stealthy; it's easy to forget they are there until they hurt you with unintended (and very mysterious) consequences.</li>
</ul>
<p>This just means they need to be carefully used for the proper circumstances; which in my experience is limited to relational integrity issues (sometimes with finer granularity than you can get declaratively); and usually not for business or transactional purposes. YMMV.</p> | {
"question_id": 460316,
"question_date": "2009-01-20T07:01:04.463Z",
"question_score": 206,
"tags": "database|triggers",
"answer_id": 460343,
"answer_date": "2009-01-20T07:22:43.203Z",
"answer_score": 172
} |
Please answer the following Stack Overflow question:
Title: Xcode 4 hangs at "Attaching to (app name)"
<p>I just upgraded to Xcode 4 and for some reason my app won't run in the simulator or iOS device. It was working perfectly in Xcode 3, but all of a sudden now when I press run the program stops at "Attaching to...". There doesn't seem to be any other info to help with this problem either.</p>
<p><strong>For summary you can try following things to tackle the issue:</strong></p>
<ol>
<li>Restart the simulator.</li>
<li>Make sure that you haven't included the Info.plist file in your Building Phases -> Copy Bundle Resources.</li>
<li>Resources folder added to the project as a folder reference (the blue folder icon). That caused the trouble, after adding the folder as a group the problem went away.</li>
</ol> | <p>Fixed it!! Hopefully this helps some people avoid a very frustrating couple hours. I solved this by:</p>
<ol>
<li>Clicking on the project name in the left pane (at the very top). This will bring up a new menu to the right, something like the project/ target editors in XCode 3.</li>
<li>Click on Build Settings up at the top.</li>
<li>Under Packaging make sure your product name is the same for every build, and equal to whatever it says it's attaching to. Eg if XCode is Hanging at "Attaching to myLCBO" but your product name is "LCBO Finder" then it won't build. That was exactly my problem because I renamed my app half way through development.</li>
</ol>
<p>Hope this helps!</p> | {
"question_id": 5382968,
"question_date": "2011-03-21T20:03:05.900Z",
"question_score": 206,
"tags": "iphone|objective-c|xcode|ipad|xcode4",
"answer_id": 5383839,
"answer_date": "2011-03-21T21:16:07.353Z",
"answer_score": 104
} |
Please answer the following Stack Overflow question:
Title: RAII and smart pointers in C++
<p>In practice with C++, what is <a href="http://en.wikipedia.org/wiki/Resource_acquisition_is_initialization" rel="noreferrer">RAII</a>, what are <a href="http://en.wikipedia.org/wiki/Smart_pointers" rel="noreferrer">smart pointers</a>, how are these implemented in a program and what are the benefits of using RAII with smart pointers?</p> | <p>A simple (and perhaps overused) example of RAII is a File class. Without RAII, the code might look something like this:</p>
<pre><code>File file("/path/to/file");
// Do stuff with file
file.close();
</code></pre>
<p>In other words, we must make sure that we close the file once we've finished with it. This has two drawbacks - firstly, wherever we use File, we will have to called File::close() - if we forget to do this, we're holding onto the file longer than we need to. The second problem is what if an exception is thrown before we close the file?</p>
<p>Java solves the second problem using a finally clause:</p>
<pre><code>try {
File file = new File("/path/to/file");
// Do stuff with file
} finally {
file.close();
}
</code></pre>
<p>or since Java 7, a try-with-resource statement:</p>
<pre><code>try (File file = new File("/path/to/file")) {
// Do stuff with file
}
</code></pre>
<p>C++ solves both problems using RAII - that is, closing the file in the destructor of File. So long as the File object is destroyed at the right time (which it should be anyway), closing the file is taken care of for us. So, our code now looks something like:</p>
<pre><code>File file("/path/to/file");
// Do stuff with file
// No need to close it - destructor will do that for us
</code></pre>
<p>This cannot be done in Java since there's no guarantee when the object will be destroyed, so we cannot guarantee when a resource such as file will be freed.</p>
<p>Onto smart pointers - a lot of the time, we just create objects on the stack. For instance (and stealing an example from another answer):</p>
<pre><code>void foo() {
std::string str;
// Do cool things to or using str
}
</code></pre>
<p>This works fine - but what if we want to return str? We could write this:</p>
<pre><code>std::string foo() {
std::string str;
// Do cool things to or using str
return str;
}
</code></pre>
<p>So, what's wrong with that? Well, the return type is std::string - so it means we're returning by value. This means that we copy str and actually return the copy. This can be expensive, and we might want to avoid the cost of copying it. Therefore, we might come up with idea of returning by reference or by pointer.</p>
<pre><code>std::string* foo() {
std::string str;
// Do cool things to or using str
return &str;
}
</code></pre>
<p>Unfortunately, this code doesn't work. We're returning a pointer to str - but str was created on the stack, so we be deleted once we exit foo(). In other words, by the time the caller gets the pointer, it's useless (and arguably worse than useless since using it could cause all sorts of funky errors)</p>
<p>So, what's the solution? We could create str on the heap using new - that way, when foo() is completed, str won't be destroyed.</p>
<pre><code>std::string* foo() {
std::string* str = new std::string();
// Do cool things to or using str
return str;
}
</code></pre>
<p>Of course, this solution isn't perfect either. The reason is that we've created str, but we never delete it. This might not be a problem in a very small program, but in general, we want to make sure we delete it. We could just say that the caller must delete the object once he's finished with it. The downside is that the caller has to manage memory, which adds extra complexity, and might get it wrong, leading to a memory leak i.e. not deleting object even though it is no longer required.</p>
<p>This is where smart pointers come in. The following example uses shared_ptr - I suggest you look at the different types of smart pointers to learn what you actually want to use.</p>
<pre><code>shared_ptr<std::string> foo() {
shared_ptr<std::string> str = new std::string();
// Do cool things to or using str
return str;
}
</code></pre>
<p>Now, shared_ptr will count the number of references to str. For instance</p>
<pre><code>shared_ptr<std::string> str = foo();
shared_ptr<std::string> str2 = str;
</code></pre>
<p>Now there are two references to the same string. Once there are no remaining references to str, it will be deleted. As such, you no longer have to worry about deleting it yourself.</p>
<p>Quick edit: as some of the comments have pointed out, this example isn't perfect for (at least!) two reasons. Firstly, due to the implementation of strings, copying a string tends to be inexpensive. Secondly, due to what's known as named return value optimisation, returning by value may not be expensive since the compiler can do some cleverness to speed things up.</p>
<p>So, let's try a different example using our File class.</p>
<p>Let's say we want to use a file as a log. This means we want to open our file in append only mode:</p>
<pre><code>File file("/path/to/file", File::append);
// The exact semantics of this aren't really important,
// just that we've got a file to be used as a log
</code></pre>
<p>Now, let's set our file as the log for a couple of other objects:</p>
<pre><code>void setLog(const Foo & foo, const Bar & bar) {
File file("/path/to/file", File::append);
foo.setLogFile(file);
bar.setLogFile(file);
}
</code></pre>
<p>Unfortunately, this example ends horribly - file will be closed as soon as this method ends, meaning that foo and bar now have an invalid log file. We could construct file on the heap, and pass a pointer to file to both foo and bar:</p>
<pre><code>void setLog(const Foo & foo, const Bar & bar) {
File* file = new File("/path/to/file", File::append);
foo.setLogFile(file);
bar.setLogFile(file);
}
</code></pre>
<p>But then who is responsible for deleting file? If neither delete file, then we have both a memory and resource leak. We don't know whether foo or bar will finish with the file first, so we can't expect either to delete the file themselves. For instance, if foo deletes the file before bar has finished with it, bar now has an invalid pointer.</p>
<p>So, as you may have guessed, we could use smart pointers to help us out.</p>
<pre><code>void setLog(const Foo & foo, const Bar & bar) {
shared_ptr<File> file = new File("/path/to/file", File::append);
foo.setLogFile(file);
bar.setLogFile(file);
}
</code></pre>
<p>Now, nobody needs to worry about deleting file - once both foo and bar have finished and no longer have any references to file (probably due to foo and bar being destroyed), file will automatically be deleted.</p> | {
"question_id": 395123,
"question_date": "2008-12-27T16:13:09.757Z",
"question_score": 206,
"tags": "c++|smart-pointers|raii",
"answer_id": 395158,
"answer_date": "2008-12-27T16:57:37.907Z",
"answer_score": 339
} |
Please answer the following Stack Overflow question:
Title: Why are Fragments in React 16 better than container divs?
<p>In React 16.2, improved support for <code>Fragments</code> has been added. More information can be found on React's blog post <a href="https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html" rel="noreferrer">here.</a></p>
<p>We are all familiar with the following code:</p>
<pre><code>render() {
return (
// Extraneous div element :(
<div>
Some text.
<h2>A heading</h2>
More text.
<h2>Another heading</h2>
Even more text.
</div>
);
}
</code></pre>
<p>Yes, we need a container div, but it's not that big of a deal.</p>
<p>In React 16.2, we can do this to avoid the surrounding container div:</p>
<pre><code>render() {
return (
<Fragment>
Some text.
<h2>A heading</h2>
More text.
<h2>Another heading</h2>
Even more text.
</Fragment>
);
}
</code></pre>
<p>In either case, we still need need a container element surround the inner elements. </p>
<p>My question is, why is using a <code>Fragment</code> preferable? Does it help with performance? If so, why? Would love some insight.</p> | <ol>
<li>It’s a tiny bit faster and has less memory usage (no need to create an extra DOM node). This only has a real benefit on very large and/or deep trees, but application performance often suffers from death by a thousand cuts. This is one cut less.</li>
<li>Some CSS mechanisms like Flexbox and CSS Grid have a special parent-child relationship, and adding <code>div</code>s in the middle makes it hard to keep the desired layout while extracting logical components.</li>
<li>The DOM inspector is less cluttered. :-)</li>
</ol>
<p>You can find the descriptions of some other use cases in this React issue: <a href="https://github.com/facebook/react/issues/2127" rel="noreferrer">Add fragment API to allow returning multiple components from render</a> </p> | {
"question_id": 47761894,
"question_date": "2017-12-11T21:41:32.093Z",
"question_score": 206,
"tags": "reactjs",
"answer_id": 47762117,
"answer_date": "2017-12-11T21:56:28.560Z",
"answer_score": 357
} |
Please answer the following Stack Overflow question:
Title: Django fix Admin plural
<p>How do I change some models name from "Categorys" to "Categories" on admin site in the new dev django version?
In the old version (whithout admin sites and admin models) you could just do this;
<a href="http://www.the-dig.com/blog/post/customize-plural-name-django-admin/" rel="noreferrer">http://www.the-dig.com/blog/post/customize-plural-name-django-admin/</a></p>
<p>However - now setting verbose_name_plural inside my modeladmin based class does nothing.
Anyone encouter the same issue?</p> | <p>Well well, it seems like the Meta class approach still works.
So placing a meta class inside your model will still do the trick:</p>
<pre><code>class Category(models.Model):
class Meta:
verbose_name_plural = "categories"
</code></pre>
<p>Note that we use the lower case here, as django is smart enough to capitalize it when we need it.</p>
<p>I find setting this option in model-class weird as opposed to the admin.py file.
Here is the location in the dev docs where it is described:<br>
<a href="http://docs.djangoproject.com/en/dev/ref/models/options/#verbose-name-plural" rel="noreferrer">http://docs.djangoproject.com/en/dev/ref/models/options/#verbose-name-plural</a></p> | {
"question_id": 2587707,
"question_date": "2010-04-06T19:35:36.147Z",
"question_score": 206,
"tags": "django|django-admin",
"answer_id": 2587829,
"answer_date": "2010-04-06T19:54:55.510Z",
"answer_score": 375
} |
Please answer the following Stack Overflow question:
Title: Xcode 10, where are the UI elements?
<p>Have been out of Swift coding for almost a year, I'm back. </p>
<p>Download Xcode 10 beta. Have I lost my mind? I've tried every trick I know, none of the UI elements show up in storyboard. Zero. The sidebar is empty. </p>
<p>Xcode 10:</p>
<p><a href="https://i.stack.imgur.com/ilCZT.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ilCZT.png" alt="Xcode 10 Screenshot"></a></p>
<p>Xcode 9, no problem there they are, all my UI buttons, etc.</p>
<p>thanks, this is kind of surreal. :-)</p> | <p>Library content has moved from the bottom of the <code>Inspector</code> area to an overlay window, which can be moved and resized like <code>Spotlight</code> search. It dismisses once items are dragged, but holding the <code>Option</code> key before dragging will keep the library open for an additional drag. </p>
<p>The library can be opened via: </p>
<ul>
<li><p>a new toolbar button (image attached);</p></li>
<li><p>the <code>View</code> > <code>Libraries</code> menu;</p></li>
<li><p>or the <kbd>⇧⌘L</kbd> keyboard shortcut.</p></li>
</ul>
<p><a href="https://i.stack.imgur.com/dVA5Y.png" rel="noreferrer"><img src="https://i.stack.imgur.com/dVA5Y.png" alt="enter image description here"></a></p> | {
"question_id": 51051532,
"question_date": "2018-06-26T21:22:22.823Z",
"question_score": 206,
"tags": "xcode|interface-builder|uistoryboard|xcode10",
"answer_id": 51051590,
"answer_date": "2018-06-26T21:27:29.690Z",
"answer_score": 280
} |
Please answer the following Stack Overflow question:
Title: Why is good UI design so hard for some Developers?
<p>Some of us just have a hard time with the softer aspects of UI design (<em>myself especially</em>). Are "back-end coders" doomed to only design business logic and data layers? Is there something we can do to <strong>retrain our brain</strong> to be more effective at designing pleasing and useful presentation layers?</p>
<p>Colleagues have recommended a few books me including <em>The Design of Sites</em>, <em>Don't make me think</em> and <em>Why Software sucks</em> , but I am wondering what others have done to remove their deficiencies in this area?</p> | <p>Let me say it directly: </p>
<p><strong>Improving on this does not begin with guidelines. It begins with reframing how you think about software.</strong></p>
<p>Most hardcore developers have practically <strong>zero</strong> empathy with users of their software. They have <strong>no clue</strong> how users think, how users build models of software they use and how they use a computer in general.</p>
<p>It is a typical problem when an expert collides with a laymen: How on earth could a normal person be so <strong>dumb</strong> not to understand what the expert understood 10 years ago?</p>
<p>One of the first facts to acknowledge that is unbelievably difficult to grasp for almost all experienced developers is this: </p>
<p><strong>Normal people have a vastly different concept of software than you have. They have no clue whatsoever of programming. None. Zero. And they don't even care. They don't even think they have to care. If you force them to, they will delete your program.</strong> </p>
<p>Now that's unbelievably harsh for a developer. He is proud of the software he produces. He loves every single feature. He can tell you exactly how the code behind it works. Maybe he even invented an unbelievable clever algorithm that made it work 50% faster than before.</p>
<p>And the user doesn't care.</p>
<p>What an idiot.</p>
<p>Many developers can't stand working with normal users. They get depressed by their non-existing knowledge of technology. And that's why most developers shy away and think users must be idiots.</p>
<p>They are not.</p>
<p>If a software developer buys a car, he expects it to run smoothly. He usually does not care about tire pressures, the mechanical fine-tuning that was important to make it run that way. Here he is <strong>not</strong> the expert. And if he buys a car that does not have the fine-tuning, he gives it back and buys one that does what he wants.</p>
<p>Many software developers like movies. Well-done movies that spark their imagination. But they are not experts in producing movies, in producing visual effects or in writing good movie scripts. Most nerds are very, very, very bad at acting because it is all about displaying complex emotions and little about analytics. If a developer watches a bad film, he just notices that it is bad as a whole. Nerds have even built up IMDB to collect information about good and bad movies so they know which ones to watch and which to avoid. But they are not experts in creating movies. If a movie is bad, they'll not go to the movies (or not download it from BitTorrent ;)</p>
<p>So it boils down to: Shunning normal users as an expert is <strong>ignorance.</strong> Because in those areas (and there are so many) where they are not experts, they expect the experts of other areas to have already thought about normal people who use their products or services. </p>
<p>What can you do to remedy it? The more hardcore you are as a programmer, the less open you will be to normal user thinking. It will be alien and clueless to you. You will think: I can't imagine how people could <strong>ever</strong> use a computer with this lack of knowledge. But they can. For every UI element, think about: Is it necessary? Does it fit to the concept a user has of my tool? How can I make him understand? Please read up on usability for this, there are many good books. It's a whole area of science, too.</p>
<p>Ah and before you say it, yes, I'm an Apple fan ;)</p> | {
"question_id": 514083,
"question_date": "2009-02-05T00:54:16.303Z",
"question_score": 206,
"tags": "user-interface",
"answer_id": 516180,
"answer_date": "2009-02-05T14:42:35.350Z",
"answer_score": 359
} |
Please answer the following Stack Overflow question:
Title: Unnecessary curly braces in C++
<p>When doing a code review for a colleague today I saw a peculiar thing. He had surrounded his new code with curly braces like this:</p>
<pre><code>Constructor::Constructor()
{
// Existing code
{
// New code: do some new fancy stuff here
}
// Existing code
}
</code></pre>
<p>What is the outcome, if any, from this? What could be the reason for doing this? Where does this habit come from?</p>
<p>The environment is embedded devices. There is a lot of legacy C code wrapped in C++ clothing. There are a lot of C turned C++ developers.</p>
<p>There are no critical sections in this part of the code. I have only seen it in this part of the code. There are no major memory allocations done, just some flags that are set, and some bit twiddling.</p>
<p>The code that is surrounded by curly braces is something like:</p>
<pre><code>{
bool isInit;
(void)isStillInInitMode(&isInit);
if (isInit) {
return isInit;
}
}
</code></pre>
<p>(Don't mind the code, just stick to the curly braces... ;) )
After the curly braces there are some more bit twiddling, state checking, and basic signaling.</p>
<p>I talked to the guy and his motivation was to limit the scope of variables, naming clashes, and some other that I couldn't really pick up.</p>
<p>From my point of view this seems rather strange and I don't think that the curly braces should be in our code. I saw some good examples in all the answers on why one could surround code with curly braces, but shouldn't you separate the code into methods instead?</p>
<pre class="lang-none prettyprint-override"><code>fsdf
</code></pre> | <p>It's sometimes nice since it gives you a new scope, where you can more "cleanly" declare new (automatic) variables.</p>
<p>In <a href="https://en.wikipedia.org/wiki/C%2B%2B" rel="nofollow noreferrer">C++</a> this is maybe not so important since you can introduce new variables anywhere, but perhaps the habit is from <a href="https://en.wikipedia.org/wiki/C_%28programming_language%29" rel="nofollow noreferrer">C</a>, where you could not do this until <a href="https://en.wikipedia.org/wiki/C99" rel="nofollow noreferrer">C99</a>. :)</p>
<p>Since C++ has destructors, it can also be handy to have resources (files, mutexes, or whatever) automatically released as the scope exits, which can make things cleaner. This means you can hold on to some shared resource for a shorter duration than you would if you grabbed it at the start of the method.</p> | {
"question_id": 9704083,
"question_date": "2012-03-14T14:39:28.110Z",
"question_score": 206,
"tags": "c++|code-formatting",
"answer_id": 9704126,
"answer_date": "2012-03-14T14:41:53.567Z",
"answer_score": 312
} |
Please answer the following Stack Overflow question:
Title: public friend swap member function
<p>In the beautiful answer to the <a href="https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom#3279550">copy-and-swap-idiom</a> there is a piece of code I need a bit of help:</p>
<pre><code>class dumb_array
{
public:
// ...
friend void swap(dumb_array& first, dumb_array& second) // nothrow
{
using std::swap;
swap(first.mSize, second.mSize);
swap(first.mArray, second.mArray);
}
// ...
};
</code></pre>
<p>and he adds a note</p>
<blockquote>
<p>There are other claims that we should specialize std::swap for our type, provide an in-class swap along-side a free-function swap, etc. But this is all unnecessary: any proper use of swap will be through an unqualified call, and our function will be found through ADL. One function will do.</p>
</blockquote>
<p>With <code>friend</code> I am a bit on "unfriendly" terms, I must admit. So, my main questions are:</p>
<ul>
<li><strong>looks like a free function</strong>, but its inside the class body?</li>
<li><strong>why isn't this <code>swap</code> static</strong>? It obviously doesn't use any member variables.</li>
<li><strong>"Any proper use of swap will find out swap via ADL"</strong>? ADL will search the namespaces, right? But does it also look inside classes? Or is here where <code>friend</code> comes in?</li>
</ul>
<p>Side-questions:</p>
<ul>
<li>With C++11, should I mark my <code>swap</code>s with <strong><code>noexcept</code></strong>?</li>
<li>With C++11 and its <strong>range-for</strong>, should I place <code>friend iter begin()</code> and <code>friend iter end()</code> the same way inside the class? I think the <code>friend</code> is not needed here, right?</li>
</ul> | <p>There are several ways to write <code>swap</code>, some better than others. Over time, though, it was found a single definition works best. Let's consider how we might think about writing a <code>swap</code> function.</p>
<hr>
<p>We first see that containers like <code>std::vector<></code> have a single-argument member function <code>swap</code>, such as:</p>
<pre><code>struct vector
{
void swap(vector&) { /* swap members */ }
};
</code></pre>
<p>Naturally, then, our class should too, right? Well, not really. The standard library has <a href="http://www.gotw.ca/gotw/084.htm" rel="noreferrer">all sorts of unnecessary things</a>, and a member <code>swap</code> is one of them. Why? Let's go on.</p>
<hr>
<p>What we should do is identify what's canonical, and what our class <em>needs</em> to do to work with it. And the canonical method of swapping is with <code>std::swap</code>. This is why member functions aren't useful: they aren't how we should swap things, in general, and have no bearing on the behavior of <code>std::swap</code>.</p>
<p>Well then, to make <code>std::swap</code> work we should provide (and <code>std::vector<></code> should have provided) a specialization of <code>std::swap</code>, right?</p>
<pre><code>namespace std
{
template <> // important! specialization in std is OK, overloading is UB
void swap(myclass&, myclass&)
{
// swap
}
}
</code></pre>
<p>Well that would certainly work in this case, but it has a glaring problem: function specializations cannot be partial. That is, we cannot specialize template classes with this, only particular instantiations:</p>
<pre><code>namespace std
{
template <typename T>
void swap<T>(myclass<T>&, myclass<T>&) // error! no partial specialization
{
// swap
}
}
</code></pre>
<p>This method works some of the time, but not all of the time. There must be a better way.</p>
<hr>
<p>There is! We can use a <code>friend</code> function, and find it through <a href="https://en.cppreference.com/w/cpp/language/adl" rel="noreferrer">ADL</a>:</p>
<pre><code>namespace xyz
{
struct myclass
{
friend void swap(myclass&, myclass&);
};
}
</code></pre>
<p>When we want to swap something, we associate<sup>†</sup> <code>std::swap</code> and then make an unqualified call:</p>
<pre><code>using std::swap; // allow use of std::swap...
swap(x, y); // ...but select overloads, first
// that is, if swap(x, y) finds a better match, via ADL, it
// will use that instead; otherwise it falls back to std::swap
</code></pre>
<p>What is a <code>friend</code> function? There is confusion around this area.</p>
<p>Before C++ was standardized, <code>friend</code> functions did something called "friend name injection", where the code behaved <em>as if</em> if the function had been written in the surrounding namespace. For example, these were equivalent pre-standard:</p>
<pre><code>struct foo
{
friend void bar()
{
// baz
}
};
// turned into, pre-standard:
struct foo
{
friend void bar();
};
void bar()
{
// baz
}
</code></pre>
<p>However, when <a href="https://en.cppreference.com/w/cpp/language/adl" rel="noreferrer">ADL</a> was invented this was removed. The <code>friend</code> function could then <em>only</em> be found via ADL; if you wanted it as a free function, it needed to be declared as so (<a href="https://stackoverflow.com/questions/4027604/c-c-automatically-cast-void-pointer-into-type-pointer-in-c-in-define-in-cas/4027734#4027734">see this</a>, for example). But lo! There was a problem.</p>
<p>If you just use <code>std::swap(x, y)</code>, your overload will <em>never</em> be found, because you've explicitly said "look in <code>std</code>, and nowhere else"! This is why some people suggested writing two functions: one as a function to be found via <a href="https://en.cppreference.com/w/cpp/language/adl" rel="noreferrer">ADL</a>, and the other to handle explicit <code>std::</code> qualifications.</p>
<p>But like we saw, this can't work in all cases, and we end up with an ugly mess. Instead, idiomatic swapping went the other route: instead of making it the classes' job to provide <code>std::swap</code>, it's the swappers' job to make sure they don't use qualified <code>swap</code>, like above. And this tends to work pretty well, as long as people know about it. But therein lies the problem: it's unintuitive to need to use an unqualified call!</p>
<p>To make this easier, some libraries like Boost provided the function <code>boost::swap</code>, which just does an unqualified call to <code>swap</code>, with <code>std::swap</code> as an associated namespace. This helps make things succinct again, but it's still a bummer.</p>
<p>Note that there is no change in C++11 to the behavior of <code>std::swap</code>, which I and others mistakenly thought would be the case. If you were bit by this, <a href="https://stackoverflow.com/q/9170247/87234">read here</a>.</p>
<hr>
<p>In short: the member function is just noise, the specialization is ugly and incomplete, but the <code>friend</code> function is complete and works. And when you swap, either use <code>boost::swap</code> or an unqualified <code>swap</code> with <code>std::swap</code> associated.</p>
<hr>
<p>†Informally, a name is <em>associated</em> if it will be considered during a function call. For the details, read §3.4.2. In this case, <code>std::swap</code> normally isn't considered; but we can <em>associate</em> it (add it to the set of overloads considered by unqualified <code>swap</code>), allowing it to be found.</p> | {
"question_id": 5695548,
"question_date": "2011-04-17T18:35:02.867Z",
"question_score": 206,
"tags": "c++|c++11|friend|copy-and-swap",
"answer_id": 5695855,
"answer_date": "2011-04-17T19:24:24.227Z",
"answer_score": 206
} |
Please answer the following Stack Overflow question:
Title: Why is it discouraged to accept a reference to a String (&String), Vec (&Vec), or Box (&Box) as a function argument?
<p>I wrote some Rust code that takes a <code>&String</code> as an argument: </p>
<pre><code>fn awesome_greeting(name: &String) {
println!("Wow, you are awesome, {}!", name);
}
</code></pre>
<p>I've also written code that takes in a reference to a <code>Vec</code> or <code>Box</code>:</p>
<pre><code>fn total_price(prices: &Vec<i32>) -> i32 {
prices.iter().sum()
}
fn is_even(value: &Box<i32>) -> bool {
**value % 2 == 0
}
</code></pre>
<p>However, I received some feedback that doing it like this isn't a good idea. Why not?</p> | <p><strong>TL;DR: One can instead use <code>&str</code>, <code>&[T]</code> or <code>&T</code> to allow for more generic code.</strong></p>
<hr />
<ol>
<li><p>One of the main reasons to use a <code>String</code> or a <code>Vec</code> is because they allow increasing or decreasing the capacity. However, when you accept an immutable reference, you cannot use any of those interesting methods on the <code>Vec</code> or <code>String</code>.</p>
</li>
<li><p>Accepting a <code>&String</code>, <code>&Vec</code> or <code>&Box</code> also <strong>requires</strong> the argument to be allocated on the heap before you can call the function. Accepting a <code>&str</code> allows a string literal (saved in the program data) and accepting a <code>&[T]</code> or <code>&T</code> allows a stack-allocated array or variable. Unnecessary allocation is a performance loss. This is usually exposed right away when you try to call these methods in a test or a <code>main</code> method:</p>
<pre><code>awesome_greeting(&String::from("Anna"));
</code></pre>
<pre><code>total_price(&vec![42, 13, 1337])
</code></pre>
<pre><code>is_even(&Box::new(42))
</code></pre>
</li>
<li><p>Another performance consideration is that <code>&String</code>, <code>&Vec</code> and <code>&Box</code> introduce an unnecessary layer of indirection as you have to dereference the <code>&String</code> to get a <code>String</code> and then perform a second dereference to end up at <code>&str</code>.</p>
</li>
</ol>
<p>Instead, you should accept a <em>string slice</em> (<code>&str</code>), a <em>slice</em> (<code>&[T]</code>), or just a reference (<code>&T</code>). A <code>&String</code>, <code>&Vec<T></code> or <code>&Box<T></code> will be automatically coerced (via <a href="https://doc.rust-lang.org/stable/reference/type-coercions.html#coercion-types" rel="noreferrer"><em>deref coercion</em></a>) to a <code>&str</code>, <code>&[T]</code> or <code>&T</code>, respectively.</p>
<pre><code>fn awesome_greeting(name: &str) {
println!("Wow, you are awesome, {}!", name);
}
</code></pre>
<pre><code>fn total_price(prices: &[i32]) -> i32 {
prices.iter().sum()
}
</code></pre>
<pre><code>fn is_even(value: &i32) -> bool {
*value % 2 == 0
}
</code></pre>
<p>Now you can call these methods with a broader set of types. For example, <code>awesome_greeting</code> can be called with a string literal (<code>"Anna"</code>) <em>or</em> an allocated <code>String</code>. <code>total_price</code> can be called with a reference to an array (<code>&[1, 2, 3]</code>) <em>or</em> an allocated <code>Vec</code>.</p>
<hr />
<p>If you'd like to add or remove items from the <code>String</code> or <code>Vec<T></code>, you can take a <em>mutable reference</em> (<code>&mut String</code> or <code>&mut Vec<T></code>):</p>
<pre><code>fn add_greeting_target(greeting: &mut String) {
greeting.push_str("world!");
}
</code></pre>
<pre><code>fn add_candy_prices(prices: &mut Vec<i32>) {
prices.push(5);
prices.push(25);
}
</code></pre>
<p>Specifically for slices, you can also accept a <code>&mut [T]</code> or <code>&mut str</code>. This allows you to mutate a specific value inside the slice, but you cannot change the number of items inside the slice (which means it's very restricted for strings):</p>
<pre><code>fn reset_first_price(prices: &mut [i32]) {
prices[0] = 0;
}
</code></pre>
<pre><code>fn lowercase_first_ascii_character(s: &mut str) {
if let Some(f) = s.get_mut(0..1) {
f.make_ascii_lowercase();
}
}
</code></pre> | {
"question_id": 40006219,
"question_date": "2016-10-12T18:50:50.360Z",
"question_score": 206,
"tags": "rust",
"answer_id": 40006220,
"answer_date": "2016-10-12T18:50:50.360Z",
"answer_score": 264
} |
Please answer the following Stack Overflow question:
Title: Java Generate Random Number Between Two Given Values
<p>I would like to know how to generate a random number between two given values.</p>
<p>I am able to generate a random number with the following:</p>
<pre><code>Random r = new Random();
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a[i].length; j++){
a[i][j] = r.nextInt();
}
}
</code></pre>
<p>However, how can I generate a random number between 0 and 100 (inclusive)?</p> | <p>You could use e.g. <code>r.nextInt(101)</code></p>
<p>For a more generic "in between two numbers" use:</p>
<pre><code>Random r = new Random();
int low = 10;
int high = 100;
int result = r.nextInt(high-low) + low;
</code></pre>
<p>This gives you a random number in between 10 (inclusive) and 100 (exclusive)</p> | {
"question_id": 5271598,
"question_date": "2011-03-11T10:15:31.973Z",
"question_score": 205,
"tags": "java|random|numbers",
"answer_id": 5271613,
"answer_date": "2011-03-11T10:17:22.980Z",
"answer_score": 513
} |
Please answer the following Stack Overflow question:
Title: Update multiple columns in SQL
<p>Is there a way to update multiple columns in SQL server the same way an insert statement is used?</p>
<p>Something like:</p>
<pre><code>Update table1 set (a,b,c,d,e,f,g,h,i,j,k)=
(t2.a,t2.b,t2.c,t2.d,t2.e,t2.f,t2.g,t2.h,t2.i,t2.j,t2.k)
from table2 t2
where table1.id=table2.id
</code></pre>
<p>Or something like that, rather than like so:</p>
<pre><code>update table set a=t2.a,b=t2.b etc
</code></pre>
<p>which can be pretty tiresome to write if you have 100+ columns.</p> | <p>The "tiresome way" is standard SQL and how mainstream RDBMS do it.</p>
<p>With a 100+ columns, you mostly likely have a design problem... also, there are mitigating methods in client tools (eg generation UPDATE statements) or by using ORMs</p> | {
"question_id": 9079617,
"question_date": "2012-01-31T12:37:03.820Z",
"question_score": 205,
"tags": "sql|sql-server|sql-update",
"answer_id": 9079656,
"answer_date": "2012-01-31T12:39:51.303Z",
"answer_score": 104
} |
Please answer the following Stack Overflow question:
Title: Setting background colour of Android layout element
<p>I am trying to, somewhat clone the design of an activity <a href="https://docs.google.com/present/view?id=0AfYilHnGmJNGZGZwNnZ4dm5fNDdkY3o2M3Bqag&hl=en_GB">from a set of slides on Android UI design</a>. However I am having a problem with a very simple task.</p>
<p>I have created the layout as shown in the image, and the header is a <code>TextView</code> in a <code>RelativeLayout</code>. Now I wish to change the background colour of the <code>RelativeLayout</code>, however I cannot seem to figure out how.</p>
<p>I know I can set the <code>android:background</code> property in the <code>RelativeLayout</code> tag in the XML file, but what do I set it to? I want to define a new colour that I can use in multiple places. Is it a <code>drawable</code> or a <code>string</code>?</p>
<p>Additionally I would expect there to be a very simple way to this from within the Eclipse Android UI designer that I must be missing?</p>
<p>I am a bit frustrated currently, as this should be an activity that is performed with a few clicks at maximum. So any help is very appreciated. :)</p>
<p><img src="https://i.stack.imgur.com/BeIBr.png" alt="Android activity design"></p> | <p>You can use <a href="http://developer.android.com/guide/topics/resources/more-resources.html#Color" rel="noreferrer">simple color resources</a>, specified usually inside <code>res/values/colors.xml</code>.</p>
<pre><code><color name="red">#ffff0000</color>
</code></pre>
<p>and use this via <code>android:background="@color/red"</code>. This color can be used anywhere else too, e.g. as a text color. Reference it in XML the same way, or get it in code via <code>getResources().getColor(R.color.red)</code>.</p>
<p>You can also use any <a href="http://developer.android.com/guide/topics/resources/drawable-resource.html" rel="noreferrer">drawable resource</a> as a background, use <code>android:background="@drawable/mydrawable"</code> for this (that means 9patch drawables, normal bitmaps, shape drawables, ..).</p> | {
"question_id": 7378636,
"question_date": "2011-09-11T13:48:22.413Z",
"question_score": 205,
"tags": "android|android-layout|user-experience|adt",
"answer_id": 7378716,
"answer_date": "2011-09-11T14:02:10.373Z",
"answer_score": 283
} |
Please answer the following Stack Overflow question:
Title: Replacing column values in a pandas DataFrame
<p>I'm trying to replace the values in one column of a dataframe. The column ('female') only contains the values 'female' and 'male'. </p>
<p>I have tried the following:</p>
<pre><code>w['female']['female']='1'
w['female']['male']='0'
</code></pre>
<p>But receive the exact same copy of the previous results.</p>
<p>I would ideally like to get some output which resembles the following loop element-wise.</p>
<pre><code>if w['female'] =='female':
w['female'] = '1';
else:
w['female'] = '0';
</code></pre>
<p>I've looked through the gotchas documentation (<a href="http://pandas.pydata.org/pandas-docs/stable/gotchas.html">http://pandas.pydata.org/pandas-docs/stable/gotchas.html</a>) but cannot figure out why nothing happens.</p>
<p>Any help will be appreciated.</p> | <p>If I understand right, you want something like this:</p>
<pre><code>w['female'] = w['female'].map({'female': 1, 'male': 0})
</code></pre>
<p>(Here I convert the values to numbers instead of strings containing numbers. You can convert them to <code>"1"</code> and <code>"0"</code>, if you really want, but I'm not sure why you'd want that.)</p>
<p>The reason your code doesn't work is because using <code>['female']</code> on a column (the second <code>'female'</code> in your <code>w['female']['female']</code>) doesn't mean "select rows where the value is 'female'". It means to select rows where the <em>index</em> is 'female', of which there may not be any in your DataFrame.</p> | {
"question_id": 23307301,
"question_date": "2014-04-26T06:04:24.873Z",
"question_score": 205,
"tags": "python|pandas",
"answer_id": 23307361,
"answer_date": "2014-04-26T06:12:02.527Z",
"answer_score": 343
} |
Please answer the following Stack Overflow question:
Title: How do I analyze a program's core dump file with GDB when it has command-line parameters?
<p>My program operates like this:</p>
<pre><code>exe -p param1 -i param2 -o param3
</code></pre>
<p>It crashed and generated a core dump file, <code>core.pid</code>.</p>
<p>I want to analyze the core dump file by</p>
<pre><code>gdb ./exe -p param1 -i param2 -o param3 core.pid
</code></pre>
<p>But GDB recognizes the parameters of the EXE file as GDB's input.</p>
<p>How do I analyze a core dump file in this situation?</p> | <p>You can use the core with GDB in many ways, but passing parameters which is to be passed to the executable to GDB is not the way to use the core file. This could also be the reason you got that error. You can use the core file in the following ways:</p>
<p><code>gdb <executable> <core-file></code> or <code>gdb <executable> -c <core-file></code> or</p>
<pre><code>gdb <executable>
...
(gdb) core <core-file>
</code></pre>
<p>When using the core file you don't have to pass arguments. The crash scenario is shown in GDB (checked with GDB version 7.1 on Ubuntu).</p>
<p>For example:</p>
<pre><code>$ ./crash -p param1 -o param2
Segmentation fault (core dumped)
$ gdb ./crash core
GNU gdb (GDB) 7.1-ubuntu
...
Core was generated by `./crash -p param1 -o param2'. <<<<< See this line shows crash scenario
Program terminated with signal 11, Segmentation fault.
#0 __strlen_ia32 () at ../sysdeps/i386/i686/multiarch/../../i586/strlen.S:99
99 ../sysdeps/i386/i686/multiarch/../../i586/strlen.S: No such file or directory.
in ../sysdeps/i386/i686/multiarch/../../i586/strlen.S
(gdb)
</code></pre>
<p>If you want to pass parameters to the executable to be debugged in GDB, use <code>--args</code>.</p>
<p>For example:</p>
<pre><code>$ gdb --args ./crash -p param1 -o param2
GNU gdb (GDB) 7.1-ubuntu
...
(gdb) r
Starting program: /home/@@@@/crash -p param1 -o param2
Program received signal SIGSEGV, Segmentation fault.
__strlen_ia32 () at ../sysdeps/i386/i686/multiarch/../../i586/strlen.S:99
99 ../sysdeps/i386/i686/multiarch/../../i586/strlen.S: No such file or directory.
in ../sysdeps/i386/i686/multiarch/../../i586/strlen.S
(gdb)
</code></pre>
<p>Man pages will be helpful to see other GDB options.</p>
<p>Most useful commands are:</p>
<ul>
<li><code>bt</code> (backtrace)</li>
<li><code>info locals</code> (show values of local variables)</li>
<li><code>info registers</code> (show values of CPU registers)</li>
<li><code>frame X</code> (change to stack frame <em>X</em>)</li>
<li><code>up</code> and <code>down</code> (navigate in the stack frame (call chain))</li>
</ul> | {
"question_id": 8305866,
"question_date": "2011-11-29T04:29:02.280Z",
"question_score": 205,
"tags": "linux|debugging|gdb|coredump",
"answer_id": 8306805,
"answer_date": "2011-11-29T06:30:33.040Z",
"answer_score": 246
} |
Please answer the following Stack Overflow question:
Title: How to convert XML into array in PHP?
<p>I want to convert below XML to PHP array. Any suggestions on how I can do this?</p>
<pre><code><aaaa Version="1.0">
<bbb>
<cccc>
<dddd Id="id:pass" />
<eeee name="hearaman" age="24" />
</cccc>
</bbb>
</aaaa>
</code></pre> | <p>Another option is the SimpleXML extension (I believe it comes standard with most php installs.)</p>
<p><a href="http://php.net/manual/en/book.simplexml.php" rel="noreferrer">http://php.net/manual/en/book.simplexml.php</a></p>
<p>The syntax looks something like this for your example</p>
<pre><code>$xml = new SimpleXMLElement($xmlString);
echo $xml->bbb->cccc->dddd['Id'];
echo $xml->bbb->cccc->eeee['name'];
// or...........
foreach ($xml->bbb->cccc as $element) {
foreach($element as $key => $val) {
echo "{$key}: {$val}";
}
}
</code></pre> | {
"question_id": 6578832,
"question_date": "2011-07-05T06:45:45.977Z",
"question_score": 205,
"tags": "php|xml",
"answer_id": 6578969,
"answer_date": "2011-07-05T06:59:30.340Z",
"answer_score": 141
} |
Please answer the following Stack Overflow question:
Title: .NET HttpClient. How to POST string value?
<p>How can I create using C# and HttpClient the following POST request:
<img src="https://i.stack.imgur.com/yp8jr.png" alt="User-Agent: Fiddler Content-type: application/x-www-form-urlencoded Host: localhost:6740 Content-Length: 6"></p>
<p>I need such a request for my WEB API service:</p>
<pre><code>[ActionName("exist")]
[HttpPost]
public bool CheckIfUserExist([FromBody] string login)
{
return _membershipProvider.CheckIfExist(login);
}
</code></pre> | <pre><code>using System;
using System.Collections.Generic;
using System.Net.Http;
class Program
{
static void Main(string[] args)
{
Task.Run(() => MainAsync());
Console.ReadLine();
}
static async Task MainAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:6740");
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("", "login")
});
var result = await client.PostAsync("/api/Membership/exists", content);
string resultContent = await result.Content.ReadAsStringAsync();
Console.WriteLine(resultContent);
}
}
}
</code></pre> | {
"question_id": 15176538,
"question_date": "2013-03-02T16:10:10.240Z",
"question_score": 205,
"tags": "c#|asp.net-web-api|dotnet-httpclient",
"answer_id": 15176685,
"answer_date": "2013-03-02T16:22:42.240Z",
"answer_score": 477
} |
Please answer the following Stack Overflow question:
Title: Retrieve CPU usage and memory usage of a single process on Linux?
<p>I want to get the CPU and memory usage of a single process on Linux - I know the PID. Hopefully, I can get it every second and write it to a CSV using the 'watch' command. What command can I use to get this info from the Linux command-line?</p> | <pre><code>ps -p <pid> -o %cpu,%mem,cmd
</code></pre>
<p>(You can leave off "cmd" but that might be helpful in debugging).</p>
<p>Note that this gives average CPU usage of the process over the time it has been running.</p> | {
"question_id": 1221555,
"question_date": "2009-08-03T10:13:50.830Z",
"question_score": 205,
"tags": "linux|shell|memory-management|cpu-usage",
"answer_id": 1221597,
"answer_date": "2009-08-03T10:23:28.030Z",
"answer_score": 278
} |
Please answer the following Stack Overflow question:
Title: Asynchronous Requests with Python requests
<p>I tried the sample provided within the documentation of the <a href="http://docs.python-requests.org/en/latest/user/advanced/#asynchronous-requests" rel="noreferrer">requests library</a> for python.</p>
<p>With <code>async.map(rs)</code>, I get the response codes, but I want to get the content of each page requested. This, for example, does not work:</p>
<pre><code>out = async.map(rs)
print out[0].content
</code></pre> | <h2>Note</h2>
<p>The below answer is <em>not</em> applicable to requests v0.13.0+. The asynchronous functionality was moved to <a href="https://github.com/kennethreitz/grequests" rel="noreferrer">grequests</a> after this question was written. However, you could just replace <code>requests</code> with <code>grequests</code> below and it should work.</p>
<p>I've left this answer as is to reflect the original question which was about using requests < v0.13.0.</p>
<hr>
<p>To do multiple tasks with <code>async.map</code> <em>asynchronously</em> you have to:</p>
<ol>
<li>Define a function for what you want to do with each object (your task)</li>
<li>Add that function as an event hook in your request</li>
<li>Call <code>async.map</code> on a list of all the requests / actions</li>
</ol>
<p>Example:</p>
<pre><code>from requests import async
# If using requests > v0.13.0, use
# from grequests import async
urls = [
'http://python-requests.org',
'http://httpbin.org',
'http://python-guide.org',
'http://kennethreitz.com'
]
# A simple task to do to each response object
def do_something(response):
print response.url
# A list to hold our things to do via async
async_list = []
for u in urls:
# The "hooks = {..." part is where you define what you want to do
#
# Note the lack of parentheses following do_something, this is
# because the response will be used as the first argument automatically
action_item = async.get(u, hooks = {'response' : do_something})
# Add the task to our list of things to do via async
async_list.append(action_item)
# Do our list of things to do via async
async.map(async_list)
</code></pre> | {
"question_id": 9110593,
"question_date": "2012-02-02T10:20:07.830Z",
"question_score": 205,
"tags": "python|asynchronous|python-requests|httprequest",
"answer_id": 9189249,
"answer_date": "2012-02-08T07:23:17.847Z",
"answer_score": 185
} |
Please answer the following Stack Overflow question:
Title: Laravel Eloquent "WHERE NOT IN"
<p>I'm having trouble to write query in <code>laravel eloquent ORM</code>. </p>
<p>my query is </p>
<pre><code>SELECT book_name,dt_of_pub,pub_lang,no_page,book_price
FROM book_mast
WHERE book_price NOT IN (100,200);
</code></pre>
<p>Now I want to convert this query into laravel eloquent.</p> | <p>Query Builder:</p>
<pre><code>DB::table(..)->select(..)->whereNotIn('book_price', [100,200])->get();
</code></pre>
<p>Eloquent:</p>
<pre><code>SomeModel::select(..)->whereNotIn('book_price', [100,200])->get();
</code></pre> | {
"question_id": 25849015,
"question_date": "2014-09-15T13:15:59.673Z",
"question_score": 205,
"tags": "laravel|laravel-4|eloquent",
"answer_id": 25850237,
"answer_date": "2014-09-15T14:19:31.573Z",
"answer_score": 441
} |
Please answer the following Stack Overflow question:
Title: Could not load file or assembly 'System.Web.Mvc'
<p>My new ASP.NET MVC Web Application works on my development workstation, but does not run on my web server...</p>
<hr>
<h1>Server Error in '/' Application.</h1>
<hr>
<h2>Configuration Error</h2>
<p><strong>Description:</strong> An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately. </p>
<p><strong>Parser Error Message:</strong> Could not load file or assembly 'System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified. </p>
<p><strong>Source Error:</strong> </p>
<pre><code>Line 44: <add assembly="System.Web.Abstractions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
Line 45: <add assembly="System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
Line 46: <add assembly="System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
Line 47: <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
Line 48: <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
</code></pre>
<p><strong>Source File:</strong> C:\inetpub\www.example.org\web.config <strong>Line:</strong> 46 </p>
<p><strong>Assembly Load Trace:</strong> The following information can be helpful to determine why the assembly 'System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' could not be loaded. </p>
<pre>
WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].
</pre>
<hr>
<p><strong>Version Information:</strong> Microsoft .NET Framework Version:2.0.50727.3053; ASP.NET Version:2.0.50727.3053</p>
<hr>
<p>Do I need to install the <em>AspNetMVCBeta-setup.msi</em> on the server? Or is there a different installer for servers?</p>
<p><img src="https://i.stack.imgur.com/V21XS.gif" alt="enter image description here"></p> | <p>I just wrote a blog post addressing this. You could install ASP.NET MVC on your server OR you can follow the <a href="http://haacked.com/archive/2008/11/03/bin-deploy-aspnetmvc.aspx" rel="noreferrer">steps here</a>.</p>
<hr>
<p><strong>EDIT:</strong> (by jcolebrand) I went through this link, then had the same issue as <a href="https://stackoverflow.com/users/653855/victor-juri">Victor</a> <a href="https://stackoverflow.com/questions/267006/could-not-load-file-or-assembly-system-web-mvc/5481834#5481834">below</a>, so I suggest you also add these:</p>
<pre><code>* Microsoft.Web.Infrastructure
* System.Web.Razor
* System.Web.WebPages.Deployment
* System.Web.WebPages.Razor
</code></pre> | {
"question_id": 267006,
"question_date": "2008-11-05T22:40:34.983Z",
"question_score": 205,
"tags": "asp.net-mvc",
"answer_id": 267021,
"answer_date": "2008-11-05T22:47:20.697Z",
"answer_score": 216
} |
Please answer the following Stack Overflow question:
Title: How to send email from Terminal?
<p>I know there are ways to send email from terminal in Linux/MacOS, but I can't seem to find proper documentation on how to do that.</p>
<p>Basically I need it for my bash script that notifies me every time there is a change in a file.</p> | <p>Go into Terminal and type <code>man mail</code> for help.</p>
<p>You will need to set <code>SMTP</code> up:</p>
<p><a href="http://hints.macworld.com/article.php?story=20081217161612647" rel="noreferrer">http://hints.macworld.com/article.php?story=20081217161612647</a></p>
<p>See also:</p>
<p><a href="http://www.mactricksandtips.com/2008/09/send-mail-over-your-network.html" rel="noreferrer">http://www.mactricksandtips.com/2008/09/send-mail-over-your-network.html</a></p>
<p>Eg:</p>
<pre><code>mail -s "hello" "[email protected]" <<EOF
hello
world
EOF
</code></pre>
<p>This will send an email to <code>[email protected]</code> with the subject <code>hello</code> and the message</p>
<blockquote>
<p>Hello</p>
<p>World</p>
</blockquote> | {
"question_id": 8260858,
"question_date": "2011-11-24T17:39:04.293Z",
"question_score": 205,
"tags": "bash|email|terminal",
"answer_id": 8260923,
"answer_date": "2011-11-24T17:46:04.747Z",
"answer_score": 137
} |
Please answer the following Stack Overflow question:
Title: How to get the current directory in a C program?
<p>I'm making a C program where I need to get the directory that the program is started from. This program is written for UNIX computers. I've been looking at <code>opendir()</code> and <code>telldir()</code>, but <code>telldir()</code> returns a <code>off_t (long int)</code>, so it really doesn't help me. </p>
<p>How can I get the current path in a string (char array)?</p> | <p>Have you had a look at <a href="http://pubs.opengroup.org/onlinepubs/9699919799/functions/getcwd.html" rel="noreferrer"><code>getcwd()</code></a>?</p>
<pre><code>#include <unistd.h>
char *getcwd(char *buf, size_t size);
</code></pre>
<p>Simple example:</p>
<pre><code>#include <unistd.h>
#include <stdio.h>
#include <limits.h>
int main() {
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != NULL) {
printf("Current working dir: %s\n", cwd);
} else {
perror("getcwd() error");
return 1;
}
return 0;
}
</code></pre> | {
"question_id": 298510,
"question_date": "2008-11-18T11:36:29.043Z",
"question_score": 205,
"tags": "c|unix|working-directory",
"answer_id": 298518,
"answer_date": "2008-11-18T11:38:24.747Z",
"answer_score": 364
} |
Please answer the following Stack Overflow question:
Title: Have a fixed position div that needs to scroll if content overflows
<p>I have actually two issues, but lets resolve the primary issue first as I believe the other is easier to address.</p>
<p>I have a fixed position div on the left side of the scroll for a menu. Right side is a standard div that scrolls properly. The issue is that when the browser view-port is too small to see the entire menu.. there is no way to get it to scroll that I can find (at least not with css). I've tried using different overflows in css, but nothing makes the div scroll. The div that contains the menu is set to min-height:100% and position:fixed.. both attributes I need to keep. </p>
<p>The div containing the <em>menu</em> is inside another wrapper div that is positioned absolutely and height set to 100%.</p>
<p>How can I get it to scroll vertically if the content is too tall for the div?</p>
<p>That leads me to the other issue, that i don't want a scroll bar to display.. but I think I may already have an answer to that (only it doesn't work yet because I can't get the div to scroll to begin with).</p>
<p>Any solutions? Perhaps javascript is needed? (of which i know little about)</p>
<p><a href="http://jsfiddle.net/csdigitaldesign/NDx47/" rel="noreferrer">JS Fiddle Example</a></p>
<p>and the relevant code that is causing the issue (since posting the whole thing in here is waaay too long):</p>
<pre><code>.fixed-content {
min-height:100%;
position:fixed;
overflow-y:scroll;
overflow-x:hidden;
}
</code></pre>
<p>Also tried adding height:100% as well just to see if that was an issue but it didn't work either... nor did a fixed height, such as 600px.</p> | <p>The problem with using <code>height:100%</code> is that it will be 100% of the page instead of 100% of the window (as you would probably expect it to be). This will cause the problem that you're seeing, because the non-fixed content is long enough to include the fixed content with 100% height without requiring a scroll bar. The browser doesn't know/care that you can't actually scroll that bar down to see it</p>
<p>You can use <code>fixed</code> to accomplish what you're trying to do.</p>
<pre><code>.fixed-content {
top: 0;
bottom:0;
position:fixed;
overflow-y:scroll;
overflow-x:hidden;
}
</code></pre>
<p>This fork of your fiddle shows my fix:
<a href="http://jsfiddle.net/strider820/84AsW/1/" rel="noreferrer">http://jsfiddle.net/strider820/84AsW/1/</a></p> | {
"question_id": 16094785,
"question_date": "2013-04-18T23:28:58.247Z",
"question_score": 205,
"tags": "css|scroll|css-position|overflow",
"answer_id": 18366583,
"answer_date": "2013-08-21T20:01:18.563Z",
"answer_score": 323
} |
Please answer the following Stack Overflow question:
Title: Mongoimport of JSON file
<p>I have a JSON file consisting of about 2000 records. Each record which will correspond to a document in the mongo database is formatted as follows:</p>
<pre><code>{jobID:"2597401",
account:"XXXXX",
user:"YYYYY",
pkgT:{"pgi/7.2-5":{libA:["libpgc.so"],flavor:["default"]}},
startEpoch:"1338497979",
runTime:"1022",
execType:"user:binary",
exec:"/share/home/01482/XXXXX/appker/ranger/NPB3.3.1/NPB3.3-MPI/bin/ft.D.64",
numNodes:"4",
sha1:"5a79879235aa31b6a46e73b43879428e2a175db5",
execEpoch:1336766742,
execModify: new Date("Fri May 11 15:05:42 2012"),
startTime: new Date("Thu May 31 15:59:39 2012"),
numCores:"64",
sizeT:{bss:"1881400168",text:"239574",data:"22504"}},
</code></pre>
<p>Each record is on a single line in the JSON file, and the only line breaks are at the end of every record. Therefore, each line in the document starts with "{jobID:"... I am trying to import these into a mongo database using the following command:</p>
<pre><code>mongoimport --db dbName --collection collectionName --file fileName.json
</code></pre>
<p>However, I get the following error:</p>
<pre><code>Sat Mar 2 01:26:12 Assertion: 10340:Failure parsing JSON string near: ,execModif
0x10059f12b 0x100562d5c 0x100562e9c 0x10025eb98 0x10000e643 0x100010b60 0x10055c4cc 0x1000014b7
0x100001454
0 mongoimport 0x000000010059f12b _ZN5mongo15printStackTraceERSo + 43
1 mongoimport 0x0000000100562d5c _ZN5mongo11msgassertedEiPKc + 204
2 mongoimport 0x0000000100562e9c _ZN5mongo11msgassertedEiRKSs + 12
3 mongoimport 0x000000010025eb98 _ZN5mongo8fromjsonEPKcPi + 1576
4 mongoimport 0x000000010000e643
_ZN6Import8parseRowEPSiRN5mongo7BSONObjERi + 2739
5 mongoimport 0x0000000100010b60 _ZN6Import3runEv + 7376
6 mongoimport 0x000000010055c4cc _ZN5mongo4Tool4mainEiPPc + 5436
7 mongoimport 0x00000001000014b7 main + 55
8 mongoimport 0x0000000100001454 start + 52
Sat Mar 2 01:26:12 exception:BSON representation of supplied JSON is too large: Failure parsing
JSON string near: ,execModif
Sat Mar 2 01:26:12
Sat Mar 2 01:26:12 imported 0 objects
Sat Mar 2 01:26:12 ERROR: encountered 1941 errors
</code></pre>
<p>I do not know what the problem is. Can someone recommend a solution?</p> | <p>I was able to fix the error using the following query:</p>
<pre><code>mongoimport --db dbName --collection collectionName --file fileName.json --jsonArray
</code></pre>
<p>Hopefully this is helpful to someone.</p> | {
"question_id": 15171622,
"question_date": "2013-03-02T06:40:10.987Z",
"question_score": 205,
"tags": "json|mongodb|import|mongoimport",
"answer_id": 15941263,
"answer_date": "2013-04-11T05:18:23.820Z",
"answer_score": 387
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.