input_text
stringlengths 115
13.8k
| output_text
stringlengths 24
15k
| metadata
dict |
---|---|---|
Please answer the following Stack Overflow question:
Title: Git: Permission denied (publickey) fatal - Could not read from remote repository. while cloning Git repository
<p>I am unable to clone a Git repository, and getting this error:</p>
<pre><code>krishna.soni@KRISHNACHANDRAS /c/Projects $ git clone http://stage.abc.com:10088/pqr
http://<url>/<repository> Cloning into '<repository>'... fatal: could not read Username for 'http://<url>': No such file or directory
</code></pre>
<p>I've read <a href="https://stackoverflow.com/questions/20923193/bitbucket-windows-and-fatal-could-not-read-password-for">Bitbucket, Windows and “fatal: could not read Password for”</a>, but still have the problem.</p>
<p>I proceeded further but am now getting this error</p>
<pre><code>sh.exe": chown: command not found
krishna.soni@KRISHNACHANDRAS /c
$ git clone ssh://[email protected].
/projects
Cloning into 'C:/projects'...
Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
> krishna.soni@KRISHNACHANDRAS /c
> $ git clone ssh:<url>
> ts
> Cloning into 'C:/projects'...
> Permission denied (publickey).
> fatal: Could not read from remote repository.
Please make sure you have the correct access rights
</code></pre>
<p>and the repository exists.</p> | <p>It looks like a permissions issue - not a Windows 7 issue. </p>
<p>Your ssh key is not authorised - <code>Permission denied (publickey)</code>. </p>
<p>You need to create a public ssh key and ask the administrator of the Git repository to add the <code>ssh</code> public key</p>
<p>Information on how to do this: <a href="https://stackoverflow.com/questions/7430311/saving-ssh-key-fails/8600087#8600087">Saving ssh key fails</a></p> | {
"question_id": 21255438,
"question_date": "2014-01-21T10:27:50.277Z",
"question_score": 209,
"tags": "git|git-clone",
"answer_id": 21258844,
"answer_date": "2014-01-21T12:58:20.623Z",
"answer_score": 73
} |
Please answer the following Stack Overflow question:
Title: Angular 2 Show and Hide an element
<p>I'm having a problem hiding and showing an element depending of a boolean variable in Angular 2.</p>
<p>this is the code for the div to show and hide:</p>
<pre><code><div *ngIf="edited==true" class="alert alert-success alert-dismissible fade in" role="alert">
<strong>List Saved!</strong> Your changes has been saved.
</div>
</code></pre>
<p>the variable is "edited" and it's stored in my component:</p>
<pre class="lang-js prettyprint-override"><code>export class AppComponent implements OnInit{
(...)
public edited = false;
(...)
saveTodos(): void {
//show box msg
this.edited = true;
//wait 3 Seconds and hide
setTimeout(function() {
this.edited = false;
console.log(this.edited);
}, 3000);
}
}
</code></pre>
<p>The element is hidden, when saveTodos function starts, the element is shown, but after 3 seconds, even if the variable come back to be false, the element does not hide. Why?</p> | <p>You should use the *ngIf Directive</p>
<pre><code><div *ngIf="edited" class="alert alert-success box-msg" role="alert">
<strong>List Saved!</strong> Your changes has been saved.
</div>
export class AppComponent implements OnInit{
(...)
public edited = false;
(...)
saveTodos(): void {
//show box msg
this.edited = true;
//wait 3 Seconds and hide
setTimeout(function() {
this.edited = false;
console.log(this.edited);
}.bind(this), 3000);
}
}
</code></pre>
<hr />
<p>Update: you are missing the reference to the outer scope when you are inside the Timeout callback.</p>
<p>so add the .bind(this) like I added Above</p>
<blockquote>
<p>Q : edited is a global variable. What would be your approach within a *ngFor-loop? – Blauhirn</p>
<p>A : I would add edit as a property to the object I am iterating over.</p>
</blockquote>
<pre><code><div *ngFor="let obj of listOfObjects" *ngIf="obj.edited" class="alert alert-success box-msg" role="alert">
<strong>List Saved!</strong> Your changes has been saved.
</div>
export class AppComponent implements OnInit{
public listOfObjects = [
{
name : 'obj - 1',
edit : false
},
{
name : 'obj - 2',
edit : false
},
{
name : 'obj - 2',
edit : false
}
];
saveTodos(): void {
//show box msg
this.edited = true;
//wait 3 Seconds and hide
setTimeout(function() {
this.edited = false;
console.log(this.edited);
}.bind(this), 3000);
}
}
</code></pre> | {
"question_id": 35163009,
"question_date": "2016-02-02T20:16:40.767Z",
"question_score": 209,
"tags": "typescript|angular",
"answer_id": 35163037,
"answer_date": "2016-02-02T20:18:43.833Z",
"answer_score": 188
} |
Please answer the following Stack Overflow question:
Title: How do I escape a single quote ( ' ) in JavaScript?
<p><strong>UPDATE:</strong>
I want to give an updated answer to this question. First, let me state if you're attempting to accomplish what I have below, I recommend that you manage events by <a href="https://developer.mozilla.org/en-US/docs/Talk:DOM/element.addEventListener" rel="noreferrer">adding event listeners</a> instead. I highly recommend that you utilize <a href="https://jquery.com/" rel="noreferrer">jQuery</a> for your project and use their syntax to <a href="http://api.jquery.com/on/" rel="noreferrer">manage event listeners</a> over using DOM.</p>
<p><strong>QUESTION</strong></p>
<p>Okay, I am basically doing this:</p>
<pre><code>document.getElementById("something").innerHTML = "<img src='something' onmouseover='change(\'ex1\')' />";
</code></pre>
<p>I don't want double quotes (") where I put the \'. I only want a single quote, so I am trying to not make it put a double when it is used. I am trying to reach this in the final outcome.</p>
<pre><code><img src="something" onmouseover="change('ex1')" />
</code></pre>
<p>Escaping isn't working for me.</p>
<p>My marked answer works fine, however, the cleaner (and more professional-looking way, IMO) is <a href="https://stackoverflow.com/a/16134953/1754890">loganfsmyth's answer</a>.</p> | <p>You should always consider what the browser will see by the end. In this case, it will see this:</p>
<pre><code><img src='something' onmouseover='change(' ex1')' />
</code></pre>
<p>In other words, the "onmouseover" attribute is just <code>change(</code>, and there's another "attribute" called <code>ex1')'</code> with no value.</p>
<p>The truth is, HTML does not use <code>\</code> for an escape character. But it does recognise <code>&quot;</code> and <code>&apos;</code> as escaped quote and apostrophe, respectively.</p>
<p>Armed with this knowledge, use this:</p>
<pre><code>document.getElementById("something").innerHTML = "<img src='something' onmouseover='change(&quot;ex1&quot;)' />";
</code></pre>
<p>... That being said, you could just use JavaScript quotes:</p>
<pre><code>document.getElementById("something").innerHTML = "<img src='something' onmouseover='change(\"ex1\")' />";
</code></pre> | {
"question_id": 16134910,
"question_date": "2013-04-21T18:49:27.083Z",
"question_score": 209,
"tags": "javascript|html|escaping",
"answer_id": 16134951,
"answer_date": "2013-04-21T18:53:16.873Z",
"answer_score": 198
} |
Please answer the following Stack Overflow question:
Title: In Python how should I test if a variable is None, True or False
<p>I have a function that can return one of three things:</p>
<ul>
<li>success (<code>True</code>)</li>
<li>failure (<code>False</code>)</li>
<li>error reading/parsing stream (<code>None</code>)</li>
</ul>
<p>My question is, if I'm not supposed to test against <code>True</code> or <code>False</code>, how should I see what the result is. Below is how I'm currently doing it:</p>
<pre><code>result = simulate(open("myfile"))
if result == None:
print "error parsing stream"
elif result == True: # shouldn't do this
print "result pass"
else:
print "result fail"
</code></pre>
<p>is it really as simple as removing the <code>== True</code> part or should I add a tri-bool data-type. I do not want the <code>simulate</code> function to throw an exception as all I want the outer program to do with an error is log it and continue. </p> | <p>Don't fear the Exception! Having your program just log and continue is as easy as:</p>
<pre><code>try:
result = simulate(open("myfile"))
except SimulationException as sim_exc:
print "error parsing stream", sim_exc
else:
if result:
print "result pass"
else:
print "result fail"
# execution continues from here, regardless of exception or not
</code></pre>
<p>And now you can have a much richer type of notification from the simulate method as to what exactly went wrong, in case you find error/no-error not to be informative enough.</p> | {
"question_id": 2020598,
"question_date": "2010-01-07T13:32:36.410Z",
"question_score": 209,
"tags": "python",
"answer_id": 2020704,
"answer_date": "2010-01-07T13:46:51Z",
"answer_score": 135
} |
Please answer the following Stack Overflow question:
Title: CSS: 100% width or height while keeping aspect ratio?
<p>Currently, with STYLE, I can use <code>width: 100%</code> and <code>auto</code> on the height (or vice versa), but I still can't constrain the image into a specific position, either being too wide or too tall, respectively.</p>
<p>Any ideas?</p> | <p>If you only define one dimension on an image the image aspect ratio will always be preserved.</p>
<p>Is the issue that the image is bigger/taller than you prefer?</p>
<p>You could put it inside a DIV that is set to the maximum height/width that you want for the image, and then set overflow:hidden. That would crop anything beyond what you want.</p>
<p>If an image is 100% wide and height:auto and you think it's too tall, that is specifically because the aspect ratio is preserved. You'll need to crop, or to change the aspect ratio.</p>
<p>Please provide some more information about what you're specifically trying to accomplish and I'll try to help more!</p>
<p>--- EDIT BASED ON FEEDBACK ---</p>
<p>Are you familiar with the <a href="http://www.w3schools.com/cssref/pr_dim_max-width.asp" rel="noreferrer">max-width</a> and <a href="http://www.w3schools.com/cssref/pr_dim_max-height.asp" rel="noreferrer">max-height</a> properties? You could always set those instead. If you don't set any minimum and you set a max height and width then your image will not be distorted (aspect ratio will be preserved) and it will not be any larger than whichever dimension is longest and hits its max.</p> | {
"question_id": 3751565,
"question_date": "2010-09-20T12:42:45.160Z",
"question_score": 209,
"tags": "css|image|height|width",
"answer_id": 3751836,
"answer_date": "2010-09-20T13:20:03.317Z",
"answer_score": 152
} |
Please answer the following Stack Overflow question:
Title: Unable to import a module that is definitely installed
<p>After installing <a href="https://pypi.org/project/mechanize/" rel="noreferrer">mechanize</a>, I don't seem to be able to import it.</p>
<p>I have tried installing from pip, easy_install, and via <code>python setup.py install</code> from this repo: <a href="https://github.com/abielr/mechanize" rel="noreferrer">https://github.com/abielr/mechanize</a>. All of this to no avail, as each time I enter my Python interactive I get:</p>
<pre><code>Python 2.7.3 (default, Aug 1 2012, 05:14:39)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import mechanize
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named mechanize
>>>
</code></pre>
<p>The installations I ran previously reported that they had completed successfully, so I expect the import to work. What could be causing this error?</p> | <p>In my case, it is permission problem. The package was somehow installed with root rw permission only, other user just cannot rw to it!</p> | {
"question_id": 14295680,
"question_date": "2013-01-12T17:07:14.360Z",
"question_score": 209,
"tags": "python|importerror|python-module",
"answer_id": 16377297,
"answer_date": "2013-05-04T17:55:33.507Z",
"answer_score": 128
} |
Please answer the following Stack Overflow question:
Title: How to start MySQL server from command line on Mac OS Lion?
<p>I installed mySQL on my Mac. Beside starting the SQL server with mySQL.prefPane tool installed in System Preferences, I want to know the instructions to start from command-line.
I do as follows:</p>
<p>After</p>
<blockquote>
<p>su root</p>
</blockquote>
<p>I start the mySQL server by command-line, but it produces an error as below:</p>
<blockquote>
<p><strong>sh-3.2#</strong> /usr/local/mysql/bin/mysqld</p>
<p><strong>111028 16:57:43</strong> [Warning] Setting lower_case_table_names=2 because
file system for /usr/local/mysql-5.5.17-osx10.6-x86_64/data/ is case
insensitive</p>
<p><strong>111028 16:57:43</strong> [ERROR] Fatal error: Please read "Security" section of
the manual to find out how to run mysqld as root!</p>
<p><strong>111028 16:57:43</strong> [ERROR] Aborting</p>
<p><strong>111028 16:57:43</strong> [Note] /usr/local/mysql/bin/mysqld: Shutdown complete</p>
</blockquote> | <p>Try <code>/usr/local/mysql/bin/mysqld_safe</code></p>
<p>Example:</p>
<pre><code>shell> sudo /usr/local/mysql/bin/mysqld_safe
(Enter your password, if necessary)
(Press Control-Z)
shell> bg
(Press Control-D or enter "exit" to exit the shell)
</code></pre>
<p>You can also add these to your bash startup scripts:</p>
<pre><code>export MYSQL_HOME=/usr/local/mysql
alias start_mysql='sudo $MYSQL_HOME/bin/mysqld_safe &'
alias stop_mysql='sudo $MYSQL_HOME/bin/mysqladmin shutdown'
</code></pre> | {
"question_id": 7927854,
"question_date": "2011-10-28T10:05:43.990Z",
"question_score": 209,
"tags": "mysql|macos|command-line|osx-lion",
"answer_id": 7943890,
"answer_date": "2011-10-30T08:09:46.003Z",
"answer_score": 209
} |
Please answer the following Stack Overflow question:
Title: How can I generate Javadoc comments in Eclipse?
<p>Is there a way to generate Javadoc comments in Eclipse? If so, what is it?</p> | <p>For me the <code>/**<NEWLINE></code> or <kbd>Shift</kbd>-<kbd>Alt</kbd>-<kbd>J</kbd> (or <kbd>⌘</kbd>-<kbd>⌥</kbd>-<kbd>J</kbd> on a Mac) approach works best.</p>
<p>I dislike seeing Javadoc comments in source code that have been auto-generated and have not been updated with real content. As far as I am concerned, such javadocs are nothing more than a waste of screen space.</p>
<p>IMO, it is much much better to generate the Javadoc comment skeletons one by one as you are about to fill in the details. </p> | {
"question_id": 1777175,
"question_date": "2009-11-21T23:44:15.420Z",
"question_score": 209,
"tags": "java|eclipse|javadoc",
"answer_id": 1777291,
"answer_date": "2009-11-22T00:23:54.983Z",
"answer_score": 361
} |
Please answer the following Stack Overflow question:
Title: Checking if a folder exists using a .bat file
<p>I would like to be able to check if a certain folder (FolderA) exists and if so, for a message to be displayed and then the batch file to be exited. </p>
<p>If FolderA does not exist, I would then like to check if another folder (FolderB) exists. If FolderB does not exist, a message should be displayed and the folder should be created, and if FolderB does exist, a message should be displayed saying so. </p>
<p>Does anybody have any idea on the code I could simply use on notepad to create a batch file to allow me to do this?</p>
<p>All of this needs to be done in one <code>.bat</code> file.</p> | <h1>For a file:</h1>
<pre><code>if exist yourfilename (
echo Yes
) else (
echo No
)
</code></pre>
<p>Replace <strong>yourfilename</strong> with the name of your file.</p>
<h1>For a directory:</h1>
<pre><code>if exist yourfoldername\ (
echo Yes
) else (
echo No
)
</code></pre>
<p>Replace <strong>yourfoldername</strong> with the name of your folder.</p>
<p>A trailing backslash (<code>\</code>) seems to be enough to distinguish between directories and ordinary files.</p>
<p><a href="https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/if" rel="noreferrer">official documentation for <code>if</code></a></p> | {
"question_id": 21033801,
"question_date": "2014-01-10T00:06:30.980Z",
"question_score": 209,
"tags": "windows|batch-file",
"answer_id": 21041546,
"answer_date": "2014-01-10T10:14:31.793Z",
"answer_score": 349
} |
Please answer the following Stack Overflow question:
Title: Convert data.frame column to a vector?
<p>I have a dataframe such as:</p>
<pre><code>a1 = c(1, 2, 3, 4, 5)
a2 = c(6, 7, 8, 9, 10)
a3 = c(11, 12, 13, 14, 15)
aframe = data.frame(a1, a2, a3)
</code></pre>
<p>I tried the following to convert one of the columns to a vector, but it doesn't work:</p>
<pre><code>avector <- as.vector(aframe['a2'])
class(avector)
[1] "data.frame"
</code></pre>
<p>This is the only solution I could come up with, but I'm assuming there has to be a better way to do this:</p>
<pre><code>class(aframe['a2'])
[1] "data.frame"
avector = c()
for(atmp in aframe['a2']) { avector <- atmp }
class(avector)
[1] "numeric"
</code></pre>
<p><strong>Note:</strong> My vocabulary above may be off, so please correct me if so. I'm still learning the world of R. Additionally, any explanation of what's going on here is appreciated (i.e. relating to Python or some other language would help!)</p> | <p>I'm going to attempt to explain this without making any mistakes, but I'm betting this will attract a clarification or two in the comments.</p>
<p>A data frame is a list. When you subset a data frame using the name of a column and <code>[</code>, what you're getting is a <em>sublist</em> (or a sub data frame). If you want the actual atomic column, you could use <code>[[</code>, or somewhat confusingly (to me) you could do <code>aframe[,2]</code> which returns a vector, not a sublist.</p>
<p>So try running this sequence and maybe things will be clearer:</p>
<pre><code>avector <- as.vector(aframe['a2'])
class(avector)
avector <- aframe[['a2']]
class(avector)
avector <- aframe[,2]
class(avector)
</code></pre> | {
"question_id": 7070173,
"question_date": "2011-08-15T20:08:35.880Z",
"question_score": 209,
"tags": "r|dataframe|vector|type-conversion",
"answer_id": 7070330,
"answer_date": "2011-08-15T20:19:35.143Z",
"answer_score": 255
} |
Please answer the following Stack Overflow question:
Title: How can I install a package with go get?
<p>I want to install packages from github to my <code>$GOPATH</code>, I have tried this:</p>
<pre><code>go get github.com:capotej/groupcache-db-experiment.git
</code></pre>
<p>the repository is <a href="https://github.com/capotej/groupcache-db-experiment" rel="noreferrer">here</a>.</p> | <blockquote>
<p><a href="http://golang.org/cmd/go/" rel="noreferrer">Command go</a></p>
<p><a href="http://golang.org/cmd/go/#hdr-Download_and_install_packages_and_dependencies" rel="noreferrer">Download and install packages and dependencies</a></p>
<p>Usage:</p>
<pre><code>go get [-d] [-f] [-t] [-u] [-v] [-fix] [-insecure] [build flags] [packages]
</code></pre>
<p>Get downloads the packages named by the import paths, along with their
dependencies. It then installs the named packages, like 'go install'.</p>
<p>The -d flag instructs get to stop after downloading the packages; that
is, it instructs get not to install the packages.</p>
<p>The -f flag, valid only when -u is set, forces get -u not to verify
that each package has been checked out from the source control
repository implied by its import path. This can be useful if the
source is a local fork of the original.</p>
<p>The -fix flag instructs get to run the fix tool on the downloaded
packages before resolving dependencies or building the code.</p>
<p>The -insecure flag permits fetching from repositories and resolving
custom domains using insecure schemes such as HTTP. Use with caution.</p>
<p>The -t flag instructs get to also download the packages required to
build the tests for the specified packages.</p>
<p>The -u flag instructs get to use the network to update the named
packages and their dependencies. By default, get uses the network to
check out missing packages but does not use it to look for updates to
existing packages.</p>
<p>The -v flag enables verbose progress and debug output.</p>
<p>Get also accepts build flags to control the installation. See 'go help
build'.</p>
<p>When checking out a new package, get creates the target directory
GOPATH/src/. If the GOPATH contains multiple entries, get
uses the first one. For more details see: 'go help gopath'.</p>
<p>When checking out or updating a package, get looks for a branch or tag
that matches the locally installed version of Go. The most important
rule is that if the local installation is running version "go1", get
searches for a branch or tag named "go1". If no such version exists it
retrieves the default branch of the package.</p>
<p>When go get checks out or updates a Git repository, it also updates
any git submodules referenced by the repository.</p>
<p>Get never checks out or updates code stored in vendor directories.</p>
<p>For more about specifying packages, see 'go help packages'.</p>
<p>For more about how 'go get' finds source code to download, see 'go
help importpath'.</p>
<p>This text describes the behavior of get when using GOPATH to manage
source code and dependencies. If instead the go command is running in
module-aware mode, the details of get's flags and effects change, as
does 'go help get'. See 'go help modules' and 'go help module-get'.</p>
<p>See also: go build, go install, go clean.</p>
</blockquote>
<hr>
<p>For example, showing verbose output,</p>
<pre><code>$ go get -v github.com/capotej/groupcache-db-experiment/...
github.com/capotej/groupcache-db-experiment (download)
github.com/golang/groupcache (download)
github.com/golang/protobuf (download)
github.com/capotej/groupcache-db-experiment/api
github.com/capotej/groupcache-db-experiment/client
github.com/capotej/groupcache-db-experiment/slowdb
github.com/golang/groupcache/consistenthash
github.com/golang/protobuf/proto
github.com/golang/groupcache/lru
github.com/capotej/groupcache-db-experiment/dbserver
github.com/capotej/groupcache-db-experiment/cli
github.com/golang/groupcache/singleflight
github.com/golang/groupcache/groupcachepb
github.com/golang/groupcache
github.com/capotej/groupcache-db-experiment/frontend
$
</code></pre> | {
"question_id": 30295146,
"question_date": "2015-05-18T04:32:23.637Z",
"question_score": 209,
"tags": "go|go-toolchain",
"answer_id": 30296041,
"answer_date": "2015-05-18T05:59:41.940Z",
"answer_score": 162
} |
Please answer the following Stack Overflow question:
Title: SQL Server database backup restore on lower version
<p>How to restore a higher version SQL Server database backup file onto a lower version SQL Server?</p>
<p>Using SQL Server <strong>2008 R2 (10.50.1600)</strong>, I made a backup file and now I want to restore it on my live server's SQL Server <strong>2008 (10.00.1600)</strong>.</p>
<p>When I tried to restore the backup onto SQL Server 2008 it gives an error i.e. <code>Restore Failed</code> because:</p>
<blockquote>
<p>The database was backed up on a server running version 10.50.1600.
That version is incompatible with this server, which is running version
10.00.1600.</p>
</blockquote>
<p>How do I restore the backup file on this server?</p> | <p>No, is not possible to downgrade a database. 10.50.1600 is the SQL Server 2008 <strong>R2</strong> version. There is absolutely no way you can restore or attach this database to the SQL Server 2008 instance you are trying to restore on (10.00.1600 is SQL Server 2008). Your only options are: </p>
<ul>
<li>upgrade this instance to SQL Server 2008 R2 <em>or</em></li>
<li>restore the backup you have on a SQL Server 2008 R2 instance, export all the data and import it on a SQL Server 2008 database.</li>
</ul> | {
"question_id": 6183139,
"question_date": "2011-05-31T04:55:41.877Z",
"question_score": 209,
"tags": "sql-server",
"answer_id": 6183418,
"answer_date": "2011-05-31T05:36:43.680Z",
"answer_score": 82
} |
Please answer the following Stack Overflow question:
Title: LINQ to read XML
<p>I am using this XML file:</p>
<pre><code><root>
<level1 name="A">
<level2 name="A1" />
<level2 name="A2" />
</level1>
<level1 name="B">
<level2 name="B1" />
<level2 name="B2" />
</level1>
<level1 name="C" />
</root>
</code></pre>
<p>Could someone give me a C# code using LINQ, the simplest way to print this result:<br>
(Note the extra space if it is a <code>level2</code> node)</p>
<pre><code>A
A1
A2
B
B1
B2
C
</code></pre>
<p>Currently I have written this code:</p>
<pre><code>XDocument xdoc = XDocument.Load("data.xml"));
var lv1s = from lv1 in xdoc.Descendants("level1")
select lv1.Attribute("name").Value;
foreach (var lv1 in lv1s)
{
result.AppendLine(lv1);
var lv2s = from lv2 in xdoc...???
}
</code></pre> | <p>Try this.</p>
<pre><code>using System.Xml.Linq;
void Main()
{
StringBuilder result = new StringBuilder();
//Load xml
XDocument xdoc = XDocument.Load("data.xml");
//Run query
var lv1s = from lv1 in xdoc.Descendants("level1")
select new {
Header = lv1.Attribute("name").Value,
Children = lv1.Descendants("level2")
};
//Loop through results
foreach (var lv1 in lv1s){
result.AppendLine(lv1.Header);
foreach(var lv2 in lv1.Children)
result.AppendLine(" " + lv2.Attribute("name").Value);
}
Console.WriteLine(result);
}
</code></pre> | {
"question_id": 670563,
"question_date": "2009-03-22T04:48:24.573Z",
"question_score": 209,
"tags": "c#|xml|linq|linq-to-xml",
"answer_id": 670569,
"answer_date": "2009-03-22T04:53:24.747Z",
"answer_score": 234
} |
Please answer the following Stack Overflow question:
Title: Selenium C# WebDriver: Wait until element is present
<p>I want to make sure that an element is present before the webdriver starts doing stuff.</p>
<p>I'm trying to get something like this to work:</p>
<pre><code>WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0, 0, 5));
wait.Until(By.Id("login"));
</code></pre>
<p>I'm mainly struggling how to setup up the anonymous function...</p> | <p>Alternatively you can use an implicit wait:</p>
<pre><code>driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
</code></pre>
<blockquote>
<p>An implicit wait is to tell WebDriver to poll the DOM for a certain
amount of time when trying to find an element or elements if they are
not immediately available. The default setting is 0. Once set, the
implicit wait is set for the life of the WebDriver object instance.</p>
</blockquote> | {
"question_id": 6992993,
"question_date": "2011-08-09T07:49:06.367Z",
"question_score": 209,
"tags": "c#|selenium|selenium-webdriver|webdriver|automated-tests",
"answer_id": 6993597,
"answer_date": "2011-08-09T08:51:11.273Z",
"answer_score": 187
} |
Please answer the following Stack Overflow question:
Title: "A project with an Output type of Class Library cannot be started directly"
<p>I downloaded a C# project and I wish to debug the project to see how an algorithm implementation works.</p>
<p>The project has come in a Folder, inside this folder there are -</p>
<ol>
<li><strong><code>.sln</code> file</strong> and </li>
<li><strong>a folder which has source files and a <code>.csproj</code> file</strong>.</li>
</ol>
<p>I installed Visual Studio and opened the <code>.sln</code> file present in the main folder. I built the project successfully, but when I try to debug the project I get this message:</p>
<blockquote>
<p>A project with an Output type of Class Library cannot be started directly In order to debug this project, add an executable project to this solution which references the library project. Set the executable project as the startup project.</p>
</blockquote>
<p>The strange part is that I don't see a main function anywhere.</p>
<p>What should I do to get round this hiccup?</p> | <p>The project you have downloaded compiles into a dll assembly and provide a set of classes with implemented functionality.</p>
<p>You should add to your solution a new project with Output Type of either Console Application or Windows Application (VS Add Project wizard will offer you different templates of Projects).</p>
<p>In the newly added project, you can implement logic to test your Class Library.</p>
<p>Output type of the project you can find and change by the following steps:</p>
<ol>
<li><p>Right click on project in Solution Explorer -> Properties.</p></li>
<li><p>In opened tab with properties select Application and there will be ComboBox marked with Output Type label.</p></li>
</ol> | {
"question_id": 3363106,
"question_date": "2010-07-29T13:42:36.903Z",
"question_score": 209,
"tags": "c#|visual-studio",
"answer_id": 3363236,
"answer_date": "2010-07-29T13:58:10.630Z",
"answer_score": 201
} |
Please answer the following Stack Overflow question:
Title: How to get the seconds since epoch from the time + date output of gmtime()?
<p>How do you do reverse <code>gmtime()</code>, where you put the time + date and get the number of seconds?</p>
<p>I have strings like <code>'Jul 9, 2009 @ 20:02:58 UTC'</code>, and I want to get back the number of seconds between the epoch and July 9, 2009.</p>
<p>I have tried <code>time.strftime</code> but I don't know how to use it properly, or if it is the correct command to use.</p> | <p>If you got here because a search engine told you this is how to get the Unix timestamp, stop reading this answer. Scroll up one.</p>
<p>If you want to reverse <code>time.gmtime()</code>, you want <code>calendar.timegm()</code>.</p>
<pre><code>>>> calendar.timegm(time.gmtime())
1293581619.0
</code></pre>
<p>You can turn your string into a time tuple with <code>time.strptime()</code>, which returns a time tuple that you can pass to <code>calendar.timegm()</code>:</p>
<pre><code>>>> import calendar
>>> import time
>>> calendar.timegm(time.strptime('Jul 9, 2009 @ 20:02:58 UTC', '%b %d, %Y @ %H:%M:%S UTC'))
1247169778
</code></pre>
<p>More information about calendar module <a href="https://docs.python.org/2/library/calendar.html" rel="nofollow noreferrer">here</a></p> | {
"question_id": 4548684,
"question_date": "2010-12-28T19:08:46.390Z",
"question_score": 209,
"tags": "python|datetime|time",
"answer_id": 4548711,
"answer_date": "2010-12-28T19:13:30.603Z",
"answer_score": 153
} |
Please answer the following Stack Overflow question:
Title: HTTPS and SSL3_GET_SERVER_CERTIFICATE:certificate verify failed, CA is OK
<p>I am using <a href="http://www.apachefriends.org" rel="noreferrer">XAMPP</a> for development. Recently I upgraded my installation of xampp from an old version to 1.7.3. </p>
<p>Now when I curl HTTPS enabled sites I get the following exception</p>
<blockquote>
<p>Fatal error: Uncaught exception 'RequestCore_Exception' with message
'cURL resource: Resource
id #55; cURL error: SSL certificate problem, verify that the CA cert is OK. Details:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed (60)'</p>
</blockquote>
<p>Everyone suggest using some specific curl options from PHP code to fix this problem. I think this shouldn't be the way. Because I didn't have any problem with my old version of XAMPP and happened only after installing the new version. </p>
<p>I need help to figure out what settings change in my PHP installation, Apache etc can fix this problem.</p> | <p><code>curl</code> used to include a list of accepted certificate authorities (CAs) but no longer bundles ANY CA certs since 7.18.1 and onwards. So by default it'll reject all TLS/SSL certificates as unverifiable.</p>
<p>You'll have to get your CA's root certificate and point curl at it. More details at curl's <a href="https://curl.se/docs/sslcerts.html" rel="nofollow noreferrer">details on TLS/SSL certificates verification</a>.</p> | {
"question_id": 6400300,
"question_date": "2011-06-19T03:18:21.080Z",
"question_score": 209,
"tags": "php|ssl|curl|openssl|ca",
"answer_id": 6400746,
"answer_date": "2011-06-19T05:23:16.410Z",
"answer_score": 145
} |
Please answer the following Stack Overflow question:
Title: Parse string to DateTime in C#
<p>I have <strong>date and time</strong> in a string formatted like that one:</p>
<pre><code>"2011-03-21 13:26" //year-month-day hour:minute
</code></pre>
<p>How can I parse it to <code>System.DateTime</code>?</p>
<p>I want to use functions like <code>DateTime.Parse()</code> or <code>DateTime.ParseExact()</code> if possible, to be able to specify the format of the date manually.</p> | <p><code>DateTime.Parse()</code> will try figure out the format of the given date, and it usually does a good job. If you can guarantee dates will always be in a given format then you can use <code>ParseExact()</code>:</p>
<pre><code>string s = "2011-03-21 13:26";
DateTime dt =
DateTime.ParseExact(s, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
</code></pre>
<p>(But note that it is usually safer to use one of the TryParse methods in case a date is not in the expected format)</p>
<p>Make sure to check <a href="https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx" rel="noreferrer">Custom Date and Time Format Strings</a> when constructing format string, especially pay attention to number of letters and case (i.e. "MM" and "mm" mean very different things).</p>
<p>Another useful resource for C# format strings is <a href="http://blog.stevex.net/string-formatting-in-csharp/" rel="noreferrer">String Formatting in C#</a></p> | {
"question_id": 5366285,
"question_date": "2011-03-20T01:58:54.587Z",
"question_score": 209,
"tags": "c#|.net|string|parsing|datetime",
"answer_id": 5366311,
"answer_date": "2011-03-20T02:07:56.107Z",
"answer_score": 334
} |
Please answer the following Stack Overflow question:
Title: Laravel 5 - How to access image uploaded in storage within View?
<p>I have got user's avatars uploaded in Laravel storage. How can I access them and render them in a view?</p>
<p>The server is pointing all requests to <code>/public</code>, so how can I show them if they are in the <code>/storage</code> folder?</p> | <p>The <strong>best</strong> approach is to create a <strong>symbolic link</strong> like @SlateEntropy very well pointed out in <a href="https://stackoverflow.com/a/30192351/351330">the answer below</a>. To help with this, since version 5.3, Laravel <a href="https://laravel.com/docs/5.3/filesystem#configuration" rel="noreferrer">includes a command</a> which makes this incredibly easy to do:</p>
<pre><code>php artisan storage:link
</code></pre>
<p>That creates a symlink from <code>public/storage</code> to <code>storage/app/public</code> for you and that's all there is to it. Now any file in <code>/storage/app/public</code> can be accessed via a link like:</p>
<pre><code>http://somedomain.com/storage/image.jpg
</code></pre>
<hr>
<p>If, for any reason, your can't create symbolic links (maybe you're on shared hosting, etc.) or you want to protect some files behind some access control logic, there is the alternative of having a special route that reads and serves the image. For example a simple closure route like this:</p>
<pre class="lang-php prettyprint-override"><code>Route::get('storage/{filename}', function ($filename)
{
$path = storage_path('public/' . $filename);
if (!File::exists($path)) {
abort(404);
}
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
return $response;
});
</code></pre>
<p>You can now access your files just as you would if you had a symlink:</p>
<pre><code>http://somedomain.com/storage/image.jpg
</code></pre>
<p>If you're using the <a href="http://image.intervention.io/api/response" rel="noreferrer">Intervention Image Library</a> you can use its built in <code>response</code> method to make things more succinct:</p>
<pre class="lang-php prettyprint-override"><code>Route::get('storage/{filename}', function ($filename)
{
return Image::make(storage_path('public/' . $filename))->response();
});
</code></pre>
<hr>
<blockquote>
<p><strong>WARNING</strong></p>
<p>Keep in mind that by <strong>manually serving</strong> the files you're incurring a <strong>performance penalty</strong>, because you're going through the entire Laravel request lifecycle in order to read and send the file contents, which is <strong>considerably slower</strong> than having the HTTP server handle it.</p>
</blockquote> | {
"question_id": 30191330,
"question_date": "2015-05-12T12:46:25.080Z",
"question_score": 209,
"tags": "php|laravel|laravel-5",
"answer_id": 30191854,
"answer_date": "2015-05-12T13:07:24.833Z",
"answer_score": 419
} |
Please answer the following Stack Overflow question:
Title: How to run eclipse in clean mode? what happens if we do so?
<p>If something is not working properly or some plug-ins are not loaded properly in my Eclipse I often get suggestion to open Eclipse in clean mode.</p>
<p>So, how to run in clean mode? And what happens if I do so?</p> | <p>What it does:</p>
<blockquote>
<p>if set to "true", any cached data used
by the OSGi framework and eclipse
runtime will be wiped clean. This will
clean the caches used to store bundle
dependency resolution and eclipse
extension registry data. Using this
option will force eclipse to
reinitialize these caches.</p>
</blockquote>
<p>How to use it:</p>
<ul>
<li>Edit the <code>eclipse.ini</code> file located in your Eclipse install directory and insert <code>-clean</code> as the first line. </li>
<li>Or edit the shortcut you use to start Eclipse and add <code>-clean</code> as the first argument. </li>
<li>Or create a batch or shell script that calls the Eclipse executable with the <code>-clean</code> argument. The advantage to this step is you can keep the script around and use it each time you want to clean out the workspace. You can name it something like <code>eclipse-clean.bat</code> (or <code>eclipse-clean.sh</code>). </li>
</ul>
<p>(From: <a href="http://www.eclipsezone.com/eclipse/forums/t61566.html" rel="noreferrer">http://www.eclipsezone.com/eclipse/forums/t61566.html</a>)</p>
<p>Other eclipse command line options: <a href="http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fmisc%2Fruntime-options.html" rel="noreferrer">http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fmisc%2Fruntime-options.html</a></p> | {
"question_id": 2030064,
"question_date": "2010-01-08T19:17:36.890Z",
"question_score": 209,
"tags": "java|eclipse",
"answer_id": 2030092,
"answer_date": "2010-01-08T19:21:50.300Z",
"answer_score": 283
} |
Please answer the following Stack Overflow question:
Title: Effect of NOLOCK hint in SELECT statements
<p>I guess the real question is: </p>
<p>If I don't care about dirty reads, will adding the <strong>with (NOLOCK)</strong> hint to a SELECT statement affect the performance of:</p>
<ol>
<li>the current SELECT statement </li>
<li>other transactions against the given table</li>
</ol>
<p>Example:</p>
<pre><code>Select *
from aTable with (NOLOCK)
</code></pre> | <p>1) <strong>Yes</strong>, a select with <code>NOLOCK</code> will complete faster than a normal select.</p>
<p>2) <strong>Yes</strong>, a select with <code>NOLOCK</code> will allow other queries against the effected table to complete faster than a normal select.</p>
<p><strong>Why would this be?</strong> </p>
<p><code>NOLOCK</code> typically (depending on your DB engine) means give me your data, and I don't care what state it is in, and don't bother holding it still while you read from it. It is all at once faster, less resource-intensive, and very very dangerous. </p>
<p>You should be warned to never do an update from or perform anything system critical, or where absolute correctness is required using data that originated from a <code>NOLOCK</code> read. It is absolutely possible that this data contains rows that were deleted during the query's run or that have been deleted in other sessions that have yet to be finalized. It is possible that this data includes rows that have been partially updated. It is possible that this data contains records that violate foreign key constraints. It is possible that this data excludes rows that have been added to the table but have yet to be committed. </p>
<p><em>You really have no way to know what the state of the data is.</em></p>
<p>If you're trying to get things like a Row Count or other summary data where some margin of error is acceptable, then <code>NOLOCK</code> is a good way to boost performance for these queries and avoid having them negatively impact database performance.</p>
<p><strong>Always use the <code>NOLOCK</code> hint with great caution and treat any data it returns suspiciously.</strong> </p> | {
"question_id": 210171,
"question_date": "2008-10-16T20:30:03.567Z",
"question_score": 209,
"tags": "sql|sql-server|locking",
"answer_id": 210227,
"answer_date": "2008-10-16T20:43:38.640Z",
"answer_score": 306
} |
Please answer the following Stack Overflow question:
Title: Android: Create spinner programmatically from array
<p>I'm all new to Android and I'm trying to create a spinner programmatically and feeding it with data from an array, but Eclipse gives me a warning that I can't handle.</p>
<p>Here's what I got:</p>
<blockquote>
<p>This ArrayList holds the elements that should be in the spinner (gets
filled from a file later on):</p>
<p><code>ArrayList<String> spinnerArray = new ArrayList<String>();</code></p>
</blockquote>
<p>This is code I found on a site which should create the spinner:</p>
<pre><code>Spinner spinner = new Spinner(this);
ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_dropdown_item,
spinnerArray);
spinner.setAdapter(spinnerArrayAdapter);
</code></pre>
<p>Now the second line (ArrayAdapter...) gives me a warning in Eclipse saying <code>"ArrayAdapter is a raw type... References to generic type ArrayAdapter<T> should be parameterized"</code>, I have no idea how to fix this (or what that means in the first place :) ).</p>
<p>It's just a warning and the App seems to run alright, but I'd still like to understand what's wrong and fix it. Any hint is appreciated.</p>
<p>Greetings,
Select0r</p> | <p><code>ArrayAdapter<String></code> should work.</p>
<p>i.e.:</p>
<pre><code>Spinner spinner = new Spinner(this);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>
(this, android.R.layout.simple_spinner_item,
spinnerArray); //selected item will look like a spinner set from XML
spinnerArrayAdapter.setDropDownViewResource(android.R.layout
.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerArrayAdapter);
</code></pre> | {
"question_id": 2784081,
"question_date": "2010-05-06T20:04:49.357Z",
"question_score": 209,
"tags": "android|spinner",
"answer_id": 2784312,
"answer_date": "2010-05-06T20:37:31.320Z",
"answer_score": 400
} |
Please answer the following Stack Overflow question:
Title: When use ResponseEntity<T> and @RestController for Spring RESTful applications
<p>I am working with Spring Framework 4.0.7, together with MVC and Rest</p>
<p>I can work in peace with:</p>
<ul>
<li><code>@Controller</code> </li>
<li><code>ResponseEntity<T></code></li>
</ul>
<p>For example:</p>
<pre><code>@Controller
@RequestMapping("/person")
@Profile("responseentity")
public class PersonRestResponseEntityController {
</code></pre>
<p>With the method (just to create)</p>
<pre><code>@RequestMapping(value="/", method=RequestMethod.POST)
public ResponseEntity<Void> createPerson(@RequestBody Person person, UriComponentsBuilder ucb){
logger.info("PersonRestResponseEntityController - createPerson");
if(person==null)
logger.error("person is null!!!");
else
logger.info("{}", person.toString());
personMapRepository.savePerson(person);
HttpHeaders headers = new HttpHeaders();
headers.add("1", "uno");
//http://localhost:8080/spring-utility/person/1
headers.setLocation(ucb.path("/person/{id}").buildAndExpand(person.getId()).toUri());
return new ResponseEntity<>(headers, HttpStatus.CREATED);
}
</code></pre>
<p>to return something</p>
<pre><code>@RequestMapping(value="/{id}", method=RequestMethod.GET)
public ResponseEntity<Person> getPerson(@PathVariable Integer id){
logger.info("PersonRestResponseEntityController - getPerson - id: {}", id);
Person person = personMapRepository.findPerson(id);
return new ResponseEntity<>(person, HttpStatus.FOUND);
}
</code></pre>
<p>Works fine</p>
<p><strong>I can do the same with</strong>: </p>
<ul>
<li><code>@RestController</code> (I know it is the same than <code>@Controller</code> + <code>@ResponseBody</code>) </li>
<li><code>@ResponseStatus</code></li>
</ul>
<p>For example:</p>
<pre><code>@RestController
@RequestMapping("/person")
@Profile("restcontroller")
public class PersonRestController {
</code></pre>
<p>With the method (just to create)</p>
<pre><code>@RequestMapping(value="/", method=RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public void createPerson(@RequestBody Person person, HttpServletRequest request, HttpServletResponse response){
logger.info("PersonRestController - createPerson");
if(person==null)
logger.error("person is null!!!");
else
logger.info("{}", person.toString());
personMapRepository.savePerson(person);
response.setHeader("1", "uno");
//http://localhost:8080/spring-utility/person/1
response.setHeader("Location", request.getRequestURL().append(person.getId()).toString());
}
</code></pre>
<p>to return something</p>
<pre><code>@RequestMapping(value="/{id}", method=RequestMethod.GET)
@ResponseStatus(HttpStatus.FOUND)
public Person getPerson(@PathVariable Integer id){
logger.info("PersonRestController - getPerson - id: {}", id);
Person person = personMapRepository.findPerson(id);
return person;
}
</code></pre>
<p>My questions are: </p>
<ol>
<li>when <em>for a solid reason</em> or <em>specific scenario</em> one option must be used mandatorily over the other</li>
<li>If (1) does not matter, what approach is suggested and why.</li>
</ol> | <p><code>ResponseEntity</code> is meant to represent the entire HTTP response. You can control anything that goes into it: status code, headers, and body.</p>
<p><code>@ResponseBody</code> is a marker for the HTTP response body and <code>@ResponseStatus</code> declares the status code of the HTTP response.</p>
<p><code>@ResponseStatus</code> isn't very flexible. It marks the entire method so you have to be sure that your handler method will always behave the same way. And you still can't set the headers. You'd need the <code>HttpServletResponse</code>.</p>
<p>Basically, <code>ResponseEntity</code> lets you do more.</p> | {
"question_id": 26549379,
"question_date": "2014-10-24T13:56:34.977Z",
"question_score": 209,
"tags": "spring|spring-mvc|spring-3|spring-4",
"answer_id": 26550981,
"answer_date": "2014-10-24T15:17:27.303Z",
"answer_score": 270
} |
Please answer the following Stack Overflow question:
Title: Check if MySQL table exists without using "select from" syntax?
<p>Is there a way to check if a table exists <em>without</em> selecting and checking values from it?</p>
<p>That is, I know I can go <code>SELECT testcol FROM testtable</code> and check the count of fields returned, but it seems there must be a more direct / elegant way to do it.</p> | <p>If you want to be correct, use <a href="http://dev.mysql.com/doc/refman/5.0/en/tables-table.html" rel="noreferrer">INFORMATION_SCHEMA</a>.</p>
<pre><code>SELECT *
FROM information_schema.tables
WHERE table_schema = 'yourdb'
AND table_name = 'testtable'
LIMIT 1;
</code></pre>
<p>Alternatively, you can use <code>SHOW TABLES</code></p>
<pre><code>SHOW TABLES LIKE 'yourtable';
</code></pre>
<p>If there is a row in the resultset, table exists.</p> | {
"question_id": 8829102,
"question_date": "2012-01-12T01:42:26.870Z",
"question_score": 209,
"tags": "mysql|sql",
"answer_id": 8829109,
"answer_date": "2012-01-12T01:44:07.870Z",
"answer_score": 394
} |
Please answer the following Stack Overflow question:
Title: Visual Studio Code cannot detect installed git
<p>Visual Studio Code reports "It look like git is not installed on your system." when I try to switch to the git view. I know I have git installed and used by other git clients. I guess if I re-install git following Visual Studio Code's instruction ("install it with Chocolatey or download it from git-scm.com"), it probably can fix the problem, but I don't want to mess up the existing git clients on my system. Is there a reliable way to configure Visual Studio Code so it can find existing git installation?</p> | <p>Visual Studio Code simply looks in your <code>PATH</code> for <code>git</code>. Many UI clients ship with a "Portable Git" for simplicity, and do not add <code>git</code> to the path.</p>
<p>If you add your existing git client to your <code>PATH</code> (so that it can find <code>git.exe</code>), Visual Studio Code should enable Git source control management.</p> | {
"question_id": 29971624,
"question_date": "2015-04-30T15:21:13.710Z",
"question_score": 209,
"tags": "git|visual-studio-code",
"answer_id": 29973715,
"answer_date": "2015-04-30T17:02:41.947Z",
"answer_score": 97
} |
Please answer the following Stack Overflow question:
Title: Python "SyntaxError: Non-ASCII character '\xe2' in file"
<p>I am writing some python code and I am receiving the error message as in the title, from searching this has to do with the character set. </p>
<p>Here is the line that causes the error</p>
<pre><code>hc = HealthCheck("instance_health", interval=15, target808="HTTP:8080/index.html")
</code></pre>
<p>I cannot figure out what character is not in the ANSI ASCII set? Furthermore searching "\xe2" does not give anymore information as to what character that appears as. Which character in that line is causing the issue? </p>
<p>I have also seen a few fixes for this issue but I am not sure which to use. Could someone clarify what the issue is (python doesn't interpret unicode unless told to do so?), and how I would clear it up properly?</p>
<p>EDIT:
Here are all the lines near the one that errors</p>
<pre><code>def createLoadBalancer():
conn = ELBConnection(creds.awsAccessKey, creds.awsSecretKey)
hc = HealthCheck("instance_health", interval=15, target808="HTTP:8080/index.html")
lb = conn.create_load_balancer('my_lb', ['us-east-1a', 'us-east-1b'],[(80, 8080, 'http'), (443, 8443, 'tcp')])
lb.configure_health_check(hc)
return lb
</code></pre> | <p>You've got a stray byte floating around. You can find it by running</p>
<pre><code>with open("x.py") as fp:
for i, line in enumerate(fp):
if "\xe2" in line:
print i, repr(line)
</code></pre>
<p>where you should replace <code>"x.py"</code> by the name of your program. You'll see the line number and the offending line(s). For example, after inserting that byte arbitrarily, I got:</p>
<pre><code>4 "\xe2 lb = conn.create_load_balancer('my_lb', ['us-east-1a', 'us-east-1b'],[(80, 8080, 'http'), (443, 8443, 'tcp')])\n"
</code></pre> | {
"question_id": 21639275,
"question_date": "2014-02-07T22:55:16.053Z",
"question_score": 209,
"tags": "python",
"answer_id": 21639459,
"answer_date": "2014-02-07T23:11:12.197Z",
"answer_score": 158
} |
Please answer the following Stack Overflow question:
Title: How using try catch for exception handling is best practice
<p>while maintaining my colleague's code from even someone who claims to be a senior developer, I often see the following code:</p>
<pre><code>try
{
//do something
}
catch
{
//Do nothing
}
</code></pre>
<p>or sometimes they write logging information to log files like following <code>try catch</code> block</p>
<pre><code>try
{
//do some work
}
catch(Exception exception)
{
WriteException2LogFile(exception);
}
</code></pre>
<p>I am just wondering if what they have done is the best practice? It makes me confused because in my thinking users should know what happens with the system.</p> | <p>My exception-handling strategy is:</p>
<ul>
<li><p>To catch <strong>all unhandled exceptions</strong> by hooking to the <code>Application.ThreadException event</code>, then decide:</p>
<ul>
<li>For a UI application: to pop it to the user with an apology message (WinForms)</li>
<li>For a Service or a Console application: log it to a file (service or console)</li>
</ul>
</li>
</ul>
<p>Then I always enclose <strong>every piece of code that is run externally</strong> in <code>try/catch</code> :</p>
<ul>
<li>All events fired by the WinForms infrastructure (Load, Click, SelectedChanged...)</li>
<li>All events fired by third party components</li>
</ul>
<p>Then I enclose in 'try/catch'</p>
<ul>
<li>All the <strong>operations that I <em>know might not work all the time</em></strong> (IO operations, calculations with a potential zero division...). In such a case, I throw a new <code>ApplicationException("custom message", innerException)</code> to keep track of what really happened</li>
</ul>
<p>Additionally, I try my best to <strong>sort exceptions correctly</strong>. There are exceptions which:</p>
<ul>
<li><p>need to be shown to the user immediately</p>
</li>
<li><p>require some extra processing to put things together when they happen to avoid cascading problems (ie: put .EndUpdate in the <code>finally</code> section during a <code>TreeView</code> fill)</p>
</li>
<li><p>the user does not care, but it is important to know what happened. So I always log them:</p>
</li>
<li><p>In the event log</p>
</li>
<li><p>or in a .log file on the disk</p>
</li>
</ul>
<p>It is a good practice to <strong>design some static methods to handle exceptions</strong> in the application top level error handlers.</p>
<p>I also force myself to try to:</p>
<ul>
<li>Remember <strong>ALL exceptions are bubbled up to the top level</strong>. It is not necessary to put exception handlers everywhere.</li>
<li>Reusable or deep called functions does not need to display or log exceptions : they are either bubbled up automatically or rethrown with some custom messages in my exception handlers.</li>
</ul>
<p>So finally:</p>
<p>Bad:</p>
<pre><code>// DON'T DO THIS; ITS BAD
try
{
...
}
catch
{
// only air...
}
</code></pre>
<p>Useless:</p>
<pre><code>// DON'T DO THIS; IT'S USELESS
try
{
...
}
catch(Exception ex)
{
throw ex;
}
</code></pre>
<p>Having a try finally without a catch is perfectly valid:</p>
<pre><code>try
{
listView1.BeginUpdate();
// If an exception occurs in the following code, then the finally will be executed
// and the exception will be thrown
...
}
finally
{
// I WANT THIS CODE TO RUN EVENTUALLY REGARDLESS AN EXCEPTION OCCURRED OR NOT
listView1.EndUpdate();
}
</code></pre>
<p>What I do at the top level:</p>
<pre><code>// i.e When the user clicks on a button
try
{
...
}
catch(Exception ex)
{
ex.Log(); // Log exception
-- OR --
ex.Log().Display(); // Log exception, then show it to the user with apologies...
}
</code></pre>
<p>What I do in some called functions:</p>
<pre><code>// Calculation module
try
{
...
}
catch(Exception ex)
{
// Add useful information to the exception
throw new ApplicationException("Something wrong happened in the calculation module:", ex);
}
// IO module
try
{
...
}
catch(Exception ex)
{
throw new ApplicationException(string.Format("I cannot write the file {0} to {1}", fileName, directoryName), ex);
}
</code></pre>
<p>There is a lot to do with exception handling (Custom Exceptions) but those rules that I try to keep in mind are enough for the simple applications I do.</p>
<p>Here is an example of extensions methods to handle caught exceptions a comfortable way. They are implemented in a way they can be chained together, and it is very easy to add your own caught exception processing.</p>
<pre><code>// Usage:
try
{
// boom
}
catch(Exception ex)
{
// Only log exception
ex.Log();
-- OR --
// Only display exception
ex.Display();
-- OR --
// Log, then display exception
ex.Log().Display();
-- OR --
// Add some user-friendly message to an exception
new ApplicationException("Unable to calculate !", ex).Log().Display();
}
// Extension methods
internal static Exception Log(this Exception ex)
{
File.AppendAllText("CaughtExceptions" + DateTime.Now.ToString("yyyy-MM-dd") + ".log", DateTime.Now.ToString("HH:mm:ss") + ": " + ex.Message + "\n" + ex.ToString() + "\n");
return ex;
}
internal static Exception Display(this Exception ex, string msg = null, MessageBoxImage img = MessageBoxImage.Error)
{
MessageBox.Show(msg ?? ex.Message, "", MessageBoxButton.OK, img);
return ex;
}
</code></pre> | {
"question_id": 14973642,
"question_date": "2013-02-20T06:32:37.503Z",
"question_score": 209,
"tags": "c#|.net|exception|try-catch",
"answer_id": 14974163,
"answer_date": "2013-02-20T07:07:30.293Z",
"answer_score": 319
} |
Please answer the following Stack Overflow question:
Title: How to quickly clear a JavaScript Object?
<p>With a JavaScript Array, I can reset it to an empty state with a single assignment:</p>
<pre><code>array.length = 0;
</code></pre>
<p>This makes the Array "appear" empty and ready to reuse, and as far as I understand is a single "operation" - that is, constant time.</p>
<p>Is there a similar way to clear a JS Object? I know I can iterate its fields deleting them:</p>
<pre><code>for (var prop in obj) { if (obj.hasOwnProperty(prop)) { delete obj[prop]; } }
</code></pre>
<p>but this has linear complexity.</p>
<p>I can also just throw the object away and create a new one:</p>
<pre><code>obj = {};
</code></pre>
<p>But "promiscuous" creation of new objects leads to problems with Garbage Collection on IE6. (<a href="http://ajaxian.com/archives/garbage-collection-in-ie6" rel="noreferrer">As described here</a>)</p> | <p>The short answer to your question, I think, is no (you can just create a new object).</p>
<ol>
<li><p>In this example, I believe setting the length to 0 still leaves all of the elements for garbage collection.</p></li>
<li><p>You could add this to Object.prototype if it's something you'd frequently use. Yes it's linear in complexity, but anything that doesn't do garbage collection later will be.</p></li>
<li><p>This is the best solution. I know it's not related to your question - but for how long do we need to continue supporting IE6? There are many campaigns to discontinue the usage of it.</p></li>
</ol>
<p>Feel free to correct me if there's anything incorrect above.</p> | {
"question_id": 684575,
"question_date": "2009-03-26T05:01:19.937Z",
"question_score": 209,
"tags": "javascript|performance",
"answer_id": 684603,
"answer_date": "2009-03-26T05:16:24.380Z",
"answer_score": 61
} |
Please answer the following Stack Overflow question:
Title: Amazon S3 - How to fix 'The request signature we calculated does not match the signature' error?
<p>I have searched on the web for over two days now, and probably have looked through most of the online documented scenarios and workarounds, but nothing worked for me so far.</p>
<p>I am on <strong>AWS SDK</strong> for PHP V2.8.7 running on PHP 5.3.</p>
<p>I am trying to connect to my Amazon S3 bucket with the following code:</p>
<pre class="lang-php prettyprint-override"><code>// Create a `Aws` object using a configuration file
$aws = Aws::factory('config.php');
// Get the client from the service locator by namespace
$s3Client = $aws->get('s3');
$bucket = "xxx";
$keyname = "xxx";
try {
$result = $s3Client->putObject(array(
'Bucket' => $bucket,
'Key' => $keyname,
'Body' => 'Hello World!'
));
$file_error = false;
} catch (Exception $e) {
$file_error = true;
echo $e->getMessage();
die();
}
</code></pre>
<p>My config.php file is as follows:</p>
<pre class="lang-php prettyprint-override"><code>return [
// Bootstrap the configuration file with AWS specific features
'includes' => ['_aws'],
'services' => [
// All AWS clients extend from 'default_settings'. Here we are
// overriding 'default_settings' with our default credentials and
// providing a default region setting.
'default_settings' => [
'params' => [
'credentials' => [
'key' => 'key',
'secret' => 'secret'
]
]
]
]
];
</code></pre>
<p>It is producing the following error:</p>
<blockquote>
<p>The request signature we calculated does not match the signature you provided. Check your key and signing method.</p>
</blockquote>
<p>I've already checked my access key and secret at least 20 times, generated new ones, used different methods to pass in the information (i.e. profile and including credentials in code) but nothing is working at the moment.</p> | <p>After two days of debugging, I finally discovered the problem...</p>
<p>The key I was assigning to the object started with a period i.e. <code>..\images\ABC.jpg</code>, and this caused the error to occur.</p>
<p>I wish the API provides more meaningful and relevant error message, alas, I hope this will help someone else out there!</p> | {
"question_id": 30518899,
"question_date": "2015-05-28T23:47:55.870Z",
"question_score": 209,
"tags": "php|amazon-web-services|amazon-s3|aws-php-sdk",
"answer_id": 30519762,
"answer_date": "2015-05-29T01:37:08.477Z",
"answer_score": 147
} |
Please answer the following Stack Overflow question:
Title: How to permanently export a variable in Linux?
<p>I am running RHEL6, and I have exported an environment variable like this:</p>
<pre><code>export DISPLAY=:0
</code></pre>
<p>That variable is lost when the terminal is closed. How do I permanently add this so that this variable value always exists with a particular user?</p> | <p>You can add it to your shell configuration file, e.g. <code>$HOME/.bashrc</code> or more globally in <code>/etc/environment</code>.
After adding these lines the changes won't reflect instantly in GUI based system's you have to exit the terminal or create a new one and in server logout the session and login to reflect these changes.</p> | {
"question_id": 13046624,
"question_date": "2012-10-24T09:42:50.733Z",
"question_score": 209,
"tags": "linux|environment-variables|redhat",
"answer_id": 13046663,
"answer_date": "2012-10-24T09:45:12.050Z",
"answer_score": 236
} |
Please answer the following Stack Overflow question:
Title: How to compare type of an object in Python?
<p>Basically I want to do this:</p>
<pre><code>obj = 'str'
type ( obj ) == string
</code></pre>
<p>I tried:</p>
<pre><code>type ( obj ) == type ( string )
</code></pre>
<p>and it didn't work.</p>
<p>Also, what about the other types? For example, I couldn't replicate <code>NoneType</code>.</p> | <pre><code>isinstance()
</code></pre>
<p>In your case, <code>isinstance("this is a string", str)</code> will return <code>True</code>.</p>
<p>You may also want to read this: <a href="http://www.canonical.org/~kragen/isinstance/" rel="noreferrer">http://www.canonical.org/~kragen/isinstance/</a></p> | {
"question_id": 707674,
"question_date": "2009-04-01T23:03:05.533Z",
"question_score": 209,
"tags": "python|types|compare",
"answer_id": 707685,
"answer_date": "2009-04-01T23:07:02.120Z",
"answer_score": 302
} |
Please answer the following Stack Overflow question:
Title: The maximum value for an int type in Go
<p>How does one specify the maximum value representable for an <code>unsigned</code> integer type?</p>
<p>I would like to know how to initialize <code>min</code> in the loop below that iteratively computes min and max lengths from some structs.</p>
<pre><code>var minLen uint = ???
var maxLen uint = 0
for _, thing := range sliceOfThings {
if minLen > thing.n { minLen = thing.n }
if maxLen < thing.n { maxLen = thing.n }
}
if minLen > maxLen {
// If there are no values, clamp min at 0 so that min <= max.
minLen = 0
}
</code></pre>
<p>so that the first time through the comparison, <code>minLen >= n</code>.</p> | <p><a href="https://groups.google.com/group/golang-nuts/msg/71c307e4d73024ce?pli=1" rel="noreferrer">https://groups.google.com/group/golang-nuts/msg/71c307e4d73024ce?pli=1</a></p>
<p>The germane part:</p>
<blockquote>
<p>Since integer types use two's complement arithmetic, you can infer the
min/max constant values for <code>int</code> and <code>uint</code>. For example,</p>
<pre><code>const MaxUint = ^uint(0)
const MinUint = 0
const MaxInt = int(MaxUint >> 1)
const MinInt = -MaxInt - 1
</code></pre>
</blockquote>
<p>As per @CarelZA's comment:</p>
<pre><code>uint8 : 0 to 255
uint16 : 0 to 65535
uint32 : 0 to 4294967295
uint64 : 0 to 18446744073709551615
int8 : -128 to 127
int16 : -32768 to 32767
int32 : -2147483648 to 2147483647
int64 : -9223372036854775808 to 9223372036854775807
</code></pre> | {
"question_id": 6878590,
"question_date": "2011-07-29T20:21:51.580Z",
"question_score": 209,
"tags": "numbers|go",
"answer_id": 6878625,
"answer_date": "2011-07-29T20:25:18.987Z",
"answer_score": 307
} |
Please answer the following Stack Overflow question:
Title: How to remove new line characters from a string?
<p>I have a string in the following format</p>
<pre><code>string s = "This is a Test String.\n This is a next line.\t This is a tab.\n'
</code></pre>
<p>I want to remove all the occurrences of <code>\n</code> and <code>\r</code> from the string above.</p>
<p>I have tried <code>string s = s.Trim(new char[] {'\n', '\r'});</code> but it didn't help.</p> | <p>I like to use regular expressions. In this case you could do:</p>
<pre><code>string replacement = Regex.Replace(s, @"\t|\n|\r", "");
</code></pre>
<p>Regular expressions aren't as popular in the .NET world as they are in the dynamic languages, but they provide a lot of power to manipulate strings.</p> | {
"question_id": 4140723,
"question_date": "2010-11-10T02:32:21.850Z",
"question_score": 209,
"tags": "c#|.net",
"answer_id": 4140802,
"answer_date": "2010-11-10T02:50:57.053Z",
"answer_score": 390
} |
Please answer the following Stack Overflow question:
Title: Return 0 if field is null in MySQL
<p>In MySQL, is there a way to set the "total" fields to zero if they are NULL?</p>
<p>Here is what I have:</p>
<pre><code>SELECT uo.order_id, uo.order_total, uo.order_status,
(SELECT SUM(uop.price * uop.qty)
FROM uc_order_products uop
WHERE uo.order_id = uop.order_id
) AS products_subtotal,
(SELECT SUM(upr.amount)
FROM uc_payment_receipts upr
WHERE uo.order_id = upr.order_id
) AS payment_received,
(SELECT SUM(uoli.amount)
FROM uc_order_line_items uoli
WHERE uo.order_id = uoli.order_id
) AS line_item_subtotal
FROM uc_orders uo
WHERE uo.order_status NOT IN ("future", "canceled")
AND uo.uid = 4172;
</code></pre>
<p>The data comes out fine, except the NULL fields should be <code>0</code>.</p>
<p>How can I return 0 for NULL in MySQL?</p> | <p>Use <a href="http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_ifnull" rel="noreferrer">IFNULL</a>:</p>
<pre><code>IFNULL(expr1, 0)
</code></pre>
<p>From the documentation:</p>
<blockquote>
<p>If expr1 is not NULL, IFNULL() returns expr1; otherwise it returns expr2. IFNULL() returns a numeric or string value, depending on the context in which it is used. </p>
</blockquote> | {
"question_id": 3997327,
"question_date": "2010-10-22T13:38:15.770Z",
"question_score": 209,
"tags": "sql|mysql",
"answer_id": 3997340,
"answer_date": "2010-10-22T13:39:57.877Z",
"answer_score": 408
} |
Please answer the following Stack Overflow question:
Title: What's the difference between "Write-Host", "Write-Output", or "[console]::WriteLine"?
<p>There are a number of different ways to output messages. What is the effective difference between outputting something via <code>Write-Host</code>, <code>Write-Output</code>, or <code>[console]::WriteLine</code>? </p>
<p>I also notice that if I use:</p>
<pre><code>write-host "count=" + $count
</code></pre>
<p>The <code>+</code> gets included in the output. Why's that? Shouldn't the expression be evaluated to produce a single concatenated string before it gets written out?</p> | <p><code>Write-Output</code> should be used when you want to send data on in the pipe line, but not necessarily want to display it on screen. The pipeline will eventually write it to <code>out-default</code> if nothing else uses it first.</p>
<p><code>Write-Host</code> should be used when you want to do the opposite. </p>
<p><code>[console]::WriteLine</code> is essentially what <code>Write-Host</code> is doing behind the scenes.</p>
<p>Run this demonstration code and examine the result. </p>
<pre><code>function Test-Output {
Write-Output "Hello World"
}
function Test-Output2 {
Write-Host "Hello World" -foreground Green
}
function Receive-Output {
process { Write-Host $_ -foreground Yellow }
}
#Output piped to another function, not displayed in first.
Test-Output | Receive-Output
#Output not piped to 2nd function, only displayed in first.
Test-Output2 | Receive-Output
#Pipeline sends to Out-Default at the end.
Test-Output
</code></pre>
<p>You'll need to enclose the concatenation operation in parentheses, so that PowerShell processes the concatenation before tokenizing the parameter list for <code>Write-Host</code>, or use string interpolation</p>
<pre><code>write-host ("count=" + $count)
# or
write-host "count=$count"
</code></pre>
<p>BTW - Watch this <a href="http://channel9.msdn.com/shows/Going+Deep/Expert-to-Expert-Erik-Meijer-and-Jeffrey-Snover-Inside-PowerShell/" rel="noreferrer">video</a> of Jeffrey Snover explaining how the pipeline works. Back when I started learning PowerShell I found this to be the most useful explanation of how the pipeline works.</p> | {
"question_id": 8755497,
"question_date": "2012-01-06T09:02:37.630Z",
"question_score": 209,
"tags": "powershell",
"answer_id": 8755614,
"answer_date": "2012-01-06T09:15:47.427Z",
"answer_score": 290
} |
Please answer the following Stack Overflow question:
Title: Is it ok to use `any?` to check if an array is not empty?
<p>Is it bad to check if an array is <strong>not</strong> empty by using <code>any?</code> method?</p>
<pre><code>a = [1,2,3]
a.any?
=> true
a.clear
a.any?
=> false
</code></pre>
<p>Or is it better to use <code>unless a.empty?</code> ?</p> | <p><code>any?</code> isn't the same as <code>not empty?</code> in some cases.</p>
<pre><code>>> [nil, 1].any?
=> true
>> [nil, nil].any?
=> false
</code></pre>
<p>From the documentation:</p>
<blockquote>
<p>If the block is not given, Ruby adds
an implicit block of {|obj| obj} (that
is any? will return true if at least
one of the collection members is not
false or nil).</p>
</blockquote> | {
"question_id": 6245929,
"question_date": "2011-06-05T21:16:46.177Z",
"question_score": 209,
"tags": "ruby|arrays",
"answer_id": 6245946,
"answer_date": "2011-06-05T21:21:03.320Z",
"answer_score": 267
} |
Please answer the following Stack Overflow question:
Title: Docker - Bind for 0.0.0.0:4000 failed: port is already allocated
<p>I am using docker for the first time and I was trying to implement this -
<a href="https://docs.docker.com/get-started/part2/#tag-the-image" rel="noreferrer">https://docs.docker.com/get-started/part2/#tag-the-image</a></p>
<p>At one stage I was trying to connect with localhost by this command -</p>
<pre><code>$ curl http://localhost:4000
</code></pre>
<p>which showed this error-</p>
<pre><code>curl: (7) Failed to connect to localhost port 4000: Connection refused
</code></pre>
<p>However, I have solved this by following code -</p>
<pre><code>$ docker-machine ip default
$ curl http://192.168.99.100:4000
</code></pre>
<p>After that everything was going fine, but in the last part, I was trying to run the app by using following line according to the tutorial...</p>
<pre><code>$ docker run -p 4000:80 anibar/get-started:part1
</code></pre>
<p>But, I got this error</p>
<pre><code>C:\Program Files\Docker Toolbox\docker.exe: Error response from daemon: driver failed programming external connectivity on endpoint goofy_bohr (63f5691ef18ad6d6389ef52c56198389c7a627e5fa4a79133d6bbf13953a7c98): Bind for 0.0.0.0:4000 failed: port is already allocated.
</code></pre> | <p>You need to make sure that the previous container you launched is killed, before launching a new one that uses the same port.</p>
<pre><code>docker container ls
docker rm -f <container-name>
</code></pre> | {
"question_id": 46176584,
"question_date": "2017-09-12T12:37:20.630Z",
"question_score": 209,
"tags": "docker|port",
"answer_id": 46177519,
"answer_date": "2017-09-12T13:17:47.167Z",
"answer_score": 345
} |
Please answer the following Stack Overflow question:
Title: Java Regex Capturing Groups
<p>I am trying to understand this code block. In the first one, what is it we are looking for in the expression?</p>
<p>My understanding is that it is any character (0 or more times *) followed by any number between 0 and 9 (one or more times +) followed by any character (0 or more times *).</p>
<p>When this is executed the result is:</p>
<pre class="lang-none prettyprint-override"><code>Found value: This order was placed for QT3000! OK?
Found value: This order was placed for QT300
Found value: 0
</code></pre>
<p>Could someone please go through this with me?</p>
<p>What is the advantage of using Capturing groups?</p>
<pre><code>import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexTut3 {
public static void main(String args[]) {
String line = "This order was placed for QT3000! OK?";
String pattern = "(.*)(\\d+)(.*)";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
if (m.find()) {
System.out.println("Found value: " + m.group(0));
System.out.println("Found value: " + m.group(1));
System.out.println("Found value: " + m.group(2));
} else {
System.out.println("NO MATCH");
}
}
}
</code></pre> | <p>The issue you're having is with the type of quantifier. You're using a <strong>greedy</strong> quantifier in your first group (index <strong>1</strong> - index 0 represents the whole <code>Pattern</code>), which means it'll match as much as it can (and since it's <em>any</em> character, it'll match <strong>as many characters</strong> as there are in order to fulfill the condition for the next groups). </p>
<p>In short, your 1st group <code>.*</code> matches anything as long as the next group <code>\\d+</code> can match something (in this case, the last digit). </p>
<p>As per the 3rd group, it will match anything after the last digit. </p>
<p>If you change it to a <strong>reluctant</strong> quantifier in your 1st group, you'll get the result I suppose you are expecting, that is, the <em>3000</em> part. </p>
<p>Note the <strong>question mark</strong> in the 1st group. </p>
<pre><code>String line = "This order was placed for QT3000! OK?";
Pattern pattern = Pattern.compile("(.*?)(\\d+)(.*)");
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
System.out.println("group 1: " + matcher.group(1));
System.out.println("group 2: " + matcher.group(2));
System.out.println("group 3: " + matcher.group(3));
}
</code></pre>
<p>Output: </p>
<pre><code>group 1: This order was placed for QT
group 2: 3000
group 3: ! OK?
</code></pre>
<p>More info on Java <code>Pattern</code> <a href="http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html" rel="noreferrer">here</a>. </p>
<p>Finally, the capturing groups are delimited by round brackets, and provide a very useful way to use back-references (amongst other things), once your <code>Pattern</code> is matched to the input. </p>
<p>In Java 6 groups can only be referenced by their order (beware of nested groups and the subtlety of ordering). </p>
<p>In Java 7 it's much easier, as you can use named groups. </p> | {
"question_id": 17969436,
"question_date": "2013-07-31T11:44:05.050Z",
"question_score": 209,
"tags": "java|regex",
"answer_id": 17969620,
"answer_date": "2013-07-31T11:51:58.453Z",
"answer_score": 292
} |
Please answer the following Stack Overflow question:
Title: Is HTML considered a programming language?
<p>I guess the question is self-explanatory, but I'm wondering whether HTML qualifies as a programming language (obviously the "L" stands for language). </p>
<p>The reason for asking is more pragmatic—I'm putting together a resume and don't want to look like a fool for listing things like HTML and XML under languages, but can't figure out how to classify them.</p> | <p>No, HTML is not a programming language. The "M" stands for "Markup". Generally, a programming language allows you to describe some sort of process of doing something, whereas HTML is a way of adding context and structure to text.</p>
<p>If you're looking to add more alphabet soup to your CV, don't classify them at all. Just put them in a big pile called "Technologies" or whatever you like. Remember, however, that anything you list is fair game for a question. </p>
<p>HTML is so common that I'd expect almost any technology person to already know it (although not stuff like CSS and so on), so you might consider not listing every initialism you've ever come across. I tend to regard CVs listing too many things as suspicious, so I ask more questions to weed out the stuff that shouldn't be listed. :)</p>
<p>However, if your HTML experience includes serious web design stuff including Ajax, JavaScript, and so on, you might talk about those in your "Experience" section.</p> | {
"question_id": 145176,
"question_date": "2008-09-28T04:00:02.663Z",
"question_score": 209,
"tags": "html",
"answer_id": 145179,
"answer_date": "2008-09-28T04:01:43.720Z",
"answer_score": 506
} |
Please answer the following Stack Overflow question:
Title: XMLHttpRequest Origin null is not allowed Access-Control-Allow-Origin for file:/// to file:/// (Serverless)
<p>I'm trying to create a website that can be downloaded and run locally by launching its index file.</p>
<p>All the files are local, no resources are used online.</p>
<p>When I try to use the AJAXSLT plugin for jQuery to process an XML file with an XSL template (in sub directories), I receive the following errors:</p>
<p><code>XMLHttpRequest cannot load file:///C:/path/to/XSL%20Website/data/home.xml. Origin null is not allowed by Access-Control-Allow-Origin.</code></p>
<p><code>XMLHttpRequest cannot load file:///C:/path/to/XSL%20Website/assets/xsl/main.xsl. Origin null is not allowed by Access-Control-Allow-Origin.</code></p>
<p>The index file making the request is <code>file:///C:/path/to/XSL%20Website/index.html</code> while the JavaScript files used are stored in <code>file:///C:/path/to/XSL%20Website/assets/js/</code>.</p>
<p>How can I do to fix this issue?</p> | <p>For instances where running a local webserver is not an option, you can allow Chrome access to <code>file://</code> files via a browser switch. After some digging, I found <a href="http://code.google.com/p/chromium/issues/detail?id=47416" rel="noreferrer">this discussion</a>, which mentions a browser switch in opening post. Run your Chrome instance with:</p>
<pre><code>chrome.exe --allow-file-access-from-files
</code></pre>
<p><strong>This may be acceptable for development environments, but little else.</strong> You certainly don't want this on all the time. This still appears to be an open issue (as of Jan 2011).</p>
<p><em>See also: <a href="https://stackoverflow.com/questions/2541949/problems-with-jquery-getjson-using-local-files-in-chrome">Problems with jQuery getJSON using local files in Chrome</a></em></p> | {
"question_id": 4208530,
"question_date": "2010-11-17T19:52:46.567Z",
"question_score": 209,
"tags": "jquery|xml|xslt|cors|xmlhttprequest",
"answer_id": 4752452,
"answer_date": "2011-01-20T20:52:17.163Z",
"answer_score": 178
} |
Please answer the following Stack Overflow question:
Title: Maven project.build.directory
<p>In Maven, what does the <code>project.build.directory</code> refer to? I am a bit confused, does it reference the source code directory or the target directory in the Maven project?</p> | <p>You can find those maven properties in the super pom.</p>
<p>You find the jar here:</p>
<pre><code>${M2_HOME}/lib/maven-model-builder-3.0.3.jar
</code></pre>
<p>Open the jar with 7-zip or some other archiver (or use the jar tool).</p>
<p>Navigate to</p>
<pre><code>org/apache/maven/model
</code></pre>
<p>There you'll find the <code>pom-4.0.0.xml</code>.</p>
<p>It contains all those "short cuts":</p>
<pre class="lang-xml prettyprint-override"><code><project>
...
<build>
<directory>${project.basedir}/target</directory>
<outputDirectory>${project.build.directory}/classes</outputDirectory>
<finalName>${project.artifactId}-${project.version}</finalName>
<testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory>
<sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
<scriptSourceDirectory>src/main/scripts</scriptSourceDirectory>
<testSourceDirectory>${project.basedir}/src/test/java</testSourceDirectory>
<resources>
<resource>
<directory>${project.basedir}/src/main/resources</directory>
</resource>
</resources>
<testResources>
<testResource>
<directory>${project.basedir}/src/test/resources</directory>
</testResource>
</testResources>
...
</build>
...
</project>
</code></pre>
<hr>
<h2>Update</h2>
<p>After some lobbying I am adding a <a href="https://github.com/apache/maven/blob/trunk/maven-model-builder/src/main/resources/org/apache/maven/model/pom-4.0.0.xml#L53">link to the <code>pom-4.0.0.xml</code></a>. This allows you to see the properties without opening up the local jar file.</p> | {
"question_id": 13354531,
"question_date": "2012-11-13T01:47:55.997Z",
"question_score": 209,
"tags": "maven",
"answer_id": 13356378,
"answer_date": "2012-11-13T06:24:29.317Z",
"answer_score": 260
} |
Please answer the following Stack Overflow question:
Title: How to list imported modules?
<p>How to enumerate all imported modules?</p>
<p>E.g. I would like to get <code>['os', 'sys']</code> from this code:</p>
<pre><code>import os
import sys
</code></pre> | <pre><code>import sys
sys.modules.keys()
</code></pre>
<p>An approximation of getting all imports for the current module only would be to inspect <a href="https://docs.python.org/2/library/functions.html#globals" rel="noreferrer"><code>globals()</code></a> for modules:</p>
<pre><code>import types
def imports():
for name, val in globals().items():
if isinstance(val, types.ModuleType):
yield val.__name__
</code></pre>
<p>This won't return local imports, or non-module imports like <code>from x import y</code>. Note that this returns <code>val.__name__</code> so you get the original module name if you used <code>import module as alias</code>; yield name instead if you want the alias.</p> | {
"question_id": 4858100,
"question_date": "2011-02-01T01:50:28.823Z",
"question_score": 209,
"tags": "python",
"answer_id": 4858123,
"answer_date": "2011-02-01T01:54:54.010Z",
"answer_score": 234
} |
Please answer the following Stack Overflow question:
Title: Postgres: check if array field contains value?
<p>I'm sure this is a duplicate question in the sense that the answer is out there somewhere, but I haven't been able to find the answer after Googling for 10 minutes, so I'd appeal to the editors not to close it on the basis that it might well be useful for other people. </p>
<p>I'm using Postgres 9.5. This is my table:</p>
<pre><code> Column │ Type │ Modifiers
─────────────────────────┼───────────────────────────┼─────────────────────────────────────────────────────────────────────────
id │ integer │ not null default nextval('mytable_id_seq'::regclass)
pmid │ character varying(200) │
pub_types │ character varying(2000)[] │ not null
</code></pre>
<p>I want to find all the rows with "Journal" in <code>pub_types</code>.</p>
<p>I've found the docs and googled and this is what I've tried:</p>
<pre><code>select * from mytable where ("Journal") IN pub_types;
select * from mytable where "Journal" IN pub_types;
select * from mytable where pub_types=ANY("Journal");
select * from mytable where pub_types IN ("Journal");
select * from mytable where where pub_types contains "Journal";
</code></pre>
<p>I've scanned <a href="https://www.postgresql.org/docs/9.1/static/arrays.html" rel="noreferrer">the postgres array docs</a> but can't see a simple example of how to run a query, and StackOverflow questions all seem to be based around more complicated examples. </p> | <p>This should work:</p>
<pre><code>select * from mytable where 'Journal'=ANY(pub_types);
</code></pre>
<p>i.e. the syntax is <code><value> = ANY ( <array> )</code>. Also notice that string literals in postresql are written with single quotes.</p> | {
"question_id": 39643454,
"question_date": "2016-09-22T15:45:00.813Z",
"question_score": 209,
"tags": "postgresql",
"answer_id": 39643544,
"answer_date": "2016-09-22T15:49:16.390Z",
"answer_score": 311
} |
Please answer the following Stack Overflow question:
Title: Swing vs JavaFx for desktop applications
<p>I have a very big program that is currently using SWT. The program can be run on both Windows, Mac and Linux, and it is a big desktop application with many elements.
Now SWT being somewhat old I would like to switch to either Swing or JavaFX. And I would like to hear your thoughts on three things.</p>
<p>My main concern is what will be better for a desktop GUI application? (I looked online and a lot of people suggest that JavaFX is just as good as Swing, but I didn't see many valid arguments except simple opinion flame wars). It has to work on both Windows, Mac and some popular Linux distributions.</p>
<ul>
<li><p>What will be cleaner and easier to maintain?</p></li>
<li><p>and what will be faster to build from scratch?</p></li>
</ul>
<p>I am using MVC methology in my application, if that is of any help.</p> | <blockquote>
<p>What will be cleaner and easier to maintain?</p>
</blockquote>
<p>All things being equal, probably JavaFX - the API is much more consistent across components. However, this depends much more on <em>how the code is written</em> rather than <em>what library is used to write it</em>.</p>
<blockquote>
<p>And what will be faster to build from scratch?</p>
</blockquote>
<p>Highly dependent on what you're building. Swing has more components around for it (3rd party as well as built in) and not all of them have made their way to the newer JavaFX platform yet, so there may be a certain amount of re-inventing the wheel if you need something a bit custom. On the other hand, if you want to do transitions / animations / video stuff then this is orders of magnitude easier in FX.</p>
<p>One other thing to bear in mind is (perhaps) look and feel. If you absolutely must have the default system look and feel, then JavaFX (at present) can't provide this. Not a big must have for me (I prefer the default FX look anyway) but I'm aware some policies mandate a restriction to system styles.</p>
<p>Personally, I see JavaFX as the "up and coming" UI library that's not <em>quite</em> there yet (but more than usable), and Swing as the borderline-legacy UI library that's fully featured and supported for the moment, but probably won't be so much in the years to come (and therefore chances are FX will overtake it at some point.)</p> | {
"question_id": 16694948,
"question_date": "2013-05-22T14:49:21.900Z",
"question_score": 209,
"tags": "java|swing|user-interface|javafx|swingx",
"answer_id": 16695225,
"answer_date": "2013-05-22T15:00:36.920Z",
"answer_score": 162
} |
Please answer the following Stack Overflow question:
Title: How can I check if a var is a string in JavaScript?
<p>How can I check if a var is a string in JavaScript?</p>
<p>I've tried this and it doesn't work...</p>
<pre><code>var a_string = "Hello, I'm a string.";
if (a_string typeof 'string') {
// this is a string
}
</code></pre> | <p>You were close:</p>
<pre><code>if (typeof a_string === 'string') {
// this is a string
}
</code></pre>
<hr>
<p>On a related note: the above check won't work if a string is created with <code>new String('hello')</code> as the type will be <code>Object</code> instead. There are complicated solutions to work around this, but it's better to just avoid creating strings that way, ever.</p> | {
"question_id": 6286542,
"question_date": "2011-06-08T23:42:11.213Z",
"question_score": 209,
"tags": "javascript|string|variable-types",
"answer_id": 6286551,
"answer_date": "2011-06-08T23:43:13.747Z",
"answer_score": 445
} |
Please answer the following Stack Overflow question:
Title: How can I check if a view is visible or not in Android?
<p>I set <code>visibility</code> to invisible like this on Android:</p>
<pre><code>myImageView.setVisibility(View.INVISIBLE);
</code></pre>
<p>And then to make it visible:</p>
<pre><code>myImageView.setVisibility(View.VISIBLE);
</code></pre>
<p>Now I don't know if <code>myImageView</code> is visible or not, how can I check it like this:</p>
<pre><code>if (myImageView IS VISIBLE) {
Do something
} else {
Do something else
}
</code></pre>
<p>How can I do that? What do I have to write within the brackets? </p> | <p>Although View.getVisibility() does get the visibility, its not a simple true/false. A view can have its visibility set to one of three things.</p>
<p><strong>View.VISIBLE</strong>
The view is visible.</p>
<p><strong>View.INVISIBLE</strong>
The view is invisible, but any spacing it would normally take up will still be used. Its "invisible"</p>
<p><strong>View.GONE</strong>
The view is gone, you can't see it and it doesn't take up the "spot".</p>
<p>So to answer your question, you're looking for:</p>
<pre><code>if (myImageView.getVisibility() == View.VISIBLE) {
// Its visible
} else {
// Either gone or invisible
}
</code></pre> | {
"question_id": 3791607,
"question_date": "2010-09-24T23:01:00.147Z",
"question_score": 209,
"tags": "android|user-interface|visible",
"answer_id": 3791698,
"answer_date": "2010-09-24T23:20:39.620Z",
"answer_score": 521
} |
Please answer the following Stack Overflow question:
Title: Print number of keys in Redis
<p>Is there a way to print the number of keys in Redis?</p>
<p>I am aware of </p>
<pre><code>keys *
</code></pre>
<p>But that seems slightly heavy weight. - Given that Redis is a key value store maybe this is the only way to do it. But I would still like to see something along the lines of </p>
<pre><code>count keys *
</code></pre> | <p>You can issue the INFO command, which returns information and statistics about the server. See <a href="http://redis.io/commands/info" rel="noreferrer">here</a> for an example output.</p>
<p>As mentioned in the comments by mVChr, you can use <code>info keyspace</code> directly on the redis-cli.</p>
<pre><code>redis> INFO
# Server
redis_version:6.0.6
redis_git_sha1:00000000
redis_git_dirty:0
redis_build_id:b63575307aaffe0a
redis_mode:standalone
os:Linux 5.4.0-1017-aws x86_64
arch_bits:64
multiplexing_api:epoll
atomicvar_api:atomic-builtin
gcc_version:9.3.0
process_id:2854672
run_id:90a5246f10e0aeb6b02cc2765b485d841ffc924e
tcp_port:6379
uptime_in_seconds:2593097
uptime_in_days:30
hz:10
configured_hz:10
lru_clock:4030200
executable:/usr/local/bin/redis-server
</code></pre> | {
"question_id": 9888387,
"question_date": "2012-03-27T11:06:15.557Z",
"question_score": 209,
"tags": "redis",
"answer_id": 9890319,
"answer_date": "2012-03-27T13:18:36.433Z",
"answer_score": 247
} |
Please answer the following Stack Overflow question:
Title: C# Test if user has write access to a folder
<p>I need to test if a user can write to a folder before actually attempting to do so. </p>
<p>I've implemented the following method (in C# 2.0) that attempts to retrieve the security permissions for the folder using <a href="http://msdn.microsoft.com/en-us/library/c1f66bc2%28VS.80%29.aspx" rel="noreferrer">Directory.GetAccessControl()</a> method.</p>
<pre><code>private bool hasWriteAccessToFolder(string folderPath)
{
try
{
// Attempt to get a list of security permissions from the folder.
// This will raise an exception if the path is read only or do not have access to view the permissions.
System.Security.AccessControl.DirectorySecurity ds = Directory.GetAccessControl(folderPath);
return true;
}
catch (UnauthorizedAccessException)
{
return false;
}
}
</code></pre>
<p>When I was googling how to test for write access nothing like this came up and it appeared very complicated to actually test permissions in Windows. I am concerned that I am over-simplifying things and that this method is not robust, although it does seem to work.</p>
<p>Will my method to test if the current user has write access work correctly?</p> | <p>That's a perfectly valid way to check for folder access in C#. The only place it might fall down is if you need to call this in a tight loop where the overhead of an exception <em>may</em> be an issue.</p>
<p>There have been other <a href="https://stackoverflow.com/questions/1281620/checking-for-directory-and-file-write-permissions-in-net">similar</a> <a href="https://stackoverflow.com/questions/130617/how-do-you-check-for-permissions-to-write-to-a-directory-or-file">questions</a> asked previously.</p> | {
"question_id": 1410127,
"question_date": "2009-09-11T10:14:55.200Z",
"question_score": 209,
"tags": "c#|permissions|directory",
"answer_id": 1410138,
"answer_date": "2009-09-11T10:18:22.387Z",
"answer_score": 68
} |
Please answer the following Stack Overflow question:
Title: In Mongoose, how do I sort by date? (node.js)
<p>let's say I run this query in Mongoose:</p>
<pre class="lang-js prettyprint-override"><code> Room.find({}, (err,docs) => {
}).sort({date:-1});
</code></pre>
<p>This doesn't work!</p> | <p><a href="http://mongoosejs.com/docs/api.html#query_Query-sort" rel="noreferrer">Sorting</a> in Mongoose has evolved over the releases such that some of these answers are no longer valid. As of the <strong>4.1.x</strong> release of Mongoose, a descending sort on the <code>date</code> field can be done in any of the following ways:</p>
<pre><code> Room.find({}).sort('-date').exec((err, docs) => { ... });
Room.find({}).sort({date: -1}).exec((err, docs) => { ... });
Room.find({}).sort({date: 'desc'}).exec((err, docs) => { ... });
Room.find({}).sort({date: 'descending'}).exec((err, docs) => { ... });
Room.find({}).sort([['date', -1]]).exec((err, docs) => { ... });
Room.find({}, null, {sort: '-date'}, (err, docs) => { ... });
Room.find({}, null, {sort: {date: -1}}, (err, docs) => { ... });
</code></pre>
<p>For an ascending sort, omit the <code>-</code> prefix on the string version or use values of <code>1</code>, <code>asc</code>, or <code>ascending</code>.</p> | {
"question_id": 5825520,
"question_date": "2011-04-28T21:55:20.057Z",
"question_score": 209,
"tags": "node.js|mongodb|mongoose",
"answer_id": 15081087,
"answer_date": "2013-02-26T03:57:41.190Z",
"answer_score": 543
} |
Please answer the following Stack Overflow question:
Title: What is the proper way to format a multi-line dict in Python?
<p>In Python, I want to write a multi-line dict in my code. There are a couple of ways one could format it. Here are a few that I could think of:</p>
<ol>
<li><pre><code>mydict = { "key1": 1,
"key2": 2,
"key3": 3, }
</code></pre></li>
<li><pre><code>mydict = { "key1": 1,
"key2": 2,
"key3": 3,
}
</code></pre></li>
<li><pre><code>mydict = {
"key1": 1,
"key2": 2,
"key3": 3,
}
</code></pre></li>
</ol>
<p>I know that any of the above is syntactically correct, but I assume that there is one preferred indentation and line-break style for Python dicts. What is it?</p>
<p>Note: This is not an issue of syntax. All of the above are (as far as I know) valid Python statements and are equivalent to each other.</p> | <p>I use #3. Same for long lists, tuples, etc. It doesn't require adding any extra spaces beyond the indentations. As always, be consistent.</p>
<pre><code>mydict = {
"key1": 1,
"key2": 2,
"key3": 3,
}
mylist = [
(1, 'hello'),
(2, 'world'),
]
nested = {
a: [
(1, 'a'),
(2, 'b'),
],
b: [
(3, 'c'),
(4, 'd'),
],
}
</code></pre>
<p>Similarly, here's my preferred way of including large strings without introducing any whitespace (like you'd get if you used triple-quoted multi-line strings):</p>
<pre><code>data = (
"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABG"
"l0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAEN"
"xBRpFYmctaKCfwrBSCrRLuL3iEW6+EEUG8XvIVjYWNgJdhFjIX"
"rz6pKtPB5e5rmq7tmxk+hqO34e1or0yXTGrj9sXGs1Ib73efh1"
"AAAABJRU5ErkJggg=="
)
</code></pre> | {
"question_id": 6388187,
"question_date": "2011-06-17T15:35:51.527Z",
"question_score": 209,
"tags": "python|indentation|code-formatting|multiline",
"answer_id": 6388237,
"answer_date": "2011-06-17T15:39:53.977Z",
"answer_score": 266
} |
Please answer the following Stack Overflow question:
Title: "OSError: [Errno 1] Operation not permitted" when installing Scrapy in OSX 10.11 (El Capitan) (System Integrity Protection)
<p>I'm trying to install Scrapy Python framework in OSX 10.11 (El Capitan) via pip. The installation script downloads the required modules and at some point returns the following error:</p>
<pre><code>OSError: [Errno 1] Operation not permitted: '/tmp/pip-nIfswi-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six-1.4.1-py2.7.egg-info'
</code></pre>
<p>I've tried to deactivate the rootless feature in OSX 10.11 with the command:</p>
<pre><code>sudo nvram boot-args="rootless=0";sudo reboot
</code></pre>
<p>but I still get the same error when the machine reboots.</p>
<p>Any clue or idea from my fellow StackExchangers?</p>
<p>If it helps, the full script output is the following:</p>
<pre><code>sudo -s pip install scrapy
Collecting scrapy
Downloading Scrapy-1.0.2-py2-none-any.whl (290kB)
100% |████████████████████████████████| 290kB 345kB/s
Requirement already satisfied (use --upgrade to upgrade): cssselect>=0.9 in /Library/Python/2.7/site-packages (from scrapy)
Requirement already satisfied (use --upgrade to upgrade): queuelib in /Library/Python/2.7/site-packages (from scrapy)
Requirement already satisfied (use --upgrade to upgrade): pyOpenSSL in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from scrapy)
Collecting w3lib>=1.8.0 (from scrapy)
Downloading w3lib-1.12.0-py2.py3-none-any.whl
Collecting lxml (from scrapy)
Downloading lxml-3.4.4.tar.gz (3.5MB)
100% |████████████████████████████████| 3.5MB 112kB/s
Collecting Twisted>=10.0.0 (from scrapy)
Downloading Twisted-15.3.0.tar.bz2 (4.4MB)
100% |████████████████████████████████| 4.4MB 94kB/s
Collecting six>=1.5.2 (from scrapy)
Downloading six-1.9.0-py2.py3-none-any.whl
Requirement already satisfied (use --upgrade to upgrade): zope.interface>=3.6.0 in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from Twisted>=10.0.0->scrapy)
Requirement already satisfied (use --upgrade to upgrade): setuptools in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from zope.interface>=3.6.0->Twisted>=10.0.0->scrapy)
Installing collected packages: six, w3lib, lxml, Twisted, scrapy
Found existing installation: six 1.4.1
DEPRECATION: Uninstalling a distutils installed project (six) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project.
Uninstalling six-1.4.1:
Exception:
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/basecommand.py", line 223, in main
status = self.run(options, args)
File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/commands/install.py", line 299, in run
root=options.root_path,
File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/req/req_set.py", line 640, in install
requirement.uninstall(auto_confirm=True)
File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/req/req_install.py", line 726, in uninstall
paths_to_remove.remove(auto_confirm)
File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/req/req_uninstall.py", line 125, in remove
renames(path, new_path)
File "/Library/Python/2.7/site-packages/pip-7.1.0-py2.7.egg/pip/utils/__init__.py", line 314, in renames
shutil.move(old, new)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 302, in move
copy2(src, real_dst)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 131, in copy2
copystat(src, dst)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 103, in copystat
os.chflags(dst, st.st_flags)
OSError: [Errno 1] Operation not permitted: '/tmp/pip-nIfswi-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six-1.4.1-py2.7.egg-info'
</code></pre> | <p>I also think it's absolutely not necessary to start hacking OS X.</p>
<p>I was able to solve it doing a</p>
<pre><code>brew install python
</code></pre>
<p>It seems that using the python / pip that comes with new El Capitan has some issues.</p> | {
"question_id": 31900008,
"question_date": "2015-08-09T01:00:37.947Z",
"question_score": 209,
"tags": "python|macos|python-2.7|scrapy",
"answer_id": 33245444,
"answer_date": "2015-10-20T19:40:42.087Z",
"answer_score": 153
} |
Please answer the following Stack Overflow question:
Title: How to set custom location for local installation of npm package?
<p>Is it possible to specify a custom package destination for <code>npm install</code>, either through a command flag or environment variable?</p>
<p>By default, npm local installs end up in <code>node_modules</code> within the current directory, but I want it to install into <code>node_modules</code> within a different directory, for example <code>vendor/node_modules</code>. How can I make that happen?</p> | <h3>TL;DR</h3>
<p>You can do this by using the <code>--prefix</code> flag and the <code>--global</code>* flag.</p>
<pre><code>pje@friendbear:~/foo $ npm install bower -g --prefix ./vendor/node_modules
[email protected] /Users/pje/foo/vendor/node_modules/bower
</code></pre>
<p>*Even though this is a "global" installation, installed bins won't be accessible through the command line unless <code>~/foo/vendor/node_modules</code> exists in <code>PATH</code>.</p>
<h3>TL;DR</h3>
<p>Every configurable attribute of <code>npm</code> can be set in any of six different places. In order of priority:</p>
<ul>
<li>Command-Line Flags: <code>--prefix ./vendor/node_modules</code></li>
<li>Environment Variables: <code>NPM_CONFIG_PREFIX=./vendor/node_modules</code></li>
<li>User Config File: <code>$HOME/.npmrc</code> or <code>userconfig</code> param</li>
<li>Global Config File: <code>$PREFIX/etc/npmrc</code> or <code>userconfig</code> param</li>
<li>Built-In Config File: <code>path/to/npm/itself/npmrc</code></li>
<li>Default Config: <a href="https://github.com/isaacs/npm/blob/master/node_modules/npmconf/config-defs.js" rel="noreferrer">node_modules/npmconf/config-defs.js</a></li>
</ul>
<p>By default, locally-installed packages go into <code>./node_modules</code>. global ones go into the <code>prefix</code> config variable (<code>/usr/local</code> by default).</p>
<p>You can run <code>npm config list</code> to see your current config and <code>npm config edit</code> to change it.</p>
<h3>PS</h3>
<p>In general, <code>npm</code>'s documentation is really helpful. The <a href="https://docs.npmjs.com/files/folders" rel="noreferrer">folders</a> section is a good structural overview of npm and the <a href="https://docs.npmjs.com/misc/config" rel="noreferrer">config</a> section answers this question.</p> | {
"question_id": 14742553,
"question_date": "2013-02-07T02:30:02.957Z",
"question_score": 209,
"tags": "node.js|npm",
"answer_id": 14867050,
"answer_date": "2013-02-14T02:53:00.307Z",
"answer_score": 200
} |
Please answer the following Stack Overflow question:
Title: How to change the appBar back button color
<p>I cannot figure out how to change the appBar's automatic back button to a different color. it's under a scaffold and I've tried to research it but I can't wrap my head around it. </p>
<pre><code>return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
title: Image.asset(
'images/.jpg',
fit: BoxFit.fill,
),
centerTitle: true,
),
</code></pre> | <p>You have to use the <code>iconTheme</code> property from the AppBar , like this:</p>
<pre><code>appBar: AppBar(
iconTheme: IconThemeData(
color: Colors.black, //change your color here
),
title: Text("Sample"),
centerTitle: true,
),
</code></pre>
<p>Or if you want to handle the back button by yourself.</p>
<pre><code>appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back, color: Colors.black),
onPressed: () => Navigator.of(context).pop(),
),
title: Text("Sample"),
centerTitle: true,
),
</code></pre>
<p>Even better, only if you want to change the color of the back button. </p>
<pre class="lang-dart prettyprint-override"><code>appBar: AppBar(
leading: BackButton(
color: Colors.black
),
title: Text("Sample"),
centerTitle: true,
),
</code></pre> | {
"question_id": 51508257,
"question_date": "2018-07-24T22:12:27.350Z",
"question_score": 209,
"tags": "flutter",
"answer_id": 51508446,
"answer_date": "2018-07-24T22:33:37.940Z",
"answer_score": 559
} |
Please answer the following Stack Overflow question:
Title: pip installs packages successfully, but executables not found from command line
<p>I am working on mac OS X Yosemite, version 10.10.3.</p>
<p>I installed python2.7 and pip using macport as done in
<a href="http://johnlaudun.org/20150512-installing-and-setting-pip-with-macports/" rel="noreferrer">http://johnlaudun.org/20150512-installing-and-setting-pip-with-macports/</a></p>
<p>I can successfully install packages and import them inside my python environment and python scripts. However any executable associated with a package that can be called from the command line in the terminal are not found.</p>
<p><strong>Does anyone know what might be wrong?</strong> (More details below)</p>
<p>For example while installing a package called "rosdep" as instructed in <a href="http://wiki.ros.org/jade/Installation/Source" rel="noreferrer">http://wiki.ros.org/jade/Installation/Source</a></p>
<p>I can run: <code>sudo pip install -U rosdep</code>
which installs without errors and corresponding files are located in <code>/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages</code></p>
<p>However if I try to run : <code>sudo rosdep init</code>,
it gives an error : <code>"sudo: rosdep: command not found"</code></p>
<p>This is not a package specific error. I get this for any package installed using pip on my computer. I even tried adding </p>
<pre><code>/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages
</code></pre>
<p>to my <code>$PATH</code>.
But the executables are not found on the command line, even though the packages work perfectly from within python.</p> | <p>check your $PATH</p>
<p><code>tox</code> has a command line mode: </p>
<pre><code>audrey:tests jluc$ pip list | grep tox
tox (2.3.1)
</code></pre>
<p>where is it?</p>
<p>(edit: the <code>2.7</code> stuff doesn't matter much here, sub in any <code>3.x</code> and pip's behaving pretty much the same way)</p>
<pre><code>audrey:tests jluc$ which tox
/opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin/tox
</code></pre>
<p>and what's in my $PATH? </p>
<pre><code>audrey:tests jluc$ echo $PATH
/opt/chefdk/bin:/opt/chefdk/embedded/bin:/opt/local/bin:..../opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin...
</code></pre>
<p>Notice the <strong>/opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin</strong>? That's what allows finding my pip-installed stuff</p>
<p>Now, to see where things are from Python, try doing this (substitute <code>rosdep</code> for <code>tox</code>).</p>
<pre><code>$python
>>> import tox
>>> tox.__file__
</code></pre>
<p>that prints out:</p>
<pre><code>'/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/tox/__init__.pyc'
</code></pre>
<p>Now, <strong>cd</strong> to the directory right above <code>lib</code> in the above. Do you see a <strong>bin</strong> directory? Do you see <code>rosdep</code> in that bin? If so try adding the <code>bin</code> to your $PATH.</p>
<pre><code>audrey:2.7 jluc$ cd /opt/local/Library/Frameworks/Python.framework/Versions/2.7
audrey:2.7 jluc$ ls -1
</code></pre>
<p>output:</p>
<pre><code>Headers
Python
Resources
bin
include
lib
man
share
</code></pre> | {
"question_id": 35898734,
"question_date": "2016-03-09T17:38:44.373Z",
"question_score": 209,
"tags": "python|macos|pip|macports",
"answer_id": 35899029,
"answer_date": "2016-03-09T17:54:59.557Z",
"answer_score": 71
} |
Please answer the following Stack Overflow question:
Title: awk without printing newline
<p>I want the variable sum/NR to be printed side-by-side in each iteration. How do we avoid awk from printing newline in each iteration ? In my code a newline is printed by default in each iteration</p>
<pre><code>for file in cg_c ep_c is_c tau xhpl
printf "\n $file" >> to-plot.xls
for f in 2.54 1.60 800
awk '{sum+=$3}; END {print sum/NR}' ${file}_${f}_v1.xls >> to-plot-p.xls
done
done
</code></pre>
<p>I want the output to appear like this</p>
<pre><code>cg_c ans1 ans2 ans3
ep_c ans1 ans2 ans3
is_c ans1 ans2 ans3
tau ans1 ans2 ans3
xhpl ans1 ans2 ans3
</code></pre>
<p>my current out put is like this</p>
<pre><code>**cg_c**
ans1
ans2
ans3
**ep_c**
ans1
ans2
ans3
**is_c**
ans1
ans2
ans3
**tau**
ans1
ans2
ans3
**xhpl**
ans1
ans2
ans3
</code></pre> | <p><code>awk '{sum+=$3}; END {printf "%f",sum/NR}' ${file}_${f}_v1.xls >> to-plot-p.xls</code></p>
<p><code>print</code> will insert a newline by default. You dont want that to happen, hence use <code>printf</code> instead.</p> | {
"question_id": 2021982,
"question_date": "2010-01-07T16:49:27.333Z",
"question_score": 209,
"tags": "scripting|awk|newline",
"answer_id": 2022026,
"answer_date": "2010-01-07T16:56:18.810Z",
"answer_score": 256
} |
Please answer the following Stack Overflow question:
Title: Multi-statement Table Valued Function vs Inline Table Valued Function
<p>A few examples to show, just incase:</p>
<p><em>Inline Table Valued</em></p>
<pre><code>CREATE FUNCTION MyNS.GetUnshippedOrders()
RETURNS TABLE
AS
RETURN SELECT a.SaleId, a.CustomerID, b.Qty
FROM Sales.Sales a INNER JOIN Sales.SaleDetail b
ON a.SaleId = b.SaleId
INNER JOIN Production.Product c ON b.ProductID = c.ProductID
WHERE a.ShipDate IS NULL
GO
</code></pre>
<p><em>Multi Statement Table Valued</em></p>
<pre><code>CREATE FUNCTION MyNS.GetLastShipped(@CustomerID INT)
RETURNS @CustomerOrder TABLE
(SaleOrderID INT NOT NULL,
CustomerID INT NOT NULL,
OrderDate DATETIME NOT NULL,
OrderQty INT NOT NULL)
AS
BEGIN
DECLARE @MaxDate DATETIME
SELECT @MaxDate = MAX(OrderDate)
FROM Sales.SalesOrderHeader
WHERE CustomerID = @CustomerID
INSERT @CustomerOrder
SELECT a.SalesOrderID, a.CustomerID, a.OrderDate, b.OrderQty
FROM Sales.SalesOrderHeader a INNER JOIN Sales.SalesOrderHeader b
ON a.SalesOrderID = b.SalesOrderID
INNER JOIN Production.Product c ON b.ProductID = c.ProductID
WHERE a.OrderDate = @MaxDate
AND a.CustomerID = @CustomerID
RETURN
END
GO
</code></pre>
<p>Is there an advantage to using one type (in-line or multi statement) over the other? Is there certain scenarios when one is better than the other or are the differences purely syntactical? I realise the two example queries are doing different things but is there a reason I would write them in that way?</p>
<p>Reading about them and the advantages/differences haven't really been explained.</p> | <p>In researching Matt's comment, I have revised my original statement. He is correct, there will be a difference in performance between an inline table valued function (ITVF) and a multi-statement table valued function (MSTVF) even if they both simply execute a SELECT statement. SQL Server will treat an ITVF somewhat like a <code>VIEW</code> in that it will calculate an execution plan using the latest statistics on the tables in question. A MSTVF is equivalent to stuffing the entire contents of your SELECT statement into a table variable and then joining to that. Thus, the compiler cannot use any table statistics on the tables in the MSTVF. So, all things being equal, (which they rarely are), the ITVF will perform better than the MSTVF. In my tests, the performance difference in completion time was negligible however from a statistics standpoint, it was noticeable.</p>
<p>In your case, the two functions are not functionally equivalent. The MSTV function does an extra query each time it is called and, most importantly, filters on the customer id. In a large query, the optimizer would not be able to take advantage of other types of joins as it would need to call the function for each customerId passed. However, if you re-wrote your MSTV function like so:</p>
<pre><code>CREATE FUNCTION MyNS.GetLastShipped()
RETURNS @CustomerOrder TABLE
(
SaleOrderID INT NOT NULL,
CustomerID INT NOT NULL,
OrderDate DATETIME NOT NULL,
OrderQty INT NOT NULL
)
AS
BEGIN
INSERT @CustomerOrder
SELECT a.SalesOrderID, a.CustomerID, a.OrderDate, b.OrderQty
FROM Sales.SalesOrderHeader a
INNER JOIN Sales.SalesOrderHeader b
ON a.SalesOrderID = b.SalesOrderID
INNER JOIN Production.Product c
ON b.ProductID = c.ProductID
WHERE a.OrderDate = (
Select Max(SH1.OrderDate)
FROM Sales.SalesOrderHeader As SH1
WHERE SH1.CustomerID = A.CustomerId
)
RETURN
END
GO
</code></pre>
<p>In a query, the optimizer would be able to call that function once and build a better execution plan but it still would not be better than an equivalent, non-parameterized ITVS or a <code>VIEW</code>.</p>
<p>ITVFs should be preferred over a MSTVFs when feasible because the datatypes, nullability and collation from the columns in the table whereas you declare those properties in a multi-statement table valued function and, importantly, you will get better execution plans from the ITVF. In my experience, I have not found many circumstances where an ITVF was a better option than a VIEW but mileage may vary.</p>
<p>Thanks to Matt.</p>
<p><strong>Addition</strong> </p>
<p>Since I saw this come up recently, here is an excellent analysis done by Wayne Sheffield comparing the performance difference between Inline Table Valued functions and Multi-Statement functions.</p>
<p><a href="http://blog.waynesheffield.com/wayne/archive/2012/02/comparing-inline-and-multistatement-table-valued-functions/#comments" rel="noreferrer">His original blog post.</a></p>
<p><a href="http://www.sqlservercentral.com/blogs/discussionofsqlserver/2012/02/15/comparing-inline-and-multistatement-table-valued-functions/" rel="noreferrer">Copy on SQL Server Central</a></p> | {
"question_id": 2554333,
"question_date": "2010-03-31T15:41:36.497Z",
"question_score": 209,
"tags": "sql|sql-server|sql-server-2008|tsql|user-defined-functions",
"answer_id": 2554544,
"answer_date": "2010-03-31T16:10:53.773Z",
"answer_score": 151
} |
Please answer the following Stack Overflow question:
Title: What is the difference between & and && in Java?
<p>I always thought that <code>&&</code> operator in Java is used for verifying whether both its boolean operands are <code>true</code>, and the <code>&</code> operator is used to do Bit-wise operations on two integer types.</p>
<p>Recently I came to know that <code>&</code> operator can also be used verify whether both its boolean operands are <code>true</code>, the only difference being that it checks the RHS operand even if the LHS operand is false.</p>
<p>Is the <code>&</code> operator in Java internally overloaded? Or is there some other concept behind this? </p> | <p>& <-- verifies both operands<br>
&& <-- stops evaluating if the first operand evaluates to false since the result will be false</p>
<p><code>(x != 0) & (1/x > 1)</code> <-- this means evaluate <code>(x != 0)</code> then evaluate <code>(1/x > 1)</code> then do the &. the problem is that for x=0 this will throw an exception.</p>
<p><code>(x != 0) && (1/x > 1)</code> <-- this means evaluate <code>(x != 0)</code> and only if this is true then evaluate <code>(1/x > 1)</code> so if you have x=0 then this is perfectly safe and won't throw any exception if (x != 0) evaluates to false the whole thing directly evaluates to false without evaluating the <code>(1/x > 1)</code>.</p>
<p>EDIT:</p>
<p><code>exprA | exprB</code> <-- this means evaluate <code>exprA</code> then evaluate <code>exprB</code> then do the <code>|</code>.</p>
<p><code>exprA || exprB</code> <-- this means evaluate <code>exprA</code> and only if this is <code>false</code> then evaluate <code>exprB</code> and do the <code>||</code>.</p> | {
"question_id": 5564410,
"question_date": "2011-04-06T09:46:55.103Z",
"question_score": 209,
"tags": "java|operators|boolean|bitwise-operators",
"answer_id": 5564484,
"answer_date": "2011-04-06T09:53:19.100Z",
"answer_score": 344
} |
Please answer the following Stack Overflow question:
Title: Build .so file from .c file using gcc command line
<p>I'm trying to create a hello world project for Linux dynamic libraries (.so files). So I have a file hello.c:</p>
<pre><code>#include <stdio.h>
void hello()
{
printf("Hello world!\n");
}
</code></pre>
<p>How do I create a .so file that exports <code>hello()</code>, using gcc from the command line?</p> | <p>To generate a shared library you need first to compile your C code with the <code>-fPIC</code> (position independent code) flag. </p>
<pre><code>gcc -c -fPIC hello.c -o hello.o
</code></pre>
<p>This will generate an object file (.o), now you take it and create the .so file:</p>
<pre><code>gcc hello.o -shared -o libhello.so
</code></pre>
<p><strong>EDIT</strong>: Suggestions from the comments:</p>
<p>You can use</p>
<pre><code>gcc -shared -o libhello.so -fPIC hello.c
</code></pre>
<p>to do it in one step. – <a href="https://stackoverflow.com/users/15168/jonathan-leffler">Jonathan Leffler</a></p>
<p>I also suggest to add <code>-Wall</code> to get all warnings, and <code>-g</code> to get debugging information, to your <code>gcc</code> commands. – <a href="https://stackoverflow.com/users/841108/basile-starynkevitch">Basile Starynkevitch</a> </p> | {
"question_id": 14884126,
"question_date": "2013-02-14T21:11:53.870Z",
"question_score": 209,
"tags": "c|linux|gcc|shared-libraries",
"answer_id": 14884166,
"answer_date": "2013-02-14T21:14:47.120Z",
"answer_score": 378
} |
Please answer the following Stack Overflow question:
Title: How do you serialize a model instance in Django?
<p>There is a lot of documentation on how to serialize a Model QuerySet but how do you just serialize to JSON the fields of a Model Instance?</p> | <p>You can easily use a list to wrap the required object and that's all what django serializers need to correctly serialize it, eg.:</p>
<pre><code>from django.core import serializers
# assuming obj is a model instance
serialized_obj = serializers.serialize('json', [ obj, ])
</code></pre> | {
"question_id": 757022,
"question_date": "2009-04-16T16:47:31.717Z",
"question_score": 209,
"tags": "django|django-models",
"answer_id": 3289057,
"answer_date": "2010-07-20T10:31:13.537Z",
"answer_score": 291
} |
Please answer the following Stack Overflow question:
Title: How to change the default collation of a table?
<pre><code>create table check2(f1 varchar(20),f2 varchar(20));
</code></pre>
<p>creates a table with the default collation <code>latin1_general_ci</code>;</p>
<pre><code>alter table check2 collate latin1_general_cs;
show full columns from check2;
</code></pre>
<p>shows the individual collation of the columns as 'latin1_general_ci'.</p>
<p>Then what is the effect of the alter table command?</p> | <p>To change the default character set and collation of a table <em>including those of existing columns</em> (note the <strong>convert to</strong> clause):</p>
<pre><code>alter table <some_table> convert to character set utf8mb4 collate utf8mb4_unicode_ci;
</code></pre>
<p>Edited the answer, thanks to the prompting of some comments:</p>
<blockquote>
<p>Should avoid recommending utf8. It's almost never what you want, and often leads to unexpected messes. The utf8 character set is not fully compatible with UTF-8. The utf8mb4 character set is what you want if you want UTF-8. – Rich Remer Mar 28 '18 at 23:41 </p>
</blockquote>
<p>and</p>
<blockquote>
<p>That seems quite important, glad I read the comments and thanks @RichRemer . Nikki , I think you should edit that in your answer considering how many views this gets. See here <a href="https://dev.mysql.com/doc/refman/8.0/en/charset-unicode-utf8.html" rel="noreferrer">https://dev.mysql.com/doc/refman/8.0/en/charset-unicode-utf8.html</a> and here <a href="https://stackoverflow.com/q/30074492/772035">What is the difference between utf8mb4 and utf8 charsets in MySQL?</a> – Paulpro Mar 12 at 17:46</p>
</blockquote> | {
"question_id": 742205,
"question_date": "2009-04-12T18:53:10.610Z",
"question_score": 209,
"tags": "mysql|sql|collation",
"answer_id": 5468980,
"answer_date": "2011-03-29T07:00:24.037Z",
"answer_score": 645
} |
Please answer the following Stack Overflow question:
Title: Use of Java's Collections.singletonList()?
<p>What is the use of <code>Collections.singletonList()</code> in Java? I understand that it returns a list with one element. Why would I want to have a separate method to do that? How does immutability play a role here?</p>
<p>Are there any special useful use-cases for this method rather than just being a convenient method?</p> | <p>The <a href="http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#singletonList(T)" rel="noreferrer">javadoc</a> says this:</p>
<blockquote>
<p><em>"Returns an immutable list containing only the specified object. The returned list is serializable."</em></p>
</blockquote>
<p>You ask:</p>
<blockquote>
<p>Why would I want to have a separate method to do that?</p>
</blockquote>
<p>Primarily as a convenience ... to save you having to write a sequence of statements to:</p>
<ul>
<li>create an empty list object</li>
<li>add an element to it, and</li>
<li>wrap it with an immutable wrapper.</li>
</ul>
<p>It may also be a bit faster and/or save a bit of memory, but it is unlikely that these small savings will be significant. (An application that creates vast numbers of singleton lists is unusual to say the least.) </p>
<blockquote>
<p>How does immutability play a role here?</p>
</blockquote>
<p>It is part of the specification of the method; see above.</p>
<blockquote>
<p>Are there any special useful use-cases for this method, rather than just being a convenience method?</p>
</blockquote>
<p>Clearly, there are use-cases where it is convenient to use the <code>singletonList</code> method. But I don't know how you would (objectively) distinguish between an ordinary use-case and a "specially useful" one ... </p> | {
"question_id": 4801794,
"question_date": "2011-01-26T06:02:29.273Z",
"question_score": 209,
"tags": "java",
"answer_id": 4801854,
"answer_date": "2011-01-26T06:19:34.280Z",
"answer_score": 188
} |
Please answer the following Stack Overflow question:
Title: How can I tell how many objects I've stored in an S3 bucket?
<p>Unless I'm missing something, it seems that none of the APIs I've looked at will tell you how many objects are in an <code><S3 bucket>/<folder></code>. Is there any way to get a count?</p> | <p>There is no way, unless you </p>
<ol>
<li><p>list them all in batches of 1000 (which can be slow and suck bandwidth - amazon seems to never compress the XML responses), or</p></li>
<li><p>log into your account on S3, and go Account - Usage. It seems the billing dept knows exactly how many objects you have stored!</p></li>
</ol>
<p>Simply downloading the list of all your objects will actually take some time and cost some money if you have 50 million objects stored.</p>
<p>Also see <a href="http://developer.amazonwebservices.com/connect/thread.jspa?messageID=164220&#164220" rel="noreferrer">this thread about StorageObjectCount</a> - which is in the usage data.</p>
<p>An S3 API to get at least the basics, even if it was hours old, would be great. </p> | {
"question_id": 2862617,
"question_date": "2010-05-19T03:15:49.457Z",
"question_score": 209,
"tags": "file|count|amazon-s3|amazon-web-services",
"answer_id": 2876394,
"answer_date": "2010-05-20T17:44:24.490Z",
"answer_score": 45
} |
Please answer the following Stack Overflow question:
Title: Toggle input disabled attribute using jQuery
<p>Here is my code:</p>
<pre><code>$("#product1 :checkbox").click(function(){
$(this)
.closest('tr') // Find the parent row.
.find(":input[type='text']") // Find text elements in that row.
.attr('disabled',false).toggleClass('disabled') // Enable them.
.end() // Go back to the row.
.siblings() // Get its siblings
.find(":input[type='text']") // Find text elements in those rows.
.attr('disabled',true).removeClass('disabled'); // Disable them.
});
</code></pre>
<p>How do I toggle <code>.attr('disabled',false);</code>?</p>
<p>I can't seem to find it on Google.</p> | <pre><code>$('#el').prop('disabled', (i, v) => !v);
</code></pre>
<p>The <a href="http://api.jquery.com/prop/" rel="nofollow noreferrer"><code>.prop()</code></a> method accepts two arguments:</p>
<ul>
<li>Property <strong>name</strong> (disabled, checked, selected) anything that is either true or false</li>
<li>Property <strong>value</strong>, can be:</li>
<li>(<em>empty</em>) - returns the current value.</li>
<li><em>boolean</em> (true/false) - sets the property value.</li>
<li><em>function</em> - Is executed for each found element, the returned value is used to set the property. There are two arguments passed; the first argument is the <em>index</em> (0, 1, 2, increases for each found element). The second argument is the current <em>value</em> of the element (true/false).</li>
</ul>
<p>So in this case, I used a function that supplied me the index (i) and the current value (v), then I returned the opposite of the current value, so the property state is reversed.</p> | {
"question_id": 4702000,
"question_date": "2011-01-15T20:37:21.293Z",
"question_score": 209,
"tags": "jquery|toggle|attr",
"answer_id": 9489400,
"answer_date": "2012-02-28T20:43:15.127Z",
"answer_score": 495
} |
Please answer the following Stack Overflow question:
Title: How to make a Java Generic method static?
<p>The following is a snippet on how to make a java generic class to append a single item to an array. How can I make appendToArray a static method. Adding static to the method signature results in compile errors.</p>
<pre><code>public class ArrayUtils<E> {
public E[] appendToArray(E[] array, E item) {
E[] result = (E[])new Object[array.length+1];
result[array.length] = item;
return result;
}
}
</code></pre> | <p>the only thing you can do is to change your signature to</p>
<pre><code>public static <E> E[] appendToArray(E[] array, E item)
</code></pre>
<p><strong>Important details:</strong></p>
<p>Generic expressions preceding the return value always introduce (declare) a new generic type variable.</p>
<p>Additionally, type variables between types (<code>ArrayUtils</code>) and static methods (<code>appendToArray</code>) never interfere with each other.</p>
<p>So, what does this mean:
In my answer <code><E></code> would hide the <code>E</code> from <code>ArrayUtils<E></code> if the method wouldn't be <code>static</code>. AND <code><E></code> has nothing to do with the <code>E</code> from <code>ArrayUtils<E></code>.</p>
<p>To reflect this fact better, a more correct answer would be:</p>
<pre><code>public static <I> I[] appendToArray(I[] array, I item)
</code></pre> | {
"question_id": 4409100,
"question_date": "2010-12-10T13:05:46.650Z",
"question_score": 209,
"tags": "java|generics",
"answer_id": 4409134,
"answer_date": "2010-12-10T13:09:05.503Z",
"answer_score": 344
} |
Please answer the following Stack Overflow question:
Title: How to document a method with parameter(s)?
<p><strong>How to document methods with parameters using Python's documentation strings?</strong></p>
<p><strong>EDIT:</strong>
<a href="http://www.python.org/dev/peps/pep-0257/" rel="noreferrer">PEP 257</a> gives this example:</p>
<pre><code>def complex(real=0.0, imag=0.0):
"""Form a complex number.
Keyword arguments:
real -- the real part (default 0.0)
imag -- the imaginary part (default 0.0)
"""
if imag == 0.0 and real == 0.0: return complex_zero
...
</code></pre>
<p>Is this the convention used by most Python developers ?</p>
<pre><code>Keyword arguments:
<parameter name> -- Definition (default value if any)
</code></pre>
<p>I was expecting something a little bit more formal such as </p>
<pre><code>def complex(real=0.0, imag=0.0):
"""Form a complex number.
@param: real The real part (default 0.0)
@param: imag The imaginary part (default 0.0)
"""
if imag == 0.0 and real == 0.0: return complex_zero
...
</code></pre>
<p><strong>Environment</strong>: Python 2.7.1</p> | <p>Based on my experience, the <a href="https://numpydoc.readthedocs.io/en/latest/format.html#docstring-standard" rel="noreferrer">numpy docstring conventions</a> (PEP257 superset) are the most widely-spread <em>followed</em> conventions that are also supported by tools, such as <a href="https://www.sphinx-doc.org/en/master/" rel="noreferrer">Sphinx</a>. </p>
<p>One example:</p>
<pre><code>Parameters
----------
x : type
Description of parameter `x`.
</code></pre> | {
"question_id": 9195455,
"question_date": "2012-02-08T14:41:52.990Z",
"question_score": 209,
"tags": "python|documentation|documentation-generation",
"answer_id": 10065932,
"answer_date": "2012-04-08T19:49:19.820Z",
"answer_score": 109
} |
Please answer the following Stack Overflow question:
Title: Log exception with traceback in python
<p>How can I log my Python errors?</p>
<pre><code>try:
do_something()
except:
# How can I log my exception here, complete with its traceback?
</code></pre> | <p>Use <a href="https://docs.python.org/library/logging.html#logging.exception" rel="noreferrer"><code>logging.exception</code></a> from within the <code>except:</code> handler/block to log the current exception along with the trace information, prepended with a message.</p>
<pre><code>import logging
LOG_FILENAME = '/tmp/logging_example.out'
logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG)
logging.debug('This message should go to the log file')
try:
run_my_stuff()
except:
logging.exception('Got exception on main handler')
raise
</code></pre>
<p>Now looking at the log file, <code>/tmp/logging_example.out</code>:</p>
<pre><code>DEBUG:root:This message should go to the log file
ERROR:root:Got exception on main handler
Traceback (most recent call last):
File "/tmp/teste.py", line 9, in <module>
run_my_stuff()
NameError: name 'run_my_stuff' is not defined
</code></pre> | {
"question_id": 1508467,
"question_date": "2009-10-02T09:07:15.017Z",
"question_score": 209,
"tags": "python|exception|logging|error-handling",
"answer_id": 1508761,
"answer_date": "2009-10-02T10:24:09.957Z",
"answer_score": 291
} |
Please answer the following Stack Overflow question:
Title: Prevent Caching in ASP.NET MVC for specific actions using an attribute
<p>I have an ASP.NET MVC 3 application. This application requests records through jQuery. jQuery calls back to a controller action that returns results in JSON format. I have not been able to prove this, but I'm concerned that my data may be getting cached. </p>
<p>I only want the caching to be applied to specific actions, not for all actions.</p>
<p>Is there an attribute that I can put on an action to ensure that the data does not get cached? If not, how do I ensure that the browser gets a new set of records each time, instead of a cached set?</p> | <p>To ensure that JQuery isn't caching the results, on your ajax methods, put the following:</p>
<pre><code>$.ajax({
cache: false
//rest of your ajax setup
});
</code></pre>
<p>Or to prevent caching in MVC, we created our own attribute, you could do the same. Here's our code:</p>
<pre><code>[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class NoCacheAttribute : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
filterContext.HttpContext.Response.Cache.SetNoStore();
base.OnResultExecuting(filterContext);
}
}
</code></pre>
<p>Then just decorate your controller with <code>[NoCache]</code>. OR to do it for all you could just put the attribute on the class of the base class that you inherit your controllers from (if you have one) like we have here:</p>
<pre><code>[NoCache]
public class ControllerBase : Controller, IControllerBase
</code></pre>
<p>You can also decorate some of the actions with this attribute if you need them to be non-cacheable, instead of decorating the whole controller.</p>
<p>If your class or action didn't have <code>NoCache</code> when it was rendered in your browser and you want to check it's working, remember that after compiling the changes you need to do a "hard refresh" (Ctrl+F5) in your browser. Until you do so, your browser will keep the old cached version, and won't refresh it with a "normal refresh" (F5).</p> | {
"question_id": 10011780,
"question_date": "2012-04-04T13:09:47.830Z",
"question_score": 209,
"tags": "c#|jquery|.net|asp.net-mvc|asp.net-mvc-3",
"answer_id": 10011896,
"answer_date": "2012-04-04T13:15:56.110Z",
"answer_score": 316
} |
Please answer the following Stack Overflow question:
Title: What are major differences between C# and Java?
<p>I just want to clarify one thing. This is not a question on which one is better, that part I leave to someone else to discuss. I don't care about it.
I've been asked this question on my job interview and I thought it might be useful to learn a bit more.</p>
<p>These are the ones I could come up with:</p>
<ul>
<li>Java is "platform independent". Well nowadays you could say there is the <a href="http://en.wikipedia.org/wiki/Mono_%28software%29" rel="noreferrer">Mono</a> project so C# could be considered too but
I believe it is a bit exaggerating. Why? Well, when a new release of Java is done it is simultaneously available on all platforms it supports, on the other hand how many features of C# 3.0 are still missing in the Mono implementation? Or is it really <a href="http://en.wikipedia.org/wiki/Common_Language_Runtime" rel="noreferrer">CLR</a> vs. <a href="http://en.wikipedia.org/wiki/JRE" rel="noreferrer">JRE</a> that we should compare here?</li>
<li>Java doesn't support events and delegates. As far as I know.</li>
<li>In Java all methods are virtual</li>
<li>Development tools: I believe there isn't such a tool yet as Visual Studio. Especially if you've worked with team editions you'll know what I mean.</li>
</ul>
<p>Please add others you think are relevant.</p>
<p>Update:
Just popped up my mind, Java doesn't have something like custom attributes on classes, methods etc. Or does it?</p> | <p><strong>Comparing Java 7 and C# 3</strong></p>
<p>(Some features of Java 7 aren't mentioned here, but the <code>using</code> statement advantage of all versions of C# over Java 1-6 has been removed.)</p>
<p>Not all of your summary is correct:</p>
<ul>
<li>In Java methods are virtual <em>by default</em> but you can make them final. (In C# they're sealed by default, but you can make them virtual.)</li>
<li>There are plenty of IDEs for Java, both free (e.g. Eclipse, Netbeans) and commercial (e.g. IntelliJ IDEA)</li>
</ul>
<p>Beyond that (and what's in your summary already):</p>
<ul>
<li>Generics are completely different between the two; Java generics are just a compile-time "trick" (but a useful one at that). In C# and .NET generics are maintained at execution time too, and work for value types as well as reference types, keeping the appropriate efficiency (e.g. a <code>List<byte></code> as a <code>byte[]</code> backing it, rather than an array of boxed bytes.)</li>
<li>C# doesn't have checked exceptions</li>
<li>Java doesn't allow the creation of user-defined value types</li>
<li>Java doesn't have operator and conversion overloading</li>
<li>Java doesn't have iterator blocks for simple implemetation of iterators</li>
<li>Java doesn't have anything like LINQ</li>
<li>Partly due to not having delegates, Java doesn't have anything quite like anonymous methods and lambda expressions. Anonymous inner classes usually fill these roles, but clunkily.</li>
<li>Java doesn't have expression trees</li>
<li>C# doesn't have anonymous inner classes</li>
<li>C# doesn't have Java's inner classes at all, in fact - all nested classes in C# are like Java's static nested classes</li>
<li>Java doesn't have static classes (which don't have <em>any</em> instance constructors, and can't be used for variables, parameters etc)</li>
<li>Java doesn't have any equivalent to the C# 3.0 anonymous types</li>
<li>Java doesn't have implicitly typed local variables</li>
<li>Java doesn't have extension methods</li>
<li>Java doesn't have object and collection initializer expressions</li>
<li>The access modifiers are somewhat different - in Java there's (currently) no direct equivalent of an assembly, so no idea of "internal" visibility; in C# there's no equivalent to the "default" visibility in Java which takes account of namespace (and inheritance)</li>
<li>The order of initialization in Java and C# is subtly different (C# executes variable initializers before the chained call to the base type's constructor)</li>
<li>Java doesn't have properties as part of the language; they're a convention of get/set/is methods</li>
<li>Java doesn't have the equivalent of "unsafe" code</li>
<li>Interop is easier in C# (and .NET in general) than Java's JNI</li>
<li>Java and C# have somewhat different ideas of enums. Java's are much more object-oriented.</li>
<li>Java has no preprocessor directives (#define, #if etc in C#).</li>
<li>Java has no equivalent of C#'s <code>ref</code> and <code>out</code> for passing parameters by reference</li>
<li>Java has no equivalent of partial types</li>
<li>C# interfaces cannot declare fields</li>
<li>Java has no unsigned integer types</li>
<li>Java has no <em>language</em> support for a decimal type. (java.math.BigDecimal provides something <em>like</em> System.Decimal - with differences - but there's no language support)</li>
<li>Java has no equivalent of nullable value types</li>
<li>Boxing in Java uses predefined (but "normal") reference types with particular operations on them. Boxing in C# and .NET is a more transparent affair, with a reference type being created for boxing by the CLR for any value type.</li>
</ul>
<p>This is not exhaustive, but it covers everything I can think of off-hand.</p> | {
"question_id": 295224,
"question_date": "2008-11-17T10:07:23.700Z",
"question_score": 209,
"tags": "c#|.net|clr|java",
"answer_id": 295248,
"answer_date": "2008-11-17T10:16:58.687Z",
"answer_score": 329
} |
Please answer the following Stack Overflow question:
Title: How do I get the different parts of a Flask request's url?
<p>I want to detect if the request came from the <code>localhost:5000</code> or <code>foo.herokuapp.com</code> host and what path was requested. How do I get this information about a Flask request?</p> | <p>You can examine the url through several <a href="http://flask.pocoo.org/docs/api/#flask.Request.path" rel="noreferrer"><code>Request</code></a> fields:</p>
<blockquote>
<p>Imagine your application is listening on the following application root:</p>
<pre><code>http://www.example.com/myapplication
</code></pre>
<p>And a user requests the following URI:</p>
<pre><code>http://www.example.com/myapplication/foo/page.html?x=y
</code></pre>
<p>In this case the values of the above mentioned attributes would be the following:</p>
<pre><code> path /foo/page.html
full_path /foo/page.html?x=y
script_root /myapplication
base_url http://www.example.com/myapplication/foo/page.html
url http://www.example.com/myapplication/foo/page.html?x=y
url_root http://www.example.com/myapplication/
</code></pre>
</blockquote>
<p>You can easily extract the host part with the appropriate splits.</p>
<p>An example of using this:</p>
<pre><code>from flask import request
@app.route('/')
def index():
return request.base_url
</code></pre> | {
"question_id": 15974730,
"question_date": "2013-04-12T15:02:05.797Z",
"question_score": 209,
"tags": "python|url|flask",
"answer_id": 15975041,
"answer_date": "2013-04-12T15:16:00.310Z",
"answer_score": 330
} |
Please answer the following Stack Overflow question:
Title: Check if a Postgres JSON array contains a string
<p>I have a table to store information about my rabbits. It looks like this:</p>
<pre><code>create table rabbits (rabbit_id bigserial primary key, info json not null);
insert into rabbits (info) values
('{"name":"Henry", "food":["lettuce","carrots"]}'),
('{"name":"Herald","food":["carrots","zucchini"]}'),
('{"name":"Helen", "food":["lettuce","cheese"]}');
</code></pre>
<p>How should I find the rabbits who like carrots? I came up with this:</p>
<pre><code>select info->>'name' from rabbits where exists (
select 1 from json_array_elements(info->'food') as food
where food::text = '"carrots"'
);
</code></pre>
<p>I don't like that query. It's a mess.</p>
<p>As a full-time rabbit-keeper, I don't have time to change my database schema. I just want to properly feed my rabbits. Is there a more readable way to do that query?</p> | <p>As of PostgreSQL 9.4, you can use the <a href="https://www.postgresql.org/docs/9.4/static/functions-json.html#FUNCTIONS-JSONB-OP-TABLE"><code>?</code> operator</a>:</p>
<pre><code>select info->>'name' from rabbits where (info->'food')::jsonb ? 'carrots';
</code></pre>
<p>You can even index the <code>?</code> query on the <code>"food"</code> key if you switch to the <em>jsonb</em> type instead:</p>
<pre><code>alter table rabbits alter info type jsonb using info::jsonb;
create index on rabbits using gin ((info->'food'));
select info->>'name' from rabbits where info->'food' ? 'carrots';
</code></pre>
<p>Of course, you probably don't have time for that as a full-time rabbit keeper.</p>
<p><strong>Update:</strong> Here's a demonstration of the performance improvements on a table of 1,000,000 rabbits where each rabbit likes two foods and 10% of them like carrots:</p>
<pre><code>d=# -- Postgres 9.3 solution
d=# explain analyze select info->>'name' from rabbits where exists (
d(# select 1 from json_array_elements(info->'food') as food
d(# where food::text = '"carrots"'
d(# );
Execution time: 3084.927 ms
d=# -- Postgres 9.4+ solution
d=# explain analyze select info->'name' from rabbits where (info->'food')::jsonb ? 'carrots';
Execution time: 1255.501 ms
d=# alter table rabbits alter info type jsonb using info::jsonb;
d=# explain analyze select info->'name' from rabbits where info->'food' ? 'carrots';
Execution time: 465.919 ms
d=# create index on rabbits using gin ((info->'food'));
d=# explain analyze select info->'name' from rabbits where info->'food' ? 'carrots';
Execution time: 256.478 ms
</code></pre> | {
"question_id": 19925641,
"question_date": "2013-11-12T09:40:59.410Z",
"question_score": 209,
"tags": "json|postgresql|postgresql-9.3",
"answer_id": 27144175,
"answer_date": "2014-11-26T08:16:52.013Z",
"answer_score": 284
} |
Please answer the following Stack Overflow question:
Title: How to make a copy of a file in android?
<p>In my app I want to save a copy of a certain file with a different name (which I get from user)</p>
<p>Do I really need to open the contents of the file and write it to another file?</p>
<p>What is the best way to do so?</p> | <p>To copy a file and save it to your destination path you can use the method below.</p>
<pre><code>public static void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
try {
OutputStream out = new FileOutputStream(dst);
try {
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} finally {
out.close();
}
} finally {
in.close();
}
}
</code></pre>
<p>On API 19+ you can use Java Automatic Resource Management:</p>
<pre><code>public static void copy(File src, File dst) throws IOException {
try (InputStream in = new FileInputStream(src)) {
try (OutputStream out = new FileOutputStream(dst)) {
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
}
}
</code></pre> | {
"question_id": 9292954,
"question_date": "2012-02-15T11:59:45.797Z",
"question_score": 209,
"tags": "java|android",
"answer_id": 9293885,
"answer_date": "2012-02-15T12:59:04.403Z",
"answer_score": 358
} |
Please answer the following Stack Overflow question:
Title: Passing arrays as parameters in bash
<p>How can I pass an array as parameter to a bash function?</p>
<p><strong>Note:</strong> After not finding an answer here on Stack Overflow, I posted my somewhat crude solution myself. It allows for only one array being passed, and it being the last element of the parameter list. Actually, it is not passing the array at all, but a list of its elements, which are re-assembled into an array by <code>called_function()</code>, but it worked for me. If someone knows a better way, feel free to add it here.</p> | <p>You can pass <strong>multiple arrays as arguments</strong> using something like this:</p>
<pre><code>takes_ary_as_arg()
{
declare -a argAry1=("${!1}")
echo "${argAry1[@]}"
declare -a argAry2=("${!2}")
echo "${argAry2[@]}"
}
try_with_local_arys()
{
# array variables could have local scope
local descTable=(
"sli4-iread"
"sli4-iwrite"
"sli3-iread"
"sli3-iwrite"
)
local optsTable=(
"--msix --iread"
"--msix --iwrite"
"--msi --iread"
"--msi --iwrite"
)
takes_ary_as_arg descTable[@] optsTable[@]
}
try_with_local_arys
</code></pre>
<h3>will echo:</h3>
<pre><code>sli4-iread sli4-iwrite sli3-iread sli3-iwrite
--msix --iread --msix --iwrite --msi --iread --msi --iwrite
</code></pre>
<p><strong>Edit/notes:</strong> (from comments below)</p>
<ul>
<li><code>descTable</code> and <code>optsTable</code> are passed as names and are expanded in the function. Thus no <code>$</code> is needed when given as parameters.</li>
<li>Note that this still works even with <code>descTable</code> etc being defined with <code>local</code>, because locals are visible to the functions they call.</li>
<li>The <code>!</code> in <code>${!1}</code> expands the arg 1 variable.</li>
<li><code>declare -a</code> just makes the indexed array explicit, it is not strictly necessary.</li>
</ul> | {
"question_id": 1063347,
"question_date": "2009-06-30T12:21:40.097Z",
"question_score": 209,
"tags": "arrays|bash",
"answer_id": 4017175,
"answer_date": "2010-10-25T17:24:53.793Z",
"answer_score": 233
} |
Please answer the following Stack Overflow question:
Title: React – the right way to pass form element state to sibling/parent elements?
<ul>
<li>Suppose I have a React class P, which renders two child classes, C1 and C2.</li>
<li>C1 contains an input field. I'll refer to this input field as Foo.</li>
<li>My goal is to let C2 react to changes in Foo.</li>
</ul>
<p>I've come up with two solutions, but neither of them feels quite right.</p>
<p>First solution:</p>
<ol>
<li>Assign P a state, <code>state.input</code>.</li>
<li>Create an <code>onChange</code> function in P, which takes in an event and sets <code>state.input</code>.</li>
<li>Pass this <code>onChange</code> to C1 as a <code>props</code>, and let C1 bind <code>this.props.onChange</code> to the <code>onChange</code> of Foo.</li>
</ol>
<p>This works. Whenever the value of Foo changes, it triggers a <code>setState</code> in P, so P will have the input to pass to C2.</p>
<p>But it doesn't feel quite right for the same reason: I'm setting the state of a parent element from a child element. This seems to betray the design principle of React: single-direction data flow.<br />
<strong>Is this how I'm supposed to do it, or is there a more React-natural solution?</strong></p>
<p>Second solution:</p>
<p>Just put Foo in P.</p>
<p><strong>But is this a design principle I should follow when I structure my app—putting all form elements in the <code>render</code> of the highest-level class?</strong></p>
<p>Like in my example, if I have a large rendering of C1, I really don't want to put the whole <code>render</code> of C1 to <code>render</code> of P just because C1 has a form element.</p>
<p>How should I do it?</p> | <p>So, if I'm understanding you correctly, your first solution is suggesting that you're keeping state in your root component? I can't speak for the creators of React, but generally, I find this to be a proper solution. </p>
<p>Maintaining state is one of the reasons (at least I think) that React was created. If you've ever implemented your own state pattern client side for dealing with a dynamic UI that has a lot of interdependent moving pieces, then you'll love React, because it alleviates a lot of this state management pain. </p>
<p>By keeping state further up in the hierarchy, and updating it through eventing, your data flow is still pretty much unidirectional, you're just responding to events in the Root component, you're not really getting the data there via two way binding, you're telling the Root component that "hey, something happened down here, check out the values" or you're passing the state of some data in the child component up in order to update the state. You changed the state in C1, and you want C2 to be aware of it, so, by updating the state in the Root component and re-rendering, C2's props are now in sync since the state was updated in the Root component and passed along.</p>
<pre class="lang-jsx prettyprint-override"><code>class Example extends React.Component {
constructor (props) {
super(props)
this.state = { data: 'test' }
}
render () {
return (
<div>
<C1 onUpdate={this.onUpdate.bind(this)}/>
<C2 data={this.state.data}/>
</div>
)
}
onUpdate (data) { this.setState({ data }) }
}
class C1 extends React.Component {
render () {
return (
<div>
<input type='text' ref='myInput'/>
<input type='button' onClick={this.update.bind(this)} value='Update C2'/>
</div>
)
}
update () {
this.props.onUpdate(this.refs.myInput.getDOMNode().value)
}
})
class C2 extends React.Component {
render () {
return <div>{this.props.data}</div>
}
})
ReactDOM.renderComponent(<Example/>, document.body)
</code></pre> | {
"question_id": 24147331,
"question_date": "2014-06-10T17:27:51.720Z",
"question_score": 209,
"tags": "reactjs",
"answer_id": 24151862,
"answer_date": "2014-06-10T22:26:15.673Z",
"answer_score": 207
} |
Please answer the following Stack Overflow question:
Title: How to change indentation mode in Atom?
<p>I haven't been able to figure this out yet. Atom seems to use spaces as the default indentation mode. I prefer to have tabs instead though. Sublime Text has built in functionality for switching and converting indentation.</p>
<p>Anyone found out how to change the indentation mode of Atom?</p>
<p>Some screenshots from Sublime Text:</p>
<p><img src="https://i.stack.imgur.com/IZC1E.png" alt="Sublime Text indentation menu open">
<img src="https://i.stack.imgur.com/Fujwp.png" alt="Sublime text indentation menu"></p> | <p>See <em>Soft Tabs</em> and <em>Tab Length</em> under <em>Settings > Editor Settings</em>.</p>
<p>To toggle indentation modes quickly you can use <em>Ctrl-Shift-P</em> and search for <em>Editor: Toggle Soft Tabs</em>.</p> | {
"question_id": 22608160,
"question_date": "2014-03-24T11:30:01.913Z",
"question_score": 209,
"tags": "indentation|atom-editor",
"answer_id": 22611893,
"answer_date": "2014-03-24T14:14:18.717Z",
"answer_score": 232
} |
Please answer the following Stack Overflow question:
Title: difference between css height : 100% vs height : auto
<p>I was asked a question in an interview that "what is the difference between the css <code>height:100%</code> and <code>height:auto</code>?" </p>
<p>Can any one explain?</p> | <p><code>height: 100%</code> gives the element 100% height of its parent container.</p>
<p><code>height: auto</code> means the element height will depend upon the height of its children.</p>
<p>Consider these examples:</p>
<p><strong>height: 100%</strong></p>
<pre><code><div style="height: 50px">
<div id="innerDiv" style="height: 100%">
</div>
</div>
</code></pre>
<p><code>#innerDiv</code> is going to have <code>height: 50px</code></p>
<p><strong>height: auto</strong></p>
<pre><code><div style="height: 50px">
<div id="innerDiv" style="height: auto">
<div id="evenInner" style="height: 10px">
</div>
</div>
</div>
</code></pre>
<p><code>#innerDiv</code> is going to have <code>height: 10px</code></p> | {
"question_id": 15943009,
"question_date": "2013-04-11T07:29:16.280Z",
"question_score": 209,
"tags": "css",
"answer_id": 15943054,
"answer_date": "2013-04-11T07:32:22.247Z",
"answer_score": 297
} |
Please answer the following Stack Overflow question:
Title: GROUP_CONCAT ORDER BY
<p>I've <a href="http://googledrive.com/host/0B53jM4a9X2fqfkhfeV83Tm05VnU4cV9ZSWZlMUNTQzRZUUJQTFdQZUptOEJkdXkyVXFIYmM" rel="noreferrer">a table</a> like:</p>
<pre><code>+-----------+-------+------------+
| client_id | views | percentage |
+-----------+-------+------------+
| 1 | 6 | 20 |
| 1 | 4 | 55 |
| 1 | 9 | 56 |
| 1 | 2 | 67 |
| 1 | 7 | 80 |
| 1 | 5 | 66 |
| 1 | 3 | 33 |
| 1 | 8 | 34 |
| 1 | 1 | 52 |
</code></pre>
<p>I tried <code>group_concat</code>:</p>
<pre><code>SELECT li.client_id, group_concat(li.views) AS views,
group_concat(li.percentage) FROM li GROUP BY client_id;
+-----------+-------------------+-----------------------------+
| client_id | views | group_concat(li.percentage) |
+-----------+-------------------+-----------------------------+
| 1 | 6,4,9,2,7,5,3,8,1 | 20,55,56,67,80,66,33,34,52 |
+-----------+-------------------+-----------------------------+
</code></pre>
<p>But I want to get the views in order, like:</p>
<pre><code>+-----------+-------------------+----------------------------+
| client_id | views | percentage |
+-----------+-------------------+----------------------------+
| 1 | 1,2,3,4,5,6,7,8,9 | 52,67,33,55,66,20,80,34,56 |
+-----------+-------------------+----------------------------+
</code></pre> | <p>You can use <code>ORDER BY</code> inside the <code>GROUP_CONCAT</code> function in this way: </p>
<pre><code>SELECT li.client_id, group_concat(li.percentage ORDER BY li.views ASC) AS views,
group_concat(li.percentage ORDER BY li.percentage ASC)
FROM li GROUP BY client_id
</code></pre> | {
"question_id": 8631210,
"question_date": "2011-12-25T19:38:54.163Z",
"question_score": 209,
"tags": "mysql|sql-order-by|group-concat",
"answer_id": 8631273,
"answer_date": "2011-12-25T19:51:08.543Z",
"answer_score": 439
} |
Please answer the following Stack Overflow question:
Title: Prevent onmouseout when hovering child element of the parent absolute div WITHOUT jQuery
<p>I am having trouble with the <code>onmouseout</code> function in an absolute positoned div. When the mouse hits a child element in the div, the mouseout event fires, but I do not want it to fire until the mouse is out of the parent, absolute div.</p>
<p>How can I prevent the <code>mouseout</code> event from firing when it hits a child element WITHOUT jquery.</p>
<p>I know this has something to do with event bubbling, but I am having no luck on finding out how to work this out. </p>
<p>I found a similar post here: <a href="https://stackoverflow.com/questions/350639/how-to-disable-mouseout-events-triggered-by-child-elements">How to disable mouseout events triggered by child elements?</a></p>
<p>However that solution uses jQuery.</p> | <pre><code>function onMouseOut(event) {
//this is the original element the event handler was assigned to
var e = event.toElement || event.relatedTarget;
if (e.parentNode == this || e == this) {
return;
}
alert('MouseOut');
// handle mouse event here!
}
document.getElementById('parent').addEventListener('mouseout',onMouseOut,true);
</code></pre>
<p>I made a quick JsFiddle demo, with all the CSS and HTML needed, check it out... </p>
<p><strong>EDIT</strong> FIXED link for cross-browser support <a href="http://jsfiddle.net/RH3tA/9/" rel="noreferrer">http://jsfiddle.net/RH3tA/9/</a></p>
<p><strong>NOTE</strong> that this only checks the immediate parent, if the parent div had nested children then you have to somehow traverse through the elements parents looking for the "Orginal element" </p>
<p><strong>EDIT</strong> example for nested children </p>
<p><strong>EDIT</strong> Fixed for hopefully cross-browser</p>
<pre><code>function makeMouseOutFn(elem){
var list = traverseChildren(elem);
return function onMouseOut(event) {
var e = event.toElement || event.relatedTarget;
if (!!~list.indexOf(e)) {
return;
}
alert('MouseOut');
// handle mouse event here!
};
}
//using closure to cache all child elements
var parent = document.getElementById("parent");
parent.addEventListener('mouseout',makeMouseOutFn(parent),true);
//quick and dirty DFS children traversal,
function traverseChildren(elem){
var children = [];
var q = [];
q.push(elem);
while (q.length > 0) {
var elem = q.pop();
children.push(elem);
pushAll(elem.children);
}
function pushAll(elemArray){
for(var i=0; i < elemArray.length; i++) {
q.push(elemArray[i]);
}
}
return children;
}
</code></pre>
<p>And a new <a href="http://jsfiddle.net/amasad/TH9Hv/8/" rel="noreferrer"><strong>JSFiddle</strong></a>, <strong>EDIT</strong> updated link</p> | {
"question_id": 4697758,
"question_date": "2011-01-15T03:20:08.317Z",
"question_score": 209,
"tags": "javascript|css|dom-events|onmouseout",
"answer_id": 4698240,
"answer_date": "2011-01-15T05:47:35.227Z",
"answer_score": 101
} |
Please answer the following Stack Overflow question:
Title: How to merge two files line by line in Bash
<p>I have two text files, each of them contains an information by line such like that</p>
<pre><code>file1.txt file2.txt
---------- ---------
linef11 linef21
linef12 linef22
linef13 linef23
. .
. .
. .
</code></pre>
<p>I would like to merge theses files lines by lines using a bash script in order to obtain:</p>
<pre><code>fileresult.txt
--------------
linef11 linef21
linef12 linef22
linef13 linef23
. .
. .
. .
</code></pre>
<p>How can this be done in Bash?</p> | <p>You can use <a href="http://ss64.com/bash/paste.html" rel="noreferrer"><code>paste</code></a>:</p>
<pre><code>paste file1.txt file2.txt > fileresults.txt
</code></pre> | {
"question_id": 3806874,
"question_date": "2010-09-27T18:55:46.163Z",
"question_score": 209,
"tags": "bash|unix",
"answer_id": 3806901,
"answer_date": "2010-09-27T18:58:52.140Z",
"answer_score": 329
} |
Please answer the following Stack Overflow question:
Title: In STL maps, is it better to use map::insert than []?
<p>A while ago, I had a discussion with a colleague about how to insert values in STL <a href="http://www.sgi.com/tech/stl/Map.html" rel="noreferrer">maps</a>. I preferred <code>map[key] = value;</code> because it feels natural and is clear to read whereas he preferred <code>map.insert(std::make_pair(key, value))</code>.</p>
<p>I just asked him and neither of us can remember the reason why insert is better, but I am sure it was not just a style preference rather there was a technical reason such as efficiency. The <a href="http://www.sgi.com/tech/stl/Map.html" rel="noreferrer">SGI STL reference</a> simply says: "Strictly speaking, this member function is unnecessary: it exists only for convenience."</p>
<p>Can anybody tell me that reason, or am I just dreaming that there is one?</p> | <p>When you write</p>
<pre><code>map[key] = value;
</code></pre>
<p>there's no way to tell if you <strong>replaced</strong> the <code>value</code> for <code>key</code>, or if you <strong>created</strong> a new <code>key</code> with <code>value</code>.</p>
<p><a href="http://en.cppreference.com/w/cpp/container/map/insert" rel="noreferrer"><code>map::insert()</code></a> will only create:</p>
<pre><code>using std::cout; using std::endl;
typedef std::map<int, std::string> MyMap;
MyMap map;
// ...
std::pair<MyMap::iterator, bool> res = map.insert(MyMap::value_type(key,value));
if ( ! res.second ) {
cout << "key " << key << " already exists "
<< " with value " << (res.first)->second << endl;
} else {
cout << "created key " << key << " with value " << value << endl;
}
</code></pre>
<p>For most of my apps, I usually don't care if I'm creating or replacing, so I use the easier to read <code>map[key] = value</code>.</p> | {
"question_id": 326062,
"question_date": "2008-11-28T15:42:52.337Z",
"question_score": 209,
"tags": "c++|dictionary|stl|insert|stdmap",
"answer_id": 327289,
"answer_date": "2008-11-29T07:03:10.760Z",
"answer_score": 246
} |
Please answer the following Stack Overflow question:
Title: Find and replace - Add carriage return OR Newline
<p>In the case of following string to be parsed.</p>
<pre><code>ford mustang,10,blue~~?bugatti veyron,13,black
</code></pre>
<p>I want to replace the <code>~~?</code> with a <code>carriage return</code></p>
<p>Replacing with <code>\n</code> just adds the string <code>"\n"</code></p>
<p>How can this be done?</p> | <p>Make sure <code>Use: Regular expressions</code> is selected in the <code>Find and Replace</code> dialog:</p>
<p><img src="https://i.stack.imgur.com/MEXXe.png" alt="Find/Replace Dialog Use Regular expressions" /></p>
<p>Note that for Visual Studio 2010, this doesn't work in the <a href="http://visualstudiogallery.msdn.microsoft.com/d0d33361-18e2-46c0-8ff2-4adea1e34fef/" rel="nofollow noreferrer">Visual Studio Productivity Power Tools</a>' <code>Quick Find</code> extension (as of the July 2011 update); instead, you'll need to use the full <code>Find and Replace</code> dialog (use <code>Ctrl+Shift+H</code>, or <code>Edit --> Find and Replace --> Replace in Files</code>), and change the scope to <code>Current Document</code>.</p> | {
"question_id": 4336417,
"question_date": "2010-12-02T15:07:05.013Z",
"question_score": 209,
"tags": "visual-studio|replace|carriage-return",
"answer_id": 4336471,
"answer_date": "2010-12-02T15:14:12.400Z",
"answer_score": 303
} |
Please answer the following Stack Overflow question:
Title: Simulating Slow Internet Connection
<p>I know this is kind of an odd question. Since I usually develop applications based on the "assumption" that all users have a slow internet connection. But, does anybody think that there is a way to programmatically simulate a slow internet connection, so I can "see" how an application performs under various "connection speeds"?</p>
<p>I'm not worried about which language is used. And I'm not looking for code samples or anything, just interested in the logic behind it.</p> | <p>If you're running windows, <a href="http://www.fiddler2.com/fiddler2/" rel="noreferrer">fiddler</a> is a great tool. It has a setting to simulate modem speed, and for someone who wants more control has a <a href="http://fiddlerdelayext.codeplex.com/" rel="noreferrer">plugin to add latency to each request</a>.</p>
<p>I prefer using a tool like this to putting latency code in my application as it is a much more realistic simulation, as well as not making me design or code the actual bits. The best code is code I don't have to write.</p>
<p><em>ADDED</em>: This article at Pavel Donchev's blog on Software Technologies shows how to create custom simulated speeds: <a href="http://donchevp.blogspot.com.es/2009/11/limiting-your-internet-connection-speed.html" rel="noreferrer">Limiting your Internet connection speed with Fiddler</a>.</p> | {
"question_id": 3536249,
"question_date": "2010-08-21T03:58:54.613Z",
"question_score": 209,
"tags": "performance|networking",
"answer_id": 3536274,
"answer_date": "2010-08-21T04:05:13.350Z",
"answer_score": 115
} |
Please answer the following Stack Overflow question:
Title: How to remove folders with a certain name
<p>In Linux, how do I remove folders with a certain name which are nested deep in a folder hierarchy?</p>
<p>The following paths are under a folder and I would like to remove all folders named <code>a</code>. </p>
<pre><code>1/2/3/a
1/2/3/b
10/20/30/a
10/20/30/b
100/200/300/a
100/200/300/b
</code></pre>
<p>What Linux command should I use from the parent folder?</p> | <p>If the target directory is empty, use find, filter with only directories, filter by name, execute rmdir:</p>
<pre><code>find . -type d -name a -exec rmdir {} \;
</code></pre>
<p>If you want to recursively delete its contents, replace <code>-exec rmdir {} \;</code> with <code>-delete</code> or <code>-prune -exec rm -rf {} \;</code>. Other answers include details about these versions, credit them too.</p> | {
"question_id": 13032701,
"question_date": "2012-10-23T14:26:23.213Z",
"question_score": 209,
"tags": "linux|unix|rm",
"answer_id": 13032768,
"answer_date": "2012-10-23T14:29:25.433Z",
"answer_score": 233
} |
Please answer the following Stack Overflow question:
Title: How to delete the last n commits on Github and locally?
<p>I'm trying to delete the last 2 commits from one of my GitHub repositories. I've tried as suggested <a href="https://stackoverflow.com/questions/448919/how-can-i-remove-a-commit-on-github">here</a> : <code>git push -f origin HEAD^^:master</code>. It seems that it works, as the last two commits are removed.</p>
<p>Then I deleted them from my local repository with <code>git rebase -i HEAD~2</code>. I remove the lines that are related to those commits, and check with <code>git log</code> that they are correctly removed.</p>
<p>After that, I make some changes in my local repository, make a new commit, and push to GitHub. The problem is that, in my GitHub account, I have the previous two commits that I've tried to delete.</p>
<p>I think the problem is in my local repository, because if I clone my Github repository to my local and make some changes here, when I push a new commit those old commits aren't pushed to GitHub.</p> | <p>To remove the last two commits locally I'd suggest using:</p>
<pre><code>git reset --hard HEAD^^
</code></pre>
<p>Rebase is a completely different operation that won't help you here.</p> | {
"question_id": 10153486,
"question_date": "2012-04-14T12:08:39.730Z",
"question_score": 209,
"tags": "git|github|commit",
"answer_id": 10153526,
"answer_date": "2012-04-14T12:14:51.967Z",
"answer_score": 287
} |
Please answer the following Stack Overflow question:
Title: Should functions return null or an empty object?
<p>What is the <em>best practice</em> when returning data from functions. Is it better to return a Null or an empty object? And why should one do one over the other?</p>
<p>Consider this:</p>
<pre><code>public UserEntity GetUserById(Guid userId)
{
//Imagine some code here to access database.....
//Check if data was returned and return a null if none found
if (!DataExists)
return null;
//Should I be doing this here instead?
//return new UserEntity();
else
return existingUserEntity;
}
</code></pre>
<p>Lets pretend that there would be valid cases in this program that there would be no user information in the database with that GUID. I Would imagine that it would not be appropriate to throw an exception in this case?? Also I am under the impression that exception handling can hurt performance.</p> | <p>Returning null is usually the best idea if you intend to indicate that no data is available. </p>
<p>An empty object implies data has been returned, whereas returning null clearly indicates that nothing has been returned.</p>
<p>Additionally, returning a null will result in a null exception if you attempt to access members in the object, which can be useful for highlighting buggy code - attempting to access a member of nothing makes no sense. Accessing members of an empty object will not fail meaning bugs can go undiscovered.</p> | {
"question_id": 1626597,
"question_date": "2009-10-26T18:44:05.730Z",
"question_score": 209,
"tags": "c#|.net|function|return-value",
"answer_id": 1626620,
"answer_date": "2009-10-26T18:46:34.820Z",
"answer_score": 207
} |
Please answer the following Stack Overflow question:
Title: Single TextView with multiple colored text
<p>As the title says, I want to know is it possible to achieve two different colored characters in a single textview element.</p> | <p>yes, if you format the <code>String</code> with <code>html</code>'s <code>font-color</code> property then pass it to the method <code>Html.fromHtml(your text here)</code></p>
<pre><code>String text = "<font color=#cc0029>First Color</font> <font color=#ffcc00>Second Color</font>";
yourtextview.setText(Html.fromHtml(text));
</code></pre> | {
"question_id": 6094315,
"question_date": "2011-05-23T07:50:26.300Z",
"question_score": 209,
"tags": "android|textview",
"answer_id": 6094346,
"answer_date": "2011-05-23T07:53:58.270Z",
"answer_score": 366
} |
Please answer the following Stack Overflow question:
Title: How do I test which class an object is in Objective-C?
<p>How do I test whether an object is an instance of a particular class in Objective-C? Let's say I want to see if object a is an instance of class b, or class c, how do I go about doing it?</p> | <p>To test if object is an instance of class a:</p>
<pre><code>[yourObject isKindOfClass:[a class]]
// Returns a Boolean value that indicates whether the receiver is an instance of
// given class or an instance of any class that inherits from that class.
</code></pre>
<p>or</p>
<pre><code>[yourObject isMemberOfClass:[a class]]
// Returns a Boolean value that indicates whether the receiver is an instance of a
// given class.
</code></pre>
<p>To get object's class name you can use <code>NSStringFromClass</code> function:</p>
<pre><code>NSString *className = NSStringFromClass([yourObject class]);
</code></pre>
<p>or c-function from objective-c runtime api:</p>
<pre><code>#import <objc/runtime.h>
/* ... */
const char* className = class_getName([yourObject class]);
NSLog(@"yourObject is a: %s", className);
</code></pre>
<p><strong>EDIT:</strong> In Swift</p>
<pre><code>if touch.view is UIPickerView {
// touch.view is of type UIPickerView
}
</code></pre> | {
"question_id": 2055940,
"question_date": "2010-01-13T10:28:56.850Z",
"question_score": 209,
"tags": "objective-c",
"answer_id": 2056036,
"answer_date": "2010-01-13T10:48:33.173Z",
"answer_score": 347
} |
Please answer the following Stack Overflow question:
Title: `elif` in list comprehension conditionals
<p>Can we use <code>elif</code> in list comprehension? </p>
<p>Example : </p>
<pre><code>l = [1, 2, 3, 4, 5]
for values in l:
if values==1:
print 'yes'
elif values==2:
print 'no'
else:
print 'idle'
</code></pre>
<p>Can we include the <code>elif</code> in our list comprehension, in a similar fashion to the code above?</p>
<p>For example, an answer like: </p>
<pre><code>['yes', 'no', 'idle', 'idle', 'idle']
</code></pre>
<p>Up until now, I have only used <code>if</code> and <code>else</code> in list comprehension.</p> | <p>Python's <a href="http://docs.python.org/release/2.5.3/whatsnew/pep-308.html" rel="noreferrer">conditional expressions</a> were designed exactly for this sort of use-case:</p>
<pre><code>>>> l = [1, 2, 3, 4, 5]
>>> ['yes' if v == 1 else 'no' if v == 2 else 'idle' for v in l]
['yes', 'no', 'idle', 'idle', 'idle']
</code></pre> | {
"question_id": 9987483,
"question_date": "2012-04-03T05:16:30.277Z",
"question_score": 209,
"tags": "python|list-comprehension|conditional-operator",
"answer_id": 9987533,
"answer_date": "2012-04-03T05:23:03.143Z",
"answer_score": 363
} |
Please answer the following Stack Overflow question:
Title: Classes residing in App_Code is not accessible
<p>I have created a website in ASP.NET and have created a class and put it inside of the App_Code folder. However I cannot access this from my other pages. Does something need to be configured to allow this? I have made it work in previous projects, but not in this one, somehow.</p>
<pre><code>namespace CLIck10.App_Code
{
public static class Glob
{
...
}
}
</code></pre> | <p>Right click on the <code>.cs</code> file in the <code>App_Code</code> folder and check its properties. </p>
<p>Make sure the "Build Action" is set to "Compile".</p> | {
"question_id": 1222281,
"question_date": "2009-08-03T13:12:04.987Z",
"question_score": 209,
"tags": "c#|asp.net",
"answer_id": 1222293,
"answer_date": "2009-08-03T13:14:37.190Z",
"answer_score": 683
} |
Please answer the following Stack Overflow question:
Title: Why does ASP.NET webforms need the Runat="Server" attribute?
<p>Why do I have to specify <code>runat="server"</code> on all my ASP.NET controls when it is a mandatory attribute and <code>server</code> is the only option available in my limited knowledge of ASP.NET, and I get an error if I don't use it?</p>
<p>I do understand that I can optionally use it on my HTML tags, and I do understand the client/server paradigm and what it is actually specifying.</p>
<p>Is it a redundant tag that could just be implied by the control being an ASP.NET control, or is there an underlying reason?</p> | <p>I've always believed it was there more for the understanding that you can mix ASP.NET tags and HTML Tags, and HTML Tags have the option of either being <code>runat="server"</code> or not. It doesn't hurt anything to leave the tag in, and it causes a compiler error to take it out. The more things you imply about web language, the less easy it is for a budding programmer to come in and learn it. That's as good a reason as any to be verbose about tag attributes.</p>
<p>This conversation was had on Mike Schinkel's <a href="http://mikeschinkel.com/blog/whyrunatserverforaspnetpart2/" rel="noreferrer">Blog</a> between himself and Talbot Crowell of Microsoft National Services. The relevant information is below (first paragraph paraphrased due to grammatical errors in source):</p>
<blockquote>
<p><em>[...]</em> but the importance of <code><runat="server"></code> is more for consistency and extensibility. </p>
<p>If the developer has to mark some tags (viz. <code><asp: /></code>) for the ASP.NET Engine to ignore, then there's also the potential issue of namespace collisions among tags and future enhancements. By requiring the <code><runat="server"></code> attribute, this is negated.</p>
</blockquote>
<p>It continues:</p>
<blockquote>
<p>If <code><runat=client></code> was required for all client-side tags, the parser would need to parse all tags and strip out the <code><runat=client></code> part.</p>
</blockquote>
<p>He continues: </p>
<blockquote>
<p>Currently,
If my guess is correct, the parser
simply ignores all text (tags or no
tags) unless it is a tag with the
<code>runat=server</code> attribute or a “<code><%</code>”
prefix or ssi “<code><!– #include</code>… <em>(...)</em>
Also, since ASP.NET is designed to
allow separation of the web designers
(foo.aspx) from the web developers
(foo.aspx.vb), the web designers can
use their own web designer tools to
place HTML and client-side JavaScript
without having to know about ASP.NET
specific tags or attributes.</p>
</blockquote> | {
"question_id": 304290,
"question_date": "2008-11-20T03:58:00.760Z",
"question_score": 209,
"tags": "asp.net|runatserver",
"answer_id": 304307,
"answer_date": "2008-11-20T04:14:21.990Z",
"answer_score": 113
} |
Please answer the following Stack Overflow question:
Title: How to do a join in linq to sql with method syntax?
<p>I have seen lots of examples in LINQ to SQL examples on how to do a join in query syntax but I am wondering how to do it with method syntax? For example how might I do the following</p>
<pre><code>var result = from sc in enumerableOfSomeClass
join soc in enumerableOfSomeOtherClass
on sc.Property1 equals soc.Property2
select new { SomeClass = sc, SomeOtherClass = soc }
</code></pre>
<p>with a <code>.Join()</code>? Can anyone illustrate or provide another simple example?</p> | <pre><code>var result = from sc in enumerableOfSomeClass
join soc in enumerableOfSomeOtherClass
on sc.Property1 equals soc.Property2
select new { SomeClass = sc, SomeOtherClass = soc };
</code></pre>
<p>Would be equivalent to:</p>
<pre><code>var result = enumerableOfSomeClass
.Join(enumerableOfSomeOtherClass,
sc => sc.Property1,
soc => soc.Property2,
(sc, soc) => new
{
SomeClass = sc,
SomeOtherClass = soc
});
</code></pre>
<p>As you can see, when it comes to joins, query syntax is usually much more readable than lambda syntax. </p> | {
"question_id": 3217669,
"question_date": "2010-07-10T03:14:55.063Z",
"question_score": 209,
"tags": "linq-to-sql|ef-fluent-api",
"answer_id": 3217679,
"answer_date": "2010-07-10T03:20:29.557Z",
"answer_score": 310
} |
Please answer the following Stack Overflow question:
Title: Where to write to localStorage in a Redux app?
<p>I want to persist some parts of my state tree to the localStorage. What is the appropriate place to do so? Reducer or action?</p> | <p>Reducer is never an appropriate place to do this because reducers should be pure and have no side effects.</p>
<p>I would recommend just doing it in a subscriber:</p>
<pre><code>store.subscribe(() => {
// persist your state
})
</code></pre>
<p>Before creating the store, read those persisted parts:</p>
<pre><code>const persistedState = // ...
const store = createStore(reducer, persistedState)
</code></pre>
<p>If you use <code>combineReducers()</code> you’ll notice that reducers that haven’t received the state will “boot up” as normal using their default <code>state</code> argument value. This can be pretty handy.</p>
<p>It is advisable that you debounce your subscriber so you don’t write to localStorage too fast, or you’ll have performance problems.</p>
<p>Finally, you can create a middleware that encapsulates that as an alternative, but I’d start with a subscriber because it’s a simpler solution and does the job well.</p> | {
"question_id": 35305661,
"question_date": "2016-02-10T02:05:03.510Z",
"question_score": 209,
"tags": "javascript|redux|local-storage|state",
"answer_id": 35675304,
"answer_date": "2016-02-27T20:52:00.797Z",
"answer_score": 272
} |
Please answer the following Stack Overflow question:
Title: What size do you use for varchar(MAX) in your parameter declaration?
<p>I normally set my column size when creating a parameter in ADO.NET.</p>
<p>But what size do I use if the column is of type <code>VARCHAR(MAX)</code>?</p>
<pre><code>cmd.Parameters.Add("@blah", SqlDbType.VarChar, ?????).Value = blah;
</code></pre> | <p>In this case you use -1.</p> | {
"question_id": 973260,
"question_date": "2009-06-10T01:08:02.200Z",
"question_score": 209,
"tags": "c#|sql-server|ado.net",
"answer_id": 973269,
"answer_date": "2009-06-10T01:11:40.787Z",
"answer_score": 317
} |
Please answer the following Stack Overflow question:
Title: Recreating a Dictionary from an IEnumerable<KeyValuePair<>>
<p>I have a method that returns an <code>IEnumerable<KeyValuePair<string, ArrayList>></code>, but some of the callers require the result of the method to be a dictionary. How can I convert the <code>IEnumerable<KeyValuePair<string, ArrayList>></code> into a <code>Dictionary<string, ArrayList></code> so that I can use <code>TryGetValue</code>?</p>
<p>method:</p>
<pre><code>public IEnumerable<KeyValuePair<string, ArrayList>> GetComponents()
{
// ...
yield return new KeyValuePair<string, ArrayList>(t.Name, controlInformation);
}
</code></pre>
<p>caller:</p>
<pre><code>Dictionary<string, ArrayList> actual = target.GetComponents();
actual.ContainsKey("something");
</code></pre> | <p>If you're using .NET 3.5 or .NET 4, it's easy to create the dictionary using LINQ:</p>
<pre><code>Dictionary<string, ArrayList> result = target.GetComponents()
.ToDictionary(x => x.Key, x => x.Value);
</code></pre>
<p>There's no such thing as an <code>IEnumerable<T1, T2></code> but a <code>KeyValuePair<TKey, TValue></code> is fine.</p> | {
"question_id": 2636603,
"question_date": "2010-04-14T10:31:36.963Z",
"question_score": 209,
"tags": "c#|collections|dictionary|ienumerable|idictionary",
"answer_id": 2636628,
"answer_date": "2010-04-14T10:35:47.710Z",
"answer_score": 364
} |
Please answer the following Stack Overflow question:
Title: How can I discard remote changes and mark a file as "resolved"?
<p>I have some local files, I pull from remote branch and there are conflicts. I know that I would like to keep my local changes and ignore the remote changes causing conflicts. Is there a command I can use to in effect say "mark all conflicts as resolved, use local"?</p> | <p><a href="http://git-scm.com/docs/git-checkout" rel="noreferrer"><code>git checkout</code></a> has the <code>--ours</code> option to check out the version of the file that you had locally (as opposed to <code>--theirs</code>, which is the version that you pulled in). You can pass <code>.</code> to <code>git checkout</code> to tell it to check out everything in the tree. Then you need to mark the conflicts as resolved, which you can do with <a href="http://www.kernel.org/pub/software/scm/git/docs/git-add.html" rel="noreferrer"><code>git add</code></a>, and commit your work once done:</p>
<pre><code>git checkout --ours . # checkout our local version of all files
git add -u # mark all conflicted files as merged
git commit # commit the merge
</code></pre>
<p>Note the <code>.</code> in the <code>git checkout</code> command. That's very important, and easy to miss. <code>git checkout</code> has two modes; one in which it switches branches, and one in which it checks files out of the index into the working copy (sometimes pulling them into the index from another revision first). The way it distinguishes is by whether you've passed a filename in; if you haven't passed in a filename, it tries switching branches (though if you don't pass in a branch either, it will just try checking out the current branch again), but it refuses to do so if there are modified files that that would effect. So, if you want a behavior that will overwrite existing files, you need to pass in <code>.</code> or a filename in order to get the second behavior from <code>git checkout</code>.</p>
<p>It's also a good habit to have, when passing in a filename, to offset it with <code>--</code>, such as <code>git checkout --ours -- <filename></code>. If you don't do this, and the filename happens to match the name of a branch or tag, Git will think that you want to check that revision out, instead of checking that filename out, and so use the first form of the <code>checkout</code> command.</p>
<p>I'll expand a bit on how conflicts and <a href="http://www.kernel.org/pub/software/scm/git/docs/git-merge.html#_how_merge_works" rel="noreferrer">merging</a> work in Git. When you merge in someone else's code (which also happens during a pull; a pull is essentially a fetch followed by a merge), there are few possible situations. </p>
<p>The simplest is that you're on the same revision. In this case, you're "already up to date", and nothing happens.</p>
<p>Another possibility is that their revision is simply a descendent of yours, in which case you will by default have a "fast-forward merge", in which your <code>HEAD</code> is just updated to their commit, with no merging happening (this can be disabled if you really want to record a merge, using <code>--no-ff</code>). </p>
<p>Then you get into the situations in which you actually need to merge two revisions. In this case, there are two possible outcomes. One is that the merge happens cleanly; all of the changes are in different files, or are in the same files but far enough apart that both sets of changes can be applied without problems. By default, when a clean merge happens, it is automatically committed, though you can disable this with <code>--no-commit</code> if you need to edit it beforehand (for instance, if you rename function <code>foo</code> to <code>bar</code>, and someone else adds new code that calls <code>foo</code>, it will merge cleanly, but produce a broken tree, so you may want to clean that up as part of the merge commit in order to avoid having any broken commits).</p>
<p>The final possibility is that there's a real merge, and there are conflicts. In this case, Git will do as much of the merge as it can, and produce files with conflict markers (<code><<<<<<<</code>, <code>=======</code>, and <code>>>>>>>></code>) in your working copy. In the index (also known as the "staging area"; the place where files are stored by <code>git add</code> before committing them), you will have 3 versions of each file with conflicts; there is the original version of the file from the ancestor of the two branches you are merging, the version from <code>HEAD</code> (your side of the merge), and the version from the remote branch.</p>
<p>In order to resolve the conflict, you can either edit the file that is in your working copy, removing the conflict markers and fixing the code up so that it works. Or, you can check out the version from one or the other sides of the merge, using <code>git checkout --ours</code> or <code>git checkout --theirs</code>. Once you have put the file into the state you want it, you indicate that you are done merging the file and it is ready to commit using <code>git add</code>, and then you can commit the merge with <code>git commit</code>.</p> | {
"question_id": 2073841,
"question_date": "2010-01-15T18:28:00.133Z",
"question_score": 209,
"tags": "git|merge|conflict|git-merge-conflict",
"answer_id": 2073854,
"answer_date": "2010-01-15T18:29:38.993Z",
"answer_score": 355
} |
Please answer the following Stack Overflow question:
Title: Swift - Convert to absolute value
<p>is there any way to get absolute value from an integer?<br>
for example </p>
<pre><code>-8
to
8
</code></pre>
<p>I already tried to use UInt() assuming it will convert the Int to unsigned value but it didn't work.</p> | <p>The standard <code>abs()</code> function works great here:</p>
<pre><code>let c = -8
print(abs(c))
// 8
</code></pre> | {
"question_id": 24159627,
"question_date": "2014-06-11T09:43:33.340Z",
"question_score": 209,
"tags": "ios|iphone|swift",
"answer_id": 24159740,
"answer_date": "2014-06-11T09:48:03.330Z",
"answer_score": 441
} |
Please answer the following Stack Overflow question:
Title: What is the claims in ASP .NET Identity
<p>Can somebody please explain, what the claim mechanism means in new ASP.NET Identity Core?</p>
<p>As I can see, there is an <code>AspNetUserLogins</code> table, which contains <code>UserId</code>, <code>LoginProvider</code> and <code>ProviderKey</code>.</p>
<p>But, I still can't understand or find any information on when data is added to the <code>AspNetUserClaims</code> table and what situations this table is used for?</p> | <blockquote>
<p>what does claim mechanism means in new ASP.NET Identity Core?</p>
</blockquote>
<p>There are two common authorization approaches that are based on Role and Claim.</p>
<p><strong>Role-Based Security</strong></p>
<p>A user gets assigned to one or more roles through which the user gets access rights.
Also, by assigning a user to a role, the user immediately gets all the access rights defined for that role.</p>
<p><strong>Claims-Based Security</strong></p>
<p>A claims-based identity is the set of claims. A claim is a statement that an entity (a user or another application) makes about
itself, it's just a claim. For example a claim list can have the user’s name, user’s e-mail, user’s age, user's authorization for an action.
In role-based Security, a user presents the credentials directly to the application. In a claims-based
model, the user presents the claims and not the credentials to the application. For a claim to have practical
value, it must come from an entity the application trusts.</p>
<p>Below steps illustrate the sequence of that happens in a claims-based security model:</p>
<ol>
<li>The user requests an action. The relying party (RP) application asks
for a token.</li>
<li>The user presents the credentials to the issuing authority that the RP application trusts.</li>
<li>The issuing authority issues a signed token with claims, after authenticating the user’s
credentials.</li>
<li>The user presents the token to the RP application. The application validates the token
signature, extracts the claims, and based on the claims, either accepts or denies the
request.</li>
</ol>
<blockquote>
<p>But, i still can't understand and find any information, when data
addes to AspNetUserClaims and what situations this table using for?</p>
</blockquote>
<p>When you are in a situation where a Role-Based Security is not used, and you chose to use Claim-Based
Security, you would need to utilize AspNetUserClaims table.
For how to use Claims in ASP.NET Identity, see below link for more information.</p>
<p><a href="http://kevin-junghans.blogspot.com/2013/12/using-claims-in-aspnet-identity.html" rel="noreferrer">http://kevin-junghans.blogspot.com/2013/12/using-claims-in-aspnet-identity.html</a></p>
<p><strong>Update</strong> </p>
<blockquote>
<p>What time i have to use role-based security and when claim-based?
Could you please write a few examples?</p>
</blockquote>
<p>There isn't a very clear situation where you would or would not use Role-Based or Claim-Based Security, Not like a case where you would use A rather than B. </p>
<p>But, claim-Based access control allows better separation of authorization rules from the core business logic. When authorization rules change, the core business logic remain unaffected. There will be situations where you might prefer using Claim-Based approach.</p>
<blockquote>
<p>Sometimes claims aren't needed. This is an important disclaimer.
Companies with a host of internal applications can use Integrated
Windows Authentication to achieve many of the benefits provided by
claims. Active Directory does a great job of storing user identities,
and because Kerberos is a part of Windows, your applications don't
have to include much authentication logic. As long as every
application you build can use Integrated Windows Authentication, you
may have already reached your identity utopia. However, there are many
reasons why you might need something other than Windows
authentication. You might have web-facing applications that are used
by people who don't have accounts in your Windows domain. Another
reason might be that your company has merged with another company and
you're having trouble authenticating across two Windows forests that
don't (and may never) have a trust relationship. Perhaps you want to
share identities with another company that has non-.NET Framework
applications or you need to share identities between applications
running on different platforms (for example, the Macintosh). These are
just a few situations in which claims-based identity can be the right
choice for you.</p>
</blockquote>
<p>For more information, please visit <a href="http://msdn.microsoft.com/en-us/library/ff359101.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ff359101.aspx</a></p> | {
"question_id": 21645323,
"question_date": "2014-02-08T11:18:04.503Z",
"question_score": 209,
"tags": "asp.net|asp.net-mvc|asp.net-identity",
"answer_id": 21647975,
"answer_date": "2014-02-08T15:40:18.970Z",
"answer_score": 232
} |
Please answer the following Stack Overflow question:
Title: git log of a single revision
<p>I have a commit c. I want to get the changeset of that exact commit c + metainformation and no other one. Is there a simpler way than <code>git log -p c^..c</code> to do that?</p> | <p>You can use <a href="https://git-scm.com/docs/git-show" rel="noreferrer"><code>show</code></a>:</p>
<pre><code>git show commit_id
</code></pre> | {
"question_id": 4082126,
"question_date": "2010-11-02T21:10:08.190Z",
"question_score": 209,
"tags": "git|git-log",
"answer_id": 4082188,
"answer_date": "2010-11-02T21:20:16.390Z",
"answer_score": 314
} |
Please answer the following Stack Overflow question:
Title: How to trigger XDebug profiler for a command line PHP script?
<p>XDebug offers the configuration directive <code>xdebug.profiler_enable_trigger</code> that allows to activate profiling by passing the GET or POST parameter "XDEBUG_PROFILE" when calling a script via HTTP. This is handy if you don't want profiling for ALL of your scripts but only for a few special cases without always changing your PHP configuration.</p>
<p>Is there a way to achieve the same behavior for command line PHP programs? I tried to pass the <code>XDEBUG_PROFILE</code> as a command line argument but it didn't work.</p>
<p>In general, profiling command line PHP works well, but I'd like to have the same per-call-flexibility as with a browser and HTTP server.</p> | <p>You can pass INI settings with the <code>-d</code> flag: <code>php -d xdebug.profiler_enable=On script.php</code>.</p> | {
"question_id": 2288612,
"question_date": "2010-02-18T12:40:13.567Z",
"question_score": 209,
"tags": "php|configuration|command-line|profiling|xdebug",
"answer_id": 2288791,
"answer_date": "2010-02-18T13:12:53.517Z",
"answer_score": 268
} |
Please answer the following Stack Overflow question:
Title: Xcode + remove all breakpoints
<p>Is there any way to remove all the breakpoints in Xcode?</p> | <p>Well there's a 3 step way:</p>
<ol>
<li>Press CMD(⌘)+7 to show all breakpoints.
In Xcode4 press CMD(⌘)+6, in Xcode3 press CMD(⌘)+ALT+B.</li>
<li>Select all breakpoints with CMD(⌘)+A and delete them, like deleting text, with backspace.</li>
<li>There's no step 3 :)</li>
</ol> | {
"question_id": 1665744,
"question_date": "2009-11-03T07:22:19.683Z",
"question_score": 209,
"tags": "xcode|breakpoints",
"answer_id": 1665772,
"answer_date": "2009-11-03T07:29:22.540Z",
"answer_score": 349
} |
Please answer the following Stack Overflow question:
Title: JavaScript: Overriding alert()
<p>Has anyone got any experience with overriding the <code>alert()</code> function in JavaScript?</p>
<ul>
<li>Which browsers support this?</li>
<li>Which browser-versions support this?</li>
<li>What are the dangers in overriding the function?</li>
</ul> | <p>It's definitely "supported". It is your web page, you do whatever you want to with it.</p>
<p>I already did this to track analytics events without modifying a library but by sneaking into events.</p>
<p>Use the proxy pattern:</p>
<pre><code>(function(proxied) {
window.alert = function() {
// do something here
return proxied.apply(this, arguments);
};
})(window.alert);
</code></pre>
<p>You can also bypass the call to the original function if you want (proxied)</p>
<p>More info here: <a href="https://api.jquery.com/Types/#Proxy_Pattern" rel="noreferrer" title="Types | jQuery API Documentation - Proxy Pattern">JQuery Types #Proxy Pattern</a></p> | {
"question_id": 1729501,
"question_date": "2009-11-13T14:22:30.970Z",
"question_score": 209,
"tags": "javascript|overriding",
"answer_id": 1729684,
"answer_date": "2009-11-13T14:50:35.340Z",
"answer_score": 215
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.