input_text
stringlengths 115
13.8k
| output_text
stringlengths 24
15k
| metadata
dict |
---|---|---|
Please answer the following Stack Overflow question:
Title: Find and kill a process in one line using bash and regex
<p>I often need to kill a process during programming.</p>
<p>The way I do it now is:</p>
<pre><code>[~]$ ps aux | grep 'python csp_build.py'
user 5124 1.0 0.3 214588 13852 pts/4 Sl+ 11:19 0:00 python csp_build.py
user 5373 0.0 0.0 8096 960 pts/6 S+ 11:20 0:00 grep python csp_build.py
[~]$ kill 5124
</code></pre>
<p>How can I extract the process id automatically and kill it in the same line?</p>
<p>Like this:</p>
<pre><code>[~]$ ps aux | grep 'python csp_build.py' | kill <regex that returns the pid>
</code></pre> | <p>In <code>bash</code>, you should be able to do:</p>
<pre><code>kill $(ps aux | grep '[p]ython csp_build.py' | awk '{print $2}')
</code></pre>
<p>Details on its workings are as follows:</p>
<ul>
<li>The <code>ps</code> gives you the list of all the processes.</li>
<li>The <code>grep</code> filters that based on your search string, <code>[p]</code> is a trick to stop you picking up the actual <code>grep</code> process itself.</li>
<li>The <code>awk</code> just gives you the second field of each line, which is the PID.</li>
<li>The <code>$(x)</code> construct means to execute <code>x</code> then take its output and put it on the command line. The output of that <code>ps</code> pipeline inside that construct above is the list of process IDs so you end up with a command like <code>kill 1234 1122 7654</code>.</li>
</ul>
<p>Here's a transcript showing it in action:</p>
<pre><code>pax> sleep 3600 &
[1] 2225
pax> sleep 3600 &
[2] 2226
pax> sleep 3600 &
[3] 2227
pax> sleep 3600 &
[4] 2228
pax> sleep 3600 &
[5] 2229
pax> kill $(ps aux | grep '[s]leep' | awk '{print $2}')
[5]+ Terminated sleep 3600
[1] Terminated sleep 3600
[2] Terminated sleep 3600
[3]- Terminated sleep 3600
[4]+ Terminated sleep 3600
</code></pre>
<p>and you can see it terminating all the sleepers.</p>
<hr>
<p>Explaining the <code>grep '[p]ython csp_build.py'</code> bit in a bit more detail:</p>
<p>When you do <code>sleep 3600 &</code> followed by <code>ps -ef | grep sleep</code>, you tend to get <em>two</em> processes with <code>sleep</code> in it, the <code>sleep 3600</code> and the <code>grep sleep</code> (because they both have <code>sleep</code> in them, that's not rocket science).</p>
<p>However, <code>ps -ef | grep '[s]leep'</code> won't create a process with <code>sleep</code> in it, it instead creates <code>grep '[s]leep'</code> and here's the tricky bit: the <code>grep</code> doesn't find it because it's looking for the regular expression "any character from the character class <code>[s]</code> (which is <code>s</code>) followed by <code>leep</code>.</p>
<p>In other words, it's looking for <code>sleep</code> but the grep process is <code>grep '[s]leep'</code> which doesn't have <code>sleep</code> in it.</p>
<p>When I was shown this (by someone here on SO), I immediately started using it because</p>
<ul>
<li>it's one less process than adding <code>| grep -v grep</code>; and</li>
<li>it's elegant <em>and</em> sneaky, a rare combination :-)</li>
</ul> | {
"question_id": 3510673,
"question_date": "2010-08-18T09:33:41.783Z",
"question_score": 758,
"tags": "regex|bash|terminal|awk",
"answer_id": 3510850,
"answer_date": "2010-08-18T09:53:24.537Z",
"answer_score": 1647
} |
Please answer the following Stack Overflow question:
Title: How to determine the current interactive shell that I'm in (command-line)
<p>How can I determine the current shell I am working on? </p>
<p>Would the output of the <code>ps</code> command alone be sufficient?</p>
<p>How can this be done in different flavors of Unix?</p> | <ul>
<li><p>There are three approaches to finding the <strong>name</strong> of the current shell's executable:</p>
<p>Please note that all three approaches can be fooled if the executable of the shell is <code>/bin/sh</code>, but it's really a renamed <code>bash</code>, for example (which frequently happens).</p>
<p><em>Thus your second question of whether <code>ps</code> output will do is answered with "<strong>not always</strong>".</em></p>
<ol>
<li><p><code>echo $0</code> - will print the program name... which in the case of the shell is the actual shell.</p></li>
<li><p><code>ps -ef | grep $$ | grep -v grep</code> - this will look for the current process ID in the list of running processes. Since the current process is the shell, it will be included.</p>
<p>This is not 100% reliable, as you might have <em>other</em> processes whose <code>ps</code> listing includes the same number as shell's process ID, especially if that ID is a small number (for example, if the shell's PID is "5", you may find processes called "java5" or "perl5" in the same <code>grep</code> output!). <em>This is the second problem with the "ps" approach, on top of not being able to rely on the shell name.</em></p></li>
<li><p><code>echo $SHELL</code> - The path to the current shell is stored as the <code>SHELL</code> variable for any shell. The caveat for this one is that if you launch a shell explicitly as a subprocess (for example, it's not your login shell), you will get your login shell's value instead. If that's a possibility, use the <code>ps</code> or <code>$0</code> approach.</p></li>
</ol>
<hr></li>
<li><p>If, however, the executable doesn't match your actual shell (e.g. <code>/bin/sh</code> is actually bash or ksh), you need heuristics. Here are some environmental variables specific to various shells:</p>
<ul>
<li><p><code>$version</code> is set on tcsh</p></li>
<li><p><code>$BASH</code> is set on bash</p></li>
<li><p><code>$shell</code> (lowercase) is set to actual shell name in csh or tcsh</p></li>
<li><p><code>$ZSH_NAME</code> is set on zsh</p></li>
<li><p>ksh has <code>$PS3</code> and <code>$PS4</code> set, whereas the normal Bourne shell (<code>sh</code>) only has <code>$PS1</code> and <code>$PS2</code> set. This generally seems like the hardest to distinguish - the <em>only</em> difference in the entire set of environment variables between <code>sh</code> and <code>ksh</code> we have installed on Solaris boxen is <code>$ERRNO</code>, <code>$FCEDIT</code>, <code>$LINENO</code>, <code>$PPID</code>, <code>$PS3</code>, <code>$PS4</code>, <code>$RANDOM</code>, <code>$SECONDS</code>, and <code>$TMOUT</code>.</p></li>
</ul></li>
</ul> | {
"question_id": 3327013,
"question_date": "2010-07-24T21:35:28.150Z",
"question_score": 758,
"tags": "bash|unix|shell|csh|tcsh",
"answer_id": 3327022,
"answer_date": "2010-07-24T21:37:34.633Z",
"answer_score": 917
} |
Please answer the following Stack Overflow question:
Title: Is arr.__len__() the preferred way to get the length of an array in Python?
<p>In <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29" rel="noreferrer">Python</a>, is the following the only way to get the number of elements?</p>
<pre><code>arr.__len__()
</code></pre>
<p>If so, why the strange syntax?</p> | <pre><code>my_list = [1,2,3,4,5]
len(my_list)
# 5
</code></pre>
<p>The same works for tuples:</p>
<pre><code>my_tuple = (1,2,3,4,5)
len(my_tuple)
# 5
</code></pre>
<p>And strings, which are really just arrays of characters:</p>
<pre><code>my_string = 'hello world'
len(my_string)
# 11
</code></pre>
<p>It was <a href="http://effbot.org/pyfaq/why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list.htm" rel="noreferrer">intentionally done this way</a> so that lists, tuples and other container types or iterables didn't all need to explicitly implement a public <code>.length()</code> method, instead you can just check the <code>len()</code> of anything that implements the 'magic' <code>__len__()</code> method.</p>
<p>Sure, this may seem redundant, but length checking implementations can vary considerably, even within the same language. It's not uncommon to see one collection type use a <code>.length()</code> method while another type uses a <code>.length</code> property, while yet another uses <code>.count()</code>. Having a language-level keyword unifies the entry point for all these types. So even objects you may not consider to be lists of elements could still be length-checked. This includes strings, queues, trees, etc.</p>
<p>The functional nature of <code>len()</code> also lends itself well to functional styles of programming.</p>
<pre><code>lengths = map(len, list_of_containers)
</code></pre> | {
"question_id": 518021,
"question_date": "2009-02-05T21:26:47.217Z",
"question_score": 757,
"tags": "python|arrays|methods",
"answer_id": 518038,
"answer_date": "2009-02-05T21:29:48.100Z",
"answer_score": 1254
} |
Please answer the following Stack Overflow question:
Title: Undoing a 'git push'
<p>Here's what I did on my <em>supposed-to-be-stable</em> branch...</p>
<pre class="lang-bash prettyprint-override"><code>% git rebase master
First, rewinding head to replay your work on top of it...
Fast-forwarded alpha-0.3.0 to master.
% git status
# On branch alpha-0.3.0
# Your branch is ahead of 'origin/alpha-0.3.0' by 53 commits.
#
nothing to commit (working directory clean)
% git push
Fetching remote heads...
refs/
refs/heads/
refs/tags/
refs/remotes/
'refs/heads/master': up-to-date
updating 'refs/heads/alpha-0.3.0'
from cc4b63bebb6e6dd04407f8788938244b78c50285
to 83c9191dea88d146400853af5eb7555f252001b0
done
'refs/heads/unstable': up-to-date
Updating remote server info
</code></pre>
<p>That was all a mistake as I later realized. I'd like to undo this entire process, and revert the alpha-0.3.0 branch back to what it was.</p>
<p>What should I do?</p> | <p>You need to make sure that no other users of this repository are fetching the incorrect changes or trying to build on top of the commits that you want removed because you are about to rewind history.</p>
<p>Then you need to 'force' push the old reference.</p>
<pre><code>git push -f origin last_known_good_commit:branch_name
</code></pre>
<p>or in your case</p>
<pre><code>git push -f origin cc4b63bebb6:alpha-0.3.0
</code></pre>
<p>You may have <code>receive.denyNonFastForwards</code> set on the remote repository. If this is the case, then you will get an error which includes the phrase <code>[remote rejected]</code>.</p>
<p>In this scenario, you will have to delete and recreate the branch.</p>
<pre><code>git push origin :alpha-0.3.0
git push origin cc4b63bebb6:refs/heads/alpha-0.3.0
</code></pre>
<p>If this doesn't work - perhaps because you have <code>receive.denyDeletes</code> set, then you have to have direct access to the repository. In the remote repository, you then have to do something like the following plumbing command.</p>
<pre><code>git update-ref refs/heads/alpha-0.3.0 cc4b63bebb6 83c9191dea8
</code></pre> | {
"question_id": 1270514,
"question_date": "2009-08-13T07:23:50.213Z",
"question_score": 757,
"tags": "git|git-push",
"answer_id": 1270608,
"answer_date": "2009-08-13T07:47:35.643Z",
"answer_score": 1196
} |
Please answer the following Stack Overflow question:
Title: Difference between \n and \r?
<p>What’s the difference between <code>\n</code> (newline) and <code>\r</code> (carriage return)?</p>
<p>In particular, are there any <em>practical</em> differences between <code>\n</code> and <code>\r</code>? Are there places where one should be used instead of the other?</p> | <p>In terms of ascii code, it's 3 -- since they're 10 and 13 respectively;-).</p>
<p>But seriously, there are many:</p>
<ul>
<li>in Unix and all Unix-like systems, <code>\n</code> is the code for end-of-line, <code>\r</code> means nothing special</li>
<li>as a consequence, in C and most languages that somehow copy it (even remotely), <code>\n</code> is the standard escape sequence for end of line (translated to/from OS-specific sequences as needed)</li>
<li>in old Mac systems (pre-OS X), <code>\r</code> was the code for end-of-line instead</li>
<li>in Windows (and many old OSs), the code for end of line is 2 characters, <code>\r\n</code>, in this order</li>
<li>as a (surprising;-) consequence (harking back to OSs much older than Windows), <code>\r\n</code> is the standard line-termination for text formats on the Internet</li>
<li>for electromechanical teletype-like "terminals", <code>\r</code> commands the carriage to go back leftwards until it hits the leftmost stop (a slow operation), <code>\n</code> commands the roller to roll up one line (a much faster operation) -- that's the reason you always have <code>\r</code> <strong>before</strong> <code>\n</code>, so that the roller can move while the carriage is still going leftwards!-) Wikipedia has a <a href="https://en.wikipedia.org/wiki/Newline#History" rel="noreferrer">more detailed explanation</a>.</li>
<li>for character-mode terminals (typically emulating even-older printing ones as above), in raw mode, <code>\r</code> and <code>\n</code> act similarly (except both in terms of the cursor, as there <strong>is</strong> no carriage or roller;-)</li>
</ul>
<p>In practice, in the modern context of writing to a text file, you should always use <code>\n</code> (the underlying runtime will translate that if you're on a weird OS, e.g., Windows;-). The only reason to use <code>\r</code> is if you're writing to a character terminal (or more likely a "console window" emulating it) and want the next line you write to overwrite the last one you just wrote (sometimes used for goofy "ascii animation" effects of e.g. progress bars) -- this is getting pretty obsolete in a world of GUIs, though;-).</p> | {
"question_id": 1761051,
"question_date": "2009-11-19T05:20:24.333Z",
"question_score": 757,
"tags": "newline|carriage-return",
"answer_id": 1761086,
"answer_date": "2009-11-19T05:29:10.620Z",
"answer_score": 980
} |
Please answer the following Stack Overflow question:
Title: How to detect when an @Input() value changes in Angular?
<p>I have a parent component (<strong>CategoryComponent</strong>), a child component (<strong>videoListComponent</strong>) and an ApiService.</p>
<p>I have most of this working fine i.e. each component can access the json api and get its relevant data via observables.</p>
<p>Currently video list component just gets all videos, I would like to filter this to just videos in a particular category, I achieved this by passing the categoryId to the child via <code>@Input()</code>.</p>
<p>CategoryComponent.html</p>
<pre class="lang-xml prettyprint-override"><code><video-list *ngIf="category" [categoryId]="category.id"></video-list>
</code></pre>
<p>This works and when the parent CategoryComponent category changes then the categoryId value gets passed through via <code>@Input()</code> but I then need to detect this in VideoListComponent and re-request the videos array via APIService (with the new categoryId).</p>
<p>In AngularJS I would have done a <code>$watch</code> on the variable. What is the best way to handle this?</p> | <p><strong>Actually, there are two ways of detecting and acting upon when an input changes in the child component in angular2+ :</strong></p>
<ol>
<li>You can use the <strong>ngOnChanges() lifecycle method</strong> as also mentioned in older answers:</li>
</ol>
<pre class="lang-js prettyprint-override"><code> @Input() categoryId: string;
ngOnChanges(changes: SimpleChanges) {
this.doSomething(changes.categoryId.currentValue);
// You can also use categoryId.previousValue and
// categoryId.firstChange for comparing old and new values
}
</code></pre>
<p>Documentation Links: <a href="https://angular.io/api/core/OnChanges" rel="noreferrer">ngOnChanges,</a> <a href="https://angular.io/api/core/SimpleChanges" rel="noreferrer">SimpleChanges,</a> <a href="https://angular.io/api/core/SimpleChange" rel="noreferrer">SimpleChange</a><br />
Demo Example: Look at <a href="https://plnkr.co/edit/LUr2bMQRhhAeuLN3R5B6?p=preview" rel="noreferrer">this plunker</a></p>
<ol start="2">
<li>Alternately, you can also use an <strong>input property setter</strong> as follows:</li>
</ol>
<pre class="lang-js prettyprint-override"><code> private _categoryId: string;
@Input() set categoryId(value: string) {
this._categoryId = value;
this.doSomething(this._categoryId);
}
get categoryId(): string {
return this._categoryId;
}
</code></pre>
<p>Documentation Link: Look <a href="https://angular.io/guide/component-interaction#intercept-input-property-changes-with-a-setter" rel="noreferrer">here</a>.</p>
<p>Demo Example: Look at <a href="https://plnkr.co/edit/EsolgwJVuvOUx6rKk8d4?p=preview" rel="noreferrer">this plunker</a>.</p>
<p><strong>WHICH APPROACH SHOULD YOU USE?</strong></p>
<p>If your component has several inputs, then, if you use ngOnChanges(), you will get all changes for all the inputs at once within ngOnChanges(). Using this approach, you can also compare current and previous values of the input that has changed and take actions accordingly.</p>
<p>However, if you want to do something when only a particular single input changes (and you don't care about the other inputs), then it might be simpler to use an input property setter. However, this approach does not provide a built in way to compare previous and current values of the changed input (which you can do easily with the ngOnChanges lifecycle method).</p>
<p><strong>EDIT 2017-07-25: ANGULAR CHANGE DETECTION MAY STILL NOT FIRE UNDER SOME CIRCUMSTANCES</strong></p>
<p>Normally, change detection for both setter and ngOnChanges will fire whenever the parent component changes the data it passes to the child, <strong>provided that the data is a JS primitive datatype(string, number, boolean)</strong>. However, in the following scenarios, it will not fire and you have to take extra actions in order to make it work.</p>
<ol>
<li><p>If you are using a nested object or array (instead of a JS primitive data type) to pass data from Parent to Child, change detection (using either setter or ngchanges) might not fire, as also mentioned in the answer by user: muetzerich. For solutions look <a href="https://stackoverflow.com/questions/34796901/angular2-change-detection-ngonchanges-not-firing-for-nested-object">here</a>.</p>
</li>
<li><p>If you are mutating data outside of the angular context (i.e., externally), then angular will not know of the changes. You may have to use ChangeDetectorRef or NgZone in your component for making angular aware of external changes and thereby triggering change detection. Refer to <a href="https://stackoverflow.com/questions/42971865/angular2-zone-run-vs-changedetectorref-detectchanges">this</a>.</p>
</li>
</ol> | {
"question_id": 38571812,
"question_date": "2016-07-25T15:28:01.043Z",
"question_score": 757,
"tags": "angular|angular2-changedetection|angular-decorator",
"answer_id": 44686085,
"answer_date": "2017-06-21T20:53:35.733Z",
"answer_score": 1201
} |
Please answer the following Stack Overflow question:
Title: When to use the different log levels
<p>There are different ways to log messages, in order of fatality:</p>
<ol>
<li><p><code>FATAL</code></p></li>
<li><p><code>ERROR</code></p></li>
<li><p><code>WARN</code></p></li>
<li><p><code>INFO</code></p></li>
<li><p><code>DEBUG</code></p></li>
<li><p><code>TRACE</code></p></li>
</ol>
<p>How do I decide when to use which?</p>
<p>What's a good heuristic to use?</p> | <p>I generally subscribe to the following convention:</p>
<ul>
<li><strong>Trace</strong> - Only when I would be "tracing" the code and trying to find one <strong>part</strong> of a function specifically.</li>
<li><strong>Debug</strong> - Information that is diagnostically helpful to people more than just developers (IT, sysadmins, etc.).</li>
<li><strong>Info</strong> - Generally useful information to log (service start/stop, configuration assumptions, etc). Info I want to always have available but usually don't care about under normal circumstances. This is my out-of-the-box config level.</li>
<li><strong>Warn</strong> - Anything that can potentially cause application oddities, but for which I am automatically recovering. (Such as switching from a primary to backup server, retrying an operation, missing secondary data, etc.)</li>
<li><strong>Error</strong> - Any error which is fatal to the <strong>operation</strong>, but not the service or application (can't open a required file, missing data, etc.). These errors will force user (administrator, or direct user) intervention. These are usually reserved (in my apps) for incorrect connection strings, missing services, etc. </li>
<li><strong>Fatal</strong> - Any error that is forcing a shutdown of the service or application to prevent data loss (or further data loss). I reserve these only for the most heinous errors and situations where there is guaranteed to have been data corruption or loss.</li>
</ul> | {
"question_id": 2031163,
"question_date": "2010-01-08T22:19:20.443Z",
"question_score": 757,
"tags": "logging|conventions",
"answer_id": 2031209,
"answer_date": "2010-01-08T22:26:35.737Z",
"answer_score": 1048
} |
Please answer the following Stack Overflow question:
Title: git cherry-pick says "...38c74d is a merge but no -m option was given"
<p>I made some changes in my master branch and want to bring those upstream. When I cherry-pick the following commits. However, I get stuck on fd9f578 where git says:</p>
<pre><code>$ git cherry-pick fd9f578
fatal: Commit fd9f57850f6b94b7906e5bbe51a0d75bf638c74d is a merge but no -m option was given.
</code></pre>
<p>What is git trying to tell me and is cherry-pick the right thing to be using here? The master branch does include changes to files which have been modified in the upstream branch, so I'm sure there will be some merge conflicts but those aren't too bad to straighten out. I know which changes are needed where.</p>
<p>These are the commits I want to bring upstream.</p>
<pre><code>e7d4cff added some comments...
23e6d2a moved static strings...
44cc65a incorporated test ...
40b83d5 whoops delete whitspace...
24f8a50 implemented global.c...
43651c3 cleaned up ...
068b2fe cleaned up version.c ...
fd9f578 Merge branch 'master' of ssh://extgit/git/sessions_common
4172caa cleaned up comments in sessions.c ...
</code></pre> | <p>The way a cherry-pick works is by taking the diff a changeset represents (the difference between the working tree at that point and the working tree of its parent), and applying it to your current branch.</p>
<p>So, if a commit has two or more parents, it also represents two or more diffs - which one should be applied?</p>
<p>You're trying to cherry pick <code>fd9f578</code>, which was a merge with two parents. So you need to tell the cherry-pick command which one against which the diff should be calculated, by using the <code>-m</code> option. For example, <code>git cherry-pick -m 1 fd9f578</code> to use parent 1 as the base.</p>
<p>I can't say for sure for your particular situation, but using <code>git merge</code> instead of <code>git cherry-pick</code> is generally advisable. When you cherry-pick a merge commit, it collapses <strong>all</strong> the changes made in the parent you didn't specify to <code>-m</code> into that <strong>one commit</strong>. You lose all their history, and glom together all their diffs. Your call.</p> | {
"question_id": 9229301,
"question_date": "2012-02-10T14:26:50.107Z",
"question_score": 757,
"tags": "git|merge|rebase|cherry-pick|git-cherry-pick",
"answer_id": 9229393,
"answer_date": "2012-02-10T14:34:53.533Z",
"answer_score": 814
} |
Please answer the following Stack Overflow question:
Title: Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6
<p>When trying to run the Example CorDapp (<a href="https://github.com/corda/cordapp-example" rel="noreferrer">GitHub CorDapp</a>) via IntelliJ, I receive the following error:</p>
<blockquote>
<p>Cannot inline bytecode built with JVM target 1.8 into bytecode that is
being built with JVM target 1.6</p>
</blockquote>
<p>How can I modify the IntelliJ settings so that all the bytecode is built with the same JVM target?</p> | <p>You can fix this issue as follows:</p>
<ul>
<li>Open the IntelliJ preferences</li>
<li>Go to <code>Build, Execution, Deployment</code> > <code>Compiler</code> > <code>Kotlin Compiler</code> <strong>BUT</strong> <code>Other Settings</code> > <code>Kotlin compiler</code> if Android Studio > <code>3.4</code></li>
<li>Change the <code>Target JVM version</code> to <code>1.8</code></li>
<li>Click <code>Apply</code></li>
</ul> | {
"question_id": 48988778,
"question_date": "2018-02-26T12:41:42.127Z",
"question_score": 757,
"tags": "android|intellij-idea|kotlin|jvm|corda",
"answer_id": 48988779,
"answer_date": "2018-02-26T12:41:42.127Z",
"answer_score": 298
} |
Please answer the following Stack Overflow question:
Title: Unzipping files in Python
<p>I read through the <a href="https://docs.python.org/3/library/zipfile.html" rel="noreferrer"><code>zipfile</code> documentation</a>, but couldn't understand how to <em>unzip</em> a file, only how to zip a file. How do I unzip all the contents of a zip file into the same directory?</p> | <pre><code>import zipfile
with zipfile.ZipFile(path_to_zip_file, 'r') as zip_ref:
zip_ref.extractall(directory_to_extract_to)
</code></pre>
<p>That's pretty much it!</p> | {
"question_id": 3451111,
"question_date": "2010-08-10T16:19:32.780Z",
"question_score": 756,
"tags": "python|zip|unzip|python-zipfile",
"answer_id": 3451150,
"answer_date": "2010-08-10T16:23:27.560Z",
"answer_score": 1408
} |
Please answer the following Stack Overflow question:
Title: Delete first character of string if it is 0
<p>I want to delete the first character of a string, if the first character is a 0. The 0 can be there more than once.</p>
<p>Is there a simple function that checks the first character and deletes it if it is 0?</p>
<p>Right now, I'm trying it with the JS <code>slice()</code> function but it is very awkward.</p> | <p>You can remove the first character of a string using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring" rel="noreferrer"><code>substring</code></a>:</p>
<pre><code>var s1 = "foobar";
var s2 = s1.substring(1);
alert(s2); // shows "oobar"
</code></pre>
<p>To remove all 0's at the start of the string:</p>
<pre><code>var s = "0000test";
while(s.charAt(0) === '0')
{
s = s.substring(1);
}
</code></pre> | {
"question_id": 4564414,
"question_date": "2010-12-30T16:39:01.370Z",
"question_score": 756,
"tags": "javascript|string",
"answer_id": 4564478,
"answer_date": "2010-12-30T16:48:32.190Z",
"answer_score": 1243
} |
Please answer the following Stack Overflow question:
Title: Delete forked repo from GitHub
<p>I'm starting with git and GitHub and there's a project I'm watching on GitHub. I unintentionally clicked to fork it. Now it appears as a new project to me.</p>
<p>I have some doubts about it:</p>
<ul>
<li>I know if commit or do another thing to my forked repo, it will be updated, but the updated code will take effect only after the project's author request the pull. Right?</li>
<li>If I go to admin panel on GitHub there's a delete option. If I delete it as the option above, will it make any effect in the original one or not?</li>
</ul>
<p>I'd like to delete it. By now I'm just studying the code and don't really need the fork.</p> | <p>Deleting it will do nothing to the original project. Editing it will only edit your fork on your repo page.</p> | {
"question_id": 11302639,
"question_date": "2012-07-02T23:38:49.710Z",
"question_score": 756,
"tags": "git|github",
"answer_id": 11302651,
"answer_date": "2012-07-02T23:40:02.457Z",
"answer_score": 381
} |
Please answer the following Stack Overflow question:
Title: Insert, on duplicate update in PostgreSQL?
<p>Several months ago I learned from an answer on Stack Overflow how to perform multiple updates at once in MySQL using the following syntax:</p>
<pre><code>INSERT INTO table (id, field, field2) VALUES (1, A, X), (2, B, Y), (3, C, Z)
ON DUPLICATE KEY UPDATE field=VALUES(Col1), field2=VALUES(Col2);
</code></pre>
<p>I've now switched over to PostgreSQL and apparently this is not correct. It's referring to all the correct tables so I assume it's a matter of different keywords being used but I'm not sure where in the PostgreSQL documentation this is covered.</p>
<p>To clarify, I want to insert several things and if they already exist to update them.</p> | <p>PostgreSQL since version 9.5 has <a href="http://www.postgresql.org/docs/devel/static/sql-insert.html" rel="noreferrer">UPSERT</a> syntax, with <strong><a href="http://www.postgresql.org/docs/current/static/sql-insert.html#SQL-ON-CONFLICT" rel="noreferrer">ON CONFLICT</a> clause.</strong> with the following syntax (similar to MySQL)</p>
<pre><code>INSERT INTO the_table (id, column_1, column_2)
VALUES (1, 'A', 'X'), (2, 'B', 'Y'), (3, 'C', 'Z')
ON CONFLICT (id) DO UPDATE
SET column_1 = excluded.column_1,
column_2 = excluded.column_2;
</code></pre>
<hr>
<p>Searching postgresql's email group archives for "upsert" leads to finding <a href="http://www.postgresql.org/docs/current/static/plpgsql-control-structures.html#PLPGSQL-UPSERT-EXAMPLE" rel="noreferrer">an example of doing what you possibly want to do, in the manual</a>:</p>
<blockquote>
<p><strong>Example 38-2. Exceptions with UPDATE/INSERT</strong></p>
<p>This example uses exception handling to perform either UPDATE or INSERT, as appropriate:</p>
</blockquote>
<pre><code>CREATE TABLE db (a INT PRIMARY KEY, b TEXT);
CREATE FUNCTION merge_db(key INT, data TEXT) RETURNS VOID AS
$$
BEGIN
LOOP
-- first try to update the key
-- note that "a" must be unique
UPDATE db SET b = data WHERE a = key;
IF found THEN
RETURN;
END IF;
-- not there, so try to insert the key
-- if someone else inserts the same key concurrently,
-- we could get a unique-key failure
BEGIN
INSERT INTO db(a,b) VALUES (key, data);
RETURN;
EXCEPTION WHEN unique_violation THEN
-- do nothing, and loop to try the UPDATE again
END;
END LOOP;
END;
$$
LANGUAGE plpgsql;
SELECT merge_db(1, 'david');
SELECT merge_db(1, 'dennis');
</code></pre>
<hr>
<p>There's possibly an example of how to do this in bulk, using CTEs in 9.1 and above, in the <a href="http://archives.postgresql.org/pgsql-hackers/2011-06/msg01826.php" rel="noreferrer">hackers mailing list</a>:</p>
<pre><code>WITH foos AS (SELECT (UNNEST(%foo[])).*)
updated as (UPDATE foo SET foo.a = foos.a ... RETURNING foo.id)
INSERT INTO foo SELECT foos.* FROM foos LEFT JOIN updated USING(id)
WHERE updated.id IS NULL;
</code></pre>
<p>See <a href="https://stackoverflow.com/a/8702291/642706">a_horse_with_no_name's answer</a> for a clearer example.</p> | {
"question_id": 1109061,
"question_date": "2009-07-10T11:38:49.187Z",
"question_score": 756,
"tags": "postgresql|upsert",
"answer_id": 1109198,
"answer_date": "2009-07-10T12:18:16.843Z",
"answer_score": 690
} |
Please answer the following Stack Overflow question:
Title: What is the difference between declarative and imperative paradigm in programming?
<p>I have been searching the web looking for a definition for <strong>declarative</strong> and <strong>imperative</strong> programming that would shed some light for me. However, the language used at some of the resources that I have found is daunting - for instance at <a href="http://en.wikipedia.org/wiki/Imperative_programming" rel="noreferrer">Wikipedia</a>.
Does anyone have a real-world example that they could show me that might bring some perspective to this subject (perhaps in C#)?</p> | <p>A great C# example of declarative vs. imperative programming is LINQ.</p>
<p>With <strong>imperative</strong> programming, you tell the compiler what you want to happen, step by step.</p>
<p>For example, let's start with this collection, and choose the odd numbers:</p>
<pre><code>List<int> collection = new List<int> { 1, 2, 3, 4, 5 };
</code></pre>
<p>With imperative programming, we'd step through this, and decide what we want:</p>
<pre><code>List<int> results = new List<int>();
foreach(var num in collection)
{
if (num % 2 != 0)
results.Add(num);
}
</code></pre>
<p>Here, we're saying:</p>
<ol>
<li>Create a result collection</li>
<li>Step through each number in the collection</li>
<li>Check the number, if it's odd, add it to the results</li>
</ol>
<p>With <strong>declarative</strong> programming, on the other hand, you write code that describes what you want, but not necessarily how to get it (declare your desired results, but not the step-by-step):</p>
<pre><code>var results = collection.Where( num => num % 2 != 0);
</code></pre>
<p>Here, we're saying "Give us everything where it's odd", not "Step through the collection. Check this item, if it's odd, add it to a result collection."</p>
<p>In many cases, code will be a mixture of both designs, too, so it's not always black-and-white.</p> | {
"question_id": 1784664,
"question_date": "2009-11-23T17:24:41.793Z",
"question_score": 756,
"tags": "c#|paradigms|imperative-programming|declarative-programming",
"answer_id": 1784702,
"answer_date": "2009-11-23T17:29:25.683Z",
"answer_score": 1028
} |
Please answer the following Stack Overflow question:
Title: Using Chrome's Element Inspector in Print Preview Mode?
<p>I am working on developing a website and need to work on the print view. Typically when I have layout issues I use Chrome's Element Inspector. However this does not exist in print preview mode. </p>
<p>Is there a Chrome plugin or some other way to change your viewing medium within chrome itself, to view a page as a printer would? I suppose it doesn't have a be a Chrome specific solution, but that is my primary browser so it would be nice to have an in-browser solution.</p>
<p>Right now I'm focused just on the print preview medium, but it would be ideal to be able to change to any of the supported media types (i.e. all/braille/embossed/handheld/print/projection/screen/speech/tty/tv). </p> | <p><em>Note: This answer covers several versions of Chrome, scroll to see <strong>v52</strong>, <strong>v48</strong>, <strong>v46</strong>, <strong>v43</strong> and <strong>v42</strong> each with their updated changes.</em></p>
<h1>Chrome v52+:</h1>
<ul>
<li>Open the <em>Developer Tools</em> (Windows: <kbd>F12</kbd> or <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>I</kbd>, Mac: <kbd>Cmd</kbd>+<kbd>Opt</kbd>+<kbd>I</kbd>)</li>
<li>Click the <em>Customize and control DevTools</em> hamburger menu button and choose <em>More tools > Rendering settings</em> (or <em>Rendering</em> in newer versions).</li>
<li>Check the <em>Emulate print media</em> checkbox at the <em>Rendering</em> tab and select the <em>Print</em> media type.</li>
</ul>
<p><a href="https://i.stack.imgur.com/7BCx7.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7BCx7.png" alt="Chrome v52+" /></a></p>
<h1>Chrome v48+ (Thanks Alex for noticing):</h1>
<ul>
<li>Open the Developer Tools (<KBD>CTRL</KBD><KBD>SHIFT</KBD><KBD>I</KBD> or <KBD>F12</KBD>)</li>
<li>Click the <em>Toggle device mode</em> button in the left top corner (<KBD>CTRL</KBD><KBD>SHIFT</KBD><KBD>M</KBD>).</li>
<li>Make sure the console is shown by clicking <em>Show console</em> in menu at (1) (<KBD>ESC</KBD> key toggles the console if Developer Toolbar has focus).</li>
<li>Check <em>Emulate print media</em> at the rendering tab which can be opened by selecting <em>Rendering</em> in menu at (2).</li>
</ul>
<p><a href="https://i.stack.imgur.com/ClmyX.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ClmyX.png" alt="Chrome v48+" /></a></p>
<h1>Chrome v46+:</h1>
<ul>
<li>Open the Developer Tools (<KBD>CTRL</KBD><KBD>SHIFT</KBD><KBD>I</KBD> or <KBD>F12</KBD>)</li>
<li>Click the <em>Toggle device mode</em> button in the left top corner (1).</li>
<li>Make sure the console is shown by clicking the menu button (2) > <em>Show console</em> (3) or pressing the <KBD>ESC</KBD> key to toggle the console (only works when Developer Toolbar has the focus).</li>
<li>Open the <em>Emulation (4) > Media (5)</em> tabs, check <em>CSS media</em> and select <em>print</em> (3).</li>
</ul>
<p><a href="https://i.stack.imgur.com/Gyoil.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Gyoil.png" alt="Chrome v46+ support" /></a></p>
<h1>Chrome v43+:</h1>
<ul>
<li>The drawer icon at step 2 has changed.</li>
</ul>
<p><img src="https://i.stack.imgur.com/jT8Wz.png" alt="Emulate print media query on Chrome v43" /></p>
<h1>Chrome v42:</h1>
<ul>
<li>Open the Developer Tools (<KBD>CTRL</KBD><KBD>SHIFT</KBD><KBD>I</KBD> or <KBD>F12</KBD>)</li>
<li>Click the <em>Toggle device mode</em> button in the left top corner (1).</li>
<li>Make sure the drawer is shown by clicking the <em>Show drawer</em> button (2) or pressing the <KBD>ESC</KBD> key to toggle the drawer.</li>
<li>Under <em>Emulation > Media</em> check <em>CSS media</em> and select <em>print</em> (3).</li>
</ul>
<p><img src="https://i.stack.imgur.com/yU62w.png" alt="Emulate print media query on Chrome v42" /></p> | {
"question_id": 9540990,
"question_date": "2012-03-02T22:03:34.570Z",
"question_score": 756,
"tags": "google-chrome|google-chrome-devtools|web-inspector|print-preview",
"answer_id": 29962072,
"answer_date": "2015-04-30T07:53:38.560Z",
"answer_score": 1283
} |
Please answer the following Stack Overflow question:
Title: Could not find a declaration file for module 'module-name'. '/path/to/module-name.js' implicitly has an 'any' type
<p>I read how TypeScript <a href="https://www.typescriptlang.org/docs/handbook/module-resolution.html" rel="noreferrer">module resolution</a> works.</p>
<p>I have the following repository: <a href="https://github.com/ts-stack/di" rel="noreferrer">@ts-stack/di</a>.
After compiling the directory structure is as follows:</p>
<pre><code>├── dist
│ ├── annotations.d.ts
│ ├── annotations.js
│ ├── index.d.ts
│ ├── index.js
│ ├── injector.d.ts
│ ├── injector.js
│ ├── profiler.d.ts
│ ├── profiler.js
│ ├── providers.d.ts
│ ├── providers.js
│ ├── util.d.ts
│ └── util.js
├── LICENSE
├── package.json
├── README.md
├── src
│ ├── annotations.ts
│ ├── index.ts
│ ├── injector.ts
│ ├── profiler.ts
│ ├── providers.ts
│ └── util.ts
└── tsconfig.json
</code></pre>
<p>In my package.json I wrote <code>"main": "dist/index.js"</code>.</p>
<p>In Node.js everything works fine, but TypeScript:</p>
<pre><code>import {Injector} from '@ts-stack/di';
</code></pre>
<blockquote>
<p>Could not find a declaration file for module '@ts-stack/di'. '/path/to/node_modules/@ts-stack/di/dist/index.js' implicitly has an 'any' type.</p>
</blockquote>
<p>And yet, if I import as follows, then everything works:</p>
<pre><code>import {Injector} from '/path/to/node_modules/@ts-stack/di/dist/index.js';
</code></pre>
<p>What am I doing wrong?</p> | <h3>For the situation where you are installing your own npm package</h3>
<p>If you're using a third party package, see <a href="https://stackoverflow.com/a/42505940/1716560">my answer below</a>.</p>
<p>Remove <code>.js</code> from <code>"main": "dist/index.js"</code> in <code>package.json</code>.</p>
<pre class="lang-json prettyprint-override"><code>"main": "dist/index",
</code></pre>
<p>Also add <a href="https://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html" rel="noreferrer"><code>typings</code> in <code>package.json</code> per the TypeScript docs</a>:</p>
<pre class="lang-json prettyprint-override"><code>"main": "dist/index",
"typings": "dist/index",
</code></pre>
<p>The folder <code>dist</code> is where the TS compiler stores your module's files.</p> | {
"question_id": 41292559,
"question_date": "2016-12-22T22:28:24.240Z",
"question_score": 755,
"tags": "typescript|node-modules",
"answer_id": 41307319,
"answer_date": "2016-12-23T20:09:54.290Z",
"answer_score": 157
} |
Please answer the following Stack Overflow question:
Title: How do I pass variables and data from PHP to JavaScript?
<p>I have a variable in PHP, and I need its value in my JavaScript code. How can I get my variable from PHP to JavaScript?</p>
<p>I have code that looks like this:</p>
<pre class="lang-php prettyprint-override"><code><?php
$val = $myService->getValue(); // Makes an API and database call
</code></pre>
<p>On the same page, I have JavaScript code that needs the value of the <code>$val</code> variable to be passed as a parameter:</p>
<pre class="lang-js prettyprint-override"><code><script>
myPlugin.start($val); // I tried this, but it didn't work
<?php myPlugin.start($val); ?> // This didn't work either
myPlugin.start(<?=$val?>); // This works sometimes, but sometimes it fails
</script>
</code></pre> | <p>There are actually several approaches to do this. Some require more overhead than others, and some are considered better than others.</p>
<p>In no particular order:</p>
<ol>
<li>Use AJAX to get the data you need from the server.</li>
<li>Echo the data into the page somewhere, and use JavaScript to get the information from the DOM.</li>
<li>Echo the data directly to JavaScript.</li>
</ol>
<p>In this post, we'll examine each of the above methods, and see the pros and cons of each, as well as how to implement them.</p>
<h1>1. Use AJAX to get the data you need from the server</h1>
<p>This method is considered the best, because <strong>your server side and client side scripts are completely separate</strong>.</p>
<h3>Pros</h3>
<ul>
<li><strong>Better separation between layers</strong> - If tomorrow you stop using PHP, and want to move to a servlet, a REST API, or some other service, you don't have to change much of the JavaScript code.</li>
<li><strong>More readable</strong> - JavaScript is JavaScript, PHP is PHP. Without mixing the two, you get more readable code on both languages.</li>
<li><strong>Allows for asynchronous data transfer</strong> - Getting the information from PHP might be time/resources expensive. Sometimes you just don't want to wait for the information, load the page, and have the information reach whenever.</li>
<li><strong>Data is not directly found on the markup</strong> - This means that your markup is kept clean of any additional data, and only JavaScript sees it.</li>
</ul>
<h3>Cons</h3>
<ul>
<li><strong>Latency</strong> - AJAX creates an HTTP request, and HTTP requests are carried over network and have network latencies.</li>
<li><strong>State</strong> - Data fetched via a separate HTTP request won't include any information from the HTTP request that fetched the HTML document. You may need this information (e.g., if the HTML document is generated in response to a form submission) and, if you do, will have to transfer it across somehow. If you have ruled out embedding the data in the page (which you have if you are using this technique) then that limits you to cookies/sessions which may be subject to race conditions.</li>
</ul>
<h2>Implementation Example</h2>
<p>With AJAX, you need two pages, one is where PHP generates the output, and the second is where JavaScript gets that output:</p>
<h3>get-data.php</h3>
<pre><code>/* Do some operation here, like talk to the database, the file-session
* The world beyond, limbo, the city of shimmers, and Canada.
*
* AJAX generally uses strings, but you can output JSON, HTML and XML as well.
* It all depends on the Content-type header that you send with your AJAX
* request. */
echo json_encode(42); // In the end, you need to <strong>echo</strong> the result.
// All data should be <em>json_encode()</em>d.
// You can json_encode() any value in PHP, arrays, strings,
//even objects.
</code></pre>
<h3>index.php (or whatever the actual page is named like)</h3>
<pre><code><!-- snip -->
<script>
function reqListener () {
console.log(this.responseText);
}
var oReq = new XMLHttpRequest(); // New request object
oReq.onload = function() {
// This is where you handle what to do with the response.
// The actual data is found on this.responseText
alert(this.responseText); // Will alert: 42
};
oReq.open("get", "get-data.php", true);
// ^ Don't block the rest of the execution.
// Don't wait until the request finishes to
// continue.
oReq.send();
</script>
<!-- snip -->
</code></pre>
<p>The above combination of the two files will alert <code>42</code> when the file finishes loading.</p>
<h2>Some more reading material</h2>
<ul>
<li><strong><a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest" rel="noreferrer">Using XMLHttpRequest - MDN</a></strong></li>
<li><strong><a href="https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest" rel="noreferrer">XMLHttpRequest object reference - MDN</a></strong></li>
<li><strong><a href="https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call">How do I return the response from an asynchronous call?</a></strong></li>
</ul>
<h1>2. Echo the data into the page somewhere, and use JavaScript to get the information from the DOM</h1>
<p>This method is less preferable to AJAX, but it still has its advantages. It's still <em>relatively</em> separated between PHP and JavaScript in a sense that there is no PHP directly in the JavaScript.</p>
<h3>Pros</h3>
<ul>
<li><strong>Fast</strong> - DOM operations are often quick, and you can store and access a lot of data relatively quickly.</li>
</ul>
<h3>Cons</h3>
<ul>
<li><strong>Potentially Unsemantic Markup</strong> - Usually, what happens is that you use some sort of <code><input type=hidden></code> to store the information, because it's easier to get the information out of <code>inputNode.value</code>, but doing so means that you have a meaningless element in your HTML. HTML has the <code><meta></code> element for data about the document, and HTML 5 introduces <code>data-*</code> attributes for data specifically for reading with JavaScript that can be associated with particular elements.</li>
<li><strong>Dirties up the Source</strong> - Data that PHP generates is outputted directly to the HTML source, meaning that you get a bigger and less focused HTML source.</li>
<li><strong>Harder to get structured data</strong> - Structured data will have to be valid HTML, otherwise you'll have to escape and convert strings yourself.</li>
<li><strong>Tightly couples PHP to your data logic</strong> - Because PHP is used in presentation, you can't separate the two cleanly.</li>
</ul>
<h2>Implementation Example</h2>
<p>With this, the idea is to create some sort of element which will not be displayed to the user, but is visible to JavaScript.</p>
<h3>index.php</h3>
<pre><code><!-- snip -->
<div id="dom-target" style="display: none;">
<?php
$output = "42"; // Again, do some operation, get the output.
echo htmlspecialchars($output); /* You have to escape because the result
will not be valid HTML otherwise. */
?>
</div>
<script>
var div = document.getElementById("dom-target");
var myData = div.textContent;
</script>
<!-- snip -->
</code></pre>
<h1>3. Echo the data directly to JavaScript</h1>
<p>This is probably the easiest to understand.</p>
<h3>Pros</h3>
<ul>
<li><strong>Very easily implemented</strong> - It takes very little to implement this, and understand.</li>
<li><strong>Does not dirty source</strong> - Variables are outputted directly to JavaScript, so the DOM is not affected.</li>
</ul>
<h3>Cons</h3>
<ul>
<li><strong>Tightly couples PHP to your data logic</strong> - Because PHP is used in presentation, you can't separate the two cleanly.</li>
</ul>
<h2>Implementation Example</h2>
<p>Implementation is relatively straightforward:</p>
<pre><code><!-- snip -->
<script>
var data = <?php echo json_encode("42", JSON_HEX_TAG); ?>; // Don't forget the extra semicolon!
</script>
<!-- snip -->
</code></pre>
<p>Good luck!</p> | {
"question_id": 23740548,
"question_date": "2014-05-19T14:37:56.930Z",
"question_score": 755,
"tags": "javascript|php",
"answer_id": 23740549,
"answer_date": "2014-05-19T14:37:56.930Z",
"answer_score": 1003
} |
Please answer the following Stack Overflow question:
Title: How to serve static files in Flask
<p>So this is embarrassing. I've got an application that I threw together in <code>Flask</code> and for now it is just serving up a single static HTML page with some links to CSS and JS. And I can't find where in the documentation <code>Flask</code> describes returning static files. Yes, I could use <code>render_template</code> but I know the data is not templatized. I'd have thought <code>send_file</code> or <code>url_for</code> was the right thing, but I could not get those to work. In the meantime, I am opening the files, reading content, and rigging up a <code>Response</code> with appropriate mimetype:</p>
<pre><code>import os.path
from flask import Flask, Response
app = Flask(__name__)
app.config.from_object(__name__)
def root_dir(): # pragma: no cover
return os.path.abspath(os.path.dirname(__file__))
def get_file(filename): # pragma: no cover
try:
src = os.path.join(root_dir(), filename)
# Figure out how flask returns static files
# Tried:
# - render_template
# - send_file
# This should not be so non-obvious
return open(src).read()
except IOError as exc:
return str(exc)
@app.route('/', methods=['GET'])
def metrics(): # pragma: no cover
content = get_file('jenkins_analytics.html')
return Response(content, mimetype="text/html")
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def get_resource(path): # pragma: no cover
mimetypes = {
".css": "text/css",
".html": "text/html",
".js": "application/javascript",
}
complete_path = os.path.join(root_dir(), path)
ext = os.path.splitext(path)[1]
mimetype = mimetypes.get(ext, "text/html")
content = get_file(complete_path)
return Response(content, mimetype=mimetype)
if __name__ == '__main__': # pragma: no cover
app.run(port=80)
</code></pre>
<p>Someone want to give a code sample or url for this? I know this is going to be dead simple.</p> | <p>In production, configure the HTTP server (Nginx, Apache, etc.) in front of your application to serve requests to <code>/static</code> from the static folder. A dedicated web server is very good at serving static files efficiently, although you probably won't notice a difference compared to Flask at low volumes.</p>
<p>Flask automatically creates a <code>/static/<path:filename></code> route that will serve any <code>filename</code> under the <code>static</code> folder next to the Python module that defines your Flask app. Use <code>url_for</code> to link to static files: <code>url_for('static', filename='js/analytics.js')</code></p>
<p>You can also use <a href="http://flask.palletsprojects.com/api/#flask.send_from_directory" rel="noreferrer"><code>send_from_directory</code></a> to serve files from a directory in your own route. This takes a base directory and a path, and ensures that the path is contained in the directory, which makes it safe to accept user-provided paths. This can be useful in cases where you want to check something before serving the file, such as if the logged in user has permission.</p>
<pre><code>from flask import send_from_directory
@app.route('/reports/<path:path>')
def send_report(path):
return send_from_directory('reports', path)
</code></pre>
<p>Do <strong>not</strong> use <code>send_file</code> or <code>send_static_file</code> with a user-supplied path. This will expose you to <a href="https://en.m.wikipedia.org/wiki/Directory_traversal_attack" rel="noreferrer">directory traversal attacks</a>. <code>send_from_directory</code> was designed to safely handle user-supplied paths under a known directory, and will raise an error if the path attempts to escape the directory.</p>
<p>If you are generating a file in memory without writing it to the filesystem, you can pass a <code>BytesIO</code> object to <a href="http://flask.palletsprojects.com/api/#flask.send_file" rel="noreferrer"><code>send_file</code></a> to serve it like a file. You'll need to pass other arguments to <code>send_file</code> in this case since it can't infer things like the file name or content type.</p> | {
"question_id": 20646822,
"question_date": "2013-12-17T23:31:02.503Z",
"question_score": 755,
"tags": "python|flask|static-files",
"answer_id": 20648053,
"answer_date": "2013-12-18T01:25:40.600Z",
"answer_score": 863
} |
Please answer the following Stack Overflow question:
Title: Automatic exit from Bash shell script on error
<p>I've been writing some shell script and I would find it useful if there was the ability to halt the execution of said shell script if any of the commands failed. See below for an example:</p>
<pre><code>#!/bin/bash
cd some_dir
./configure --some-flags
make
make install
</code></pre>
<p>So in this case, if the script can't change to the indicated directory, then it would certainly not want to do a <em>./configure</em> afterwards if it fails.</p>
<p>Now I'm well aware that I could have an if check for each command (which I think is a hopeless solution), but is there a global setting to make the script exit if one of the commands fails?</p> | <p>Use the <a href="http://www.gnu.org/software/bash/manual/bashref.html#The-Set-Builtin" rel="noreferrer"><code>set -e</code></a> builtin:</p>
<pre><code>#!/bin/bash
set -e
# Any subsequent(*) commands which fail will cause the shell script to exit immediately
</code></pre>
<p>Alternatively, you can pass <code>-e</code> on the command line:</p>
<pre><code>bash -e my_script.sh
</code></pre>
<p>You can also <strong>disable</strong> this behavior with <code>set +e</code>.</p>
<p>You may also want to employ all or some of the the <code>-e</code> <code>-u</code> <code>-x</code> and <code>-o pipefail</code> options like so:</p>
<pre><code>set -euxo pipefail
</code></pre>
<p><code>-e</code> exits on error, <code>-u</code> errors on undefined variables, and <code>-o (for option) pipefail</code> exits on command pipe failures. Some gotchas and workarounds are documented well <a href="https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo_pipefail/" rel="noreferrer">here</a>.</p>
<p>(*) Note:</p>
<blockquote>
<p>The shell does <em>not</em> exit if the command that fails is part of the
command list immediately following a <strong>while</strong> or <strong>until</strong> keyword,
part of the test following the <strong>if</strong> or <strong>elif</strong> reserved words, part
of any command executed in a <strong>&&</strong> or <strong>||</strong> list except the command
following the final <strong>&&</strong> or <strong>||</strong>, any command in a pipeline but
the last, or if the command's return value is being inverted with
<strong>!</strong></p>
</blockquote>
<p>(from <code>man bash</code>)</p> | {
"question_id": 2870992,
"question_date": "2010-05-20T04:21:53.670Z",
"question_score": 755,
"tags": "bash|shell|error-handling|exit",
"answer_id": 2871034,
"answer_date": "2010-05-20T04:36:01.670Z",
"answer_score": 1202
} |
Please answer the following Stack Overflow question:
Title: Pull request vs Merge request
<p>What is the difference between a Pull request and a Merge request?</p>
<p>In GitHub, it's a Pull Request while in GitLab, for example, it's a Merge Request. So, is there a difference between both of these?</p> | <p>GitLab's <a href="http://doc.gitlab.com/ce/api/merge_requests.html">"merge request"</a> feature is equivalent to GitHub's <a href="https://help.github.com/articles/using-pull-requests/">"pull request"</a> feature. Both are means of pulling changes from another branch or fork into your branch and merging the changes with your existing code. They are useful tools for code review and change management.</p>
<p>An <a href="https://about.gitlab.com/2014/09/29/gitlab-flow/">article from GitLab</a> discusses the differences in naming the feature:</p>
<blockquote>
<p>Merge or pull requests are created in a git management application and ask an assigned person to merge two branches. Tools such as GitHub and Bitbucket choose the name pull request since the first manual action would be to pull the feature branch. Tools such as GitLab and Gitorious choose the name merge request since that is the final action that is requested of the assignee. In this article we'll refer to them as merge requests.</p>
</blockquote>
<p>A "merge request" should not be confused with the <a href="http://git-scm.com/docs/git-merge"><code>git merge</code></a> command. Neither should a "pull request" be confused with the <a href="http://git-scm.com/docs/git-pull"><code>git pull</code></a> command. Both <code>git</code> commands are used behind the scenes in both pull requests and merge requests, but a merge/pull request refers to a much broader topic than just these two commands.</p> | {
"question_id": 22199432,
"question_date": "2014-03-05T13:39:16.757Z",
"question_score": 755,
"tags": "git|github|gitlab",
"answer_id": 29951658,
"answer_date": "2015-04-29T18:28:04.197Z",
"answer_score": 1171
} |
Please answer the following Stack Overflow question:
Title: IntelliJ: Never use wildcard imports
<p>Is there a way to tell IntelliJ never to use wildcard imports?
Under 'Settings > Code Style > Imports', I can see that you can specify the 'class count' prior to IntelliJ using wildcard imports. However, if I never want to use wildcard imports can I turn this functionality off? </p>
<p>I have tried putting -1 or leaving the field blank but that just tells IntelliJ to always use wildcard imports. Obviously a not-so-nice solution would be to put a ridiculously high number so that you never encounter wildcard imports but I was hoping there was a nicer way to just turn it off.</p> | <p>It's obvious why you'd want to disable this: To force IntelliJ to include each and every import individually. It makes it easier for people to figure out exactly where classes you're using come from.</p>
<p>Click on the Settings "wrench" icon on the toolbar, open "Imports" under "Code Style", and check the "Use single class import" selection. You can also completely remove entries under "Packages to use import with <code>*</code>", or specify a threshold value that only uses the "<code>*</code>" when the individual classes from a package exceeds that threshold.</p>
<p><strong>Update:</strong> in IDEA 13 "Use single class import" does not prevent wildcard imports. The solution is to go to <code>Preferences</code> (<kbd>⌘</kbd> + <kbd>,</kbd> on macOS / <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>S</kbd> on Windows and Linux) <code>> Editor > Code Style > Java > Imports tab</code> set <code>Class count to use import with '*'</code> and <code>Names count to use static import with '*'</code> to a higher value. Any value over 99 seems to work fine.</p> | {
"question_id": 3348816,
"question_date": "2010-07-27T23:36:33.903Z",
"question_score": 755,
"tags": "java|intellij-idea|settings",
"answer_id": 3348855,
"answer_date": "2010-07-27T23:45:12.333Z",
"answer_score": 1031
} |
Please answer the following Stack Overflow question:
Title: Hide strange unwanted Xcode logs
<p>When using the Xcode 8+ and creating a new blank project, the following logs appear when running the application:</p>
<pre><code>2016-06-13 16:33:34.406093 TestiOS10[8209:100611] bundleid: com.appc.TestiOS10, enable_level: 0, persist_level: 0, propagate_with_activity: 0
2016-06-13 16:33:34.406323 TestiOS10[8209:100607] Created DB, header sequence number = 248
2016-06-13 16:33:34.409564 TestiOS10[8209:100611] subsystem: com.apple.UIKit, category: HIDEvents, enable_level: 0, persist_level: 0, default_ttl: 0, info_ttl: 0, debug_ttl: 0, generate_symptoms: 0, enable_oversize: 0, privacy_setting: 0
2016-06-13 16:33:34.504117 TestiOS10[8209:100607] Created DB, header sequence number = 248
2016-06-13 16:33:34.548023 TestiOS10[8209:100607] subsystem: com.apple.BaseBoard, category: MachPort, enable_level: 0, persist_level: 0, default_ttl: 0, info_ttl: 0, debug_ttl: 0, generate_symptoms: 0, enable_oversize: 0, privacy_setting: 0
2016-06-13 16:33:34.568458 TestiOS10[8209:100608] subsystem: com.apple.FrontBoard, category: Common, enable_level: 0, persist_level: 0, default_ttl: 0, info_ttl: 0, debug_ttl: 0, generate_symptoms: 0, enable_oversize: 0, privacy_setting: 0
</code></pre>
<p>Maybe someone already found a configuration for this to handle?</p> | <p>Try this:</p>
<p>1 - From <strong>Xcode menu</strong> open: <code>Product</code> > <code>Scheme</code> > <code>Edit Scheme</code></p>
<p>2 - On your <strong>Environment Variables</strong> set <code>OS_ACTIVITY_MODE</code> = <code>disable</code></p>
<p><a href="https://i.stack.imgur.com/p7BlV.png" rel="noreferrer"><img src="https://i.stack.imgur.com/p7BlV.png" alt="Screenshot" /></a></p> | {
"question_id": 37800790,
"question_date": "2016-06-13T23:39:11.920Z",
"question_score": 755,
"tags": "ios|xcode|logging|xcode8|ios10",
"answer_id": 39461256,
"answer_date": "2016-09-13T02:11:47.247Z",
"answer_score": 1600
} |
Please answer the following Stack Overflow question:
Title: How to find out if an item is present in a std::vector?
<p>All I want to do is to check whether an element exists in the vector or not, so I can deal with each case.</p>
<pre><code>if ( item_present )
do_this();
else
do_that();
</code></pre> | <p>You can use <a href="http://en.cppreference.com/w/cpp/algorithm/find" rel="noreferrer"><code>std::find</code></a> from <code><algorithm></code>:</p>
<pre><code>#include <algorithm>
#include <vector>
vector<int> vec;
//can have other data types instead of int but must same datatype as item
std::find(vec.begin(), vec.end(), item) != vec.end()
</code></pre>
<p>This returns an iterator to the first element found. If not present, it returns an iterator to one-past-the-end. With your example:</p>
<pre><code>#include <algorithm>
#include <vector>
if ( std::find(vec.begin(), vec.end(), item) != vec.end() )
do_this();
else
do_that();
</code></pre> | {
"question_id": 571394,
"question_date": "2009-02-20T21:58:41.557Z",
"question_score": 754,
"tags": "c++|vector|std",
"answer_id": 571405,
"answer_date": "2009-02-20T22:00:50.537Z",
"answer_score": 1117
} |
Please answer the following Stack Overflow question:
Title: wget command to download a file and save as a different filename
<p>I am downloading a file using the <code>wget</code> command. But when it downloads to my local machine, I want it to be saved as a different filename.</p>
<p>For example: I am downloading a file from <code>www.examplesite.com/textfile.txt</code></p>
<p>I want to use <code>wget</code> to save the file <code>textfile.txt</code> on my local directory as <code>newfile.txt</code>. I am using the <code>wget</code> command as follows:</p>
<pre><code>wget www.examplesite.com/textfile.txt
</code></pre> | <p>Use the <code>-O file</code> option. </p>
<p>E.g.</p>
<pre><code>wget google.com
...
16:07:52 (538.47 MB/s) - `index.html' saved [10728]
</code></pre>
<p>vs.</p>
<pre><code>wget -O foo.html google.com
...
16:08:00 (1.57 MB/s) - `foo.html' saved [10728]
</code></pre> | {
"question_id": 16678487,
"question_date": "2013-05-21T20:01:54.030Z",
"question_score": 754,
"tags": "download|wget",
"answer_id": 16678611,
"answer_date": "2013-05-21T20:09:05.123Z",
"answer_score": 1109
} |
Please answer the following Stack Overflow question:
Title: Check if a user has scrolled to the bottom (not just the window, but any element)
<p>I'm making a pagination system (sort of like Facebook) where the content loads when the user scrolls to the bottom. I imagine the best way to do that is to find when the user is at the bottom of the page and run an Ajax query to load more posts.</p>
<p>The only problem is I don't know how to check if the user has scrolled to the bottom of the page. Any ideas?</p>
<p>I'm using jQuery, so feel free to provide answers that use it.</p> | <p>Use the <a href="http://api.jquery.com/scroll/" rel="noreferrer"><code>.scroll()</code></a> event on <code>window</code>, like this:</p>
<pre><code>$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
alert("bottom!");
}
});
</code></pre>
<p><a href="http://jsfiddle.net/nick_craver/gWD66/" rel="noreferrer">You can test it here</a>, this takes the top scroll of the window, so how much it's scrolled down, adds the height of the visible window and checks if that equals the height of the overall content (<code>document</code>). If you wanted to instead check if the user is <em>near</em> the bottom, it'd look something like this:</p>
<pre><code>$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
alert("near bottom!");
}
});
</code></pre>
<p><a href="http://jsfiddle.net/nick_craver/gWD66/1/" rel="noreferrer">You can test that version here</a>, just adjust that <code>100</code> to whatever pixel from the bottom you want to trigger on.</p> | {
"question_id": 3898130,
"question_date": "2010-10-09T22:28:45.167Z",
"question_score": 754,
"tags": "javascript|jquery|scroll|pagination",
"answer_id": 3898152,
"answer_date": "2010-10-09T22:34:02.320Z",
"answer_score": 1101
} |
Please answer the following Stack Overflow question:
Title: Does a "Find in project..." feature exist in Eclipse IDE?
<p>Does Eclipse have a way to search a whole project for some text like Xcode's "find in project" feature?</p> | <p>1. <kbd>Ctrl</kbd> + <kbd>H</kbd> <BR>
2. Choose <strong>File Search</strong> for plain text search in workspace/selected projects <BR></p>
<p><em>For specific expression searches, choose the relevant tab (such as Java Search which allows you to search for specific identifiers)</em></p>
<p>For whole project search:</p>
<p>3. Scope (in the form section) > Enclosing project (Radio button selection).</p> | {
"question_id": 3175035,
"question_date": "2010-07-04T14:51:14.203Z",
"question_score": 754,
"tags": "eclipse|find",
"answer_id": 3175051,
"answer_date": "2010-07-04T14:56:13.257Z",
"answer_score": 962
} |
Please answer the following Stack Overflow question:
Title: Which exception should I raise on bad/illegal argument combinations in Python?
<p>I was wondering about the best practices for indicating invalid argument combinations in Python. I've come across a few situations where you have a function like so:</p>
<pre><code>def import_to_orm(name, save=False, recurse=False):
"""
:param name: Name of some external entity to import.
:param save: Save the ORM object before returning.
:param recurse: Attempt to import associated objects as well. Because you
need the original object to have a key to relate to, save must be
`True` for recurse to be `True`.
:raise BadValueError: If `recurse and not save`.
:return: The ORM object.
"""
pass
</code></pre>
<p>The only annoyance with this is that every package has its own, usually slightly differing <code>BadValueError</code>. I know that in Java there exists <code>java.lang.IllegalArgumentException</code> -- is it well understood that everybody will be creating their own <code>BadValueError</code>s in Python or is there another, preferred method?</p> | <p>I would just raise <a href="https://docs.python.org/3/library/exceptions.html#ValueError" rel="noreferrer">ValueError</a>, unless you need a more specific exception..</p>
<pre><code>def import_to_orm(name, save=False, recurse=False):
if recurse and not save:
raise ValueError("save must be True if recurse is True")
</code></pre>
<p>There's really no point in doing <code>class BadValueError(ValueError):pass</code> - your custom class is identical in use to <a href="https://docs.python.org/3/library/exceptions.html#ValueError" rel="noreferrer">ValueError</a>, so why not use that?</p> | {
"question_id": 256222,
"question_date": "2008-11-01T23:02:36.767Z",
"question_score": 754,
"tags": "python|exception|arguments",
"answer_id": 256260,
"answer_date": "2008-11-01T23:37:31.643Z",
"answer_score": 825
} |
Please answer the following Stack Overflow question:
Title: Getting started with Haskell
<p>For a few days I've tried to wrap my head around the functional programming paradigm in Haskell. I've done this by reading tutorials and watching screencasts, but nothing really seems to stick.
Now, in learning various imperative/OO languages (like C, Java, PHP), exercises have been a good way for me to go. But since I don't really know what Haskell is capable of and because there are many new concepts to utilize, I haven't known where to start.</p>
<p>So, how did you learn Haskell? What made you really "break the ice"? Also, any good ideas for beginning exercises?</p> | <p>I'm going to order this guide by the level of skill you have in Haskell, going from an absolute beginner right up to an expert. Note that this process will take many months (years?), so it is rather long.</p>
<p><strong>Absolute Beginner</strong></p>
<p>Firstly, Haskell is capable of anything, with enough skill. It is very fast (behind only C and C++ in my experience), and can be used for anything from simulations to servers, guis and web applications.</p>
<p>However there are some problems that are easier to write for a beginner in Haskell than others. Mathematical problems and list process programs are good candidates for this, as they only require the most basic of Haskell knowledge to be able to write.</p>
<p>Some good guides to learning the very basics of Haskell are the <a href="http://www.happylearnhaskelltutorial.com" rel="noreferrer">Happy Learn Haskell Tutorial</a> and the first 6 chapters of <a href="http://learnyouahaskell.com/" rel="noreferrer">Learn You a Haskell for Great Good</a> (or its <a href="https://github.com/jamesdbrock/learn-you-a-haskell-notebook" rel="noreferrer">JupyterLab adaptation</a>). While reading these, it is a very good idea to also be solving simple problems with what you know.</p>
<p>Another two good resources are <a href="http://haskellbook.com/" rel="noreferrer">Haskell Programming from first principles</a>, and <a href="http://www.cs.nott.ac.uk/%7Epszgmh/pih.html" rel="noreferrer">Programming in Haskell</a>. They both come with exercises for each chapter, so you have small simple problems matching what you learned on the last few pages.</p>
<p>A good list of problems to try is the <a href="https://wiki.haskell.org/H-99:_Ninety-Nine_Haskell_Problems" rel="noreferrer">haskell 99 problems page</a>. These start off very basic, and get more difficult as you go on. It is very good practice doing a lot of those, as they let you practice your skills in recursion and higher order functions. I would recommend skipping any problems that require randomness as that is a bit more difficult in Haskell. Check <a href="https://stackoverflow.com/questions/5683911/simple-haskell-unit-testing">this SO question</a> in case you want to test your solutions with QuickCheck (see <em>Intermediate</em> below).</p>
<p>Once you have done a few of those, you could move on to doing a few of the <a href="http://projecteuler.net/index.php?section=problems" rel="noreferrer">Project Euler</a> problems. These are sorted by how many people have completed them, which is a fairly good indication of difficulty. These test your logic and Haskell more than the previous problems, but you should still be able to do the first few. A big advantage Haskell has with these problems is Integers aren't limited in size. To complete some of these problems, it will be useful to have read chapters 7 and 8 of learn you a Haskell as well.</p>
<p><strong>Beginner</strong></p>
<p>After that you should have a fairly good handle on recursion and higher order functions, so it would be a good time to start doing some more real world problems. A very good place to start is <a href="http://book.realworldhaskell.org/" rel="noreferrer">Real World Haskell</a> (online book, you can also purchase a hard copy). I found the first few chapters introduced too much too quickly for someone who has never done functional programming/used recursion before. However with the practice you would have had from doing the previous problems you should find it perfectly understandable.</p>
<p>Working through the problems in the book is a great way of learning how to manage abstractions and building reusable components in Haskell. This is vital for people used to object-orientated (oo) programming, as the normal oo abstraction methods (oo classes) don't appear in Haskell (Haskell has type classes, but they are very different to oo classes, more like oo interfaces). I don't think it is a good idea to skip chapters, as each introduces a lot new ideas that are used in later chapters.</p>
<p>After a while you will get to chapter 14, the dreaded monads chapter (dum dum dummmm). Almost everyone who learns Haskell has trouble understanding monads, due to how abstract the concept is. I can't think of any concept in another language that is as abstract as monads are in functional programming. Monads allows many ideas (such as IO operations, computations that might fail, parsing,...) to be unified under one idea. So don't feel discouraged if after reading the monads chapter you don't really understand them. I found it useful to read many different explanations of monads; each one gives a new perspective on the problem. Here is a very good <a href="https://wiki.haskell.org/Tutorials#Using_monads" rel="noreferrer">list of monad tutorials</a>. I highly recommend the <a href="https://wiki.haskell.org/All_About_Monads" rel="noreferrer">All About Monads</a>, but the others are also good.</p>
<p>Also, it takes a while for the concepts to truly sink in. This comes through use, but also through time. I find that sometimes sleeping on a problem helps more than anything else! Eventually, the idea will click, and you will wonder why you struggled to understand a concept that in reality is incredibly simple. It is awesome when this happens, and when it does, you might find Haskell to be your favorite imperative programming language :)</p>
<p>To make sure that you are understanding Haskell type system perfectly, you should try to solve <a href="http://blog.tmorris.net/posts/20-intermediate-haskell-exercises/" rel="noreferrer">20 intermediate haskell exercises</a>. Those exercises using fun names of functions like "furry" and "banana" and helps you to have a good understanding of some basic functional programming concepts if you don't have them already. Nice way to spend your evening with a bunch of papers covered with arrows, unicorns, sausages and furry bananas.</p>
<p><strong>Intermediate</strong></p>
<p>Once you understand Monads, I think you have made the transition from a beginner Haskell programmer to an intermediate haskeller. So where to go from here? The first thing I would recommend (if you haven't already learnt them from learning monads) is the various types of monads, such as Reader, Writer and State. Again, Real world Haskell and All about monads gives great coverage of this. To complete your monad training learning about monad transformers is a must. These let you combine different types of Monads (such as a Reader and State monad) into one. This may seem useless to begin with, but after using them for a while you will wonder how you lived without them.</p>
<p>Now you can finish the real world Haskell book if you want. Skipping chapters now doesn't really matter, as long as you have monads down pat. Just choose what you are interested in.</p>
<p>With the knowledge you would have now, you should be able to use most of the packages on cabal (well the documented ones at least...), as well as most of the libraries that come with Haskell. A list of interesting libraries to try would be:</p>
<ul>
<li><p><a href="https://wiki.haskell.org/Parsec" rel="noreferrer">Parsec</a>: for parsing programs and text. Much better than using regexps. Excellent documentation, also has a real world Haskell chapter.</p>
</li>
<li><p><a href="http://www.cse.chalmers.se/%7Erjmh/QuickCheck/" rel="noreferrer">QuickCheck</a>: A very cool testing program. What you do is write a predicate that should always be true (eg <code>length (reverse lst) == length lst</code>). You then pass the predicate the QuickCheck, and it will generate a lot of random values (in this case lists) and test that the predicate is true for all results. See also the <a href="http://www.cse.chalmers.se/%7Erjmh/QuickCheck/manual.html" rel="noreferrer">online manual</a>.</p>
</li>
<li><p><a href="http://hunit.sourceforge.net/" rel="noreferrer">HUnit</a>: Unit testing in Haskell.</p>
</li>
<li><p><a href="http://projects.haskell.org/gtk2hs/" rel="noreferrer">gtk2hs</a>: The most popular gui framework for Haskell, lets you write gtk applications.</p>
</li>
<li><p><a href="http://happstack.com/" rel="noreferrer">happstack</a>: A web development framework for Haskell. Doesn't use databases, instead a data type store. Pretty good docs (other popular frameworks would be <a href="http://snapframework.com/" rel="noreferrer">snap</a> and <a href="http://www.yesodweb.com/" rel="noreferrer">yesod</a>).</p>
</li>
</ul>
<p>Also, there are many concepts (like the Monad concept) that you should eventually learn. This will be easier than learning Monads the first time, as your brain will be used to dealing with the level of abstraction involved. A very good overview for learning about these high level concepts and how they fit together is the <a href="http://www.haskell.org/haskellwiki/Typeclassopedia" rel="noreferrer">Typeclassopedia</a>.</p>
<ul>
<li><p>Applicative: An interface like Monads, but less powerful. Every Monad is Applicative, but not vice versa. This is useful as there are some types that are Applicative but are not Monads. Also, code written using the Applicative functions is often more composable than writing the equivalent code using the Monad functions. See <a href="http://learnyouahaskell.com/functors-applicative-functors-and-monoids#functors-redux" rel="noreferrer">Functors, Applicative Functors and Monoids</a> from the learn you a haskell guide.</p>
</li>
<li><p><a href="http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-Foldable.html" rel="noreferrer">Foldable</a>,<a href="http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-Traversable.html" rel="noreferrer">Traversable</a>: Typeclasses that abstract many of the operations of lists, so that the same functions can be applied to other container types. See also the <a href="https://wiki.haskell.org/Foldable_and_Traversable" rel="noreferrer">haskell wiki explanation</a>.</p>
</li>
<li><p><a href="https://wiki.haskell.org/Monoid" rel="noreferrer">Monoid</a>: A Monoid is a type that has a zero (or mempty) value, and an operation, notated <code><></code> that joins two Monoids together, such that <code>x <> mempty = mempty <> x = x</code> and <code>x <> (y <> z) = (x <> y) <> z</code>. These are called identity and associativity laws. Many types are Monoids, such as numbers, with <code>mempty = 0</code> and <code><> = +</code>. This is useful in many situations.</p>
</li>
<li><p><a href="http://www.haskell.org/arrows/" rel="noreferrer">Arrows</a>: Arrows are a way of representing computations that take an input and return an output. A function is the most basic type of arrow, but there are many other types. The library also has many very useful functions for manipulating arrows - they are very useful even if only used with plain old Haskell functions.</p>
</li>
<li><p><a href="https://wiki.haskell.org/Modern_array_libraries" rel="noreferrer">Arrays</a>: the various mutable/immutable arrays in Haskell.</p>
</li>
<li><p><a href="https://wiki.haskell.org/Monad/ST" rel="noreferrer">ST Monad</a>: lets you write code with a mutable state that runs very quickly, while still remaining pure outside the monad. See the link for more details.</p>
</li>
<li><p>FRP: Functional Reactive Programming, a new, experimental way of writing code that handles events, triggers, inputs and outputs (such as a gui). I don't know much about this though. <a href="http://vimeo.com/96744621" rel="noreferrer">Paul Hudak's talk about yampa</a> is a good start.</p>
</li>
</ul>
<p>There are a lot of new language features you should have a look at. I'll just list them, you can find lots of info about them from google, the <a href="http://en.wikibooks.org/wiki/Haskell" rel="noreferrer">haskell wikibook</a>, the haskellwiki.org site and <a href="https://wiki.haskell.org/GHC" rel="noreferrer">ghc documentation</a>.</p>
<ul>
<li>Multiparameter type classes/functional dependencies</li>
<li>Type families</li>
<li>Existentially quantified types</li>
<li>Phantom types</li>
<li>GADTS</li>
<li>others...</li>
</ul>
<p>A lot of Haskell is based around <a href="http://en.wikipedia.org/wiki/Category_theory" rel="noreferrer">category theory</a>, so you may want to look into that. A good starting point is <a href="https://rads.stackoverflow.com/amzn/click/com/0262660717" rel="noreferrer" rel="nofollow noreferrer">Category Theory for Computer Scientist</a>. If you don't want to buy the book, the author's related <a href="http://repository.cmu.edu/cgi/viewcontent.cgi?article=2846&context=compsci" rel="noreferrer">article</a> is also excellent.</p>
<p>Finally you will want to learn more about the various Haskell tools. These include:</p>
<ul>
<li><a href="https://wiki.haskell.org/GHC" rel="noreferrer">ghc</a> (and all its features)</li>
<li><a href="http://www.haskell.org/cabal/" rel="noreferrer">cabal</a>: the Haskell package system</li>
<li><a href="http://darcs.net/" rel="noreferrer">darcs</a>: a distributed version control system written in Haskell, very popular for Haskell programs.</li>
<li><a href="http://www.haskell.org/haddock/" rel="noreferrer">haddock</a>: a Haskell automatic documentation generator</li>
</ul>
<p>While learning all these new libraries and concepts, it is very useful to be writing a moderate-sized project in Haskell. It can be anything (e.g. a small game, data analyser, website, <a href="http://en.wikibooks.org/wiki/Write_Yourself_a_Scheme_in_48_Hours" rel="noreferrer">compiler</a>). Working on this will allow you to apply many of the things you are now learning. You stay at this level for ages (this is where I'm at).</p>
<p><strong>Expert</strong></p>
<p>It will take you years to get to this stage (hello from 2009!), but from here I'm guessing you start writing phd papers, new ghc extensions, and coming up with new abstractions.</p>
<p><strong>Getting Help</strong></p>
<p>Finally, while at any stage of learning, there are multiple places for getting information. These are:</p>
<ul>
<li>the #haskell irc channel</li>
<li>the <a href="https://wiki.haskell.org/Mailing_lists" rel="noreferrer">mailing lists</a>. These are worth signing up for just to read the discussions that take place - some are very interesting.</li>
<li>other places listed on the haskell.org home page</li>
</ul>
<p><strong>Conclusion</strong></p>
<p>Well this turned out longer than I expected... Anyway, I think it is a very good idea to become proficient in Haskell. It takes a long time, but that is mainly because you are learning a completely new way of thinking by doing so. It is not like learning Ruby after learning Java, but like learning Java after learning C. Also, I am finding that my object-orientated programming skills have improved as a result of learning Haskell, as I am seeing many new ways of abstracting ideas.</p> | {
"question_id": 1012573,
"question_date": "2009-06-18T13:17:11.043Z",
"question_score": 754,
"tags": "haskell|functional-programming",
"answer_id": 1016986,
"answer_date": "2009-06-19T08:57:11.467Z",
"answer_score": 2557
} |
Please answer the following Stack Overflow question:
Title: In plain English, what does "git reset" do?
<p>I have seen <a href="https://stackoverflow.com/questions/1634115/whats-the-difference-between-git-reset-hard-and-git-reset-merge">interesting posts</a> explaining subtleties about <code>git reset</code>.</p>
<p>Unfortunately, the more I read about it, the more it appears that I don't understand it fully. I come from a SVN background and Git is a whole new paradigm. I got mercurial easily, but Git is much more technical.</p>
<p>I think <code>git reset</code> is close to <code>hg revert</code>, but it seems there are differences.</p>
<p>So what exactly does <code>git reset</code> do? Please include detailed explanations about:</p>
<ul>
<li>the options <code>--hard</code>, <code>--soft</code> and <code>--merge</code>;</li>
<li>the strange notation you use with <code>HEAD</code> such as <code>HEAD^</code> and <code>HEAD~1</code>;</li>
<li>concrete use cases and work flows;</li>
<li>consequences on the working copy, the <code>HEAD</code> and your global stress level.</li>
</ul> | <p>In general, <code>git reset</code>'s function is to take the current branch and reset it to point somewhere else, and possibly bring the index and work tree along. More concretely, if your master branch (currently checked out) is like this:</p>
<pre><code>- A - B - C (HEAD, master)
</code></pre>
<p>and you realize you want master to point to B, not C, you will use <code>git reset B</code> to move it there:</p>
<pre><code>- A - B (HEAD, master) # - C is still here, but there's no branch pointing to it anymore
</code></pre>
<p>Digression: This is different from a checkout. If you'd run <code>git checkout B</code>, you'd get this:</p>
<pre><code>- A - B (HEAD) - C (master)
</code></pre>
<p>You've ended up in a detached HEAD state. <code>HEAD</code>, work tree, index all match <code>B</code>, but the master branch was left behind at <code>C</code>. If you make a new commit <code>D</code> at this point, you'll get this, which is probably not what you want:</p>
<pre><code>- A - B - C (master)
\
D (HEAD)
</code></pre>
<p>Remember, reset doesn't make commits, it just updates a branch (which is a pointer to a commit) to point to a different commit. The rest is just details of what happens to your index and work tree.</p>
<h1>Use cases</h1>
<p>I cover many of the main use cases for <code>git reset</code> within my descriptions of the various options in the next section. It can really be used for a wide variety of things; the common thread is that all of them involve resetting the branch, index, and/or work tree to point to/match a given commit. </p>
<h1>Things to be careful of</h1>
<ul>
<li><p><code>--hard</code> can cause you to really lose work. It modifies your work tree.</p></li>
<li><p><code>git reset [options] commit</code> can cause you to (sort of) lose commits. In the toy example above, we lost commit <code>C</code>. It's still in the repo, and you can find it by looking at <code>git reflog show HEAD</code> or <code>git reflog show master</code>, but it's not actually accessible from any branch anymore.</p></li>
<li><p>Git permanently deletes such commits after 30 days, but until then you can recover C by pointing a branch at it again (<code>git checkout C; git branch <new branch name></code>).</p></li>
</ul>
<h1>Arguments</h1>
<p>Paraphrasing the man page, most common usage is of the form <code>git reset [<commit>] [paths...]</code>, which will reset the given paths to their state from the given commit. If the paths aren't provided, the entire tree is reset, and if the commit isn't provided, it's taken to be HEAD (the current commit). This is a common pattern across git commands (e.g. checkout, diff, log, though the exact semantics vary), so it shouldn't be too surprising.</p>
<p>For example, <code>git reset other-branch path/to/foo</code> resets everything in path/to/foo to its state in other-branch, <code>git reset -- .</code> resets the current directory to its state in HEAD, and a simple <code>git reset</code> resets everything to its state in HEAD.</p>
<h1>The main work tree and index options</h1>
<p>There are four main options to control what happens to your work tree and index during the reset.</p>
<p>Remember, the index is git's "staging area" - it's where things go when you say <code>git add</code> in preparation to commit.</p>
<ul>
<li><p><code>--hard</code> makes everything match the commit you've reset to. This is the easiest to understand, probably. All of your local changes get clobbered. One primary use is blowing away your work but not switching commits: <code>git reset --hard</code> means <code>git reset --hard HEAD</code>, i.e. don't change the branch but get rid of all local changes. The other is simply moving a branch from one place to another, and keeping index/work tree in sync. <em>This is the one that can really make you lose work, because it modifies your work tree.</em> Be very very sure you want to throw away local work before you run any <code>reset --hard</code>.</p></li>
<li><p><code>--mixed</code> is the default, i.e. <code>git reset</code> means <code>git reset --mixed</code>. It resets the index, but not the work tree. This means all your files are intact, but any differences between the original commit and the one you reset to will show up as local modifications (or untracked files) with git status. Use this when you realize you made some bad commits, but you want to keep all the work you've done so you can fix it up and recommit. In order to commit, you'll have to add files to the index again (<code>git add ...</code>).</p></li>
<li><p><code>--soft</code> doesn't touch the index <em>or</em> work tree. All your files are intact as with <code>--mixed</code>, but all the changes show up as <code>changes to be committed</code> with git status (i.e. checked in in preparation for committing). Use this when you realize you've made some bad commits, but the work's all good - all you need to do is recommit it differently. The index is untouched, so you can commit immediately if you want - the resulting commit will have all the same content as where you were before you reset.</p></li>
<li><p><code>--merge</code> was added recently, and is intended to help you abort a failed merge. This is necessary because <code>git merge</code> will actually let you attempt a merge with a dirty work tree (one with local modifications) as long as those modifications are in files unaffected by the merge. <code>git reset --merge</code> resets the index (like <code>--mixed</code> - all changes show up as local modifications), and resets the files affected by the merge, but leaves the others alone. This will hopefully restore everything to how it was before the bad merge. You'll usually use it as <code>git reset --merge</code> (meaning <code>git reset --merge HEAD</code>) because you only want to reset away the merge, not actually move the branch. (<code>HEAD</code> hasn't been updated yet, since the merge failed)</p>
<p>To be more concrete, suppose you've modified files A and B, and you attempt to merge in a branch which modified files C and D. The merge fails for some reason, and you decide to abort it. You use <code>git reset --merge</code>. It brings C and D back to how they were in <code>HEAD</code>, but leaves your modifications to A and B alone, since they weren't part of the attempted merge.</p></li>
</ul>
<h1>Want to know more?</h1>
<p>I do think <code>man git reset</code> is really quite good for this - perhaps you do need a bit of a sense of the way git works for them to really sink in though. In particular, if you take the time to carefully read them, those tables detailing states of files in index and work tree for all the various options and cases are very very helpful. (But yes, they're very dense - they're conveying an awful lot of the above information in a very concise form.)</p>
<h1>Strange notation</h1>
<p>The "strange notation" (<code>HEAD^</code> and <code>HEAD~1</code>) you mention is simply a shorthand for specifying commits, without having to use a hash name like <code>3ebe3f6</code>. It's fully documented in the <a href="http://www.kernel.org/pub/software/scm/git/docs/git-rev-parse.html#_specifying_revisions" rel="noreferrer">"specifying revisions" section</a> of the man page for git-rev-parse, with lots of examples and related syntax. The caret and the tilde actually mean <a href="http://paulboxley.com/blog/2011/06/git-caret-and-tilde" rel="noreferrer">different things</a>:</p>
<ul>
<li><code>HEAD~</code> is short for <code>HEAD~1</code> and means the commit's first parent. <code>HEAD~2</code> means the commit's first parent's first parent. Think of <code>HEAD~n</code> as "n commits before HEAD" or "the nth generation ancestor of HEAD".</li>
<li><code>HEAD^</code> (or <code>HEAD^1</code>) also means the commit's first parent. <code>HEAD^2</code> means the commit's <em>second</em> parent. Remember, a normal merge commit has two parents - the first parent is the merged-into commit, and the second parent is the commit that was merged. In general, merges can actually have arbitrarily many parents (octopus merges).</li>
<li>The <code>^</code> and <code>~</code> operators can be strung together, as in <code>HEAD~3^2</code>, the second parent of the third-generation ancestor of <code>HEAD</code>, <code>HEAD^^2</code>, the second parent of the first parent of <code>HEAD</code>, or even <code>HEAD^^^</code>, which is equivalent to <code>HEAD~3</code>.</li>
</ul>
<p><img src="https://i.stack.imgur.com/J73jv.png" alt="caret and tilde"></p> | {
"question_id": 2530060,
"question_date": "2010-03-27T16:44:39.930Z",
"question_score": 754,
"tags": "git|reset",
"answer_id": 2530073,
"answer_date": "2010-03-27T16:48:14.477Z",
"answer_score": 1092
} |
Please answer the following Stack Overflow question:
Title: How do I compare two string variables in an 'if' statement in Bash?
<p>I'm trying to get an <code>if</code> statement to work in <a href="http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29" rel="noreferrer">Bash</a> (using <a href="http://en.wikipedia.org/wiki/Ubuntu_%28operating_system%29" rel="noreferrer">Ubuntu</a>):</p>
<pre><code>#!/bin/bash
s1="hi"
s2="hi"
if ["$s1" == "$s2"]
then
echo match
fi
</code></pre>
<p>I've tried various forms of the <code>if</code> statement, using <code>[["$s1" == "$s2"]]</code>, with and without quotes, using <code>=</code>, <code>==</code> and <code>-eq</code>, but I still get the following error:</p>
<blockquote>
<p>[hi: command not found</p>
</blockquote>
<p>I've looked at various sites and tutorials and copied those, but it doesn't work - what am I doing wrong?</p>
<p>Eventually, I want to say if <code>$s1</code> contains <code>$s2</code>, so how can I do that?</p>
<p>I did just work out the spaces bit... :/ How do I say <em>contains</em>?</p>
<p>I tried</p>
<pre><code>if [[ "$s1" == "*$s2*" ]]
</code></pre>
<p>but it didn't work.</p> | <p>For string equality comparison, use:</p>
<pre><code>if [[ "$s1" == "$s2" ]]
</code></pre>
<p>For string does NOT equal comparison, use:</p>
<pre><code>if [[ "$s1" != "$s2" ]]
</code></pre>
<p>For the <code>a</code> contains <code>b</code>, use:</p>
<pre><code>if [[ $s1 == *"$s2"* ]]
</code></pre>
<p>(and make sure to add spaces between the symbols):</p>
<p>Bad:</p>
<pre><code>if [["$s1" == "$s2"]]
</code></pre>
<p>Good:</p>
<pre><code>if [[ "$s1" == "$s2" ]]
</code></pre> | {
"question_id": 4277665,
"question_date": "2010-11-25T13:39:33.683Z",
"question_score": 753,
"tags": "bash|if-statement|scripting",
"answer_id": 4277753,
"answer_date": "2010-11-25T13:49:49.207Z",
"answer_score": 1071
} |
Please answer the following Stack Overflow question:
Title: How do I call a parent class's method from a child class in Python?
<p>When creating a simple object hierarchy in Python, I'd like to be able to invoke methods of the parent class from a derived class. In Perl and Java, there is a keyword for this (<a href="https://docs.oracle.com/javase/tutorial/java/IandI/super.html" rel="noreferrer"><code>super</code></a>). In Perl, I might do this:</p>
<pre><code>package Foo;
sub frotz {
return "Bamf";
}
package Bar;
@ISA = qw(Foo);
sub frotz {
my $str = SUPER::frotz();
return uc($str);
}
</code></pre>
<p>In Python, it appears that I have to name the parent class explicitly from the child.
In the example above, I'd have to do something like <code>Foo::frotz()</code>. </p>
<p>This doesn't seem right since this behavior makes it hard to make deep hierarchies. If children need to know what class defined an inherited method, then all sorts of information pain is created. </p>
<p>Is this an actual limitation in python, a gap in my understanding or both?</p> | <p>Use the <a href="http://docs.python.org/library/functions.html#super" rel="noreferrer"><code>super()</code></a> function:</p>
<pre class="lang-py prettyprint-override"><code>class Foo(Bar):
def baz(self, **kwargs):
return super().baz(**kwargs)
</code></pre>
<p>For Python < 3, you must explicitly opt in to using <a href="http://docs.python.org/glossary.html#term-new-style-class" rel="noreferrer">new-style classes</a> and use:</p>
<pre class="lang-py prettyprint-override"><code>class Foo(Bar):
def baz(self, arg):
return super(Foo, self).baz(arg)
</code></pre> | {
"question_id": 805066,
"question_date": "2009-04-30T01:52:31.707Z",
"question_score": 753,
"tags": "python|class|oop|object|inheritance",
"answer_id": 805081,
"answer_date": "2009-04-30T01:58:28.557Z",
"answer_score": 947
} |
Please answer the following Stack Overflow question:
Title: What is the difference between a deep copy and a shallow copy?
<p>What is the difference between a deep copy and a shallow copy?</p> | <p>Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements.</p>
<p>Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection duplicated. </p> | {
"question_id": 184710,
"question_date": "2008-10-08T20:22:42.850Z",
"question_score": 753,
"tags": "language-agnostic|copy|deep-copy|shallow-copy",
"answer_id": 184745,
"answer_date": "2008-10-08T20:29:36.737Z",
"answer_score": 891
} |
Please answer the following Stack Overflow question:
Title: Shuffle DataFrame rows
<p>I have the following DataFrame:</p>
<pre><code> Col1 Col2 Col3 Type
0 1 2 3 1
1 4 5 6 1
...
20 7 8 9 2
21 10 11 12 2
...
45 13 14 15 3
46 16 17 18 3
...
</code></pre>
<p>The DataFrame is read from a CSV file. All rows which have <code>Type</code> 1 are on top, followed by the rows with <code>Type</code> 2, followed by the rows with <code>Type</code> 3, etc.</p>
<p>I would like to shuffle the order of the DataFrame's rows so that all <code>Type</code>'s are mixed. A possible result could be:</p>
<pre><code> Col1 Col2 Col3 Type
0 7 8 9 2
1 13 14 15 3
...
20 1 2 3 1
21 10 11 12 2
...
45 4 5 6 1
46 16 17 18 3
...
</code></pre>
<p>How can I achieve this?</p> | <p>The idiomatic way to do this with Pandas is to use the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sample.html" rel="noreferrer"><code>.sample</code></a> method of your data frame to sample all rows without replacement:</p>
<pre class="lang-py prettyprint-override"><code>df.sample(frac=1)
</code></pre>
<p>The <code>frac</code> keyword argument specifies the fraction of rows to return in the random sample, so <code>frac=1</code> means to return all rows (in random order).</p>
<hr />
<p><strong>Note:</strong>
If you wish to shuffle your dataframe in-place and reset the index, you could do e.g.</p>
<pre class="lang-py prettyprint-override"><code>df = df.sample(frac=1).reset_index(drop=True)
</code></pre>
<p>Here, specifying <code>drop=True</code> prevents <code>.reset_index</code> from creating a column containing the old index entries.</p>
<p><strong>Follow-up note:</strong> Although it may not look like the above operation is <em>in-place</em>, python/pandas is smart enough not to do another malloc for the shuffled object. That is, even though the <em>reference</em> object has changed (by which I mean <code>id(df_old)</code> is not the same as <code>id(df_new)</code>), the underlying C object is still the same. To show that this is indeed the case, you could run a simple memory profiler:</p>
<pre><code>$ python3 -m memory_profiler .\test.py
Filename: .\test.py
Line # Mem usage Increment Line Contents
================================================
5 68.5 MiB 68.5 MiB @profile
6 def shuffle():
7 847.8 MiB 779.3 MiB df = pd.DataFrame(np.random.randn(100, 1000000))
8 847.9 MiB 0.1 MiB df = df.sample(frac=1).reset_index(drop=True)
</code></pre> | {
"question_id": 29576430,
"question_date": "2015-04-11T09:47:57.653Z",
"question_score": 753,
"tags": "python|pandas|dataframe|permutation|shuffle",
"answer_id": 34879805,
"answer_date": "2016-01-19T14:49:17.730Z",
"answer_score": 1384
} |
Please answer the following Stack Overflow question:
Title: SecurityError: Blocked a frame with origin from accessing a cross-origin frame
<p>I am loading an <code><iframe></code> in my HTML page and trying to access the elements within it using JavaScript, but when I try to execute my code, I get the following error:</p>
<blockquote>
<p>SecurityError: Blocked a frame with origin "http://www.example.com" from accessing a cross-origin frame.</p>
</blockquote>
<p>How can I access the elements in the frame?</p>
<p>I am using this code for testing, but in vain:</p>
<pre><code>$(document).ready(function() {
var iframeWindow = document.getElementById("my-iframe-id").contentWindow;
iframeWindow.addEventListener("load", function() {
var doc = iframe.contentDocument || iframe.contentWindow.document;
var target = doc.getElementById("my-target-id");
target.innerHTML = "Found it!";
});
});
</code></pre> | <h2>Same-origin policy</h2>
<p>You <strong>can't</strong> access an <code><iframe></code> with different origin using JavaScript, it would be a huge security flaw if you could do it. For the <a href="https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy" rel="noreferrer">same-origin policy</a> <strong>browsers block scripts trying to access a frame with a different origin</strong>.</p>
<p>Origin is considered different if at least one of the following parts of the address isn't maintained:</p>
<pre><b>protocol</b>://<b>hostname</b>:<b>port</b>/...</pre>
<p>Protocol, hostname and port must be the same of your domain if you want to access a frame.</p>
<p><sup>NOTE: Internet Explorer is known to not strictly follow this rule, see <a href="https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy#Exceptions_in_Internet_Explorer" rel="noreferrer">here</a> for details.</sup></p>
<h3>Examples</h3>
<p>Here's what would happen trying to access the following URLs from <code>http://www.example.com/home/index.html</code></p>
<pre class="lang-none prettyprint-override"><code>URL RESULT
http://www.example.com/home/other.html -> Success
http://www.example.com/dir/inner/another.php -> Success
http://www.example.com:80 -> Success (default port for HTTP)
http://www.example.com:2251 -> Failure: different port
http://data.example.com/dir/other.html -> Failure: different hostname
https://www.example.com/home/index.html:80 -> Failure: different protocol
ftp://www.example.com:21 -> Failure: different protocol & port
https://google.com/search?q=james+bond -> Failure: different protocol, port & hostname
</code></pre>
<h2>Workaround</h2>
<p>Even though same-origin policy blocks scripts from accessing the content of sites with a different origin, <strong>if you own both the pages, you can work around this problem using <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage" rel="noreferrer"><code>window.postMessage</code></a> and its relative <code>message</code> event</strong> to send messages between the two pages, like this:</p>
<ul>
<li><p>In your main page:</p>
<pre><code>const frame = document.getElementById('your-frame-id');
frame.contentWindow.postMessage(/*any variable or object here*/, 'https://your-second-site.example');
</code></pre>
<p>The second argument to <code>postMessage()</code> can be <code>'*'</code> to indicate no preference about the origin of the destination. A target origin should always be provided when possible, to avoid disclosing the data you send to any other site.</p>
</li>
<li><p>In your <code><iframe></code> (contained in the main page):</p>
<pre><code>window.addEventListener('message', event => {
// IMPORTANT: check the origin of the data!
if (event.origin === 'https://your-first-site.example') {
// The data was sent from your site.
// Data sent with postMessage is stored in event.data:
console.log(event.data);
} else {
// The data was NOT sent from your site!
// Be careful! Do not use it. This else branch is
// here just for clarity, you usually shouldn't need it.
return;
}
});
</code></pre>
</li>
</ul>
<p>This method can be applied in <strong>both directions</strong>, creating a listener in the main page too, and receiving responses from the frame. The same logic can also be implemented in pop-ups and basically any new window generated by the main page (e.g. using <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/open" rel="noreferrer"><code>window.open()</code></a>) as well, without any difference.</p>
<h2>Disabling same-origin policy in <em>your</em> browser</h2>
<p>There already are some good answers about this topic (I just found them googling), so, for the browsers where this is possible, I'll link the relative answer. However, please remember that <strong>disabling the same-origin policy will only affect <em>your</em> browser</strong>. Also, running a browser with same-origin security settings disabled grants <em>any</em> website access to cross-origin resources, so <strong>it's very unsafe and should NEVER be done if you do not know exactly what you are doing (e.g. development purposes)</strong>.</p>
<ul>
<li><a href="https://stackoverflow.com/q/3102819/3889449">Google Chrome</a></li>
<li><a href="https://stackoverflow.com/q/17088609/3889449">Mozilla Firefox</a></li>
<li><a href="https://stackoverflow.com/q/4556429/3889449">Safari</a></li>
<li><a href="https://stackoverflow.com/q/7543678/3889449">Opera</a>: same as Chrome</li>
<li>Microsoft Edge: same as Chrome</li>
<li>Brave: same as Chrome</li>
<li>Microsoft Edge (old non-Chromium version): <a href="https://superuser.com/q/1020612/591004">not possible</a></li>
<li><a href="https://stackoverflow.com/q/20947359/3889449">Microsoft Internet Explorer</a></li>
</ul> | {
"question_id": 25098021,
"question_date": "2014-08-02T18:14:39.280Z",
"question_score": 752,
"tags": "javascript|jquery|security|iframe|same-origin-policy",
"answer_id": 25098153,
"answer_date": "2014-08-02T18:28:50.747Z",
"answer_score": 1069
} |
Please answer the following Stack Overflow question:
Title: How to update a value, given a key in a hashmap?
<p>Suppose we have a <code>HashMap<String, Integer></code> in Java.</p>
<p>How do I update (increment) the integer-value of the string-key for each existence of the string I find?</p>
<p>One could remove and reenter the pair, but overhead would be a concern.<br>
Another way would be to just put the new pair and the old one would be replaced.</p>
<p>In the latter case, what happens if there is a hashcode collision with a new key I am trying to insert? The correct behavior for a hashtable would be to assign a different place for it, or make a list out of it in the current bucket.</p> | <pre><code>map.put(key, map.get(key) + 1);
</code></pre>
<p>should be fine. It will update the value for the existing mapping. Note that this uses auto-boxing. With the help of <code>map.get(key)</code> we get the value of corresponding key, then you can update with your requirement. Here I am updating to increment value by 1.</p> | {
"question_id": 4157972,
"question_date": "2010-11-11T18:34:01.397Z",
"question_score": 752,
"tags": "java|key|hashmap",
"answer_id": 4158002,
"answer_date": "2010-11-11T18:39:31.237Z",
"answer_score": 1176
} |
Please answer the following Stack Overflow question:
Title: PHP parse/syntax errors; and how to solve them
<p>Everyone runs into syntax errors. Even experienced programmers make typos. For newcomers, it's just part of the learning process. However, it's often easy to interpret error messages such as:</p>
<blockquote>
<p>PHP Parse error: syntax error, unexpected '{' in index.php on line 20</p>
</blockquote>
<p>The unexpected symbol isn't always the real culprit. But the line number gives a rough idea of where to start looking.</p>
<blockquote>
<p>Always look at the <strong>code context</strong>. The syntax mistake often hides in the mentioned <em>or</em> in <strong>previous code lines</strong>. Compare your code against syntax examples from the manual.</p>
</blockquote>
<p>While not every case matches the other. Yet there are some <a href="https://stackoverflow.com/a/18050072">general steps to <strong>solve syntax mistakes</strong></a>.
This references summarized the common pitfalls:</p>
<ul>
<li><p><a href="https://stackoverflow.com/a/18092277">Unexpected T_STRING</a></p>
</li>
<li><p><a href="https://stackoverflow.com/a/18092267">Unexpected T_VARIABLE <br> Unexpected '$varname' (T_VARIABLE)</a></p>
</li>
<li><p><a href="https://stackoverflow.com/a/18092288">Unexpected T_CONSTANT_ENCAPSED_STRING <br> Unexpected T_ENCAPSED_AND_WHITESPACE</a></p>
</li>
<li><p><a href="https://stackoverflow.com/questions/18050071/php-parse-syntax-errors-and-how-to-solve-them#29500670">Unexpected $end</a></p>
</li>
<li><p><a href="https://stackoverflow.com/questions/3723748/php-version-5-2-14-parse-error-syntax-error-unexpected-t-function-expecting">Unexpected T_FUNCTION</a>…</p>
</li>
<li><p><a href="https://stackoverflow.com/a/18092308">Unexpected <code>{</code><br>Unexpected <code>}</code><br>Unexpected <code>(</code><br>Unexpected <code>)</code></a></p>
</li>
<li><p><a href="https://stackoverflow.com/a/29505827">Unexpected <code>[</code><br>Unexpected <code>]</code></a></p>
</li>
<li><p><a href="https://stackoverflow.com/a/18092318">Unexpected T_IF <br> Unexpected T_FOREACH <br> Unexpected T_FOR <br> Unexpected T_WHILE <br> Unexpected T_DO <br> Unexpected T_PRINT <br> Unexpected T_ECHO</a></p>
</li>
<li><p><a href="//stackoverflow.com/a/47202089">Unexpected T_LNUMBER</a></p>
</li>
<li><p><a href="//stackoverflow.com/a/48670368">Unexpected ?</a></p>
</li>
<li><p><a href="//stackoverflow.com/a/51786865">Unexpected continue (T_CONTINUE)<br>Unexpected continue (T_BREAK)<br>Unexpected continue (T_RETURN)</a></p>
</li>
<li><p><a href="//stackoverflow.com/a/53037930">Unexpected '='</a></p>
</li>
<li><p><a href="https://stackoverflow.com/questions/4934754/t-inline-html-whats-wrong-with-this">Unexpected T_INLINE_HTML</a>…</p>
</li>
<li><p><a href="https://stackoverflow.com/questions/1966010/what-does-this-mean-parse-error-syntax-error-unexpected-t-paamayim-nekudotay">Unexpected T_PAAMAYIM_NEKUDOTAYIM</a>…</p>
</li>
<li><p><a href="https://stackoverflow.com/questions/3990212/help-with-this-error-message-unexpected-t-object-operator">Unexpected T_OBJECT_OPERATOR</a>…</p>
</li>
<li><p><a href="https://stackoverflow.com/questions/2622624/parse-error-syntax-error-unexpected-t-double-arrow-php">Unexpected T_DOUBLE_ARROW</a>…</p>
</li>
<li><p><a href="https://stackoverflow.com/questions/11208725/parse-error-syntax-error-unexpected-t-sl-php-heredoc">Unexpected T_SL</a>…</p>
</li>
<li><p><a href="https://stackoverflow.com/questions/4419095/syntax-error-unexpected-t-boolean-or">Unexpected T_BOOLEAN_OR</a>…
<br>
<a href="https://stackoverflow.com/questions/11500935/parse-error-syntax-error-unexpected-t-boolean-and-expecting-in">Unexpected T_BOOLEAN_AND</a>…</p>
</li>
<li><p><a href="https://stackoverflow.com/a/30142092/345031">Unexpected T_IS_EQUAL <br>
Unexpected T_IS_GREATER_OR_EQUAL <br>
Unexpected T_IS_IDENTICAL <br>
Unexpected T_IS_NOT_EQUAL <br>
Unexpected T_IS_NOT_IDENTICAL <br>
Unexpected T_IS_SMALLER_OR_EQUAL <br>
Unexpected <code><</code> <br>
Unexpected <code>></code></a></p>
</li>
<li><p><a href="https://stackoverflow.com/questions/6263105/parsing-error-syntax-error-unexpected-t-ns-separator">Unexpected T_NS_SEPARATOR</a>…</p>
</li>
<li><p><a href="https://stackoverflow.com/questions/17156251/unexpected-character-in-input-ascii-92-state-1">Unexpected character in input: '<code>\</code>' (ASCII=92) state=1</a></p>
</li>
<li><p><a href="https://stackoverflow.com/questions/13341378/php-parse-error-syntax-error-unexpected-t-public">Unexpected 'public' (T_PUBLIC) <br> Unexpected 'private' (T_PRIVATE) <br> Unexpected 'protected' (T_PROTECTED) <br> Unexpected 'final' (T_FINAL)</a>…</p>
</li>
<li><p><a href="https://stackoverflow.com/questions/4668557/parse-error-syntax-error-unexpected-t-static">Unexpected T_STATIC</a>…</p>
</li>
<li><p><a href="https://stackoverflow.com/questions/32205590/laravel-parse-error-syntax-error-unexpected-t-class-expecting-t-string-or-t-v">Unexpected T_CLASS</a>…</p>
</li>
<li><p><a href="https://stackoverflow.com/questions/33342994/unexpected-use-t-use-when-trying-to-use-composer">Unexpected 'use' (T_USE)</a></p>
</li>
<li><p><a href="https://stackoverflow.com/questions/27783613/parse-error-syntax-error-unexpected-t-dnumber-in-home-a3206525-public-html-ea">Unexpected T_DNUMBER</a></p>
</li>
<li><p><a href="https://stackoverflow.com/questions/29241208/php-parse-error-syntax-error-unexpected-in">Unexpected <code>,</code></a> <em>(comma)</em></p>
</li>
<li><p><a href="https://stackoverflow.com/questions/10969342/parse-error-syntax-error-unexpected-expecting-or">Unpexected <code>.</code></a> <em>(period)</em></p>
</li>
<li><p><a href="https://stackoverflow.com/questions/12961248/php-string-parse-error-with-necessary-semicolon-after-variable">Unexpected <code>;</code></a> <em>(semicolon)</em></p>
</li>
<li><p><a href="https://stackoverflow.com/q/32905365/3933332">Unexpected <code>*</code></a> <em>(asterisk)</em></p>
</li>
<li><p><a href="https://stackoverflow.com/questions/33178974/parse-error-unexpected-works-fine-in-localhost">Unexpected <code>:</code></a> <em>(colon)</em></p>
</li>
<li><p><a href="https://stackoverflow.com/a/65539862">Unexpected ':', expecting ',' or ')'</a></p>
</li>
<li><p><a href="https://stackoverflow.com/questions/4665782/php-warning-call-time-pass-by">Unexpected <code>&</code></a> (call-time pass-by-reference)</p>
</li>
<li><p><a href="https://stackoverflow.com/a/61407635/250259">Unexpected <code>.</code></a></p>
</li>
</ul>
<p>Closely related references:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php">What does this error mean in PHP? (runtime errors)</a>
<ul>
<li><a href="https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php/12770089/#12770089">Parse error: syntax error, unexpected T_XXX</a></li>
<li><a href="https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php/13935532#13935532">Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE</a></li>
<li><a href="https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php/15539535#15539535">Parse error: syntax error, unexpected T_VARIABLE</a></li>
</ul>
</li>
<li><a href="https://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php">What does this symbol mean in PHP? (language tokens)</a></li>
<li><a href="https://stackoverflow.com/questions/14303353/double-quotes-are-not-copied-normally-how-can-i-edit-them">Those <code>“”</code> smart <code>‘’</code> quotes mean nothing to PHP</a></li>
</ul>
<p>And:</p>
<ul>
<li>The <a href="http://www.php.net/manual/en/" rel="noreferrer">PHP manual on php.net</a> and its various <a href="http://php.net/tokens" rel="noreferrer">language tokens</a></li>
<li>Or Wikipedia's <a href="http://en.wikipedia.org/wiki/PHP_syntax_and_semantics" rel="noreferrer">syntax introduction on PHP</a>.</li>
<li>And lastly our <a href="https://stackoverflow.com/tags/php/info"><strong>php</strong> tag-wiki</a> of course.</li>
</ul>
<p>While Stack Overflow is also welcoming rookie coders, it's mostly targetted at professional programming questions.</p>
<ul>
<li>Answering everyone's coding mistakes and narrow typos is considered mostly off-topic.</li>
<li>So please take the time to follow the <a href="https://stackoverflow.com/a/18050072">basic steps</a>, before posting syntax fixing requests.</li>
<li>If you still have to, please show your own solving initiative, attempted fixes, and your thought process on what looks or might be wrong.</li>
</ul>
<p>If your <em>browser</em> displays error messages such as "SyntaxError: illegal character", then it's not actually <a href="/questions/tagged/php" class="post-tag" title="show questions tagged 'php'" rel="tag">php</a>-related, but a <a href="/questions/tagged/javascript" class="post-tag" title="show questions tagged 'javascript'" rel="tag">javascript</a>-<a href="https://stackoverflow.com/questions/2120093/how-to-find-javascript-syntax-errors">syntax error</a>.</p>
<hr />
<p><strong>Syntax errors raised on vendor code:</strong> Finally, consider that if the syntax error was not raised by editing your codebase, but after an external vendor package install or upgrade, it could be due to PHP version incompatibility, so check the vendor's requirements against your platform setup.</p> | <h3>What are the syntax errors?</h3>
<p>PHP belongs to the <a href="http://en.wikipedia.org/wiki/List_of_C-based_programming_languages" rel="noreferrer">C-style</a> and <a href="http://en.wikipedia.org/wiki/Imperative_programming" rel="noreferrer">imperative</a> programming languages. It has rigid grammar rules, which it cannot recover from when encountering misplaced symbols or identifiers. It can't guess your coding intentions.</p>
<p><img src="https://i.stack.imgur.com/jY6k7.gif" alt="Function definition syntax abstract"></p>
<h3>Most important tips</h3>
<p>There are a few basic precautions you can always take:</p>
<ul>
<li><p>Use proper <strong>code indentation</strong>, or adopt any lofty coding style.
Readability prevents irregularities.</p></li>
<li><p>Use an <a href="http://en.wikipedia.org/wiki/List_of_PHP_editors" rel="noreferrer"><strong><em>IDE</em></strong> or editor for PHP</a> with <strong>syntax highlighting</strong>.
Which also help with parentheses/bracket balancing.</p>
<p><img src="https://i.stack.imgur.com/z2FBC.png" alt="Expected: semicolon"></p></li>
<li><p>Read <a href="http://www.php.net/langref" rel="noreferrer">the language reference</a> and examples in the manual.
Twice, to become somewhat proficient.</p></li>
</ul>
<h3>How to interpret parser errors</h3>
<p>A typical syntax error message reads:</p>
<blockquote>
<p>Parse error: syntax error, unexpected <strong>T_STRING</strong>, expecting <strong>'<code>;</code>'</strong> in <em>file.php</em> on <strong>line</strong> <em>217</em></p>
</blockquote>
<p>Which lists the <em>possible</em> location of a syntax mistake. See the mentioned <strong>file name</strong> and <strong>line number</strong>.</p>
<p>A <a href="http://php.net/tokens" rel="noreferrer">moniker</a> such as <code>T_STRING</code> explains which symbol the parser/tokenizer couldn't process finally. This isn't necessarily the cause of the syntax mistake, however.</p>
<p>It's important to look into <strong>previous code lines</strong> as well. Often syntax errors are just mishaps that happened earlier. The error line number is just where the parser conclusively gave up to process it all.</p>
<h2>Solving syntax errors</h2>
<p>There are many approaches to narrow down and fix syntax hiccups.</p>
<ul>
<li><p>Open the mentioned source file. Look at the mentioned <strong>code line</strong>.</p>
<ul>
<li><p>For runaway strings and misplaced operators, this is usually where you find the culprit.</p></li>
<li><p>Read the line left to right and imagine what each symbol does.</p></li>
</ul></li>
<li><p>More regularly you need to look at <strong>preceding lines</strong> as well.</p>
<ul>
<li><p>In particular, missing <code>;</code> semicolons are missing at the previous line ends/statement. (At least from the stylistic viewpoint. )</p></li>
<li><p>If <code>{</code> code blocks <code>}</code> are incorrectly closed or nested, you may need to investigate even further up the source code. Use proper <em>code indentation</em> to simplify that.</p></li>
</ul></li>
<li><p>Look at the <strong>syntax colorization</strong>!</p>
<ul>
<li><p>Strings and variables and constants should all have different colors.</p></li>
<li><p>Operators <code>+-*/.</code> should be tinted distinct as well. Else they might be in the wrong context.</p></li>
<li><p>If you see string colorization extend too far or too short, then you have found an unescaped or missing closing <code>"</code> or <code>'</code> string marker.</p></li>
<li><p>Having two same-colored punctuation characters next to each other can also mean trouble. Usually, operators are lone if it's not <code>++</code>, <code>--</code>, or parentheses following an operator. Two strings/identifiers directly following each other are incorrect in most contexts.</p></li>
</ul></li>
<li><p><strong>Whitespace is your friend</strong>.
Follow <em>any</em> coding style.
</p></li>
<li><p>Break up long lines temporarily.</p>
<ul>
<li><p>You can freely <strong>add newlines</strong> between operators or constants and strings. The parser will then concretize the line number for parsing errors. Instead of looking at the very lengthy code, you can isolate the missing or misplaced syntax symbol.</p></li>
<li><p>Split up complex <code>if</code> statements into distinct or nested <code>if</code> conditions.</p></li>
<li><p>Instead of lengthy math formulas or logic chains, use temporary variables to simplify the code. (More readable = fewer errors.)</p></li>
<li><p>Add newlines between:</p>
<ol>
<li>The code you can easily identify as correct,</li>
<li>The parts you're unsure about,</li>
<li>And the lines which the parser complains about. <br/></li>
</ol>
<p>Partitioning up long code blocks <em>really</em> helps to locate the origin of syntax errors.</p></li>
</ul></li>
<li><p><strong>Comment out</strong> offending code.</p>
<ul>
<li><p>If you can't isolate the problem source, start to comment out (and thus temporarily remove) blocks of code.</p></li>
<li><p>As soon as you got rid of the parsing error, you have found the problem source. Look more closely there.</p></li>
<li><p>Sometimes you want to temporarily remove complete function/method blocks. (In case of unmatched curly braces and wrongly indented code.)</p></li>
<li><p>When you can't resolve the syntax issue, try to <strong>rewrite</strong> the commented out sections <strong>from scratch</strong>.</p></li>
</ul></li>
<li><p>As a newcomer, avoid some of the confusing syntax constructs.</p>
<ul>
<li><p>The ternary <code>? :</code> condition operator can compact code and is useful indeed. But it doesn't aid readability in all cases. Prefer plain <code>if</code> statements while unversed.</p></li>
<li><p>PHP's alternative syntax (<code>if:</code>/<code>elseif:</code>/<code>endif;</code>) is common for templates, but arguably less easy to follow than normal <code>{</code> code <code>}</code> blocks.</p></li>
</ul></li>
<li><p>The most prevalent newcomer mistakes are:</p>
<ul>
<li><p>Missing semicolons <code>;</code> for terminating statements/lines.</p></li>
<li><p>Mismatched string quotes for <code>"</code> or <code>'</code> and unescaped quotes within.</p></li>
<li><p>Forgotten operators, in particular for the string <code>.</code> concatenation.</p></li>
<li><p>Unbalanced <code>(</code> parentheses <code>)</code>. Count them in the reported line. Are there an equal number of them?</p></li>
</ul></li>
<li><p>Don't forget that solving one syntax problem can uncover the next.</p>
<ul>
<li><p>If you make one issue go away, but other crops up in some code below, you're mostly on the right path.</p></li>
<li><p>If after editing a new syntax error crops up in the same line, then your attempted change was possibly a failure. (Not always though.)</p></li>
</ul></li>
<li><p>Restore a backup of previously working code, if you can't fix it.</p>
<ul>
<li>Adopt a source code versioning system. You can always view a <code>diff</code> of the broken and last working version. Which might be enlightening as to what the syntax problem is.
<br/></li>
</ul></li>
<li><p><strong>Invisible stray Unicode characters</strong>: In some cases, you need to <a href="https://stackoverflow.com/questions/28952930/parse-error-syntax-error-unexpected-t-variable/28953112#28953112">use a hexeditor</a> or different editor/viewer on your source. Some problems cannot be found just from looking at your code.</p>
<ul>
<li><p>Try <a href="https://stackoverflow.com/questions/3001177/how-do-i-grep-for-all-non-ascii-characters-in-unix"><code>grep --color -P -n "\[\x80-\xFF\]" file.php</code></a> as the first measure to find non-ASCII symbols.</p></li>
<li><p>In particular BOMs, zero-width spaces, or non-breaking spaces, and smart quotes regularly can find their way into the source code.</p></li>
</ul></li>
<li><p>Take care of which <strong>type of linebreaks</strong> are saved in files.</p>
<ul>
<li><p>PHP just honors <kbd>\n</kbd> newlines, not <kbd>\r</kbd> carriage returns.</p></li>
<li><p>Which is occasionally an issue for MacOS users (even on OS X for misconfigured editors).</p></li>
<li><p>It often only surfaces as an issue when single-line <code>//</code> or <code>#</code> comments are used. Multiline <code>/*...*/</code> comments do seldom disturb the parser when linebreaks get ignored.</p></li>
</ul></li>
<li><p>If your <strong>syntax error does not transmit over the web</strong>:
It happens that you have a syntax error on your machine. But posting the very same file online does not exhibit it anymore. Which can only mean one of two things:</p>
<ul>
<li><p>You are looking at the wrong file!</p></li>
<li><p>Or your code contained invisible stray Unicode (see above).
You can easily find out: Just copy your code back from the web form into your text editor.</p></li>
</ul></li>
<li><p>Check your <strong>PHP version</strong>. Not all syntax constructs are available on every server.</p>
<ul>
<li><p><code>php -v</code> for the command line interpreter</p></li>
<li><p><code><?php phpinfo();</code> for the one invoked through the webserver.</p></li>
</ul>
<p><br> Those aren't necessarily the same. In particular when working with frameworks, you will them to match up.</p></li>
<li><p>Don't use <a href="http://www.php.net/reserved.keywords" rel="noreferrer">PHP's reserved keywords</a> as identifiers for functions/methods, classes or constants.</p></li>
<li><p>Trial-and-error is your last resort.</p></li>
</ul>
<p>If all else fails, you can always <strong>google</strong> your error message. Syntax symbols aren't as easy to search for (Stack Overflow itself is indexed by <a href="http://symbolhound.com/" rel="noreferrer">SymbolHound</a> though). Therefore it may take looking through a few more pages before you find something relevant.</p>
<p>Further guides:</p>
<ul>
<li><em><a href="http://www.onlamp.com/pub/a/php/2004/08/12/debuggingphp.html" rel="noreferrer">PHP Debugging Basics</a></em> by David Sklar</li>
<li><em><a href="http://jason.pureconcepts.net/2013/05/fixing-php-errors/" rel="noreferrer">Fixing PHP Errors</a></em> by Jason McCreary</li>
<li><em><a href="http://www.phpreferencebook.com/misc/php-errors-common-mistakes/" rel="noreferrer">PHP Errors – 10 Common Mistakes</a></em> by Mario Lurig</li>
<li><em><a href="http://coursesweb.net/php-mysql/common-php-errors-solution_t" rel="noreferrer">Common PHP Errors and Solutions</a></em></li>
<li><em><a href="http://diythemes.com/thesis/troubleshoot-wordpress-website/" rel="noreferrer">How to Troubleshoot and Fix your WordPress Website</a></em></li>
<li><em><a href="http://coding.smashingmagazine.com/2011/11/30/a-guide-to-php-error-messages-for-designers/" rel="noreferrer">A Guide To PHP Error Messages For Designers</a></em> - Smashing Magazine</li>
</ul>
<h3>White screen of death</h3>
<p>If your website is just blank, then typically a syntax error is the cause.
Enable their display with:</p>
<ul>
<li><code>error_reporting = E_ALL</code></li>
<li><code>display_errors = 1</code></li>
</ul>
<p>In your <a href="http://www.php.net/manual/en/configuration.file.php" rel="noreferrer"><code>php.ini</code></a> generally, or via <a href="http://www.php.net/manual/en/configuration.changes.php" rel="noreferrer"><code>.htaccess</code></a> for mod_php,
or even <a href="http://php.net/manual/en/configuration.file.per-user.php" rel="noreferrer"><code>.user.ini</code></a> with FastCGI setups.</p>
<p>Enabling it within the broken script is too late because PHP can't even interpret/run the first line. A quick workaround is crafting a wrapper script, say <code>test.php</code>:</p>
<pre><code><?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
include("./broken-script.php");
</code></pre>
<p>Then invoke the failing code by accessing this wrapper script.</p>
<p>It also helps to enable PHP's <code>error_log</code> and look into your <a href="http://www.cyberciti.biz/faq/apache-logs/" rel="noreferrer">webserver's <code>error.log</code></a> when a script crashes with HTTP 500 responses.</p> | {
"question_id": 18050071,
"question_date": "2013-08-05T03:11:15.813Z",
"question_score": 752,
"tags": "php|parsing|debugging|syntax-error",
"answer_id": 18050072,
"answer_date": "2013-08-05T03:11:15.813Z",
"answer_score": 314
} |
Please answer the following Stack Overflow question:
Title: How does collections.defaultdict work?
<p>I've read the examples in python docs, but still can't figure out what this method means. Can somebody help? Here are two examples from the python docs</p>
<pre><code>>>> from collections import defaultdict
>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> for k in s:
... d[k] += 1
...
>>> d.items()
[('i', 4), ('p', 2), ('s', 4), ('m', 1)]
</code></pre>
<p>and</p>
<pre><code>>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
... d[k].append(v)
...
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
</code></pre>
<p>the parameters <code>int</code> and <code>list</code> are for what? </p> | <p>Usually, a Python dictionary throws a <code>KeyError</code> if you try to get an item with a key that is not currently in the dictionary. The <code>defaultdict</code> in contrast will simply create any items that you try to access (provided of course they do not exist yet). To create such a "default" item, it calls the function object that you pass to the constructor (more precisely, it's an arbitrary "callable" object, which includes function and type objects). For the first example, default items are created using <code>int()</code>, which will return the integer object <code>0</code>. For the second example, default items are created using <code>list()</code>, which returns a new empty list object.</p> | {
"question_id": 5900578,
"question_date": "2011-05-05T15:45:00.130Z",
"question_score": 752,
"tags": "python|dictionary|default-value|defaultdict",
"answer_id": 5900634,
"answer_date": "2011-05-05T15:49:23.923Z",
"answer_score": 819
} |
Please answer the following Stack Overflow question:
Title: Generating random numbers in Objective-C
<p>I'm a Java head mainly, and I want a way to generate a pseudo-random number between 0 and 74. In Java I would use the method:</p>
<pre><code>Random.nextInt(74)
</code></pre>
<p>I'm not interested in a discussion about seeds or true randomness, just how you accomplish the same task in Objective-C. I've scoured Google, and there just seems to be lots of different and conflicting bits of information.</p> | <p>You should use the <code>arc4random_uniform()</code> function. It uses a superior algorithm to <code>rand</code>. You don't even need to set a seed.</p>
<pre><code>#include <stdlib.h>
// ...
// ...
int r = arc4random_uniform(74);
</code></pre>
<p>The <code>arc4random</code> man page:</p>
<blockquote>
<pre><code>NAME
arc4random, arc4random_stir, arc4random_addrandom -- arc4 random number generator
LIBRARY
Standard C Library (libc, -lc)
SYNOPSIS
#include <stdlib.h>
u_int32_t
arc4random(void);
void
arc4random_stir(void);
void
arc4random_addrandom(unsigned char *dat, int datlen);
DESCRIPTION
The arc4random() function uses the key stream generator employed by the arc4 cipher, which uses 8*8 8
bit S-Boxes. The S-Boxes can be in about (2**1700) states. The arc4random() function returns pseudo-
random numbers in the range of 0 to (2**32)-1, and therefore has twice the range of rand(3) and
random(3).
The arc4random_stir() function reads data from /dev/urandom and uses it to permute the S-Boxes via
arc4random_addrandom().
There is no need to call arc4random_stir() before using arc4random(), since arc4random() automatically
initializes itself.
EXAMPLES
The following produces a drop-in replacement for the traditional rand() and random() functions using
arc4random():
#define foo4random() (arc4random() % ((unsigned)RAND_MAX + 1))
</code></pre>
</blockquote> | {
"question_id": 160890,
"question_date": "2008-10-02T04:35:21.967Z",
"question_score": 752,
"tags": "objective-c|random",
"answer_id": 163178,
"answer_date": "2008-10-02T16:00:17.797Z",
"answer_score": 1036
} |
Please answer the following Stack Overflow question:
Title: How to disable Python warnings?
<p>I am working with code that throws a lot of (for me at the moment) useless warnings using the <a href="https://docs.python.org/3/library/warnings.html" rel="noreferrer"><code>warnings</code></a> library. Reading (/scanning) the documentation I only found a way <a href="https://docs.python.org/3/library/warnings.html#temporarily-suppressing-warnings" rel="noreferrer">to disable warnings for single functions</a>. But I don't want to change so much of the code.</p>
<p>Is there a flag like <code>python -no-warning foo.py</code>?</p>
<p>What would you recommend?</p> | <p>There's the <a href="https://docs.python.org/3/using/cmdline.html#cmdoption-w" rel="noreferrer"><code>-W</code> option</a>.</p>
<pre><code>python -W ignore foo.py
</code></pre> | {
"question_id": 14463277,
"question_date": "2013-01-22T16:26:49.193Z",
"question_score": 751,
"tags": "python|suppress-warnings",
"answer_id": 14463321,
"answer_date": "2013-01-22T16:28:31.550Z",
"answer_score": 605
} |
Please answer the following Stack Overflow question:
Title: How to link to apps on the app store
<p>I am creating a free version of my iPhone game. I want to have a button inside the free version that takes people to the paid version in the app store. If I use a standard link</p>
<p><a href="http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=300136119&mt=8" rel="noreferrer">http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=300136119&mt=8</a></p>
<p>the iPhone opens Safari first, and then the app store. I have used other apps that open the app store directly, so I know it is possible.</p>
<p>Any ideas? What is the URL Scheme for the app store?</p> | <p><strong>Edited on 2016-02-02</strong></p>
<p>Starting from iOS 6 <a href="https://developer.apple.com/library/prerelease/ios/documentation/StoreKit/Reference/SKITunesProductViewController_Ref/index.html" rel="noreferrer">SKStoreProductViewController</a> class was introduced. You can link an app without leaving your app. Code snippet in <strong>Swift 3.x/2.x</strong> and <strong>Objective-C</strong> is <a href="https://stackoverflow.com/a/32008404/1151916">here</a>.</p>
<blockquote>
<p>A <a href="https://developer.apple.com/library/prerelease/ios/documentation/StoreKit/Reference/SKITunesProductViewController_Ref/index.html" rel="noreferrer">SKStoreProductViewController</a> object presents a store that allows the
user to purchase other media from the App Store. For example, your app
might display the store to allow the user to purchase another app.</p>
</blockquote>
<hr />
<p>From <a href="https://developer.apple.com/news/?id=01062010a" rel="noreferrer">News and Announcement For Apple Developers</a>.</p>
<blockquote>
<p>Drive Customers Directly to Your App
on the App Store with iTunes Links
With iTunes links you can provide your
customers with an easy way to access
your apps on the App Store directly
from your website or marketing
campaigns. Creating an iTunes link is
simple and can be made to direct
customers to either a single app, all
your apps, or to a specific app with
your company name specified.</p>
<p>To send customers to a specific
application:
<a href="http://itunes.com/apps/appname" rel="noreferrer">http://itunes.com/apps/appname</a></p>
<p>To send
customers to a list of apps you have
on the App Store:
<a href="http://itunes.com/apps/developername" rel="noreferrer">http://itunes.com/apps/developername</a></p>
<p>To send customers to a specific app
with your company name included in the
URL:
<a href="http://itunes.com/apps/developername/appname" rel="noreferrer">http://itunes.com/apps/developername/appname</a></p>
</blockquote>
<hr />
<p><strong>Additional notes:</strong></p>
<p>You can replace <code>http://</code> with <code>itms://</code> or <code>itms-apps://</code> to avoid redirects.</p>
<p><strong>Please note</strong> that <code>itms://</code> will send the user to the <strong>iTunes store</strong> and <code>itms-apps://</code> with send them to the <strong>App Store!</strong></p>
<p>For info on naming, see Apple QA1633:</p>
<p><a href="https://developer.apple.com/library/content/qa/qa1633/_index.html" rel="noreferrer">https://developer.apple.com/library/content/qa/qa1633/_index.html</a>.</p>
<p><strong>Edit (as of January 2015):</strong></p>
<p>itunes.com/apps links should be updated to appstore.com/apps. See QA1633 above, which has been updated. A new <a href="https://developer.apple.com/library/content/qa/qa1629/_index.html" rel="noreferrer">QA1629</a> suggests these steps and code for launching the store from an app:</p>
<ol>
<li>Launch iTunes on your computer.</li>
<li>Search for the item you want to link to.</li>
<li>Right-click or control-click on the item's name in iTunes, then choose "Copy iTunes Store URL" from the pop-up menu.</li>
<li>In your application, create an <code>NSURL</code> object with the copied iTunes URL, then pass this object to <code>UIApplication</code>' s <code>openURL</code>: method to open your item in the App Store.</li>
</ol>
<p>Sample code:</p>
<pre><code>NSString *iTunesLink = @"itms://itunes.apple.com/app/apple-store/id375380948?mt=8";
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:iTunesLink]];
</code></pre>
<p>iOS10+:</p>
<pre><code> [[UIApplication sharedApplication] openURL:[NSURL URLWithString:iTunesLink] options:@{} completionHandler:nil];
</code></pre>
<p><strong>Swift 4.2</strong></p>
<pre><code> let urlStr = "itms-apps://itunes.apple.com/app/apple-store/id375380948?mt=8"
if #available(iOS 10.0, *) {
UIApplication.shared.open(URL(string: urlStr)!, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(URL(string: urlStr)!)
}
</code></pre> | {
"question_id": 433907,
"question_date": "2009-01-11T22:48:36.487Z",
"question_score": 751,
"tags": "ios|objective-c|app-store",
"answer_id": 2337601,
"answer_date": "2010-02-25T21:03:08.150Z",
"answer_score": 809
} |
Please answer the following Stack Overflow question:
Title: How to define hash tables in Bash?
<p>What is the equivalent of <a href="https://docs.python.org/2/tutorial/datastructures.html#dictionaries" rel="noreferrer">Python dictionaries</a> but in Bash (should work across OS X and Linux).</p> | <h1>Bash 4</h1>
<p>Bash 4 natively supports this feature. Make sure your script's hashbang is <code>#!/usr/bin/env bash</code> or <code>#!/bin/bash</code> so you don't end up using <code>sh</code>. Make sure you're either executing your script directly, or execute <code>script</code> with <code>bash script</code>. (Not actually executing a Bash script with Bash <em>does</em> happen, and will be <em>really</em> confusing!)</p>
<p>You declare an associative array by doing:</p>
<pre><code>declare -A animals
</code></pre>
<p>You can fill it up with elements using the normal array assignment operator. For example, if you want to have a map of <code>animal[sound(key)] = animal(value)</code>:</p>
<pre><code>animals=( ["moo"]="cow" ["woof"]="dog")
</code></pre>
<p>Or declare and instantiate in one line:</p>
<pre><code>declare -A animals=( ["moo"]="cow" ["woof"]="dog")
</code></pre>
<p>Then use them just like normal arrays. Use</p>
<ul>
<li><p><code>animals['key']='value'</code> to set value</p>
</li>
<li><p><code>"${animals[@]}"</code> to expand the values</p>
</li>
<li><p><code>"${!animals[@]}"</code> (notice the <code>!</code>) to expand the keys</p>
</li>
</ul>
<p>Don't forget to quote them:</p>
<pre><code>echo "${animals[moo]}"
for sound in "${!animals[@]}"; do echo "$sound - ${animals[$sound]}"; done
</code></pre>
<h1>Bash 3</h1>
<p>Before bash 4, you don't have associative arrays. <strong>Do not use <code>eval</code> to emulate them</strong>. Avoid <code>eval</code> like the plague, because it <em>is</em> the plague of shell scripting. The most important reason is that <code>eval</code> treats your data as executable code (there are many other reasons too).</p>
<p><em>First and foremost</em>: Consider upgrading to bash 4. This will make the whole process much easier for you.</p>
<p>If there's a reason you can't upgrade, <code>declare</code> is a far safer option. It does not evaluate data as bash code like <code>eval</code> does, and as such does not allow arbitrary code injection quite so easily.</p>
<p>Let's prepare the answer by introducing the concepts:</p>
<p>First, indirection.</p>
<pre><code>$ animals_moo=cow; sound=moo; i="animals_$sound"; echo "${!i}"
cow
</code></pre>
<p>Secondly, <code>declare</code>:</p>
<pre><code>$ sound=moo; animal=cow; declare "animals_$sound=$animal"; echo "$animals_moo"
cow
</code></pre>
<p>Bring them together:</p>
<pre><code># Set a value:
declare "array_$index=$value"
# Get a value:
arrayGet() {
local array=$1 index=$2
local i="${array}_$index"
printf '%s' "${!i}"
}
</code></pre>
<p>Let's use it:</p>
<pre><code>$ sound=moo
$ animal=cow
$ declare "animals_$sound=$animal"
$ arrayGet animals "$sound"
cow
</code></pre>
<p>Note: <code>declare</code> cannot be put in a function. Any use of <code>declare</code> inside a bash function turns the variable it creates <em>local</em> to the scope of that function, meaning we can't access or modify global arrays with it. (In bash 4 you can use <code>declare -g</code> to declare global variables - but in bash 4, you can use associative arrays in the first place, avoiding this workaround.)</p>
<p>Summary:</p>
<ul>
<li>Upgrade to bash 4 and use <code>declare -A</code> for associative arrays.</li>
<li>Use the <code>declare</code> option if you can't upgrade.</li>
<li>Consider using <code>awk</code> instead and avoid the issue altogether.</li>
</ul> | {
"question_id": 1494178,
"question_date": "2009-09-29T18:29:38.220Z",
"question_score": 751,
"tags": "bash|dictionary|hashtable|associative-array",
"answer_id": 3467959,
"answer_date": "2010-08-12T13:09:35.597Z",
"answer_score": 1264
} |
Please answer the following Stack Overflow question:
Title: There is already an open DataReader associated with this Command which must be closed first
<p>I have this query and I get the error in this function:</p>
<pre><code>var accounts = from account in context.Accounts
from guranteer in account.Gurantors
select new AccountsReport
{
CreditRegistryId = account.CreditRegistryId,
AccountNumber = account.AccountNo,
DateOpened = account.DateOpened,
};
return accounts.AsEnumerable()
.Select((account, index) => new AccountsReport()
{
RecordNumber = FormattedRowNumber(account, index + 1),
CreditRegistryId = account.CreditRegistryId,
DateLastUpdated = DateLastUpdated(account.CreditRegistryId, account.AccountNumber),
AccountNumber = FormattedAccountNumber(account.AccountType, account.AccountNumber)
})
.OrderBy(c=>c.FormattedRecordNumber)
.ThenByDescending(c => c.StateChangeDate);
public DateTime DateLastUpdated(long creditorRegistryId, string accountNo)
{
return (from h in context.AccountHistory
where h.CreditorRegistryId == creditorRegistryId && h.AccountNo == accountNo
select h.LastUpdated).Max();
}
</code></pre>
<p>Error is:</p>
<blockquote>
<p>There is already an open DataReader associated with this Command which must be closed first. </p>
</blockquote>
<p><strong>Update:</strong></p>
<p>stack trace added:</p>
<pre><code>InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.]
System.Data.SqlClient.SqlInternalConnectionTds.ValidateConnectionForExecute(SqlCommand command) +5008639
System.Data.SqlClient.SqlConnection.ValidateConnectionForExecute(String method, SqlCommand command) +23
System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async) +144
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +87
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +32
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +141
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +12
System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +10
System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) +443
[EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details.]
System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) +479
System.Data.Objects.Internal.ObjectQueryExecutionPlan.Execute(ObjectContext context, ObjectParameterCollection parameterValues) +683
System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) +119
System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator() +38
System.Linq.Enumerable.Single(IEnumerable`1 source) +114
System.Data.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__3(IEnumerable`1 sequence) +4
System.Data.Objects.ELinq.ObjectQueryProvider.ExecuteSingle(IEnumerable`1 query, Expression queryRoot) +29
System.Data.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute(Expression expression) +91
System.Data.Entity.Internal.Linq.DbQueryProvider.Execute(Expression expression) +69
System.Linq.Queryable.Max(IQueryable`1 source) +216
CreditRegistry.Repositories.CreditRegistryRepository.DateLastUpdated(Int64 creditorRegistryId, String accountNo) in D:\Freelance Work\SuperExpert\CreditRegistry\CreditRegistry\Repositories\CreditRegistryRepository.cs:1497
CreditRegistry.Repositories.CreditRegistryRepository.<AccountDetails>b__88(AccountsReport account, Int32 index) in D:\Freelance Work\SuperExpert\CreditRegistry\CreditRegistry\Repositories\CreditRegistryRepository.cs:1250
System.Linq.<SelectIterator>d__7`2.MoveNext() +198
System.Linq.Buffer`1..ctor(IEnumerable`1 source) +217
System.Linq.<GetEnumerator>d__0.MoveNext() +96
</code></pre> | <p>This can happen if you execute a query while iterating over the results from another query. It is not clear from your example where this happens because the example is not complete.</p>
<p>One thing that can cause this is lazy loading triggered when iterating over the results of some query.</p>
<p>This can be easily solved by allowing MARS in your connection string. Add <code>MultipleActiveResultSets=true</code> to the provider part of your connection string (where Data Source, Initial Catalog, etc. are specified).</p> | {
"question_id": 6062192,
"question_date": "2011-05-19T17:01:46.823Z",
"question_score": 751,
"tags": "c#|entity-framework|entity-framework-4",
"answer_id": 6064422,
"answer_date": "2011-05-19T20:21:57.513Z",
"answer_score": 1482
} |
Please answer the following Stack Overflow question:
Title: Xcode building for iOS Simulator, but linking in an object file built for iOS, for architecture 'arm64'
<p>I am trying to get a large (and working on Xcode 11!) project building in Xcode 12 (beta 5) to prepare for iOS 14. The codebase was previously in Objective-C, but now it contains both Objective-C and Swift, and uses pods that are Objective-C and/or Swift as well.</p>
<p>I have pulled the new beta of <a href="https://en.wikipedia.org/wiki/CocoaPods" rel="noreferrer">CocoaPods</a> with Xcode 12 support (currently 1.10.0.beta 2).</p>
<p>Pod install is successful. When I do a build, I get the following error on a pod framework:</p>
<blockquote>
<p>building for iOS Simulator, but linking in object file built for iOS, for architecture arm64</p>
</blockquote>
<p>and possibly also the error:</p>
<blockquote>
<p>Unable to load standard library for target 'arm64-apple-ios11.0'</p>
</blockquote>
<p>When I go run <code>lipo -info</code> on the framework, it has: armv7s armv7 i386 x86_64 arm64.</p>
<p>Previously, the project had <em>Valid Architectures</em> set to: armv7, armv7s and arm64.</p>
<p>In Xcode 12, that setting goes away, as per Apple's documentation. Architectures is set to $(ARCHS_STANDARD). I have nothing set in excluded architectures.</p>
<p>What may be going on here? I have not been able to reproduce this with a simpler project yet.</p> | <p>Basically, you have to exclude <code>arm64</code> for the simulator architecture, both from your project and the Pod project.</p>
<ul>
<li><p>To do that, navigate to <strong>Build Settings</strong> of your project and add <em>Any iOS Simulator SDK</em> with value <code>arm64</code> inside <em>Excluded Architecture</em>.</p>
<p><a href="https://i.stack.imgur.com/XGVJM.png" rel="noreferrer"><img src="https://i.stack.imgur.com/XGVJM.png" alt="Enter image description here" /></a></p>
</li>
</ul>
<p><strong>OR</strong></p>
<ul>
<li><p>If you are using custom <code>XCConfig</code> files, you can simply add this line for excluding simulator architecture.</p>
<pre><code>EXCLUDED_ARCHS[sdk=iphonesimulator*] = arm64
</code></pre>
<p><strong>Then</strong></p>
<p>You have to do the same for the <strong>Pod project</strong> until all the Cocoa pod vendors are done adding following in their <strong>Podspec</strong>.</p>
<pre class="lang-rb prettyprint-override"><code>s.pod_target_xcconfig = { 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64' }
s.user_target_xcconfig = { 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64' }
</code></pre>
<p>You can manually add the <em>Excluded Architecture</em> in your Pod project's <strong>Build Settings</strong>, but it will be overwritten when you
use <code>pod install</code>.</p>
<p>In place of this, you can add this snippet in your <code>Podfile</code>. It will write the necessary <strong>Build Settings</strong> every time you run <code>pod install</code>.</p>
<pre class="lang-none prettyprint-override"><code>post_install do |installer|
installer.pods_project.build_configurations.each do |config|
config.build_settings["EXCLUDED_ARCHS[sdk=iphonesimulator*]"] = "arm64"
end
end
</code></pre>
</li>
</ul> | {
"question_id": 63607158,
"question_date": "2020-08-26T23:40:26.720Z",
"question_score": 751,
"tags": "ios|xcode|xcode12|xcode12beta5|xcode12beta6",
"answer_id": 63955114,
"answer_date": "2020-09-18T11:41:45.217Z",
"answer_score": 1118
} |
Please answer the following Stack Overflow question:
Title: Understanding checked vs unchecked exceptions in Java
<p>Joshua Bloch in "<em>Effective Java</em>" said that </p>
<blockquote>
<p>Use checked exceptions for
recoverable conditions and runtime
exceptions for programming errors
(Item 58 in 2nd edition)</p>
</blockquote>
<p>Let's see if I understand this correctly.</p>
<p>Here is my understanding of a checked exception:</p>
<pre><code>try{
String userInput = //read in user input
Long id = Long.parseLong(userInput);
}catch(NumberFormatException e){
id = 0; //recover the situation by setting the id to 0
}
</code></pre>
<p><strong>1. Is the above considered a checked exception?</strong></p>
<p><strong>2. Is RuntimeException an unchecked exception?</strong></p>
<p>Here is my understanding of an unchecked exception:</p>
<pre><code>try{
File file = new File("my/file/path");
FileInputStream fis = new FileInputStream(file);
}catch(FileNotFoundException e){
//3. What should I do here?
//Should I "throw new FileNotFoundException("File not found");"?
//Should I log?
//Or should I System.exit(0);?
}
</code></pre>
<p><strong>4. Now, couldn't the above code also be a checked exception? I can try to recover the situation like this? Can I?</strong> (Note: my 3rd question is inside the <code>catch</code> above)</p>
<pre><code>try{
String filePath = //read in from user input file path
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
}catch(FileNotFoundException e){
//Kindly prompt the user an error message
//Somehow ask the user to re-enter the file path.
}
</code></pre>
<p><strong>5. Why do people do this?</strong></p>
<pre><code>public void someMethod throws Exception{
}
</code></pre>
<p>Why do they let the exception bubble up? Isn't handling the error sooner better? Why bubble up? </p>
<p><strong>6. Should I bubble up the exact exception or mask it using Exception?</strong></p>
<p><strong>Below are my readings</strong></p>
<p><a href="https://stackoverflow.com/questions/499437/in-java-when-should-i-create-a-checked-exception-and-when-should-it-be-a-runtim">In Java, when should I create a checked exception, and when should it be a runtime exception?</a></p>
<p><a href="https://stackoverflow.com/questions/27578/when-to-choose-checked-and-unchecked-exceptions">When to choose checked and unchecked exceptions</a></p> | <p>Many people say that checked exceptions (i.e. these that you should explicitly catch or rethrow) should not be used at all. They were eliminated in C# for example, and most languages don't have them. So you can always throw a subclass of <code>RuntimeException</code> (unchecked exception)</p>
<p>However, I think checked exceptions are useful - they are used when you want to force the user of your API to think how to handle the exceptional situation (if it is recoverable). It's just that checked exceptions are overused in the Java platform, which makes people hate them.</p>
<p><a href="http://techblog.bozho.net/?p=316" rel="noreferrer">Here's my extended view on the topic</a>.</p>
<p>As for the particular questions:</p>
<ol>
<li><p><strong>Is the <code>NumberFormatException</code> consider a checked exception?</strong><br>
No. <code>NumberFormatException</code> is unchecked (= is subclass of <code>RuntimeException</code>). Why? I don't know. (but there should have been a method <code>isValidInteger(..)</code>)</p></li>
<li><p><strong>Is <code>RuntimeException</code> an unchecked exception?</strong><br>
Yes, exactly.</p></li>
<li><p><strong>What should I do here?</strong><br>
It depends on where this code is and what you want to happen. If it is in the UI layer - catch it and show a warning; if it's in the service layer - don't catch it at all - let it bubble. Just don't swallow the exception. If an exception occurs in most of the cases you should choose one of these:</p>
<ul>
<li>log it and return</li>
<li>rethrow it (declare it to be thrown by the method)</li>
<li>construct a new exception by passing the current one in constructor </li>
</ul></li>
<li><p><strong>Now, couldn't the above code also be a checked exception? I can try to recover the situation like this? Can I?</strong><br>
It could've been. But nothing stops you from catching the unchecked exception as well</p></li>
<li><p><strong>Why do people add class <code>Exception</code> in the throws clause?</strong><br>
Most often because people are lazy to consider what to catch and what to rethrow. Throwing <code>Exception</code> is a bad practice and should be avoided.</p></li>
</ol>
<p>Alas, there is no single rule to let you determine when to catch, when to rethrow, when to use checked and when to use unchecked exceptions. I agree this causes much confusion and a lot of bad code. The general principle is stated by Bloch (you quoted a part of it). And the general principle is to rethrow an exception to the layer where you can handle it.</p> | {
"question_id": 6115896,
"question_date": "2011-05-24T19:38:31.743Z",
"question_score": 751,
"tags": "java|exception|runtimeexception|checked-exceptions|unchecked-exception",
"answer_id": 6116020,
"answer_date": "2011-05-24T19:49:42.087Z",
"answer_score": 513
} |
Please answer the following Stack Overflow question:
Title: How to fix committing to the wrong Git branch?
<p>I just made a perfectly good commit to the wrong branch.
How do I undo the last commit in my master branch and then take those same changes and get them into my upgrade branch?</p> | <p>If you haven't yet pushed your changes, you can also do a soft reset:</p>
<pre><code>git reset --soft HEAD^
</code></pre>
<p>This will revert the commit, but put the committed changes back into your index. Assuming the branches are relatively up-to-date with regard to each other, git will let you do a checkout into the other branch, whereupon you can simply commit:</p>
<pre><code>git checkout branch
git commit -c ORIG_HEAD
</code></pre>
<p>The <code>-c ORIG_HEAD</code> part is useful to not type commit message again.</p> | {
"question_id": 2941517,
"question_date": "2010-05-31T05:30:21.633Z",
"question_score": 751,
"tags": "git|git-commit",
"answer_id": 2941598,
"answer_date": "2010-05-31T05:53:20.067Z",
"answer_score": 1185
} |
Please answer the following Stack Overflow question:
Title: Placeholder in UITextView
<p>My application uses an <code>UITextView</code>. Now I want the <code>UITextView</code> to have a placeholder similar to the one you can set for an <code>UITextField</code>.</p>
<p>How to do this?</p> | <p>I made a few minor modifications to bcd's solution to allow for initialization from a <code>Xib</code> file, text wrapping, and to maintain background color. Hopefully it will save others the trouble.</p>
<p><strong>UIPlaceHolderTextView.h:</strong></p>
<pre><code>#import <Foundation/Foundation.h>
IB_DESIGNABLE
@interface UIPlaceHolderTextView : UITextView
@property (nonatomic, retain) IBInspectable NSString *placeholder;
@property (nonatomic, retain) IBInspectable UIColor *placeholderColor;
-(void)textChanged:(NSNotification*)notification;
@end
</code></pre>
<p><strong>UIPlaceHolderTextView.m:</strong></p>
<pre><code>#import "UIPlaceHolderTextView.h"
@interface UIPlaceHolderTextView ()
@property (nonatomic, retain) UILabel *placeHolderLabel;
@end
@implementation UIPlaceHolderTextView
CGFloat const UI_PLACEHOLDER_TEXT_CHANGED_ANIMATION_DURATION = 0.25;
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
#if __has_feature(objc_arc)
#else
[_placeHolderLabel release]; _placeHolderLabel = nil;
[_placeholderColor release]; _placeholderColor = nil;
[_placeholder release]; _placeholder = nil;
[super dealloc];
#endif
}
- (void)awakeFromNib
{
[super awakeFromNib];
// Use Interface Builder User Defined Runtime Attributes to set
// placeholder and placeholderColor in Interface Builder.
if (!self.placeholder) {
[self setPlaceholder:@""];
}
if (!self.placeholderColor) {
[self setPlaceholderColor:[UIColor lightGrayColor]];
}
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil];
}
- (id)initWithFrame:(CGRect)frame
{
if( (self = [super initWithFrame:frame]) )
{
[self setPlaceholder:@""];
[self setPlaceholderColor:[UIColor lightGrayColor]];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil];
}
return self;
}
- (void)textChanged:(NSNotification *)notification
{
if([[self placeholder] length] == 0)
{
return;
}
[UIView animateWithDuration:UI_PLACEHOLDER_TEXT_CHANGED_ANIMATION_DURATION animations:^{
if([[self text] length] == 0)
{
[[self viewWithTag:999] setAlpha:1];
}
else
{
[[self viewWithTag:999] setAlpha:0];
}
}];
}
- (void)setText:(NSString *)text {
[super setText:text];
[self textChanged:nil];
}
- (void)drawRect:(CGRect)rect
{
if( [[self placeholder] length] > 0 )
{
if (_placeHolderLabel == nil )
{
_placeHolderLabel = [[UILabel alloc] initWithFrame:CGRectMake(8,8,self.bounds.size.width - 16,0)];
_placeHolderLabel.lineBreakMode = NSLineBreakByWordWrapping;
_placeHolderLabel.numberOfLines = 0;
_placeHolderLabel.font = self.font;
_placeHolderLabel.backgroundColor = [UIColor clearColor];
_placeHolderLabel.textColor = self.placeholderColor;
_placeHolderLabel.alpha = 0;
_placeHolderLabel.tag = 999;
[self addSubview:_placeHolderLabel];
}
_placeHolderLabel.text = self.placeholder;
[_placeHolderLabel sizeToFit];
[self sendSubviewToBack:_placeHolderLabel];
}
if( [[self text] length] == 0 && [[self placeholder] length] > 0 )
{
[[self viewWithTag:999] setAlpha:1];
}
[super drawRect:rect];
}
@end
</code></pre> | {
"question_id": 1328638,
"question_date": "2009-08-25T14:26:22.567Z",
"question_score": 750,
"tags": "ios|objective-c|cocoa-touch|uitextview|placeholder",
"answer_id": 1704469,
"answer_date": "2009-11-09T22:44:52.693Z",
"answer_score": 676
} |
Please answer the following Stack Overflow question:
Title: SQL injection that gets around mysql_real_escape_string()
<p>Is there an SQL injection possibility even when using <code>mysql_real_escape_string()</code> function?</p>
<p>Consider this sample situation. SQL is constructed in PHP like this:</p>
<pre><code>$login = mysql_real_escape_string(GetFromPost('login'));
$password = mysql_real_escape_string(GetFromPost('password'));
$sql = "SELECT * FROM table WHERE login='$login' AND password='$password'";
</code></pre>
<p>I have heard numerous people say to me that code like that is still dangerous and possible to hack even with <code>mysql_real_escape_string()</code> function used. But I cannot think of any possible exploit?</p>
<p>Classic injections like this:</p>
<pre><code>aaa' OR 1=1 --
</code></pre>
<p>do not work.</p>
<p>Do you know of any possible injection that would get through the PHP code above?</p> | <p>Consider the following query:</p>
<pre><code>$iId = mysql_real_escape_string("1 OR 1=1");
$sSql = "SELECT * FROM table WHERE id = $iId";
</code></pre>
<p><code>mysql_real_escape_string()</code> will not protect you against this.
<strong>The fact that you use single quotes (<code>' '</code>) around your variables inside your query is what protects you against this.</strong> The following is also an option:</p>
<pre><code>$iId = (int)"1 OR 1=1";
$sSql = "SELECT * FROM table WHERE id = $iId";
</code></pre> | {
"question_id": 5741187,
"question_date": "2011-04-21T07:56:11.147Z",
"question_score": 750,
"tags": "php|mysql|sql|security|sql-injection",
"answer_id": 5741264,
"answer_date": "2011-04-21T08:05:21.203Z",
"answer_score": 416
} |
Please answer the following Stack Overflow question:
Title: How to hide reference counts in VS2013?
<p>Visual Studio 2013 introduced a new feature where it shows you how many times each of your methods are used.</p>
<p><img src="https://i.imgur.com/2XpPlYH.png" alt=""></p>
<p>I don't find it very useful, and it messes up the spacing of my file. How do I disable it? Can't seem to find the option.</p> | <p>I guess you probably are running the preview of VS2013 Ultimate, because it is not present in my professional preview. But looking online I found that the feature is called <code>Code Information Indicators</code> or <code>CodeLens</code>, and can be located under </p>
<blockquote>
<p><strong>Tools → Options → Text Editor → All Languages → CodeLens</strong> </p>
<p>(for RC/final version)</p>
</blockquote>
<p>or</p>
<blockquote>
<p><strong>Tools → Options → Text Editor → All Languages → Code Information Indicators</strong> </p>
<p>(for preview version)</p>
</blockquote>
<p>That was according to this <a href="http://dailydotnettips.com/2013/07/17/configuring-code-information-indicators-in-visual-studio-2013/" rel="noreferrer">link</a>. It seems to be pretty well hidden.</p>
<p><strong>In Visual Studio 2013 RTM</strong>, you can also get to the CodeLens options by right clicking the indicators themselves in the editor:</p>
<p><img src="https://i.stack.imgur.com/zZ2Tg.png" alt="editor options"></p>
<p>documented in the Q&A section of the <a href="http://msdn.microsoft.com/en-us/library/vstudio/dn269218%28v=vs.120%29.aspx" rel="noreferrer">msdn CodeLens documentation</a></p> | {
"question_id": 17847927,
"question_date": "2013-07-25T02:17:28.200Z",
"question_score": 750,
"tags": "visual-studio-2013|codelens",
"answer_id": 17848184,
"answer_date": "2013-07-25T02:49:18.333Z",
"answer_score": 842
} |
Please answer the following Stack Overflow question:
Title: How to download a file from server using SSH?
<p>I need to download a file from server to my desktop. (UBUNTU 10.04) I don't have a web access to the server, just ssh.</p>
<p>If it helps, my OS is Mac OS X and iTerm 2 as a terminal.</p> | <p>In your terminal, type:</p>
<pre><code>scp [email protected]:foobar.txt /local/dir
</code></pre>
<p>replacing the username, host, remote filename, and local directory as appropriate.</p>
<p>If you want to access EC2 (or other service that requires authenticating with a private key), use the <code>-i</code> option:</p>
<pre><code>scp -i key_file.pem [email protected]:/remote/dir/foobar.txt /local/dir
</code></pre>
<p>From: <a href="http://www.hypexr.org/linux_scp_help.php">http://www.hypexr.org/linux_scp_help.php</a></p> | {
"question_id": 9427553,
"question_date": "2012-02-24T08:25:28.777Z",
"question_score": 749,
"tags": "linux|unix|ssh",
"answer_id": 9427585,
"answer_date": "2012-02-24T08:28:23.527Z",
"answer_score": 1166
} |
Please answer the following Stack Overflow question:
Title: How to append text to an existing file in Java?
<p>I need to append text repeatedly to an existing file in Java. How do I do that?</p> | <p>Are you doing this for logging purposes? If so there are <a href="http://en.wikipedia.org/wiki/Java_logging_framework" rel="noreferrer">several libraries for this</a>. Two of the most popular are <a href="http://logging.apache.org/log4j/" rel="noreferrer">Log4j</a> and <a href="http://logback.qos.ch/" rel="noreferrer">Logback</a>.</p>
<h2>Java 7+</h2>
<p>For a one-time task, the <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html" rel="noreferrer">Files class</a> makes this easy:</p>
<pre><code>try {
Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
//exception handling left as an exercise for the reader
}
</code></pre>
<p><strong>Careful</strong>: The above approach will throw a <code>NoSuchFileException</code> if the file does not already exist. It also does not append a newline automatically (which you often want when appending to a text file). Another approach is to pass both <code>CREATE</code> and <code>APPEND</code> options, which will create the file first if it doesn't already exist:</p>
<pre><code>private void write(final String s) throws IOException {
Files.writeString(
Path.of(System.getProperty("java.io.tmpdir"), "filename.txt"),
s + System.lineSeparator(),
CREATE, APPEND
);
}
</code></pre>
<p>However, if you will be writing to the same file many times, the above snippets must open and close the file on the disk many times, which is a slow operation. In this case, a <code>BufferedWriter</code> is faster:</p>
<pre><code>try(FileWriter fw = new FileWriter("myfile.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
out.println("the text");
//more code
out.println("more text");
//more code
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
</code></pre>
<p><strong>Notes:</strong></p>
<ul>
<li>The second parameter to the <code>FileWriter</code> constructor will tell it to append to the file, rather than writing a new file. (If the file does not exist, it will be created.)</li>
<li>Using a <code>BufferedWriter</code> is recommended for an expensive writer (such as <code>FileWriter</code>).</li>
<li>Using a <code>PrintWriter</code> gives you access to <code>println</code> syntax that you're probably used to from <code>System.out</code>.</li>
<li>But the <code>BufferedWriter</code> and <code>PrintWriter</code> wrappers are not strictly necessary.</li>
</ul>
<hr />
<h2>Older Java</h2>
<pre><code>try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));
out.println("the text");
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
</code></pre>
<hr />
<h2>Exception Handling</h2>
<p>If you need robust exception handling for older Java, it gets very verbose:</p>
<pre><code>FileWriter fw = null;
BufferedWriter bw = null;
PrintWriter out = null;
try {
fw = new FileWriter("myfile.txt", true);
bw = new BufferedWriter(fw);
out = new PrintWriter(bw);
out.println("the text");
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
finally {
try {
if(out != null)
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
try {
if(fw != null)
fw.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
}
</code></pre> | {
"question_id": 1625234,
"question_date": "2009-10-26T14:43:50.190Z",
"question_score": 749,
"tags": "java|file-io|io|text-files",
"answer_id": 1625263,
"answer_date": "2009-10-26T14:47:47.780Z",
"answer_score": 902
} |
Please answer the following Stack Overflow question:
Title: How can I echo a newline in a batch file?
<p>How can you you insert a newline from your batch file output?</p>
<p>I want to do something like:</p>
<pre class="lang-bat prettyprint-override"><code>echo hello\nworld
</code></pre>
<p>Which would output:</p>
<pre class="lang-bat prettyprint-override"><code>hello
world
</code></pre> | <p><code>echo hello & echo.world</code></p>
<p>This means you could define <code>& echo.</code> as a constant for a newline <code>\n</code>.</p> | {
"question_id": 132799,
"question_date": "2008-09-25T11:50:24.720Z",
"question_score": 749,
"tags": "windows|batch-file|newline",
"answer_id": 132811,
"answer_date": "2008-09-25T11:52:13.127Z",
"answer_score": 524
} |
Please answer the following Stack Overflow question:
Title: How to remove the border highlight on an input text element
<p>When an HTML element is 'focused' (currently selected/tabbed into), many browsers (at least Safari and Chrome) will put a blue border around it.</p>
<p>For the layout I am working on, this is distracting and does not look right.</p>
<pre><code><input type="text" name="user" class="middle" id="user" tabindex="1" />
</code></pre>
<p>Firefox does not seem to do this, or at least, will let me control it with:</p>
<pre><code>border: x;
</code></pre>
<p>If someone can tell me how IE performs, I would be curious. </p>
<p>Getting Safari to remove this little bit of flare would be nice.</p> | <p>Before you do that, keep in mind that the focus outline is an accessibility and usability feature; it clues the user into what element is currently focused, and a lot of users depend on it. You need to find some other means to make focus visible.</p>
<p>In your case, try:</p>
<pre><code>input.middle:focus {
outline-width: 0;
}
</code></pre>
<p>Or in general, to affect all basic form elements:</p>
<pre><code>input:focus,
select:focus,
textarea:focus,
button:focus {
outline: none;
}
</code></pre>
<hr />
<p>In the comments, <a href="https://stackoverflow.com/users/2316623">Noah Whitmore</a> suggested taking this even further to support elements that have the <code>contenteditable</code> attribute set to <code>true</code> (effectively making them a type of input element). The following should target those as well (in CSS3 capable browsers):</p>
<pre><code>[contenteditable="true"]:focus {
outline: none;
}
</code></pre>
<p>Although I wouldn't recommend it, for completeness' sake, you could always disable the focus outline on <strong>everything</strong> with this:</p>
<pre><code>*:focus {
outline: none;
}
</code></pre> | {
"question_id": 1457849,
"question_date": "2009-09-22T02:22:23.333Z",
"question_score": 749,
"tags": "css|input|safari|webkit|border",
"answer_id": 1457976,
"answer_date": "2009-09-22T03:27:22.517Z",
"answer_score": 1327
} |
Please answer the following Stack Overflow question:
Title: makefile:4: *** missing separator. Stop
<p>This is my makefile:</p>
<pre><code>all:ll
ll:ll.c
gcc -c -Wall -Werror -02 c.c ll.c -o ll $@ $<
clean :
\rm -fr ll
</code></pre>
<p>When I try to <code>make clean</code> or <code>make make</code>, I get this error:</p>
<pre><code>:makefile:4: *** missing separator. Stop.
</code></pre>
<p>How can I fix it?</p> | <p>make defines a <a href="https://www.gnu.org/software/make/manual/make.html#Rule-Introduction" rel="noreferrer">tab is required to start each recipe</a>. All actions of every rule are identified by tabs. If you prefer to prefix your recipes with a character other than tab, you can set the .RECIPEPREFIX variable to an alternate character.</p>
<p>To check, I use the command <code>cat -e -t -v makefile_name</code>.</p>
<p>It shows the presence of tabs with <code>^I</code> and line endings with <code>$</code>. Both are vital to ensure that dependencies end properly and tabs mark the action for the rules so that they are easily identifiable to the make utility.</p>
<p>Example:</p>
<pre class="lang-bash prettyprint-override"><code>Kaizen ~/so_test $ cat -e -t -v mk.t
all:ll$ ## here the $ is end of line ...
$
ll:ll.c $
^Igcc -c -Wall -Werror -02 c.c ll.c -o ll $@ $<$
## the ^I above means a tab was there before the action part, so this line is ok .
$
clean :$
\rm -fr ll$
## see here there is no ^I which means , tab is not present ....
## in this case you need to open the file again and edit/ensure a tab
## starts the action part
</code></pre> | {
"question_id": 16931770,
"question_date": "2013-06-05T04:48:50.027Z",
"question_score": 749,
"tags": "c|makefile",
"answer_id": 16945143,
"answer_date": "2013-06-05T16:27:25.233Z",
"answer_score": 1499
} |
Please answer the following Stack Overflow question:
Title: Wait until all jQuery Ajax requests are done?
<p>How do I make a function wait until all jQuery Ajax requests are done inside another function?</p>
<p>In short, I need to wait for all Ajax requests to be done before I execute the next. But how?</p> | <p>jQuery now defines a <a href="http://api.jquery.com/jQuery.when/" rel="noreferrer">when function</a> for this purpose.</p>
<p>It accepts any number of Deferred objects as arguments, and executes a function when all of them resolve.</p>
<p>That means, if you want to initiate (for example) four ajax requests, then perform an action when they are done, you could do something like this:</p>
<pre><code>$.when(ajax1(), ajax2(), ajax3(), ajax4()).done(function(a1, a2, a3, a4){
// the code here will be executed when all four ajax requests resolve.
// a1, a2, a3 and a4 are lists of length 3 containing the response text,
// status, and jqXHR object for each of the four ajax calls respectively.
});
function ajax1() {
// NOTE: This function must return the value
// from calling the $.ajax() method.
return $.ajax({
url: "someUrl",
dataType: "json",
data: yourJsonData,
...
});
}
</code></pre>
<p>In my opinion, it makes for a clean and clear syntax, and avoids involving any global variables such as ajaxStart and ajaxStop, which could have unwanted side effects as your page develops.</p>
<p>If you don't know in advance how many ajax arguments you need to wait for (i.e. you want to use a variable number of arguments), it can still be done but is just a little bit trickier. See <a href="https://stackoverflow.com/q/5627284/1048572">Pass in an array of Deferreds to $.when()</a> (and maybe <a href="https://stackoverflow.com/questions/9865586/jquery-when-troubleshooting-with-variable-number-of-arguments">jQuery .when troubleshooting with variable number of arguments</a>).</p>
<p>If you need deeper control over the failure modes of the ajax scripts etc., you can save the object returned by <code>.when()</code> - it's a jQuery <a href="http://api.jquery.com/Types/#Promise" rel="noreferrer">Promise</a> object encompassing all of the original ajax queries. You can call <code>.then()</code> or <code>.fail()</code> on it to add detailed success/failure handlers.</p> | {
"question_id": 3709597,
"question_date": "2010-09-14T14:02:45.300Z",
"question_score": 749,
"tags": "javascript|jquery|ajax",
"answer_id": 9865124,
"answer_date": "2012-03-25T23:54:14.543Z",
"answer_score": 1006
} |
Please answer the following Stack Overflow question:
Title: Standard Android Button with a different color
<p>I'd like to change the color of a standard Android button slightly in order to better match a client's branding.</p>
<p>The best way I've found to do this so far is to change the <code>Button</code>'s drawable to the drawable located in <code>res/drawable/red_button.xml</code>:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/red_button_pressed" />
<item android:state_focused="true" android:drawable="@drawable/red_button_focus" />
<item android:drawable="@drawable/red_button_rest" />
</selector>
</code></pre>
<p>But doing that requires that I actually create three different drawables for each button I want to customize (one for the button at rest, one when focused, and one when pressed). That seems more complicated and non-DRY than I need.</p>
<p>All I really want to do is apply some sort of color transform to the button. Is there an easier way to go about changing a button's color than I'm doing?</p> | <p>I discovered that this can all be done in one file fairly easily. Put something like the following code in a file named <code>custom_button.xml</code> and then set <code>background="@drawable/custom_button"</code> in your button view:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" >
<shape>
<gradient
android:startColor="@color/yellow1"
android:endColor="@color/yellow2"
android:angle="270" />
<stroke
android:width="3dp"
android:color="@color/grey05" />
<corners
android:radius="3dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
</item>
<item android:state_focused="true" >
<shape>
<gradient
android:endColor="@color/orange4"
android:startColor="@color/orange5"
android:angle="270" />
<stroke
android:width="3dp"
android:color="@color/grey05" />
<corners
android:radius="3dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
</item>
<item>
<shape>
<gradient
android:endColor="@color/blue2"
android:startColor="@color/blue25"
android:angle="270" />
<stroke
android:width="3dp"
android:color="@color/grey05" />
<corners
android:radius="3dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
</item>
</selector>
</code></pre> | {
"question_id": 1521640,
"question_date": "2009-10-05T18:23:30.063Z",
"question_score": 749,
"tags": "android|android-layout",
"answer_id": 1726352,
"answer_date": "2009-11-13T00:19:34.667Z",
"answer_score": 738
} |
Please answer the following Stack Overflow question:
Title: How can we make xkcd style graphs?
<p>Apparently, folk have figured out how to make <a href="http://xkcd.com/" rel="noreferrer">xkcd</a> style graphs <a href="https://mathematica.stackexchange.com/questions/11350/xkcd-style-graphs">in Mathematica</a> and <a href="https://tex.stackexchange.com/questions/74878/create-xkcd-style-diagram-in-tex">in LaTeX</a>. Can we do it in R? Ggplot2-ers? A geom_xkcd and/or theme_xkcd?</p>
<p>I guess in base graphics, par(xkcd=TRUE)? How do I do it?</p>
<p><img src="https://i.stack.imgur.com/f2UqI.png" alt="xkcd#1064" title="FYI: I'll be releasing a wolf into a randomly-chosen front yard sometime in the next 30 years. Now your fear is reasonable, and you don't need to feel embarrassed anymore. Problem solved!"></p>
<p>As a first stab (and as much more elegantly shown below) in ggplot2, adding the jitter argument to a line makes for a great hand-drawn look. So - </p>
<pre><code>ggplot(mapping=aes(x=seq(1,10,.1), y=seq(1,10,.1))) +
geom_line(position="jitter", color="red", size=2) + theme_bw()
</code></pre>
<p>It makes for a nice example - but the axes and fonts appear trickier. Fonts appear solved (below), though. Is the only way to deal with axes to blank them out and draw them in by hand? Is there a more elegant solution? In particular, in ggplot2, can element_line in the new theme system be modified to take a jitter-like argument?</p> | <p>You might want to consider the following package:</p>
<p><a href="http://xkcd.r-forge.r-project.org/">Package xkcd</a>: Plotting ggplot2 graphics in a XKCD style.</p>
<pre><code>library(xkcd)
vignette("xkcd-intro")
</code></pre>
<p>Some examples (Scatterplots, Bar Charts):</p>
<ul>
<li>Scatterplot:</li>
</ul>
<p><img src="https://i.stack.imgur.com/IWMKd.png" alt="Scatterplot"></p>
<ul>
<li>Bar Chart:</li>
</ul>
<p><img src="https://i.stack.imgur.com/LyEvh.png" alt="Bar Chart"></p> | {
"question_id": 12675147,
"question_date": "2012-10-01T14:22:51.340Z",
"question_score": 749,
"tags": "r|ggplot2|plot",
"answer_id": 16597217,
"answer_date": "2013-05-16T20:49:51.410Z",
"answer_score": 459
} |
Please answer the following Stack Overflow question:
Title: 'IF' in 'SELECT' statement - choose output value based on column values
<pre><code>SELECT id, amount FROM report
</code></pre>
<p>I need <code>amount</code> to be <code>amount</code> if <code>report.type='P'</code> and <code>-amount</code> if <code>report.type='N'</code>. How do I add this to the above query?</p> | <pre><code>SELECT id,
IF(type = 'P', amount, amount * -1) as amount
FROM report
</code></pre>
<p>See <a href="http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html</a>.</p>
<p>Additionally, you could handle when the condition is null. In the case of a null amount:</p>
<pre><code>SELECT id,
IF(type = 'P', IFNULL(amount,0), IFNULL(amount,0) * -1) as amount
FROM report
</code></pre>
<p>The part <code>IFNULL(amount,0)</code> means <em>when amount is not null return amount else return 0</em>.</p> | {
"question_id": 5951157,
"question_date": "2011-05-10T13:53:31.433Z",
"question_score": 748,
"tags": "mysql|sql|database",
"answer_id": 5951204,
"answer_date": "2011-05-10T13:58:23.903Z",
"answer_score": 1101
} |
Please answer the following Stack Overflow question:
Title: Finding the number of days between two dates
<p>How to find number of days between two dates using PHP?</p> | <pre><code>$now = time(); // or your date as well
$your_date = strtotime("2010-01-31");
$datediff = $now - $your_date;
echo round($datediff / (60 * 60 * 24));
</code></pre> | {
"question_id": 2040560,
"question_date": "2010-01-11T08:06:57.490Z",
"question_score": 748,
"tags": "php|datetime",
"answer_id": 2040589,
"answer_date": "2010-01-11T08:16:23.673Z",
"answer_score": 1058
} |
Please answer the following Stack Overflow question:
Title: Regular expression to stop at first match
<p>My regex pattern looks something like</p>
<pre><code><xxxx location="file path/level1/level2" xxxx some="xxx">
</code></pre>
<p>I am only interested in the part in quotes assigned to location. Shouldn't it be as easy as below without the greedy switch? </p>
<pre><code>/.*location="(.*)".*/
</code></pre>
<p>Does not seem to work.</p> | <p>You need to make your regular expression lazy/non-greedy, because by default, <code>"(.*)"</code> will match all of <code>"file path/level1/level2" xxx some="xxx"</code>.</p>
<p>Instead you can make your dot-star non-greedy, which will make it match as few characters as possible:</p>
<pre><code>/location="(.*?)"/
</code></pre>
<p>Adding a <code>?</code> on a quantifier (<code>?</code>, <code>*</code> or <code>+</code>) makes it non-greedy.</p>
<p>Note: this is only available in regex engines which implement the Perl 5 extensions (Java, Ruby, Python, etc) but not in "traditional" regex engines (including Awk, <code>sed</code>, <code>grep</code> without <code>-P</code>, etc.).</p> | {
"question_id": 2503413,
"question_date": "2010-03-23T20:36:35.240Z",
"question_score": 748,
"tags": "regex",
"answer_id": 2503438,
"answer_date": "2010-03-23T20:40:17.060Z",
"answer_score": 1483
} |
Please answer the following Stack Overflow question:
Title: Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object
<p>I am getting this error:</p>
<pre><code>Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
</code></pre>
<p>This is my code:</p>
<pre><code>var React = require('react')
var ReactDOM = require('react-dom')
var Router = require('react-router')
var Route = Router.Route
var Link = Router.Link
var App = React.createClass({
render() {
return (
<div>
<h1>App</h1>
<ul>
<li><Link to="/about">About</Link></li>
</ul>
</div>
)
}
})
var About = require('./components/Home')
ReactDOM.render((
<Router>
<Route path="/" component={App}>
<Route path="about" component={About} />
</Route>
</Router>
), document.body)
</code></pre>
<p>My <code>Home.jsx</code> file:</p>
<pre><code>var React = require('react');
var RaisedButton = require('material-ui/lib/raised-button');
var Home = React.createClass({
render:function() {
return (
<RaisedButton label="Default" />
);
},
});
module.exports = Home;
</code></pre> | <p>In my case (<strong>using Webpack</strong>) it was the difference between:</p>
<pre class="lang-js prettyprint-override"><code>import {MyComponent} from '../components/xyz.js';
</code></pre>
<p>vs</p>
<pre class="lang-js prettyprint-override"><code>import MyComponent from '../components/xyz.js';
</code></pre>
<p>The second one works while the first is causing the error. Or the opposite.</p> | {
"question_id": 34130539,
"question_date": "2015-12-07T09:46:00.897Z",
"question_score": 748,
"tags": "javascript|node.js|reactjs|react-router|jsx",
"answer_id": 36265067,
"answer_date": "2016-03-28T15:06:33.410Z",
"answer_score": 1156
} |
Please answer the following Stack Overflow question:
Title: How can I copy the output of a command directly into my clipboard?
<p>How can I pipe the output of a command into my clipboard and paste it back when using a terminal? For instance:</p>
<pre><code>cat file | clipboard
</code></pre> | <p>I always wanted to do this and found a nice and easy way of doing it. I wrote down the complete procedure just in case anyone else needs it.</p>
<p>First install a 16 kB program called <code>xclip</code>:</p>
<pre><code>sudo apt-get install xclip
</code></pre>
<p>You can then pipe the output into <code>xclip</code> to be copied into the clipboard:</p>
<pre><code>cat file | xclip
</code></pre>
<p>To paste the text you just copied, you shall use:</p>
<pre><code>xclip -o
</code></pre>
<p>To simplify life, you can set up an alias in your .bashrc file as I did:</p>
<pre><code>alias "c=xclip"
alias "v=xclip -o"
</code></pre>
<p>To see how useful this is, imagine I want to open my current path in a new terminal window (there may be other ways of doing it like <kbd>Ctrl</kbd>+<kbd>T</kbd> on some systems, but this is just for illustration purposes):</p>
<pre><code>Terminal 1:
pwd | c
Terminal 2:
cd `v`
</code></pre>
<p>Notice the <code>` `</code> around <code>v</code>. This executes <code>v</code> as a command first and then substitutes it in-place for <code>cd</code> to use.</p>
<p>Only copy the content to the <code>X</code> clipboard</p>
<pre><code>cat file | xclip
</code></pre>
<p>If you want to paste somewhere else other than a <code>X</code> application, try this one: </p>
<pre><code>cat file | xclip -selection clipboard
</code></pre> | {
"question_id": 5130968,
"question_date": "2011-02-27T02:10:46.180Z",
"question_score": 748,
"tags": "linux|shell|unix|terminal|clipboard",
"answer_id": 5130969,
"answer_date": "2011-02-27T02:11:09.690Z",
"answer_score": 792
} |
Please answer the following Stack Overflow question:
Title: Git keeps asking me for my ssh key passphrase
<p>I created keys as instructed in the github tutorial, registered them with github, and tried using ssh-agent explicitly — yet git continues to ask me for my passphrase every time I try to do a pull or a push.</p>
<p>What could be the cause?</p> | <p>Once you have started the SSH agent with:</p>
<pre><code>eval $(ssh-agent)
</code></pre>
<p>Do either:</p>
<ol>
<li><p>To add your private key to it:</p>
<pre><code> ssh-add
</code></pre>
<p>This will ask you your passphrase just once, and then you should be allowed to push, provided that you uploaded the public key to Github.</p>
</li>
<li><p>To add and save your key permanently on <strong>macOS</strong>:</p>
<pre><code> ssh-add -K
</code></pre>
<p>This will persist it after you close and re-open it by storing it in user's keychain.</p>
<p>If you see a warning about <code>deprecated</code> flags, try the new variant:</p>
<pre><code> ssh-add --apple-use-keychain
</code></pre>
</li>
<li><p>To add and save your key permanently on <strong>Ubuntu</strong> (or equivalent):</p>
<pre><code> ssh-add ~/.ssh/id_rsa
</code></pre>
</li>
</ol> | {
"question_id": 10032461,
"question_date": "2012-04-05T16:33:49.180Z",
"question_score": 748,
"tags": "git|ssh-agent",
"answer_id": 10032655,
"answer_date": "2012-04-05T16:47:05.897Z",
"answer_score": 1405
} |
Please answer the following Stack Overflow question:
Title: How to resolve "Error: bad index – Fatal: index file corrupt" when using Git
<p>After <code>git init</code>, I added and committed a few files, made some changes, added and committed. Set up the git daemon (running under Cygwin on WinXP) and cloned the repository once.
Now, I get this error with the cloned repository:</p>
<pre><code>$ git status
error: bad index file sha1 signature
fatal: index file corrupt
</code></pre>
<p>Is there any way to fix this, other than getting a new copy of the repository?</p> | <p>If the problem is with the index as <strong>the staging area for commits</strong> (i.e. <code>.git/index</code>), you can simply remove the index (make a backup copy if you want), and then restore index to version in the last commit:</p>
<p>On OSX/Linux/Windows(With Git bash):</p>
<pre><code>rm -f .git/index
git reset
</code></pre>
<p>On Windows (with CMD and not git bash):</p>
<pre><code>del .git\index
git reset
</code></pre>
<p>(The <code>reset</code> command above is the same as <code>git reset --mixed HEAD</code>)</p>
<p>You can alternatively use lower level <a href="http://git-scm.com/book/ch9-1.html" rel="noreferrer">plumbing</a> <code>git read-tree</code> instead of <code>git reset</code>.</p>
<hr />
<p>If the problem is with <strong>index for <a href="http://git-scm.com/book/en/Git-Internals-Packfiles" rel="noreferrer">packfile</a></strong>, you can recover it using <code>git index-pack</code>.</p> | {
"question_id": 1115854,
"question_date": "2009-07-12T11:23:10.757Z",
"question_score": 748,
"tags": "git|corruption",
"answer_id": 1115956,
"answer_date": "2009-07-12T12:28:32.783Z",
"answer_score": 1558
} |
Please answer the following Stack Overflow question:
Title: Read file line by line using ifstream in C++
<p>The contents of file.txt are:</p>
<pre><code>5 3
6 4
7 1
10 5
11 6
12 3
12 4
</code></pre>
<p>Where <code>5 3</code> is a coordinate pair.
How do I process this data line by line in C++?</p>
<p>I am able to get the first line, but how do I get the next line of the file?</p>
<pre><code>ifstream myfile;
myfile.open ("file.txt");
</code></pre> | <p>First, make an <code>ifstream</code>:</p>
<pre><code>#include <fstream>
std::ifstream infile("thefile.txt");
</code></pre>
<p>The two standard methods are:</p>
<ol>
<li><p>Assume that every line consists of two numbers and read token by token:</p>
<pre><code>int a, b;
while (infile >> a >> b)
{
// process pair (a,b)
}
</code></pre></li>
<li><p>Line-based parsing, using string streams:</p>
<pre><code>#include <sstream>
#include <string>
std::string line;
while (std::getline(infile, line))
{
std::istringstream iss(line);
int a, b;
if (!(iss >> a >> b)) { break; } // error
// process pair (a,b)
}
</code></pre></li>
</ol>
<p>You shouldn't mix (1) and (2), since the token-based parsing doesn't gobble up newlines, so you may end up with spurious empty lines if you use <code>getline()</code> after token-based extraction got you to the end of a line already.</p> | {
"question_id": 7868936,
"question_date": "2011-10-23T20:24:31.450Z",
"question_score": 747,
"tags": "c++|file-io|ofstream",
"answer_id": 7868998,
"answer_date": "2011-10-23T20:34:53.720Z",
"answer_score": 1092
} |
Please answer the following Stack Overflow question:
Title: Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
<p>I want to filter my dataframe with an <code>or</code> condition to keep rows with a particular column's values that are outside the range <code>[-0.25, 0.25]</code>. I tried:</p>
<pre><code>df = df[(df['col'] < -0.25) or (df['col'] > 0.25)]
</code></pre>
<p>But I get the error:</p>
<blockquote>
<p>Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()</p>
</blockquote> | <p>The <code>or</code> and <code>and</code> python statements require <code>truth</code>-values. For <code>pandas</code>, these are considered ambiguous so you should use "bitwise" <code>|</code> (or) or <code>&</code> (and) operations:</p>
<pre><code>df = df[(df['col'] < -0.25) | (df['col'] > 0.25)]
</code></pre>
<p>These are overloaded for these kinds of data structures to yield the element-wise <code>or</code> or <code>and</code>.</p>
<hr />
<p>Just to add some more explanation to this statement:</p>
<p>The exception is thrown when you want to get the <code>bool</code> of a <code>pandas.Series</code>:</p>
<pre><code>>>> import pandas as pd
>>> x = pd.Series([1])
>>> bool(x)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
</code></pre>
<p>What you hit was a place where the operator <strong>implicitly</strong> converted the operands to <code>bool</code> (you used <code>or</code> but it also happens for <code>and</code>, <code>if</code> and <code>while</code>):</p>
<pre><code>>>> x or x
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
>>> x and x
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
>>> if x:
... print('fun')
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
>>> while x:
... print('fun')
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
</code></pre>
<p>Besides these 4 statements there are several python functions that hide some <code>bool</code> calls (like <code>any</code>, <code>all</code>, <code>filter</code>, ...) these are normally not problematic with <code>pandas.Series</code> but for completeness I wanted to mention these.</p>
<hr />
<p>In your case, the exception isn't really helpful, because it doesn't mention the <strong>right alternatives</strong>. For <code>and</code> and <code>or</code>, if you want element-wise comparisons, you can use:</p>
<ul>
<li><p><a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.logical_or.html" rel="noreferrer"><code>numpy.logical_or</code></a>:</p>
<pre><code> >>> import numpy as np
>>> np.logical_or(x, y)
</code></pre>
<p>or simply the <code>|</code> operator:</p>
<pre><code> >>> x | y
</code></pre>
</li>
<li><p><a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.logical_and.html" rel="noreferrer"><code>numpy.logical_and</code></a>:</p>
<pre><code> >>> np.logical_and(x, y)
</code></pre>
<p>or simply the <code>&</code> operator:</p>
<pre><code> >>> x & y
</code></pre>
</li>
</ul>
<p>If you're using the operators, then be sure to set your parentheses correctly because of <a href="https://docs.python.org/reference/expressions.html#operator-precedence" rel="noreferrer">operator precedence</a>.</p>
<p>There are <a href="https://docs.scipy.org/doc/numpy/reference/routines.logic.html" rel="noreferrer">several logical numpy functions</a> which <em>should</em> work on <code>pandas.Series</code>.</p>
<hr />
<p>The alternatives mentioned in the Exception are more suited if you encountered it when doing <code>if</code> or <code>while</code>. I'll shortly explain each of these:</p>
<ul>
<li><p>If you want to check if your Series is <strong>empty</strong>:</p>
<pre><code> >>> x = pd.Series([])
>>> x.empty
True
>>> x = pd.Series([1])
>>> x.empty
False
</code></pre>
<p>Python normally interprets the <code>len</code>gth of containers (like <code>list</code>, <code>tuple</code>, ...) as truth-value if it has no explicit boolean interpretation. So if you want the python-like check, you could do: <code>if x.size</code> or <code>if not x.empty</code> instead of <code>if x</code>.</p>
</li>
<li><p>If your <code>Series</code> contains <strong>one and only one</strong> boolean value:</p>
<pre><code> >>> x = pd.Series([100])
>>> (x > 50).bool()
True
>>> (x < 50).bool()
False
</code></pre>
</li>
<li><p>If you want to check the <strong>first and only item</strong> of your Series (like <code>.bool()</code> but works even for not boolean contents):</p>
<pre><code> >>> x = pd.Series([100])
>>> x.item()
100
</code></pre>
</li>
<li><p>If you want to check if <strong>all</strong> or <strong>any</strong> item is not-zero, not-empty or not-False:</p>
<pre><code> >>> x = pd.Series([0, 1, 2])
>>> x.all() # because one element is zero
False
>>> x.any() # because one (or more) elements are non-zero
True
</code></pre>
</li>
</ul> | {
"question_id": 36921951,
"question_date": "2016-04-28T17:46:30.520Z",
"question_score": 747,
"tags": "python|pandas|dataframe|boolean|filtering",
"answer_id": 36922103,
"answer_date": "2016-04-28T17:54:30.553Z",
"answer_score": 987
} |
Please answer the following Stack Overflow question:
Title: How to remove spaces from a string using JavaScript?
<p>How to remove spaces in a string? For instance:</p>
<p><strong>Input:</strong></p>
<pre><code>'/var/www/site/Brand new document.docx'
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>'/var/www/site/Brandnewdocument.docx'
</code></pre> | <p>This?</p>
<pre><code>str = str.replace(/\s/g, '');
</code></pre>
<p>Example</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var str = '/var/www/site/Brand new document.docx';
document.write( str.replace(/\s/g, '') );</code></pre>
</div>
</div>
</p>
<hr>
<p><strong>Update:</strong> Based on <a href="https://stackoverflow.com/questions/5964373/is-there-a-difference-between-s-g-and-s-g">this question</a>, this:</p>
<pre><code>str = str.replace(/\s+/g, '');
</code></pre>
<p>is a better solution. It produces the same result, but it does it faster.</p>
<p><strong>The Regex</strong></p>
<p><code>\s</code> is the regex for "whitespace", and <code>g</code> is the "global" flag, meaning match ALL <code>\s</code> (whitespaces). </p>
<p>A great explanation for <code>+</code> can be found <a href="https://stackoverflow.com/questions/5964373/is-there-a-difference-between-s-g-and-s-g">here</a>.</p>
<p>As a side note, you could replace the content between the single quotes to anything you want, so you can replace whitespace with any other string.</p> | {
"question_id": 5963182,
"question_date": "2011-05-11T11:04:12.270Z",
"question_score": 747,
"tags": "javascript|text",
"answer_id": 5963202,
"answer_date": "2011-05-11T11:06:00.757Z",
"answer_score": 1629
} |
Please answer the following Stack Overflow question:
Title: What is the difference between == and equals() in Java?
<p>I wanted to clarify if I understand this correctly:</p>
<ul>
<li><code>==</code> is a reference comparison, i.e. both objects point to the same memory location</li>
<li><code>.equals()</code> evaluates to the comparison of values in the objects</li>
</ul> | <p>In general, the answer to your question is "yes", but...</p>
<ul>
<li><code>.equals(...)</code> will only compare what it is written to compare, no more, no less.</li>
<li>If a class does not override the equals method, then it defaults to the <code>equals(Object o)</code> method of the closest parent class that has overridden this method. </li>
<li>If no parent classes have provided an override, then it defaults to the method from the ultimate parent class, Object, and so you're left with the <code>Object#equals(Object o)</code> method. Per the Object API this is the same as <code>==</code>; that is, it returns true <em>if and only if</em> both variables refer to the same object, if their references are one and the same. Thus you will be testing for <strong>object equality</strong> and not <strong>functional equality</strong>.</li>
<li>Always remember to override <code>hashCode</code> if you override <code>equals</code> so as not to "break the contract". As per the API, the result returned from the <code>hashCode()</code> method for two objects <strong>must</strong> be the same if their <code>equals</code> methods show that they are equivalent. The converse is <em>not</em> necessarily true. </li>
</ul> | {
"question_id": 7520432,
"question_date": "2011-09-22T19:36:43.463Z",
"question_score": 747,
"tags": "java|identity|equality|object-comparison",
"answer_id": 7520464,
"answer_date": "2011-09-22T19:39:18.297Z",
"answer_score": 718
} |
Please answer the following Stack Overflow question:
Title: How do I alias commands in git?
<p>I saw a screencast where someone had gotten </p>
<pre><code>git st
git ci
</code></pre>
<p>to work. When I do it I get an error asking me if I meant something else.<br>
Being a git newb, I need to know what you have to do to get this done?</p> | <p>Basically you just need to add lines to <code>~/.gitconfig</code></p>
<pre><code>[alias]
st = status
ci = commit -v
</code></pre>
<p>Or you can use the git config alias command:</p>
<pre><code>$ git config --global alias.st status
</code></pre>
<p>On unix, use single quotes if the alias has a space:</p>
<pre><code>$ git config --global alias.ci 'commit -v'
</code></pre>
<p>On windows, use double quotes if the alias has a space or a command line argument:</p>
<pre><code>c:\dev> git config --global alias.ci "commit -v"
</code></pre>
<p>The alias command even accepts functions as parameters. Take a look at <a href="https://git.wiki.kernel.org/index.php/Aliases#Aliases" rel="noreferrer">aliases</a>.</p> | {
"question_id": 2553786,
"question_date": "2010-03-31T14:31:20.063Z",
"question_score": 747,
"tags": "git|git-alias",
"answer_id": 2553799,
"answer_date": "2010-03-31T14:33:40.197Z",
"answer_score": 1174
} |
Please answer the following Stack Overflow question:
Title: How to write ternary conditional operator?
<p>What is the equivalent of this expression in Kotlin?</p>
<pre><code>a ? b : c
</code></pre>
<p>This is not valid code in Kotlin.</p> | <p>In Kotlin, <code>if</code> statements are expressions. So the following code is equivalent:</p>
<pre><code>if (a) b else c
</code></pre>
<p>The distinction between expression and statement is important here. In Java/C#/JavaScript, <code>if</code> forms a statement, meaning that it does not resolve to a value. More concretely, you can't assign it to a variable.</p>
<pre><code>// Valid Kotlin, but invalid Java/C#/JavaScript
var v = if (a) b else c
</code></pre>
<p>If you're coming from a language where <code>if</code> is a statement, this might seem unnatural but that feeling should soon subside.</p> | {
"question_id": 16336500,
"question_date": "2013-05-02T11:07:57.070Z",
"question_score": 747,
"tags": "kotlin|conditional-operator",
"answer_id": 16336507,
"answer_date": "2013-05-02T11:08:15.273Z",
"answer_score": 968
} |
Please answer the following Stack Overflow question:
Title: When to use single quotes, double quotes, and backticks in MySQL
<p>I am trying to learn the best way to write queries. I also understand the importance of being consistent. Until now, I have randomly used single quotes, double quotes, and backticks without any real thought.</p>
<p>Example:</p>
<pre><code>$query = 'INSERT INTO table (id, col1, col2) VALUES (NULL, val1, val2)';
</code></pre>
<p>Also, in the above example, consider that <code>table</code>, <code>col1</code>, <code>val1</code>, etc. may be variables.</p>
<p>What is the standard for this? What do you do?</p>
<p><sub>I've been reading answers to similar questions on here for about 20 minutes, but it seems like there is no definitive answer to this question.</sub></p> | <p>Backticks are to be used for table and column identifiers, but are only necessary when the identifier is a <a href="https://dev.mysql.com/doc/refman/5.7/en/keywords.html" rel="noreferrer">MySQL reserved keyword</a>, or when the identifier contains whitespace characters or characters beyond a limited set (see below) It is often recommended to avoid using reserved keywords as column or table identifiers when possible, avoiding the quoting issue.</p>
<p>Single quotes should be used for string values like in the <code>VALUES()</code> list. Double quotes are supported by MySQL for string values as well, but single quotes are more widely accepted by other RDBMS, so it is a good habit to use single quotes instead of double.</p>
<p>MySQL also expects <code>DATE</code> and <code>DATETIME</code> literal values to be single-quoted as strings like <code>'2001-01-01 00:00:00'</code>. Consult <a href="https://dev.mysql.com/doc/refman/5.7/en/date-and-time-literals.html" rel="noreferrer">the Date and Time Literals</a> documentation for more details, in particular alternatives to using the hyphen <code>-</code> as a segment delimiter in date strings.</p>
<p>So using your example, I would double-quote the PHP string and use single quotes on the values <code>'val1', 'val2'</code>. <code>NULL</code> is a MySQL keyword, and a special (non)-value, and is therefore unquoted.</p>
<p>None of these table or column identifiers are reserved words or make use of characters requiring quoting, but I've quoted them anyway with backticks (more on this later...).</p>
<p>Functions native to the RDBMS (for example, <code>NOW()</code> in MySQL) should not be quoted, although their arguments are subject to the same string or identifier quoting rules already mentioned.</p>
<pre>Backtick (`)
table & column ───────┬─────┬──┬──┬──┬────┬──┬────┬──┬────┬──┬───────┐
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
$query = "<b>INSERT INTO `table` (`id`, `col1`, `col2`, `date`, `updated`)
VALUES (NULL, 'val1', 'val2', '2001-01-01', NOW())</b>";
↑↑↑↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑↑↑↑↑
Unquoted keyword ─────┴┴┴┘ │ │ │ │ │ │ │││││
Single-quoted (') strings ───────────┴────┴──┴────┘ │ │ │││││
Single-quoted (') DATE ───────────────────────────┴──────────┘ │││││
Unquoted function ─────────────────────────────────────────┴┴┴┴┘
</pre>
<h3>Variable interpolation</h3>
<p>The quoting patterns for variables do not change, although if you intend to interpolate the variables directly in a string, it must be double-quoted in PHP. Just make sure that you have properly escaped the variables for use in SQL. (<a href="https://stackoverflow.com/questions/60174/how-to-prevent-sql-injection-in-php">It is recommended to use an API supporting prepared statements instead, as protection against SQL injection</a>).</p>
<pre>// Same thing with some variable replacements
// Here, a variable table name $table is backtick-quoted, and variables
// in the VALUES list are single-quoted
$query = "INSERT INTO <b>`$table`</b> (`id`, `col1`, `col2`, `date`) VALUES (NULL, <b>'$val1'</b>, <b>'$val2'</b>, <b>'$date'</b>)";
</pre>
<h3>Prepared statements</h3>
<p>When working with prepared statements, consult the documentation to determine whether or not the statement's placeholders must be quoted. The most popular APIs available in PHP, PDO and MySQLi, expect <em>unquoted</em> placeholders, as do most prepared statement APIs in other languages:</p>
<pre><code>// PDO example with named parameters, unquoted
$query = "INSERT INTO `table` (`id`, `col1`, `col2`, `date`) VALUES (:id, :col1, :col2, :date)";
// MySQLi example with ? parameters, unquoted
$query = "INSERT INTO `table` (`id`, `col1`, `col2`, `date`) VALUES (?, ?, ?, ?)";
</code></pre>
<h3>Characters requring backtick quoting in identifiers:</h3>
<p><a href="http://dev.mysql.com/doc/refman/5.5/en/identifiers.html" rel="noreferrer">According to MySQL documentation</a>, you do not need to quote (backtick) identifiers using the following character set:</p>
<blockquote>
<p>ASCII: <code>[0-9,a-z,A-Z$_]</code> (basic Latin letters, digits 0-9, dollar, underscore)</p>
</blockquote>
<p>You can use characters beyond that set as table or column identifiers, including whitespace for example, but then you <em>must</em> quote (backtick) them.</p>
<p>Also, although numbers are valid characters for identifiers, identifiers cannot consist solely of numbers. If they do they must be wrapped in backticks.</p> | {
"question_id": 11321491,
"question_date": "2012-07-04T01:53:36.917Z",
"question_score": 747,
"tags": "mysql|sql|quotes",
"answer_id": 11321508,
"answer_date": "2012-07-04T01:57:55.800Z",
"answer_score": 724
} |
Please answer the following Stack Overflow question:
Title: jQuery Ajax POST example with PHP
<p>I am trying to send data from a form to a database. Here is the form I am using:</p>
<pre><code><form name="foo" action="form.php" method="POST" id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>
</code></pre>
<p>The typical approach would be to submit the form, but this causes the browser to redirect. Using jQuery and <a href="http://en.wikipedia.org/wiki/Ajax_%28programming%29" rel="noreferrer">Ajax</a>, is it possible to capture all of the form's data and submit it to a PHP script (an example, <em>form.php</em>)?</p> | <p>Basic usage of <a href="https://api.jquery.com/jQuery.ajax/" rel="noreferrer"><code>.ajax</code></a> would look something like this:</p>
<p><strong>HTML:</strong></p>
<pre><code><form id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>
</code></pre>
<p><strong>jQuery:</strong></p>
<pre><code>// Variable to hold request
var request;
// Bind to the submit event of our form
$("#foo").submit(function(event){
// Prevent default posting of form - put here to work in case of errors
event.preventDefault();
// Abort any pending request
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// Let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// Serialize the data in the form
var serializedData = $form.serialize();
// Let's disable the inputs for the duration of the Ajax request.
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);
// Fire off the request to /form.php
request = $.ajax({
url: "/form.php",
type: "post",
data: serializedData
});
// Callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// Log a message to the console
console.log("Hooray, it worked!");
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// Log the error to the console
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// Reenable the inputs
$inputs.prop("disabled", false);
});
});
</code></pre>
<p><em>Note: Since jQuery 1.8, <code>.success()</code>, <code>.error()</code> and <code>.complete()</code> are deprecated in favor of <code>.done()</code>, <code>.fail()</code> and <code>.always()</code>.</em></p>
<p><em>Note: Remember that the above snippet has to be done after DOM ready, so you should put it inside a <a href="https://api.jquery.com/ready/" rel="noreferrer"><code>$(document).ready()</code></a> handler (or use the <code>$()</code> shorthand).</em></p>
<p><em>Tip: You can <a href="http://www.jquerybyexample.net/2012/06/what-is-chaining-in-jquery.html" rel="noreferrer">chain</a> the callback handlers like this: <code>$.ajax().done().fail().always();</code></em></p>
<p><strong>PHP (that is, form.php):</strong></p>
<pre><code>// You can access the values posted by jQuery.ajax
// through the global variable $_POST, like this:
$bar = isset($_POST['bar']) ? $_POST['bar'] : null;
</code></pre>
<p><em>Note: Always <a href="https://stackoverflow.com/questions/1314518/sanitizing-users-data-in-get-by-php">sanitize posted data</a>, to prevent injections and other malicious code.</em></p>
<p>You could also use the shorthand <a href="https://api.jquery.com/jQuery.post/" rel="noreferrer"><code>.post</code></a> in place of <code>.ajax</code> in the above JavaScript code:</p>
<pre><code>$.post('/form.php', serializedData, function(response) {
// Log the response to the console
console.log("Response: "+response);
});
</code></pre>
<p><em>Note: The above JavaScript code is made to work with jQuery 1.8 and later, but it should work with previous versions down to jQuery 1.5.</em></p> | {
"question_id": 5004233,
"question_date": "2011-02-15T13:28:57.217Z",
"question_score": 746,
"tags": "javascript|jquery|ajax|post",
"answer_id": 5004276,
"answer_date": "2011-02-15T13:32:44.673Z",
"answer_score": 1011
} |
Please answer the following Stack Overflow question:
Title: What is the difference between Cygwin and MinGW?
<p>I want to make my C++ project cross platform, and I'm considering using Cygwin/MinGW.
But what is the difference between them ?</p>
<p>Another question is whether I will be able to run the binary on a system without Cygwin/MinGW ?</p> | <p><strong>As a simplification, it's like this:</strong></p>
<ul>
<li><p>Compile something in Cygwin and you are compiling it <em>for Cygwin</em>.</p>
</li>
<li><p>Compile something in MinGW and you are compiling it <em>for Windows</em>.</p>
</li>
</ul>
<p><strong>About Cygwin</strong></p>
<p>Cygwin is a compatibility layer that makes it easy to port simple Unix-based applications to Windows, by emulating many of the basic interfaces that Unix-based operating systems provide, such as pipes, Unix-style file and directory access, and so on as documented by the <a href="https://en.wikipedia.org/wiki/POSIX" rel="noreferrer">POSIX</a> standards. If you have existing source code that uses these interfaces, you may be able to compile it for use with Cygwin after making very few or even no changes, greatly simplifying the process of porting simple IO based Unix code for use on Windows.</p>
<p>When you distribute your software, the recipient will need to run it along with the Cygwin run-time environment (provided by the file <code>cygwin1.dll</code>). You may distribute this with your software, but your software will have to comply with its open source license. Even just linking your software with it, but distributing the dll separately, can still impose license restrictions on your code.</p>
<p><strong>About MinGW</strong></p>
<p>MinGW aims to simply be a port of GNU's development tools for Windows. It does not attempt to emulate or provide comprehensive compatibility with Unix, other that to provide a version of the GNU Compiler Collection, GNU Binutils and GNU Debugger that can be used natively in Windows. It also includes header files allowing the use of Windows' native API in your code.</p>
<p>As a result your application needs to specifically be programmed for Windows, using the Windows API, which may mean significant alteration if it was created to rely on being run in a standard Unix environment and use Unix-specific features. By default, code compiled in MinGW's GCC will compile to a native Windows X86 target, including .exe and .dll files, though you could also cross-compile with the right settings, since you are basically using the GNU compiler tools suite.</p>
<p>MinGW is a free and open source alternative to using the <a href="https://en.wikipedia.org/wiki/Visual_C%2B%2B" rel="noreferrer">Microsoft Visual C++</a> compiler and its associated linking/make tools on Windows. It may be possible in some cases to use MinGW to compile something that was intended for compiling with Microsoft Visual C++ without too many modifications.</p>
<p>Even though MingW includes some header files and interface code allowing your code to interact with the Windows API, as with the regular standard libraries this doesn't impose licensing restrictions on software you have created.</p>
<p><strong>Other considerations</strong></p>
<p>For any non-trivial software application, such as one that uses a graphical interface, multimedia or accesses devices on the system, you leave the boundary of what Cygwin can do for you and further work will be needed to make your code cross-platform. But, this task can be simplified by using cross-platform toolkits or frameworks that allow coding once and having your code compile successfully for any platform. If you use such a framework from the start, you can not only reduce your headaches when it comes time to port to another platform but you can use the same graphical widgets - windows, menus and controls - across all platforms if you're writing a GUI app, and have them appear native to the user.</p>
<p>For instance, the open source <a href="https://en.wikipedia.org/wiki/Qt_(framework)" rel="noreferrer">Qt framework</a> is a popular and comprehensive cross-platform development framework, allowing the building of graphical applications that work across operating systems including windows. There are other such frameworks too. In addition to the large frameworks there are thousands of more specialized software libraries in existence which support multiple platforms allowing you to worry less about writing different code for different platforms.</p>
<p>When you are developing cross-platform software from the start, you would not normally have any reason to use Cygwin. When compiled on Windows, you would usually aim to make your code able to be compiled with either MingW or Microsoft Visual C/C++, or both. When compiling on Linux/*nix, you'd most often compile it with the GNU compilers and tools directly.</p> | {
"question_id": 771756,
"question_date": "2009-04-21T09:16:37.470Z",
"question_score": 746,
"tags": "windows|cygwin|mingw",
"answer_id": 792142,
"answer_date": "2009-04-27T03:15:41.377Z",
"answer_score": 724
} |
Please answer the following Stack Overflow question:
Title: What does the star and doublestar operator mean in a function call?
<p>What does the <code>*</code> operator mean in Python, such as in code like <code>zip(*x)</code> or <code>f(**k)</code>?</p>
<ol>
<li>How is it handled internally in the interpreter?</li>
<li>Does it affect performance at all? Is it fast or slow?</li>
<li>When is it useful and when is it not?</li>
<li>Should it be used in a function declaration or in a call?</li>
</ol> | <p>The single star <code>*</code> unpacks the sequence/collection into positional arguments, so you can do this:</p>
<pre><code>def sum(a, b):
return a + b
values = (1, 2)
s = sum(*values)
</code></pre>
<p>This will unpack the tuple so that it actually executes as:</p>
<pre><code>s = sum(1, 2)
</code></pre>
<p>The double star <code>**</code> does the same, only using a dictionary and thus named arguments:</p>
<pre><code>values = { 'a': 1, 'b': 2 }
s = sum(**values)
</code></pre>
<p>You can also combine:</p>
<pre><code>def sum(a, b, c, d):
return a + b + c + d
values1 = (1, 2)
values2 = { 'c': 10, 'd': 15 }
s = sum(*values1, **values2)
</code></pre>
<p>will execute as: </p>
<pre><code>s = sum(1, 2, c=10, d=15)
</code></pre>
<p>Also see section <a href="http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists" rel="noreferrer">4.7.4 - Unpacking Argument Lists</a> of the Python documentation.</p>
<hr>
<p>Additionally you can define functions to take <code>*x</code> and <code>**y</code> arguments, this allows a function to accept any number of positional and/or named arguments that aren't specifically named in the declaration.</p>
<p>Example:</p>
<pre><code>def sum(*values):
s = 0
for v in values:
s = s + v
return s
s = sum(1, 2, 3, 4, 5)
</code></pre>
<p>or with <code>**</code>:</p>
<pre><code>def get_a(**values):
return values['a']
s = get_a(a=1, b=2) # returns 1
</code></pre>
<p>this can allow you to specify a large number of optional parameters without having to declare them.</p>
<p>And again, you can combine:</p>
<pre><code>def sum(*values, **options):
s = 0
for i in values:
s = s + i
if "neg" in options:
if options["neg"]:
s = -s
return s
s = sum(1, 2, 3, 4, 5) # returns 15
s = sum(1, 2, 3, 4, 5, neg=True) # returns -15
s = sum(1, 2, 3, 4, 5, neg=False) # returns 15
</code></pre> | {
"question_id": 2921847,
"question_date": "2010-05-27T14:10:38.667Z",
"question_score": 746,
"tags": "python|syntax|parameter-passing|iterable-unpacking|argument-unpacking",
"answer_id": 2921893,
"answer_date": "2010-05-27T14:15:08.097Z",
"answer_score": 1124
} |
Please answer the following Stack Overflow question:
Title: How to filter Pandas dataframe using 'in' and 'not in' like in SQL
<p>How can I achieve the equivalents of SQL's <code>IN</code> and <code>NOT IN</code>?</p>
<p>I have a list with the required values.
Here's the scenario:</p>
<pre><code>df = pd.DataFrame({'country': ['US', 'UK', 'Germany', 'China']})
countries_to_keep = ['UK', 'China']
# pseudo-code:
df[df['country'] not in countries_to_keep]
</code></pre>
<p>My current way of doing this is as follows:</p>
<pre><code>df = pd.DataFrame({'country': ['US', 'UK', 'Germany', 'China']})
df2 = pd.DataFrame({'country': ['UK', 'China'], 'matched': True})
# IN
df.merge(df2, how='inner', on='country')
# NOT IN
not_in = df.merge(df2, how='left', on='country')
not_in = not_in[pd.isnull(not_in['matched'])]
</code></pre>
<p>But this seems like a horrible kludge. Can anyone improve on it?</p> | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html" rel="nofollow noreferrer"><code>pd.Series.isin</code></a>.</p>
<p>For "IN" use: <code>something.isin(somewhere)</code></p>
<p>Or for "NOT IN": <code>~something.isin(somewhere)</code></p>
<p>As a worked example:</p>
<pre><code>>>> df
country
0 US
1 UK
2 Germany
3 China
>>> countries_to_keep
['UK', 'China']
>>> df.country.isin(countries_to_keep)
0 False
1 True
2 False
3 True
Name: country, dtype: bool
>>> df[df.country.isin(countries_to_keep)]
country
1 UK
3 China
>>> df[~df.country.isin(countries_to_keep)]
country
0 US
2 Germany
</code></pre> | {
"question_id": 19960077,
"question_date": "2013-11-13T17:11:07.133Z",
"question_score": 745,
"tags": "python|pandas|dataframe|sql-function",
"answer_id": 19960116,
"answer_date": "2013-11-13T17:13:39.863Z",
"answer_score": 1322
} |
Please answer the following Stack Overflow question:
Title: How to link to a named anchor in Multimarkdown?
<p>I have come across a number of mentions of MultiMarkdown's support for internal links / named anchors but I am unable to find a single example of how to actually do it. </p>
<p>So, what is the syntax for denoting the named anchor, and what is the syntax for linking to it the same as linking to any other URLs (only using #foo instead of <code>http://....</code>)? </p> | <p>Taken from the <a href="http://fletcher.github.com/peg-multimarkdown/index#cross-references">Multimarkdown Users Guide</a> (thanks to @MultiMarkdown on Twitter for pointing it out)</p>
<p><code>[Some Text][]</code>will link to a header named “Some Text”<br>
e.g. </p>
<pre><code>### Some Text ###
</code></pre>
<p>An optional label of your choosing to help disambiguate cases where multiple headers have the same title:</p>
<pre><code>### Overview [MultiMarkdownOverview] ##
</code></pre>
<blockquote>
<p>This allows you to use [MultiMarkdownOverview] to refer to this section specifically, and not another section named Overview. This works with atx- or settext-style headers.</p>
<p>If you have already defined an anchor using the same id that is used by a header, then the defined anchor takes precedence.</p>
<p>In addition to headers within the document, you can provide labels for images and tables which can then be used for cross-references as well.</p>
</blockquote> | {
"question_id": 6695439,
"question_date": "2011-07-14T15:06:14.780Z",
"question_score": 745,
"tags": "markdown|multimarkdown",
"answer_id": 6706594,
"answer_date": "2011-07-15T11:51:42.710Z",
"answer_score": 149
} |
Please answer the following Stack Overflow question:
Title: How can I get the list of files in a directory using C or C++?
<p>How can I determine the list of files in a directory from inside my C or C++ code?</p>
<p>I'm not allowed to execute the <code>ls</code> command and parse the results from within my program.</p> | <p><strong>UPDATE 2017</strong>:</p>
<p>In C++17 there is now an official way to list files of your file system: <code>std::filesystem</code>. There is an excellent answer from <a href="https://stackoverflow.com/a/37494654/23264"><strong>Shreevardhan</strong></a> below with this source code:</p>
<blockquote>
<pre><code>#include <string>
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main()
{
std::string path = "/path/to/directory";
for (const auto & entry : fs::directory_iterator(path))
std::cout << entry.path() << std::endl;
}
</code></pre>
</blockquote>
<p><strong>Old Answer:</strong></p>
<p>In small and simple tasks I do not use boost, I use <strong>dirent.h</strong>. It is available as a standard header in UNIX, and also available for Windows via a <a href="https://github.com/tronkko/dirent" rel="noreferrer">compatibility layer created by Toni Ronkko</a>.</p>
<pre><code>DIR *dir;
struct dirent *ent;
if ((dir = opendir ("c:\\src\\")) != NULL) {
/* print all the files and directories within directory */
while ((ent = readdir (dir)) != NULL) {
printf ("%s\n", ent->d_name);
}
closedir (dir);
} else {
/* could not open directory */
perror ("");
return EXIT_FAILURE;
}
</code></pre>
<p>It is just a small header file and does most of the simple stuff you need without using a big template-based approach like boost (no offence, I like boost!).</p> | {
"question_id": 612097,
"question_date": "2009-03-04T19:35:58.303Z",
"question_score": 744,
"tags": "c++|c|file|directory",
"answer_id": 612176,
"answer_date": "2009-03-04T19:57:51.700Z",
"answer_score": 1026
} |
Please answer the following Stack Overflow question:
Title: Using LINQ to remove elements from a List<T>
<p>Say that I have LINQ query such as:</p>
<pre><code>var authors = from x in authorsList
where x.firstname == "Bob"
select x;
</code></pre>
<p>Given that <code>authorsList</code> is of type <code>List<Author></code>, how can I delete the <code>Author</code> elements from <code>authorsList</code> that are returned by the query into <code>authors</code>?</p>
<p>Or, put another way, how can I delete all of the firstname's equalling Bob from <code>authorsList</code>?</p>
<p>Note: This is a simplified example for the purposes of the question.</p> | <p>Well, it would be easier to exclude them in the first place:</p>
<pre><code>authorsList = authorsList.Where(x => x.FirstName != "Bob").ToList();
</code></pre>
<p>However, that would just change the value of <code>authorsList</code> instead of removing the authors from the previous collection. Alternatively, you can use <a href="http://msdn.microsoft.com/en-us/library/wdka673a.aspx" rel="noreferrer"><code>RemoveAll</code></a>:</p>
<pre><code>authorsList.RemoveAll(x => x.FirstName == "Bob");
</code></pre>
<p>If you really need to do it based on another collection, I'd use a HashSet, RemoveAll and Contains:</p>
<pre><code>var setToRemove = new HashSet<Author>(authors);
authorsList.RemoveAll(x => setToRemove.Contains(x));
</code></pre> | {
"question_id": 853526,
"question_date": "2009-05-12T15:56:24.570Z",
"question_score": 744,
"tags": "c#|.net|linq|list",
"answer_id": 853551,
"answer_date": "2009-05-12T16:01:39.680Z",
"answer_score": 1288
} |
Please answer the following Stack Overflow question:
Title: Rename a file in C#
<p>How do I rename a file using C#?</p> | <p>Take a look at <a href="http://msdn.microsoft.com/en-us/library/system.io.file.move.aspx" rel="noreferrer">System.IO.File.Move</a>, "move" the file to a new name.</p>
<pre><code>System.IO.File.Move("oldfilename", "newfilename");
</code></pre> | {
"question_id": 3218910,
"question_date": "2010-07-10T11:05:54.027Z",
"question_score": 744,
"tags": "c#|file|rename",
"answer_id": 3218923,
"answer_date": "2010-07-10T11:08:22.167Z",
"answer_score": 1141
} |
Please answer the following Stack Overflow question:
Title: node.js remove file
<p>How do I delete a file with node.js?</p>
<p><a href="http://nodejs.org/api/fs.html#fs_fs_rename_oldpath_newpath_callback" rel="noreferrer">http://nodejs.org/api/fs.html#fs_fs_rename_oldpath_newpath_callback</a></p>
<p>I don't see a remove command?</p> | <p>I think you want to use <a href="https://nodejs.org/api/fs.html#fs_fs_unlink_path_callback" rel="noreferrer"><code>fs.unlink</code></a>.</p>
<p>More info on <code>fs</code> can be found <a href="https://nodejs.org/api/fs.html#fs_file_system" rel="noreferrer">here</a>.</p> | {
"question_id": 5315138,
"question_date": "2011-03-15T16:55:43.427Z",
"question_score": 744,
"tags": "node.js",
"answer_id": 5315175,
"answer_date": "2011-03-15T16:58:03.200Z",
"answer_score": 995
} |
Please answer the following Stack Overflow question:
Title: How do I view events fired on an element in Chrome DevTools?
<p>I have a customizable form element on a page from a library. I want to see what javascript events are fired when I interact with it because I am trying to find out which event handler to use.</p>
<p>How do I do that using Chrome Web Developer?</p> | <ul>
<li>Hit <kbd>F12</kbd> to open Dev Tools</li>
<li>Click the Sources tab</li>
<li>On right-hand side, scroll down to "Event Listener Breakpoints", and expand tree</li>
<li>Click on the events you want to listen for. </li>
<li>Interact with the target element, if they fire you will get a break point in the debugger</li>
</ul>
<p>Similarly, you can right click on the target element -> select "inspect element" Scroll down on the right side of the dev frame, at the bottom is 'event listeners'. Expand the tree to see what events are attached to the element. Not sure if this works for events that are handled through bubbling (I'm guessing not)</p> | {
"question_id": 10213703,
"question_date": "2012-04-18T16:23:22.633Z",
"question_score": 744,
"tags": "javascript|google-chrome-devtools",
"answer_id": 10213800,
"answer_date": "2012-04-18T16:29:12.267Z",
"answer_score": 1037
} |
Please answer the following Stack Overflow question:
Title: Set default syntax to different filetype in Sublime Text 2
<p>How do I set a default filetype for a certain file extension in Sublime Text 2? Specifically I want to have *.cfg files default to having Ini syntax highlighting but I cannot seem to figure out how I could create this custom setting.</p> | <p>In the current version of Sublime Text 2 (Build: 2139), you can set the syntax for all files of a certain file extension using an option in the menu bar. Open a file with the extension you want to set a default for and navigate through the following menus: <code>View -> Syntax -> Open all with current extension as... ->[your syntax choice]</code>.</p>
<p><strong>Updated 2012-06-28:</strong> Recent builds of Sublime Text 2 (at least since Build 2181) have allowed the syntax to be set by clicking the current syntax type in the lower right corner of the window. This will open the syntax selection menu with the option to <code>Open all with current extension as...</code> at the top of the menu.</p>
<p><strong>Updated 2016-04-19:</strong> As of now, this also works for Sublime Text 3.</p> | {
"question_id": 7574502,
"question_date": "2011-09-27T19:16:42.317Z",
"question_score": 744,
"tags": "sublimetext2|text-editor|sublimetext",
"answer_id": 8014142,
"answer_date": "2011-11-04T18:33:46.967Z",
"answer_score": 1623
} |
Please answer the following Stack Overflow question:
Title: How to add a browser tab icon (favicon) for a website?
<p>I've been working on a website and I'd like to add a small icon to the browser tab.</p>
<p>How can I do this in HTML and where in the code would I need to place it (e.g. header)? I have a <code>.png</code> logo file that I'd like to convert to an icon.</p>
<p>Related: <a href="https://stackoverflow.com/questions/2359866/html-set-image-on-browser-tab">HTML set image on browser tab</a>.</p> | <p>There are actually two ways to add a favicon to a website.</p>
<h1><code><link rel="icon"></code></h1>
<p>Simply add the following code to the <code><head></code> element:</p>
<pre><code><link rel="icon" href="http://example.com/favicon.png">
</code></pre>
<p>PNG favicons <a href="http://caniuse.com/#feat=link-icon-png" rel="noreferrer">are supported by most browsers, except IE <= 10</a>. For backwards compatibility, you can use ICO favicons.</p>
<p>Note that you <strong>don't have to precede <code>icon</code> in <code>rel</code> attribute with <code>shortcut</code></strong> anymore. From <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Link_types" rel="noreferrer">MDN Link types</a>:</p>
<blockquote>
<p>The <code>shortcut</code> link type is often seen before <code>icon</code>, but this link type is non-conforming, ignored and <strong>web authors must not use it anymore</strong>.</p>
</blockquote>
<h1><code>favicon.ico</code> in the root directory</h1>
<p>From <a href="https://stackoverflow.com/a/1344379/3853934">another SO answer</a> (by <a href="https://stackoverflow.com/users/23263/mercator">@mercator</a>):</p>
<blockquote>
<p>All modern browsers (tested with Chrome 4, Firefox 3.5, IE8, Opera 10 and Safari 4) will always request a <code>favicon.ico</code> unless you've specified a shortcut icon via <code><link></code>.</p>
</blockquote>
<p>So all you have to do is to make the <code>/favicon.ico</code> request to your website return your favicon. This option unfortunately doesn't allow you to use a PNG icon.</p>
<p>See also <a href="https://stackoverflow.com/q/1344122/3853934">favicon.png vs favicon.ico - why should I use PNG instead of ICO?</a></p> | {
"question_id": 4888377,
"question_date": "2011-02-03T15:55:10.257Z",
"question_score": 743,
"tags": "html|icons|favicon",
"answer_id": 35625707,
"answer_date": "2016-02-25T11:15:50.317Z",
"answer_score": 629
} |
Please answer the following Stack Overflow question:
Title: How do I invoke a Java method when given the method name as a string?
<p>If I have two variables:</p>
<pre><code>Object obj;
String methodName = "getName";
</code></pre>
<p>Without knowing the class of <code>obj</code>, how can I call the method identified by <code>methodName</code> on it?</p>
<p>The method being called has no parameters, and a <code>String</code> return value. It's <em>a getter for a Java bean</em>.</p> | <p>Coding from the hip, it would be something like:</p>
<pre><code>java.lang.reflect.Method method;
try {
method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..);
} catch (SecurityException e) { ... }
catch (NoSuchMethodException e) { ... }
</code></pre>
<p>The parameters identify the very specific method you need (if there are several overloaded available, if the method has no arguments, only give <code>methodName</code>).</p>
<p>Then you invoke that method by calling</p>
<pre><code>try {
method.invoke(obj, arg1, arg2,...);
} catch (IllegalArgumentException e) { ... }
catch (IllegalAccessException e) { ... }
catch (InvocationTargetException e) { ... }
</code></pre>
<p>Again, leave out the arguments in <code>.invoke</code>, if you don't have any. But yeah. Read about <a href="http://java.sun.com/docs/books/tutorial/reflect/index.html" rel="noreferrer">Java Reflection</a></p> | {
"question_id": 160970,
"question_date": "2008-10-02T05:15:43.430Z",
"question_score": 743,
"tags": "java|reflection|invoke",
"answer_id": 161005,
"answer_date": "2008-10-02T05:30:02.057Z",
"answer_score": 1056
} |
Please answer the following Stack Overflow question:
Title: How to apply color on text in Markdown
<p>I want to use Markdown to store textual information. But quick googling says Markdown does not support color. Also Stack Overflow does not support color. Same as in case of GitHub markdown.</p>
<p>Is there any flavor of markdown that allows colored text?</p> | <p><strong>TL;DR</strong></p>
<p>Markdown doesn't support color but you can inline HTML inside Markdown, e.g.:</p>
<pre><code><span style="color:blue">some *blue* text</span>.
</code></pre>
<p><strong>Longer answer</strong></p>
<p>As the original/official <a href="http://daringfireball.net/projects/markdown/syntax#html" rel="noreferrer">syntax rules</a> state (emphasis added):</p>
<blockquote>
<p>Markdown’s syntax is intended for one purpose: to be used as a format for writing for the web.</p>
<p>Markdown is not a replacement for HTML, or even close to it. Its syntax is very small, corresponding only to a very small subset of HTML tags. The idea is not to create a syntax that makes it easier to insert HTML tags. In my opinion, HTML tags are already easy to insert. The idea for Markdown is to make it easy to read, write, and edit prose. HTML is a publishing format; Markdown is a writing format. Thus, <em><strong>Markdown’s formatting syntax only addresses issues that can be conveyed in plain text</strong></em>.</p>
<p>For any markup that is not covered by Markdown’s syntax, you simply use HTML itself.</p>
</blockquote>
<p>As it is not a "publishing format," providing a way to color your text is out-of-scope for Markdown. That said, it is not impossible as you can include raw HTML (and HTML is a publishing format). For example, the following Markdown text (as suggested by @scoa in a comment):</p>
<pre><code>Some Markdown text with <span style="color:blue">some *blue* text</span>.
</code></pre>
<p>Would result in the following HTML:</p>
<pre><code><p>Some Markdown text with <span style="color:blue">some <em>blue</em> text</span>.</p>
</code></pre>
<p>Now, StackOverflow (and probably GitHub) will strip the raw HTML out (as a security measure) so you lose the color here, but it should work on any standard Markdown implementation.</p>
<p>Another possibility is to use the non-standard Attribute Lists originally introduced by the <a href="http://maruku.rubyforge.org/proposal.html#attribute_lists" rel="noreferrer">Markuru</a> implementation of Markdown and later adopted by a <a href="https://pythonhosted.org/Markdown/extensions/attr_list.html" rel="noreferrer">few</a> <a href="http://kramdown.gettalong.org/syntax.html#attribute-list-definitions" rel="noreferrer">others</a> (there may be more, or slightly different implementations of the same idea, like <a href="http://pandoc.org/MANUAL.html#divs-and-spans" rel="noreferrer">div and span attributes in pandoc</a>). In that case, you could assign a class to a paragraph or inline element, and then use CSS to define a color for a class. However, you absolutely must be using one of the few implementations which actually support the non-standard feature and your documents are no longer portable to other systems.</p> | {
"question_id": 35465557,
"question_date": "2016-02-17T19:09:18.673Z",
"question_score": 743,
"tags": "markdown",
"answer_id": 35485694,
"answer_date": "2016-02-18T15:32:32.723Z",
"answer_score": 800
} |
Please answer the following Stack Overflow question:
Title: How to get the last value of an ArrayList
<p>How can I get the last value of an ArrayList?</p> | <p>The following is part of the <a href="http://java.sun.com/javase/6/docs/api/java/util/List.html" rel="noreferrer"><code>List</code></a> interface (which ArrayList implements):</p>
<pre><code>E e = list.get(list.size() - 1);
</code></pre>
<p><code>E</code> is the element type. If the list is empty, <code>get</code> throws an <a href="http://java.sun.com/javase/6/docs/api/java/lang/IndexOutOfBoundsException.html" rel="noreferrer"><code>IndexOutOfBoundsException</code></a>. You can find the whole API documentation <a href="http://java.sun.com/javase/6/docs/api/" rel="noreferrer">here</a>.</p> | {
"question_id": 687833,
"question_date": "2009-03-26T22:38:57.667Z",
"question_score": 743,
"tags": "java|arraylist",
"answer_id": 687842,
"answer_date": "2009-03-26T22:42:45.427Z",
"answer_score": 826
} |
Please answer the following Stack Overflow question:
Title: How to fix a locale setting warning from Perl
<p>When I run <code>perl</code>, I get the warning:</p>
<pre>perl: warning: Setting locale failed.
perl: warning: Please check that your locale settings:
LANGUAGE = (unset),
LC_ALL = (unset),
LANG = "en_US.UTF-8"
are supported and installed on your system.
perl: warning: Falling back to the standard locale ("C").</pre>
<p>How do I fix it?</p> | <p>Your OS doesn't know about <code>en_US.UTF-8</code>.</p>
<p>You didn't mention a specific platform, but I can reproduce your problem:</p>
<pre>% uname -a
OSF1 hunter2 V5.1 2650 alpha
% perl -e exit
perl: warning: Setting locale failed.
perl: warning: Please check that your locale settings:
LC_ALL = (unset),
LANG = "en_US.UTF-8"
are supported and installed on your system.
perl: warning: Falling back to the standard locale ("C").</pre>
<p>My guess is you used ssh to connect to this older host from a newer desktop machine. It's common for <code>/etc/ssh/sshd_config</code> to contain</p>
<pre><code>AcceptEnv LANG LC_*
</code></pre>
<p>which allows clients to propagate the values of those environment variables into new sessions.</p>
<p>The warning gives you a hint about how to squelch it if you don't require the full-up locale:</p>
<pre>% env LANG=C perl -e exit
%</pre>
<p>or with Bash:</p>
<pre>$ LANG=C perl -e exit
$ </pre>
<p>For a permanent fix, choose one of</p>
<ol>
<li>On the older host, set the <code>LANG</code> environment variable in your shell's initialization file.</li>
<li>Modify your environment on the client side, <em>e.g.</em>, rather than <code>ssh hunter2</code>, use the command <code>LANG=C ssh hunter2</code>.</li>
<li>If you have administrator rights, stop ssh from sending the environment variables by commenting out the <code>SendEnv LANG LC_*</code> line in the <em>local</em> <code>/etc/ssh/ssh_config</code> file. (Thanks to <a href="https://askubuntu.com/questions/144235/locale-variables-have-no-effect-in-remote-shell-perl-warning-setting-locale-f/144448#144448">this answer</a>. See <a href="https://bugzilla.mindrot.org/show_bug.cgi?id=1285#c2" rel="noreferrer">Bug 1285</a> for OpenSSH for more.)</li>
</ol> | {
"question_id": 2499794,
"question_date": "2010-03-23T12:27:18.667Z",
"question_score": 743,
"tags": "perl|locale",
"answer_id": 2510548,
"answer_date": "2010-03-24T18:50:55.233Z",
"answer_score": 514
} |
Please answer the following Stack Overflow question:
Title: Gitignore not working
<p>My <code>.gitignore</code> file isn't working for some reason, and no amount of Googling has been able to fix it. Here is what I have:</p>
<pre><code>*.apk
*.ap_
*.dex
*.class
**/bin/
**/gen/
.gradle/
build/
local.properties
**/proguard/
*.log
</code></pre>
<p>It's in the directory <code>master</code>, which is my git repo. I'm running Git 1.8.4.2 because I'm on a MacBook running OSX 10.8.6.</p> | <p>The files/folder in your version control will not just delete themselves just because you added them to the <code>.gitignore</code>. They are already in the repository and you have to remove them. You can just do that with this:</p>
<p><strong>Remember to commit everything you've changed before you do this!</strong></p>
<pre><code>git rm -rf --cached .
git add .
</code></pre>
<p>This removes all files from the repository and adds them back (this time respecting the rules in your <code>.gitignore</code>).</p> | {
"question_id": 25436312,
"question_date": "2014-08-21T21:34:26.753Z",
"question_score": 743,
"tags": "git|gitignore",
"answer_id": 25436481,
"answer_date": "2014-08-21T21:46:22.580Z",
"answer_score": 1817
} |
Please answer the following Stack Overflow question:
Title: Are (non-void) self-closing tags valid in HTML5?
<p>The <a href="https://validator.w3.org/" rel="noreferrer">W3C validator</a> (<a href="http://en.wikipedia.org/wiki/W3C_Markup_Validation_Service" rel="noreferrer">Wikipedia</a>) doesn't like self-closing tags (those that end with “<code>/></code>”) on <a href="https://html.spec.whatwg.org/multipage/syntax.html#elements-2" rel="noreferrer">non-void</a> elements. (<a href="https://html.spec.whatwg.org/multipage/syntax.html#void-elements" rel="noreferrer">Void elements</a> are those that may not ever contain any content.) Are they still valid in HTML5?</p>
<p>Some examples of <em>accepted</em> void elements:</p>
<pre class="lang-html prettyprint-override"><code><br />
<img src="" />
<input type="text" name="username" />
</code></pre>
<p>Some examples of <em>rejected</em> non-void elements:</p>
<pre class="lang-html prettyprint-override"><code><div id="myDiv" />
<span id="mySpan" />
<textarea id="someTextMessage" />
</code></pre>
<sub>
<b>Note:</b> <br>
The W3C validator actually accepts void self-closing tags: the author originally had a problem because of a simple typo (<code>\></code> instead of <code>/></code>); however, self-closing tags are not 100% valid in HTML5 in general, and the answers elaborate on the issue of self-closing tags across various HTML flavors.
</sub> | <ul>
<li><p>(Theoretically) in <strong>HTML 4</strong>, <code><foo /</code> (yes, with no <code>></code> at all) means <code><foo></code> (which leads to <code><br /></code> meaning <code><br>></code> (i.e. <code><br>&gt;</code>) and <code><title/hello/</code> meaning <code><title>hello</title></code>). I use the term "theoretically" because this is an <strong>SGML</strong> rule that browsers did a very poor job of supporting. There was so little support (I only ever saw it work in <a href="https://www.emacswiki.org/emacs/emacs-w3m" rel="noreferrer">emacs-w3m</a>) that <a href="http://www.w3.org/TR/html4/appendix/notes.html#h-B.3.3" rel="noreferrer">the spec advises authors to avoid the syntax</a>.</p>
</li>
<li><p>In <strong>XHTML</strong>, <a href="http://www.w3.org/TR/xml/#d0e2480" rel="noreferrer"><code><foo /></code> means <code><foo></foo></code></a>. This is an <strong>XML</strong> rule that applies to all XML documents. That said, XHTML is often served as <code>text/html</code> which (historically at least) gets processed by browsers using a different parser than documents served as <code>application/xhtml+xml</code>. The W3C provides <a href="http://www.w3.org/TR/xhtml-media-types/#C_2" rel="noreferrer">compatibility guidelines</a> to follow for XHTML as <code>text/html</code>. (Essentially: Only use self-closing tag syntax when the element is defined as EMPTY (and the end tag was forbidden in the HTML spec)).</p>
</li>
<li><p>In <strong>HTML5</strong>, the meaning of <code><foo /></code> <a href="https://www.w3.org/TR/html5/syntax.html#start-tags" rel="noreferrer">depends on the type of element</a>:</p>
<ul>
<li>On HTML elements that are designated as <a href="https://html.spec.whatwg.org/multipage/syntax.html#void-elements" rel="noreferrer">void elements</a> (essentially "An element that existed before HTML5 and which was forbidden to have any content"), end tags are simply forbidden. The slash at the end of the start tag is allowed, but has no meaning. It is just syntactic sugar for people (and syntax highlighters) that are addicted to XML.</li>
<li>On other HTML elements, the slash is <a href="https://html.spec.whatwg.org/multipage/parsing.html#parse-error-non-void-html-element-start-tag-with-trailing-solidus" rel="noreferrer">an error</a>, but error recovery will cause browsers to ignore it and treat the tag as a regular start tag. This will usually end up with a missing end tag causing subsequent elements to be children instead of siblings.</li>
<li>Foreign elements (imported from XML applications such as SVG) treat it as self-closing syntax.</li>
</ul>
</li>
</ul> | {
"question_id": 3558119,
"question_date": "2010-08-24T15:28:40.037Z",
"question_score": 743,
"tags": "html|syntax|w3c-validation",
"answer_id": 3558200,
"answer_date": "2010-08-24T15:37:41.560Z",
"answer_score": 1313
} |
Please answer the following Stack Overflow question:
Title: How to set a JavaScript breakpoint from code in Chrome?
<p>I want to force the Chrome debugger to break on a line <em>via code</em>, or else using some sort of comment tag such as something like <code>console.break()</code>.</p> | <p>You can use <code>debugger;</code> within your code. If the developer console is open, execution will break. It works in firebug as well.</p> | {
"question_id": 10050465,
"question_date": "2012-04-06T23:44:48.693Z",
"question_score": 743,
"tags": "javascript|debugging|google-chrome|breakpoints",
"answer_id": 10050496,
"answer_date": "2012-04-06T23:49:37.850Z",
"answer_score": 1245
} |
Please answer the following Stack Overflow question:
Title: Why aren't ◎ܫ◎ and ☺ valid JavaScript variable names?
<p>I noticed that in Internet Explorer (but, unfortunately, not in the other browsers I tested), you can use some Unicode variable names. This made my day, and I was absolutely delighted that I could write fun Unicode-laden code like this:</p>
<pre><code>var ктоείναι草泥马 = "You dirty horse.",
happy☺n☺mat☺p☺eia = ":)Yay!",
ಠ_ಠ = "emoticon";
alert(ктоείναι草泥马 + happy☺n☺mat☺p☺eia + ಠ_ಠ);
</code></pre>
<p>For some reason, though, <code>◎ܫ◎</code>, <code>♨_♨</code> and <code>☺</code> are not valid variable names.</p>
<p>Why do <code>ಠ_ಠ</code> and <code>草泥马</code> work, but <code>◎ܫ◎</code>, <code>♨_♨</code> and <code>☺</code> don't?</p>
<p>EDIT: Test it out in your browser on <a href="http://jsfiddle.net/h5Gsf/1/" rel="noreferrer">JSFiddle</a>. I've tested it in Internet Explorer 9, Chrome, Firefox, and Opera. So far, it seems to only work in Internet Explorer 9. (I don't know about Internet Explorer 8 and below.) Let me know if it works in another browser.</p> | <p>ಠ_ಠ
and 草泥马 only contain "letters" used in actual alphabets; that is, ಠ
is a symbol from the <a href="http://en.wikipedia.org/wiki/Kannada_alphabet">Kannada alphabet</a>, and 草泥马 consists of Chinese characters.</p>
<p>◎ and ☺, however, are purely symbols; they are not associated with any alphabet.</p>
<p>The <a href="http://es5.github.com/#x7.6">ECMAScript standard, chapter 7.6</a> (which all the browsers except Internet Explorer are following), states that an identifier must start with one of the following.</p>
<ul>
<li>a Unicode letter</li>
<li><code>$</code> or <code>_</code></li>
<li><code>\</code> followed by a unicode escape sequence.</li>
</ul>
<p>The following characters of an identifier must be one of the following.</p>
<ul>
<li>any of the characters permitted at the start</li>
<li>a Unicode combining mark</li>
<li>a Unicode digit</li>
<li>a Unicode connector punctuation</li>
<li>a zero-width-non-joiner</li>
<li>a zero-width joiner</li>
</ul>
<p>IE goes beyond the standard and is permissive enough to allow some symbols, such as ☺.</p>
<p>There’s <a href="http://mothereff.in/js-variables">a tool</a> that will tell you if any string that you enter is a valid JavaScript variable name according to ECMAScript 5.1 and Unicode 6.1.</p> | {
"question_id": 7451524,
"question_date": "2011-09-17T00:05:07.273Z",
"question_score": 743,
"tags": "javascript|naming-conventions|invalid-characters",
"answer_id": 7451569,
"answer_date": "2011-09-17T00:15:43.140Z",
"answer_score": 625
} |
Please answer the following Stack Overflow question:
Title: How do I update Node.js?
<p>I did the following to update my npm: </p>
<pre><code>npm update npm -g
</code></pre>
<p>But I have no idea how to update Node.js. Any suggestions? (I'm using Node.js 0.4.1 and want to update to Node.js 0.6.1.)</p> | <p>Use <a href="https://github.com/creationix/nvm" rel="noreferrer">Node Version Manager (NVM)</a></p>
<p>It's a Bash script that lets you download and manage different versions of node. Full source code is <a href="https://github.com/creationix/nvm/blob/master/nvm.sh" rel="noreferrer">here</a>.</p>
<p>There is a separate project for nvm for Windows: <a href="https://github.com/coreybutler/nvm-windows" rel="noreferrer">github.com/coreybutler/nvm-windows</a></p>
<p>Below are the full steps to use NVM for multiple version of node on windows </p>
<ol>
<li>download <a href="https://github.com/coreybutler/nvm-windows/releases/download/1.1.7/nvm-setup.zip" rel="noreferrer">nvm-setup.zip</a> extract and install it.</li>
<li>execute command <code>nvm list available</code> from cmd or gitbash or powershell, this will list all available version of node <a href="https://i.stack.imgur.com/oPgbv.png" rel="noreferrer"><img src="https://i.stack.imgur.com/oPgbv.png" alt="enter image description here"></a> </li>
<li>use command <code>nvm install version</code> e.g. <code>nvm install 12.14.0</code> to install on the machine</li>
<li>last once installed use <code>nvm use version</code> to use newer version e.g. <code>nvm use 12.14.0</code></li>
</ol> | {
"question_id": 8191459,
"question_date": "2011-11-19T02:37:17.940Z",
"question_score": 742,
"tags": "node.js|software-update",
"answer_id": 8191466,
"answer_date": "2011-11-19T02:39:01.853Z",
"answer_score": 663
} |
Please answer the following Stack Overflow question:
Title: Selecting last element in JavaScript array
<p>I'm making an application that updates a user's location and path in real time and displays this on a Google Map. I have functionality that allows multiple users to be tracked at the same time using an object, which is updated every second. </p>
<p>Right now, when a user pressed a button in the Android app, the coordinates are sent to a database and each time the location changes, a marker is updated on the map (and a polyline is formed). </p>
<p>Since I have multiple users, I send a unique and randomly generated alphanumeric string so that I can display an individual path for each user. When the JS pulls this data from the database, it checks if the user exists, if it does not, it creates a new key with the value being a list. It would look something like this:</p>
<pre><code>loc = {f096012e-2497-485d-8adb-7ec0b9352c52: [new google.maps.LatLng(39, -86),
new google.maps.LatLng(38, -87),
new google.maps.LatLng(37, -88)],
44ed0662-1a9e-4c0e-9920-106258dcc3e7: [new google.maps.LatLng(40, -83),
new google.maps.LatLng(41, -82),
new google.maps.LatLng(42, -81)]}
</code></pre>
<p>What I'm doing is storing a list of coordinates as the value of the key, which is the user's ID. My program keeps updating this list each time the location is changed by adding to the list (this works properly). </p>
<p>What I need to do is update the marker's location each time the location changes. I would like to do this by selecting the last item in the array since that would be the last known location. Right now, each time the location is changed a new marker is added to the map (each one of the points in the example would show a marker at that location) so markers continue to be added. </p>
<p>I would use a ´for (x in loc)` statement each time the location updates to grab the last location from the list and use that to update the marker. How do I select this last element from the array within the hash?</p> | <h2>How to access last element of an array</h2>
<p>It looks like that:</p>
<pre class="lang-js prettyprint-override"><code>var my_array = /* some array here */;
var last_element = my_array[my_array.length - 1];
</code></pre>
<p>Which in your case looks like this:</p>
<pre class="lang-js prettyprint-override"><code>var array1 = loc['f096012e-2497-485d-8adb-7ec0b9352c52'];
var last_element = array1[array1.length - 1];
</code></pre>
<p>or, in longer version, without creating new variables:</p>
<pre class="lang-js prettyprint-override"><code>loc['f096012e-2497-485d-8adb-7ec0b9352c52'][loc['f096012e-2497-485d-8adb-7ec0b9352c52'].length - 1];
</code></pre>
<h2>How to add a method for getting it simpler</h2>
<p>If you are a fan for creating functions/shortcuts to fulfill such tasks, the following code:</p>
<pre><code>if (!Array.prototype.last){
Array.prototype.last = function(){
return this[this.length - 1];
};
};
</code></pre>
<p>will allow you to get the last element of an array by invoking array's <code>last()</code> method, in your case eg.:</p>
<pre><code>loc['f096012e-2497-485d-8adb-7ec0b9352c52'].last();
</code></pre>
<p>You can check that it works here: <a href="http://jsfiddle.net/D4NRN/" rel="noreferrer">http://jsfiddle.net/D4NRN/</a></p> | {
"question_id": 9050345,
"question_date": "2012-01-29T02:11:43.727Z",
"question_score": 742,
"tags": "javascript|arrays|google-maps|google-maps-markers",
"answer_id": 9050354,
"answer_date": "2012-01-29T02:14:03.647Z",
"answer_score": 1078
} |
Please answer the following Stack Overflow question:
Title: How do you easily horizontally center a <div> using CSS?
<p>I'm trying to horizontally center a <code><div></code> block element on a page and have it set to a minimum width. What is the simplest way to do this? I want the <code><div></code> element to be inline with rest of my page. I'll try to draw an example:</p>
<pre><code>page text page text page text page text
page text page text page text page text
-------
| div |
-------
page text page text page text page text
page text page text page text page text
</code></pre> | <p>In the case of a <strong>non-fixed width</strong> div (i.e. you don't know how much space the div will occupy).</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#wrapper {
background-color: green; /* for visualization purposes */
text-align: center;
}
#yourdiv {
background-color: red; /* for visualization purposes */
display: inline-block;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
<div id="yourdiv">Your text</div>
</div></code></pre>
</div>
</div>
</p>
<p>Keep in mind that the width of <code>#yourdiv</code> is dynamic -> it will grow and shrink to accommodate the text inside it.</p>
<p>You can check browser compatibility on <a href="http://caniuse.com/inline-block" rel="noreferrer">Caniuse</a></p> | {
"question_id": 618097,
"question_date": "2009-03-06T08:51:07.980Z",
"question_score": 742,
"tags": "css|html",
"answer_id": 10797328,
"answer_date": "2012-05-29T10:28:09.240Z",
"answer_score": 823
} |
Please answer the following Stack Overflow question:
Title: Python int to binary string?
<p>Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python?</p>
<p>There are a myriad of dec2bin() functions out on Google... But I was hoping I could use a built-in function / library.</p> | <p>Python's string format method can take a format spec. </p>
<pre><code>>>> "{0:b}".format(37)
'100101'
</code></pre>
<p><a href="https://docs.python.org/2/library/string.html#formatspec" rel="noreferrer">Format spec docs for Python 2</a> </p>
<p><a href="https://docs.python.org/3/library/string.html#formatspec" rel="noreferrer">Format spec docs for Python 3</a></p> | {
"question_id": 699866,
"question_date": "2009-03-31T03:04:37.603Z",
"question_score": 742,
"tags": "python|binary|string.format",
"answer_id": 699891,
"answer_date": "2009-03-31T03:17:18.057Z",
"answer_score": 1010
} |
Please answer the following Stack Overflow question:
Title: How to convert index of a pandas dataframe into a column
<p>This seems rather obvious, but I can't seem to figure out how to convert an index of data frame to a column?</p>
<p>For example:</p>
<pre><code>df=
gi ptt_loc
0 384444683 593
1 384444684 594
2 384444686 596
</code></pre>
<p>To,</p>
<pre><code>df=
index1 gi ptt_loc
0 0 384444683 593
1 1 384444684 594
2 2 384444686 596
</code></pre> | <p>either:</p>
<pre><code>df['index1'] = df.index
</code></pre>
<p>or, <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="noreferrer"><code>.reset_index</code></a>:</p>
<pre><code>df = df.reset_index(level=0)
</code></pre>
<hr />
<p>so, if you have a multi-index frame with 3 levels of index, like:</p>
<pre><code>>>> df
val
tick tag obs
2016-02-26 C 2 0.0139
2016-02-27 A 2 0.5577
2016-02-28 C 6 0.0303
</code></pre>
<p>and you want to convert the 1st (<code>tick</code>) and 3rd (<code>obs</code>) levels in the index into columns, you would do:</p>
<pre><code>>>> df.reset_index(level=['tick', 'obs'])
tick obs val
tag
C 2016-02-26 2 0.0139
A 2016-02-27 2 0.5577
C 2016-02-28 6 0.0303
</code></pre> | {
"question_id": 20461165,
"question_date": "2013-12-09T00:34:16.403Z",
"question_score": 742,
"tags": "python|pandas|dataframe|indexing|series",
"answer_id": 20461206,
"answer_date": "2013-12-09T00:39:17.983Z",
"answer_score": 1233
} |
Please answer the following Stack Overflow question:
Title: How can I obfuscate (protect) JavaScript?
<p>I want to make a JavaScript application that's not open source, and thus I wish to learn how to can obfuscate my JS code? Is this possible?</p> | <p><strong>Obfuscation:</strong></p>
<p><strike> Try <a href="http://yuilibrary.com/" rel="noreferrer"><strong>YUI Compressor</strong></a>. It's a very popular tool, built, enhanced and maintained by the Yahoo UI team.</p>
<p>You may also use:</p>
<ul>
<li><a href="http://closure-compiler.appspot.com/home" rel="noreferrer">Google Closure Compiler</a></li>
<li><a href="http://marijnhaverbeke.nl/uglifyjs" rel="noreferrer">UglifyJS</a>
</strike></li>
</ul>
<p><code>UPDATE: This question was originally asked on 2008, and The mentioned technologies are deprecated. you can use:</code></p>
<ul>
<li><a href="https://github.com/terser/terser" rel="noreferrer">terser</a> - more information in <a href="https://web.dev/unminified-javascript/" rel="noreferrer">web.dev</a>.</li>
</ul>
<p><strong>Private String Data:</strong></p>
<p>Keeping string values private is a different concern, and obfuscation won't really be of much benefit. Of course, by packaging up your source into a garbled, minified mess, you have a light version of <strong>security</strong> through <strong>obscurity</strong>. Most of the time, it's your user who is viewing the source, and the string values on the client are intended for their use, so that sort of private string value isn't often necessary.</p>
<p>If you really had a value that you never wanted a user to see, you would have a couple of options. First, you could do some kind of encryption, which is decrypted at page load. That would probably be one of the most secure options, but also a lot of work which may be unnecessary. You could probably base64 encode some string values, and that would be easier.. but someone who really wanted those string values could <strong>easily decode them</strong>. Encryption is the only way to truly prevent anyone from accessing your data, and most people find that to be more security than they need.</p>
<p><strong>Sidenote:</strong></p>
<p>Obfuscation in Javascript has been known to cause some bugs. The obfuscators are getting a little better about it, but many outfits decide that they see enough benefit from <strong>minifying</strong> and <strong>gzipping</strong>, and the added savings of obfuscation <strong>isn't always worth the trouble</strong>. If you're trying to protect your source, maybe you'll decide that it's worth your while, just to make your code harder to read. <a href="http://www.crockford.com/javascript/jsmin.html" rel="noreferrer"><strong>JSMin</strong></a> is a good alternative.</p> | {
"question_id": 194397,
"question_date": "2008-10-11T18:17:18.970Z",
"question_score": 742,
"tags": "javascript|obfuscation|source-code-protection",
"answer_id": 194399,
"answer_date": "2008-10-11T18:21:22.910Z",
"answer_score": 428
} |
Please answer the following Stack Overflow question:
Title: How do I protect Python code from being read by users?
<p>I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time-restricted license file.</p>
<p>If we distribute the <code>.py</code> files or even <code>.pyc</code> files it will be easy to (decompile and) remove the code that checks the license file.</p>
<p>Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas".</p>
<p>Is there a good way to handle this problem?</p> | <p>Python, being a byte-code-compiled interpreted language, is very difficult to lock down. Even if you use a exe-packager like <a href="http://py2exe.org" rel="noreferrer">py2exe</a>, the layout of the executable is well-known, and the Python byte-codes are well understood.</p>
<p>Usually in cases like this, you have to make a tradeoff. How important is it really to protect the code? Are there real secrets in there (such as a key for symmetric encryption of bank transfers), or are you just being paranoid? Choose the language that lets you develop the best product quickest, and be realistic about how valuable your novel ideas are.</p>
<p>If you decide you really need to enforce the license check securely, write it as a small C extension so that the license check code can be extra-hard (but not impossible!) to reverse engineer, and leave the bulk of your code in Python.</p> | {
"question_id": 261638,
"question_date": "2008-11-04T11:57:27.653Z",
"question_score": 742,
"tags": "python|licensing|obfuscation|copy-protection",
"answer_id": 261645,
"answer_date": "2008-11-04T12:00:34.417Z",
"answer_score": 411
} |
Please answer the following Stack Overflow question:
Title: How can I alias a default import in JavaScript?
<p>Using ES6 modules, I know I can alias a named import:</p>
<pre><code>import { foo as bar } from 'my-module';
</code></pre>
<p>And I know I can import a default import:</p>
<pre><code>import defaultMember from 'my-module';
</code></pre>
<p>I'd like to alias a default import and I had thought the following would work:</p>
<pre><code>import defaultMember as alias from 'my-module';
</code></pre>
<p>But that results in a parsing (syntax) error.</p>
<p>How can I (or can I?) alias a default import?</p> | <p><code>defaultMember</code> already <em>is</em> an alias - it doesn't need to be the name of the exported function/thing. Just do</p>
<pre><code>import alias from 'my-module';
</code></pre>
<p>Alternatively you can do</p>
<pre><code>import {default as alias} from 'my-module';
</code></pre>
<p>but that's rather esoteric.</p> | {
"question_id": 39282253,
"question_date": "2016-09-01T23:24:09.413Z",
"question_score": 742,
"tags": "javascript|ecmascript-6|es6-modules",
"answer_id": 39282290,
"answer_date": "2016-09-01T23:30:27.680Z",
"answer_score": 1410
} |
Please answer the following Stack Overflow question:
Title: How do I create a unique constraint that also allows nulls?
<p>I want to have a unique constraint on a column which I am going to populate with GUIDs. However, my data contains null values for this columns. How do I create the constraint that allows multiple null values?</p>
<p>Here's an <a href="http://sqlfiddle.com/#!3/36a10/1" rel="noreferrer">example scenario</a>. Consider this schema:</p>
<pre><code>CREATE TABLE People (
Id INT CONSTRAINT PK_MyTable PRIMARY KEY IDENTITY,
Name NVARCHAR(250) NOT NULL,
LibraryCardId UNIQUEIDENTIFIER NULL,
CONSTRAINT UQ_People_LibraryCardId UNIQUE (LibraryCardId)
)
</code></pre>
<p>Then see this code for what I'm trying to achieve:</p>
<pre><code>-- This works fine:
INSERT INTO People (Name, LibraryCardId)
VALUES ('John Doe', 'AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA');
-- This also works fine, obviously:
INSERT INTO People (Name, LibraryCardId)
VALUES ('Marie Doe', 'BBBBBBBB-BBBB-BBBB-BBBB-BBBBBBBBBBBB');
-- This would *correctly* fail:
--INSERT INTO People (Name, LibraryCardId)
--VALUES ('John Doe the Second', 'AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA');
-- This works fine this one first time:
INSERT INTO People (Name, LibraryCardId)
VALUES ('Richard Roe', NULL);
-- THE PROBLEM: This fails even though I'd like to be able to do this:
INSERT INTO People (Name, LibraryCardId)
VALUES ('Marcus Roe', NULL);
</code></pre>
<p>The final statement fails with a message:</p>
<blockquote>
<p>Violation of UNIQUE KEY constraint 'UQ_People_LibraryCardId'. Cannot insert duplicate key in object 'dbo.People'.</p>
</blockquote>
<p>How can I change my schema and/or uniqueness constraint so that it allows multiple <code>NULL</code> values, while still checking for uniqueness on actual data?</p> | <h3>SQL Server 2008 +</h3>
<p>You can create a unique index that accept multiple NULLs with a <code>WHERE</code> clause. See the <a href="https://stackoverflow.com/a/767702/290343">answer below</a>.</p>
<h3>Prior to SQL Server 2008</h3>
<p>You cannot create a UNIQUE constraint and allow NULLs. You need set a default value of NEWID(). </p>
<p>Update the existing values to NEWID() where NULL before creating the UNIQUE constraint.</p> | {
"question_id": 767657,
"question_date": "2009-04-20T10:12:55.640Z",
"question_score": 742,
"tags": "sql-server|tsql",
"answer_id": 767676,
"answer_date": "2009-04-20T10:20:27.247Z",
"answer_score": 178
} |
Please answer the following Stack Overflow question:
Title: How to move screen without moving cursor in Vim?
<p>I recently discovered <kbd>Ctrl</kbd>+<kbd>E</kbd> and <kbd>Ctrl</kbd>+<kbd>Y</kbd> shortcuts for Vim that respectively move the screen up and down with a one line step, <em>without moving the cursor</em>.</p>
<p>Do you know any command that leaves the cursor where it is but moves the screen so that the line which has the cursor becomes the first line? (having a command for the last line would be a nice bonus).</p>
<p>I can achieve this by manually pressing <kbd>Ctrl</kbd>+<kbd>E</kbd> (or <kbd>Ctrl</kbd>+<kbd>Y</kbd>) the proper number of times, but having a command that somehow does this directly would be nice.</p>
<p>Any ideas?</p> | <ul>
<li><kbd>z</kbd><kbd>z</kbd> - move current line to the middle
of the screen<br>
<em>(<strong>Careful with <kbd>z</kbd><kbd>z</kbd></strong>, if you happen to have <kbd>Caps Lock</kbd> on accidentally, you will save and exit <code>vim</code>!)</em></li>
<li><kbd>z</kbd><kbd>t</kbd> - move current line
to the top of the screen </li>
<li><kbd>z</kbd><kbd>b</kbd> - move
current line to the bottom of the
screen</li>
</ul> | {
"question_id": 3458689,
"question_date": "2010-08-11T13:21:23.410Z",
"question_score": 742,
"tags": "vim|scroll|cursor-position",
"answer_id": 3458821,
"answer_date": "2010-08-11T13:34:12.810Z",
"answer_score": 1070
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.