id
int64 4
73.8M
| title
stringlengths 10
150
| body
stringlengths 17
50.8k
| accepted_answer_id
int64 7
73.8M
| answer_count
int64 1
182
| comment_count
int64 0
89
| community_owned_date
stringlengths 23
27
⌀ | creation_date
stringlengths 23
27
| favorite_count
int64 0
11.6k
⌀ | last_activity_date
stringlengths 23
27
| last_edit_date
stringlengths 23
27
⌀ | last_editor_display_name
stringlengths 2
29
⌀ | last_editor_user_id
int64 -1
20M
⌀ | owner_display_name
stringlengths 1
29
⌀ | owner_user_id
int64 1
20M
⌀ | parent_id
null | post_type_id
int64 1
1
| score
int64 -146
26.6k
| tags
stringlengths 1
125
| view_count
int64 122
11.6M
| answer_body
stringlengths 19
51k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
863,356 | jQuery: How to select "from here until the next H2"? | <p>I'm setting up a very straightforward FAQ page with jQuery. Like so:</p>
<pre><code><h2>What happens when you click on this question?</h2>
<p>This answer will appear!</p>
</code></pre>
<p>This is all inside a very specific div, so I'll be selecting the header with <code>$('#faq h2')</code>. Simple, right? Click on the H2, and use <code>this.next()</code> to make the next paragraph show up.</p>
<p>(The caveat with this page is that a non-programmer will be maintaining it, which is why I'm not using classes: there's no guarantee that any new entries would have the right classes in them.)</p>
<p>So! The problem:</p>
<pre><code><h2>What happens when you click on the next question?</h2>
<p>That is an interesting conundrum.</p>
<p>Because the maintainer is kind of long-winded</p>
<p>and many answers will span a few paragraphs.</p>
</code></pre>
<p>So how, without adding in <code>div</code>s and classes and whatnot, can I have my <code>this.next()</code> routine select everything between the question-that-was-clicked-on and the next question (H2 header)?</p> | 863,428 | 9 | 5 | null | 2009-05-14 13:29:13.68 UTC | 8 | 2013-10-27 04:58:15.163 UTC | 2009-12-09 20:06:07.17 UTC | null | 811 | null | 73,930 | null | 1 | 30 | javascript|jquery|dom|jquery-selectors|css-selectors | 16,047 | <p>Interesting problem. First let me say that I think the best strategy is to enclose the whole answer in a div and then the problem becomes trivial to solve:</p>
<pre><code><h2>Question here</h2>
<div>
<p>Answer here</p>
</div>
</h2>Next Question</h2>
...
</code></pre>
<p>with:</p>
<pre><code>$(function() {
$("h2").click(function() {
$(this).next().toggleClass("highlighted");
});
});
</code></pre>
<p>But that being said, it is solvable without that.</p>
<pre><code>$(function() {
$("h2").click(function() {
$(this).nextAll().each(function() {
if (this.tagName == 'H2') {
return false; // stop execution
}
$(this).toggleClass("highlighted");
});
});
});
</code></pre>
<p>Not supremely elegant but it'll work.</p>
<p><strong>Note:</strong> This assumes the questions are siblings. If they are not it gets much more complicated.</p> |
154,256 | Is there a way to iterate through all enum values? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/105372/c-how-to-enumerate-an-enum">C#: How to enumerate an enum?</a> </p>
</blockquote>
<p>The subject says all. I want to use that to add the values of an enum in a combobox.</p>
<p>Thanks</p>
<p>vIceBerg</p> | 154,263 | 9 | 0 | null | 2008-09-30 18:09:54.787 UTC | 3 | 2018-04-24 12:40:19.287 UTC | 2017-05-23 12:08:28.667 UTC | null | -1 | vIceBerg | 17,766 | null | 1 | 31 | c#|enumeration | 19,021 | <pre><code>string[] names = Enum.GetNames (typeof(MyEnum));
</code></pre>
<p>Then just populate the dropdown withe the array</p> |
1,038,534 | What does the Excel range.Rows property really do? | <p>OK, I am finishing up an add-on project for a legacy Excel-VBA application, and I have once again run up against the conundrum of the mysterious <code>range.Rows</code> (?) and <code>worksheet.Rows</code> properties. </p>
<p>Does anyone know what these properties really do and what they are supposed to provide to me? (Note: all of this probably applies to the corresponding <code>*.Columns</code> properties also).</p>
<p>What I would really <em>like</em> to be able to use it for is to return a range of rows, like this:</p>
<pre><code> SET rng = wks.Rows(iStartRow, iEndRow)
</code></pre>
<p>But I have never been able to get it to do that, even though the Intellisense shows two arguments for it. Instead I have to use one of the two or three other (very kludgy) techniques. </p>
<p>The help is very unhelpful (typically so for Office VBA), and googling for "Rows" is not very useful, no matter how many other terms I add to it.</p>
<p>The only things that I have been able to use it for are 1) return a single row as a range ( <code>rng.Rows(i)</code> ) and 2) return a count of the rows in a range ( <code>rng.Rows.Count</code> ). Is that it? Is there really nothing else that it's good for?</p>
<p><strong>Clarification:</strong> I know that it returns a range and that there are other ways to get a range of rows. What I am asking for is specifically what do we get from <code>.Rows()</code> that we do not already get from <code>.Cells()</code> and <code>.Range()</code>? The two things that I know are 1) an easier way to return a range of a single row and 2) a way to count the number of rows in a range. </p>
<p>Is there anything else?</p> | 1,039,407 | 9 | 6 | null | 2009-06-24 13:54:24.983 UTC | 14 | 2019-07-12 16:16:24.78 UTC | 2019-07-12 16:16:24.78 UTC | null | 109,122 | null | 109,122 | null | 1 | 60 | vba|excel|ole-automation | 156,549 | <p><code>Range.Rows</code> and <code>Range.Columns</code> return essentially the same Range except for the fact that the new Range has a flag which indicates that it represents Rows or Columns. This is necessary for some Excel properties such as Range.Count and Range.Hidden and for some methods such as <code>Range.AutoFit()</code>:</p>
<ul>
<li><code>Range.Rows.Count</code> returns the number of rows in Range.</li>
<li><code>Range.Columns.Count</code> returns the number of columns in Range.</li>
<li><code>Range.Rows.AutoFit()</code> autofits the rows in Range.</li>
<li><code>Range.Columns.AutoFit()</code> autofits the columns in Range.</li>
</ul>
<p>You might find that <code>Range.EntireRow</code> and <code>Range.EntireColumn</code> are useful, although they still are not exactly what you are looking for. They return all possible columns for <code>EntireRow</code> and all possible rows for <code>EntireColumn</code> for the represented range.</p>
<p>I know this because <a href="http://www.spreadsheetgear.com/" rel="noreferrer">SpreadsheetGear for .NET</a> comes with .NET APIs which are very similar to Excel's APIs. The SpreadsheetGear API comes with several strongly typed overloads to the IRange indexer including the one you probably wish Excel had:</p>
<ul>
<li><code>IRange this[int row1, int column1, int row2, int column2];</code></li>
</ul>
<p>Disclaimer: I own SpreadsheetGear LLC</p> |
575,685 | Looking for simple Java in-memory cache | <p>I'm looking for a simple Java in-memory cache that has good concurrency (so LinkedHashMap isn't good enough), and which can be serialized to disk periodically.</p>
<p>One feature I need, but which has proved hard to find, is a way to "peek" at an object. By this I mean retrieve an object from the cache without causing the cache to hold on to the object any longer than it otherwise would have.</p>
<p><strong>Update:</strong> An additional requirement I neglected to mention is that I need to be able to modify the cached objects (they contain float arrays) in-place.</p>
<p>Can anyone provide any recommendations?</p> | 15,619,390 | 9 | 4 | null | 2009-02-22 20:11:54.9 UTC | 35 | 2017-03-09 10:31:12.837 UTC | 2009-02-22 20:46:10.373 UTC | sanity | 16,050 | sanity | 16,050 | null | 1 | 119 | java|caching | 254,371 | <p>Since this question was originally asked, <a href="https://github.com/google/guava/wiki/CachesExplained">Google's Guava library</a> now includes a powerful and flexible cache. I would recommend using this.</p> |
565,497 | In Cygwin how do I change the font color? | <p>I want to start using Cygwin, but I am not pleased with the font color and would like to change it to light green with a black background. </p>
<p>(I tried googling to no avail BTW)</p> | 565,666 | 10 | 1 | null | 2009-02-19 14:19:15.44 UTC | 9 | 2015-11-16 08:17:59.48 UTC | 2009-02-19 14:53:32.817 UTC | Rich B | 5,640 | Luis | 65,034 | null | 1 | 24 | fonts|cygwin | 55,018 | <p>I find the standard shell to be pretty horrible myself.</p>
<p>I download and install the rxvt package and change the cygwin.bat to launch rxvt which has nicer support of copy-cut-n-paste.</p>
<pre><code>@echo off
c:
chdir c:\data\cygwin\bin
set EDITOR=vi
set VISUAL=vi
set CYGWIN=codepage:ansi
rxvt -fn '*-courier-*-r-*-16-*' -sl 9999 -bg Black -fg Cyan -e /bin/bash -login
</code></pre>
<p>The -e and -login switch the launch shell to the rxvt one and the rest:
-fn sets a courier size 16 font (sue me)
-sl scroll lines of 9999
Black background and Cyan foreground
selecting text will fill the paste buffer automatically
the last bit (-e /bin/bash -login) launches bash and tells it that its a login shell which runs the profile setups and such.</p> |
143,420 | How can I modify a saved Microsoft Access 2007 or 2010 Import Specification? | <p>Does anyone know how to modify an existing import specification in Microsoft Access 2007 or 2010? In older versions there used to be an Advanced button presented during the import wizard that allowed you to select and edit an existing specification. I no longer see this feature but hope that it still exists and has just been moved somewhere else.</p> | 149,417 | 10 | 0 | null | 2008-09-27 11:03:01.687 UTC | 11 | 2020-11-06 13:36:44.49 UTC | 2012-11-20 19:47:09.747 UTC | null | 14,420 | L G | null | null | 1 | 44 | ms-access | 173,982 | <p>I am able to use this feature on my machine using MS Access 2007.</p>
<ul>
<li>On the Ribbon, select External Data </li>
<li>Select the "Text File" option </li>
<li>This displays the Get External Data Wizard </li>
<li>Specify the location of the file you wish to import </li>
<li>Click OK. This displays the "Import Text Wizard" </li>
<li>On the bottom of this dialog screen is the Advanced button you referenced </li>
<li>Clicking on this button should display the Import Specification screen and allow you to select and modify an existing import spec. </li>
</ul>
<p>For what its worth, I'm using Access 2007 SP1</p> |
427,760 | When to use If-else if-else over switch statements and vice versa | <p>Why you would want to use a <code>switch</code> block over a series of <code>if</code> statements?</p>
<p><code>switch</code> statements seem to do the same thing but take longer to type.</p> | 427,792 | 10 | 0 | null | 2009-01-09 11:33:54.297 UTC | 18 | 2020-12-13 10:39:00.543 UTC | 2017-08-13 10:23:55.987 UTC | null | 1,033,581 | null | 52,381 | null | 1 | 105 | switch-statement | 123,583 | <p>As with most things you should pick which to use based on the context and what is conceptually the correct way to go. A switch is really saying "pick one of these based on this variables value" but an if statement is just a series of boolean checks.</p>
<p>As an example, if you were doing:</p>
<pre><code>int value = // some value
if (value == 1) {
doThis();
} else if (value == 2) {
doThat();
} else {
doTheOther();
}
</code></pre>
<p>This would be much better represented as a switch as it then makes it immediately obviously that the choice of action is occurring based on the value of "value" and not some arbitrary test.</p>
<p>Also, if you find yourself writing switches and if-elses and using an OO language you should be considering getting rid of them and using polymorphism to achieve the same result if possible.</p>
<p>Finally, regarding switch taking longer to type, I can't remember who said it but I did once read someone ask "is your typing speed really the thing that affects how quickly you code?" (paraphrased)</p> |
1,180,411 | Activate a virtualenv via fabric as deploy user | <p>I want to run my fabric script locally, which will in turn, log into my server, switch user to deploy, activate the projects .virtualenv, which will change dir to the project and issue a git pull.</p>
<pre><code>def git_pull():
sudo('su deploy')
# here i need to switch to the virtualenv
run('git pull')
</code></pre>
<p>I typically use the workon command from virtualenvwrapper which sources the activate file and the postactivate file will put me in the project folder. In this case, it seems that because fabric runs from within shell, control is give over to fabric, so I can't use bash's source built-in to '$source ~/.virtualenv/myvenv/bin/activate'</p>
<p>Anybody have an example and explanation of how they have done this?</p> | 1,180,665 | 10 | 1 | null | 2009-07-24 22:03:57.003 UTC | 64 | 2021-01-06 16:17:52.423 UTC | 2013-04-25 14:13:39.403 UTC | null | 247,696 | null | 93,559 | null | 1 | 130 | python|virtualenv|fabric|automated-deploy | 38,525 | <p>Right now, you can do what I do, which is kludgy but works perfectly well* (this usage assumes you're using virtualenvwrapper -- which you should be -- but you can easily substitute in the rather longer 'source' call you mentioned, if not):</p>
<pre><code>def task():
workon = 'workon myvenv && '
run(workon + 'git pull')
run(workon + 'do other stuff, etc')
</code></pre>
<p>Since version 1.0, Fabric has a <a href="http://docs.fabfile.org/en/1.11/api/core/context_managers.html?highlight=prefix#fabric.context_managers.prefix" rel="noreferrer"><code>prefix</code> context manager</a> which uses this technique so you can for example:</p>
<pre><code>def task():
with prefix('workon myvenv'):
run('git pull')
run('do other stuff, etc')
</code></pre>
<hr>
<p>* There are bound to be cases where using the <code>command1 && command2</code> approach may blow up on you, such as when <code>command1</code> fails (<code>command2</code> will never run) or if <code>command1</code> isn't properly escaped and contains special shell characters, and so forth.</p> |
1,144,207 | Bridge crossing puzzle | <p>Four men have to cross a bridge at night.Any party who crosses, either one or two men, must carry the flashlight with them. The flashlight must be walked back and forth; it cannot be thrown, etc. Each man walks at a different speed. One takes 1 minute to cross, another 2 minutes, another 5, and the last 10 minutes. If two men cross together, they must walk at the slower man's pace. There are no tricks--the men all start on the same side, the flashlight cannot shine a long distance, no one can be carried, etc.</p>
<p>And the question is What's the fastest they can all get across. I am basically looking for some generalized approach to these kind of problem. I was told by my friend, that this can be solved by Fibonacci series, but the solution does not work for all.</p>
<p>Please note this is not a home work.</p> | 1,144,239 | 11 | 7 | null | 2009-07-17 16:00:37.913 UTC | 12 | 2018-06-28 15:47:28.923 UTC | null | null | null | null | 43,502 | null | 1 | 17 | algorithm|puzzle | 29,923 | <p>There is <a href="http://www.inf.fu-berlin.de/inst/ag-ti/members/uploads/tx_tipublications/Crossing_the_bridge_at_night.pdf" rel="nofollow noreferrer">an entire PDF</a> (<a href="http://page.mi.fu-berlin.de/rote/Papers/pdf/Crossing+the+bridge+at+night.pdf" rel="nofollow noreferrer">alternate link</a>) that solves the general case of this problem (in a formal proof).</p> |
1,141,686 | Visual SVN diff and compare tools for Linux | <p>Which is the best Visual SVN Diff displayer for Linux.</p>
<p>BeyondCompare and VisualSVN 1.5 work well on Windows. What are the equivalent tools for Linux? (Specifically Ubuntu). </p>
<p>I know command line diff works; But I'd like multiple column syntax highlighted and differences.</p>
<p>Better if the tool has a support for Git and Hg as well.</p> | 1,141,769 | 11 | 1 | null | 2009-07-17 06:32:12.603 UTC | 3 | 2017-02-28 21:26:33.35 UTC | 2012-12-17 08:14:51.673 UTC | null | 761,095 | null | 55,562 | null | 1 | 25 | linux|svn|git|diff | 41,953 | <p>Note: If your diff tool has a CLI (a command line interface), it can be integrated with Git quite easily, both for diff and merge (if it supports <a href="https://stackoverflow.com/questions/170309/three-way-merge/170537#170537">3-way merges</a>).<br>
Since Git1.6.3, the <code>difftool</code> - <code>mergetool</code> options allow you to integrate that diff program (see "<strong><a href="https://stackoverflow.com/questions/255202/how-do-i-view-git-diff-output-with-visual-diff-program/949242#949242">How do I view '<code>git diff</code>' output with visual diff program?</a></strong>"). </p>
<p><a href="http://kdiff3.sourceforge.net/" rel="nofollow noreferrer">KDiff3</a> for instance is a good candidate for that, since it is even <a href="https://stackoverflow.com/questions/1064103/is-gits-auto-detection-scripted-or-is-it-within-some-git-executable/1064221#1064221">auto-detected by Git</a>.</p> |
10,616 | Differences between MySQL and SQL Server | <p>I'm an <a href="http://en.wikipedia.org/wiki/ASP.NET" rel="noreferrer">ASP.NET</a> developer who has used <code>Microsoft SQL Server</code> for all my database needs (both at work and for personal projects). </p>
<p>I am considering trying out the <a href="http://en.wikipedia.org/wiki/LAMP_%28software_bundle%29" rel="noreferrer">LAMP</a> stack for some of my personal projects. </p>
<p>What are some of the main differences between <code>MySQL</code> and <code>SQL Server</code>? Is using <a href="http://en.wikipedia.org/wiki/Stored_procedure" rel="noreferrer">stored procedures</a> a common practice in <code>MySQL</code>? </p>
<p>Any advice or resources you'd recommend to help me with the switch? </p>
<p>To those who have experience with both, are there any missing features from <code>MySQL</code>?</p> | 10,623 | 12 | 0 | null | 2008-08-14 03:13:26.633 UTC | 49 | 2018-03-23 06:47:26.037 UTC | 2018-03-23 06:47:26.037 UTC | Nigel Campbell | 3,876,565 | sestocker | 285 | null | 1 | 147 | mysql|sql-server|tsql | 330,436 | <p>One thing you have to watch out for is the fairly severe differences in the way SQL Server and MySQL implement the SQL syntax.</p>
<p>Here's a nice <a href="http://troels.arvin.dk/db/rdbms/" rel="noreferrer">Comparison of Different SQL Implementations</a>.</p>
<p>For example, take a look at the top-n section. In MySQL:</p>
<pre><code>SELECT age
FROM person
ORDER BY age ASC
LIMIT 1 OFFSET 2
</code></pre>
<p>In SQL Server (T-SQL):</p>
<pre><code>SELECT TOP 3 WITH TIES *
FROM person
ORDER BY age ASC
</code></pre> |
829,656 | C++ for Game Programming - Love or Distrust? | <p>In the name of efficiency in game programming, some programmers do not trust several C++ features. One of my friends claims to understand how game industry works, and would come up with the following remarks:</p>
<ul>
<li>Do not use smart pointers. Nobody in games does.</li>
<li>Exceptions should not be (and is usually not) used in game programming for memory and speed.</li>
</ul>
<p>How much of these statements are true? C++ features have been designed keeping efficiency in mind. Is that efficiency not sufficient for game programming? For 97% of game programming? </p>
<p>The C-way-of-thinking still seems to have a good grasp on the game development community. Is this true?</p>
<p>I watched another video of a talk on multi-core programming in GDC 2009. His talk was almost exclusively oriented towards Cell Programming, where DMA transfer is needed before processing (simple pointer access won't work with the SPE of Cell). He discouraged the use of polymorphism as the pointer has to be "re-based" for DMA transfer. How sad. It is like going back to the square one. I don't know if there is an elegant solution to program C++ polymorphism on the Cell. The topic of DMA transfer is esoteric and I do not have much background here. </p>
<p>I agree that C++ has also not been very nice to programmers who want a small language to hack with, and not read stacks of books. Templates have also scared the hell out of debugging. Do you agree that C++ is too much feared by the gaming community?</p> | 829,726 | 15 | 4 | null | 2009-05-06 13:48:39.347 UTC | 16 | 2021-07-02 18:47:39.62 UTC | 2013-05-30 15:28:27.01 UTC | null | 183,120 | null | 19,501 | null | 1 | 27 | c++|performance | 6,829 | <p>Look, most everything you hear <em>anyone</em> say about efficiency in programming is magical thinking and superstition. Smart pointers do have a performance cost; especially if you're doing a lot of fancy pointer manipulations in an inner loop, it could make a difference.</p>
<p>Maybe.</p>
<p>But when people <em>say</em> things like that, it's usually the result of someone who told them long ago that X was true, without anything but intuition behind it. Now, the Cell/polymorphism issue <em>sounds</em> plausible — and I bet it did to the first guy who said it. But I haven't verified it.</p>
<p>You'll hear the very same things said about C++ for operating systems: that it is too slow, that it does things you want to do well, badly.</p>
<p>None the less we built OS/400 (from v3r6 forward) entirely in C++, bare-metal on up, and got a code base that was fast, efficient, and small. It took some work; especially working from bare metal, there are some bootstrapping issues, use of placement new, that kind of thing.</p>
<p>C++ can be a problem just because it's too damn big: I'm rereading Stroustrup's wristbreaker right now, and it's pretty intimidating. But I don't think there's anything inherent that says you can't use C++ in an effective way in game programming.</p> |
477,550 | Is there a way to access an iteration-counter in Java's for-each loop? | <p>Is there a way in Java's for-each loop</p>
<pre><code>for(String s : stringArray) {
doSomethingWith(s);
}
</code></pre>
<p>to find out how often the loop has already been processed?</p>
<p>Aside from using the old and well-known <code>for(int i=0; i < boundary; i++)</code> - loop, is the construct</p>
<pre><code>int i = 0;
for(String s : stringArray) {
doSomethingWith(s);
i++;
}
</code></pre>
<p>the only way to have such a counter available in a for-each loop?</p> | 477,592 | 15 | 2 | null | 2009-01-25 11:05:37.447 UTC | 30 | 2022-02-01 11:00:00.537 UTC | 2017-01-27 12:28:09.923 UTC | Kosi2801 | 2,553,443 | Kosi2801 | 57,601 | null | 1 | 324 | java|loops|for-loop|foreach | 278,875 | <p>No, but you can provide your own counter.</p>
<p>The reason for this is that the for-each loop internally does not <em>have</em> a counter; it is based on the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Iterable.html" rel="noreferrer">Iterable</a> interface, i.e. it uses an <code>Iterator</code> to loop through the "collection" - which may not be a collection at all, and may in fact be something not at all based on indexes (such as a linked list).</p> |
263,359 | How can I determine if an image has loaded, using Javascript/jQuery? | <p>I'm writing some Javascript to resize the large image to fit into the user's browser window. (I don't control the size of the source images unfortunately.)</p>
<p>So something like this would be in the HTML:</p>
<pre><code><img id="photo"
src="a_really_big_file.jpg"
alt="this is some alt text"
title="this is some title text" />
</code></pre>
<p><strong>Is there a way for me to determine if the <code>src</code> image in an <code>img</code> tag has been downloaded?</strong></p>
<p>I need this because I'm running into a problem if <code>$(document).ready()</code> is executed before the browser has loaded the image. <code>$("#photo").width()</code> and <code>$("#photo").height()</code> will return the size of the placeholder (the alt text). In my case this is something like 134 x 20.</p>
<p>Right now I'm just checking if the photo's height is less than 150, and assuming that if so it is just alt text. But this is quite a hack, and it would break if a photo is less than 150 pixels tall (not likely in my particular case), or if the alt text is more than 150 pixels tall (could possibly happen on a small browser window).</p>
<hr>
<p><strong>Edit:</strong> For anyone wanting to see the code:</p>
<pre><code>$(function()
{
var REAL_WIDTH = $("#photo").width();
var REAL_HEIGHT = $("#photo").height();
$(window).resize(adjust_photo_size);
adjust_photo_size();
function adjust_photo_size()
{
if(REAL_HEIGHT < 150)
{
REAL_WIDTH = $("#photo").width();
REAL_HEIGHT = $("#photo").height();
if(REAL_HEIGHT < 150)
{
//image not loaded.. try again in a quarter-second
setTimeout(adjust_photo_size, 250);
return;
}
}
var new_width = . . . ;
var new_height = . . . ;
$("#photo").width(Math.round(new_width));
$("#photo").height(Math.round(new_height));
}
});
</code></pre>
<hr>
<p><strong>Update</strong>: Thanks for the suggestions. There is a risk of the event not being fired if I set a callback for the <code>$("#photo").load</code> event, so I have defined an onLoad event directly on the image tag. For the record, here is the code I ended up going with:</p>
<pre><code><img id="photo"
onload="photoLoaded();"
src="a_really_big_file.jpg"
alt="this is some alt text"
title="this is some title text" />
</code></pre>
<p>Then in Javascript:</p>
<pre><code>//This must be outside $() because it may get called first
var isPhotoLoaded = false;
function photoLoaded()
{
isPhotoLoaded = true;
}
$(function()
{
//Hides scrollbars, so we can resize properly. Set with JS instead of
// CSS so that page doesn't break with JS disabled.
$("body").css("overflow", "hidden");
var REAL_WIDTH = -1;
var REAL_HEIGHT = -1;
$(window).resize(adjust_photo_size);
adjust_photo_size();
function adjust_photo_size()
{
if(!isPhotoLoaded)
{
//image not loaded.. try again in a quarter-second
setTimeout(adjust_photo_size, 250);
return;
}
else if(REAL_WIDTH < 0)
{
//first time in this function since photo loaded
REAL_WIDTH = $("#photo").width();
REAL_HEIGHT = $("#photo").height();
}
var new_width = . . . ;
var new_height = . . . ;
$("#photo").width(Math.round(new_width));
$("#photo").height(Math.round(new_height));
}
});
</code></pre> | 263,447 | 15 | 7 | null | 2008-11-04 20:44:37.84 UTC | 31 | 2021-06-11 05:21:54.707 UTC | 2010-01-22 20:57:00.363 UTC | Kip | 18,511 | Kip | 18,511 | null | 1 | 87 | javascript|jquery|image | 136,247 | <p>Either add an event listener, or have the image announce itself with onload. Then figure out the dimensions from there.</p>
<pre><code><img id="photo"
onload='loaded(this.id)'
src="a_really_big_file.jpg"
alt="this is some alt text"
title="this is some title text" />
</code></pre> |
460,316 | Are database triggers necessary? | <p>In my experience, they are not a good idea because they can result in surprising side effects, and are difficult to debug (especially when one trigger fires another). Often developers do not even think of looking if there is a trigger.</p>
<p>On the other hand, if you have logic that must occur every time a new <code>FOO</code> is created in the database, then it may be the most foolproof place to put it is an insert trigger on the <code>FOO</code> table.</p>
<p>The only time we're using triggers is for really simple things like setting the modified date field of a row.</p>
<p>I'm struggling to figure out whether triggers are necessary and would appreciate any input. If they are necessary, what are the most important issues to consider when implementing them?</p> | 460,343 | 20 | 6 | null | 2009-01-20 07:01:04.463 UTC | 51 | 2022-08-30 06:14:39.79 UTC | 2022-08-30 06:14:39.79 UTC | null | 14,860 | WW | 14,663 | null | 1 | 206 | database|triggers | 67,607 | <p>The main problems with triggers are </p>
<ul>
<li>They are completely Global - they apply no matter what the context of the table activity; </li>
<li>They are stealthy; it's easy to forget they are there until they hurt you with unintended (and very mysterious) consequences.</li>
</ul>
<p>This just means they need to be carefully used for the proper circumstances; which in my experience is limited to relational integrity issues (sometimes with finer granularity than you can get declaratively); and usually not for business or transactional purposes. YMMV.</p> |
306,252 | How to align checkboxes and their labels consistently cross-browsers | <p>This is one of the minor CSS problems that plague me constantly.</p>
<p>How do folks around Stack Overflow vertically align <em><strong><code>checkboxes</code></strong></em> and their <em><strong><code>labels</code></strong></em> consistently <strong>cross-browser</strong>?</p>
<p>Whenever I align them correctly in Safari (usually using <code>vertical-align: baseline</code> on the <code>input</code>), they're completely off in Firefox and IE.</p>
<p>Fix it in Firefox, and Safari and IE are inevitably messed up. I waste time on this every time I code a form.</p>
<p>Here's the standard code that I work with:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
<div>
<label><input type="checkbox" /> Label text</label>
</div>
</form></code></pre>
</div>
</div>
</p>
<p>I usually use Eric Meyer's reset, so form elements are relatively clean of overrides. Looking forward to any tips or tricks that you have to offer!</p> | 306,593 | 40 | 5 | 2013-11-21 09:31:41.447 UTC | 2008-11-20 18:02:01.65 UTC | 558 | 2021-11-17 12:30:48.37 UTC | 2021-04-01 09:14:18.447 UTC | null | 11,926,970 | One Crayon | 38,666 | null | 1 | 1,853 | html|css|cross-browser|alignment|forms | 1,161,937 | <h1>Warning! This answer is <em><strong>too old</strong></em> and <em><strong>doesn't work</strong></em> on modern browsers.</h1>
<p><sub>
I'm not the poster of this answer, but at the time of writing this, this is the most voted answer by far in both positive and negative votes (+1035 -17), and it's still marked as accepted answer (probably because the original poster of the question is the one who wrote this answer).</sub></p>
<p>As already noted many times in the comments, this answer does not work on most browsers anymore (and seems to be failing to do that since 2013).</p>
<hr />
<p>After over an hour of tweaking, testing, and trying different styles of markup, I think I may have a decent solution. The requirements for this particular project were:</p>
<ol>
<li>Inputs must be on their own line.</li>
<li>Checkbox inputs need to align vertically with the label text similarly (if not identically) across all browsers.</li>
<li>If the label text wraps, it needs to be indented (so no wrapping down underneath the checkbox).</li>
</ol>
<p>Before I get into any explanation, I'll just give you the code:</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>label {
display: block;
padding-left: 15px;
text-indent: -15px;
}
input {
width: 13px;
height: 13px;
padding: 0;
margin:0;
vertical-align: bottom;
position: relative;
top: -1px;
*overflow: hidden;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
<div>
<label><input type="checkbox" /> Label text</label>
</div>
</form></code></pre>
</div>
</div>
</p>
<p>Here is the working example in <a href="http://jsfiddle.net/t8EGn/6/" rel="noreferrer">JSFiddle</a>.</p>
<p>This code assumes that you're using a reset like Eric Meyer's that doesn't override form input margins and padding (hence putting margin and padding resets in the input CSS). Obviously in a live environment you'll probably be nesting/overriding stuff to support other input elements, but I wanted to keep things simple.</p>
<p>Things to note:</p>
<ul>
<li>The <code>*overflow</code> declaration is an inline IE hack (the star-property hack). Both IE 6 and 7 will notice it, but Safari and Firefox will properly ignore it. I think it might be valid CSS, but you're still better off with conditional comments; just used it for simplicity.</li>
<li>As best I can tell, the only <code>vertical-align</code> statement that was consistent across browsers was <code>vertical-align: bottom</code>. Setting this and then relatively positioning upwards behaved almost identically in Safari, Firefox and IE with only a pixel or two of discrepancy.</li>
<li>The major problem in working with alignment is that IE sticks a bunch of mysterious space around input elements. It isn't padding or margin, and it's damned persistent. Setting a width and height on the checkbox and then <code>overflow: hidden</code> for some reason cuts off the extra space and allows IE's positioning to act very similarly to Safari and Firefox.</li>
<li>Depending on your text sizing, you'll no doubt need to adjust the relative positioning, width, height, and so forth to get things looking right.</li>
</ul>
<p>Hope this helps someone else! I haven't tried this specific technique on any projects other than the one I was working on this morning, so definitely pipe up if you find something that works more consistently.</p>
<hr />
<h1>Warning! This answer is <em><strong>too old</strong></em> and <em><strong>doesn't work</strong></em> on modern browsers.</h1> |
7,010,760 | C++ keypress: getch, cin.get? | <p>I have a Win32 program that runs on a loop. I would like to be able to pause that program while awaiting a keypress. It doesn't matter whether I use 'any key' or a specific key, but I need to have the program freeze until I press something.</p>
<p>I am wondering which command I should use. I am working with Visual C++ and the compiler doesn't recognise any of the following commands:</p>
<pre><code>cin.get()
std::cin.get()
getch()
</code></pre>
<p>I am relatively new to C++. I understand that in a console app this is a fairly simple action to take (cin.get), but that it can be more difficult in Win32. Any simple solution or workaround would be appreciated. The program is bespoke to be used in a single scientific experiment, so for now I'm not fussed if the solution is a little botchy(!)</p>
<p>Apologies if I've missed any important info from my question.</p> | 7,010,817 | 6 | 6 | null | 2011-08-10 12:28:07.457 UTC | 7 | 2017-02-13 19:16:18.02 UTC | null | null | null | null | 741,739 | null | 1 | 34 | c++|keypress | 91,649 | <p>You should use neither. </p>
<p>You should use</p>
<pre><code>#include <iostream>
...
int main()
{
...
std::cin.ignore(); //why read something if you need to ignore it? :)
}'
</code></pre>
<p><a href="http://en.cppreference.com/w/cpp/io/basic_istream/ignore" rel="noreferrer">Here's the documentation</a></p> |
6,598,244 | private static member function or free function in anonymous namespace? | <p>I've recently made a change stylistically and wanted to see how other c++ programmers felt about it and if there were any downsides to it.</p>
<p>Essentially, when I needed a utility function which doesn't need access to a given class member, what I used to do was something like this:</p>
<p><strong>file.h</strong></p>
<pre><code>class A {
public:
// public interface
private:
static int some_function(int);
};
</code></pre>
<p><strong>file.cpp</strong></p>
<pre><code>int A::some_function(int) {
// ...
}
</code></pre>
<p>But more recently, I have been preferring to do something more like this:</p>
<p><strong>file.cpp</strong></p>
<pre><code>namespace {
int some_function(int) {
}
}
// the rest of file.cpp
</code></pre>
<p>Here's my thought process:</p>
<ul>
<li>it's one less file the edit</li>
<li>simply having the function be listed in the header file can hint at implementation details
which have no need to be exposed (even if not publically available).</li>
<li>if the prototype of the function needs to change, only one file needs to be recompiled.</li>
</ul>
<p>The last one is the most compelling to me. So my question is: <strong>are there any downsides to this?</strong></p>
<p>They are functionally equivalent for most purposes that I can think of. It kind of seems to me that a <code>private static</code> function can almost always be converted to a free function in an anonymous <code>namespace</code>.</p>
<p><strong>EDIT</strong>: One thing that comes to mind is that a <code>private static</code> function would have access to <code>private</code> members if given a pointer to an object to operate on, but if that's the case, why not make it a non-<code>static</code> member?</p>
<p>What do you guys think?</p> | 6,598,350 | 7 | 3 | null | 2011-07-06 14:40:35.32 UTC | 15 | 2017-12-21 20:36:15.733 UTC | 2011-07-06 17:13:06.76 UTC | null | 13,430 | null | 13,430 | null | 1 | 39 | c++|function|static|namespaces | 12,435 | <p>If the function is only used in one source file, it makes perfect sense to define it there. If nobody else is using it, it doesn't belong in the header.</p>
<p>As you say, it reduces dependencies and can potentially save some recompiles.</p> |
6,783,194 | Background thread with QThread in PyQt | <p>I have a program which interfaces with a radio I am using via a gui I wrote in PyQt. Obviously one of the main functions of the radio is to transmit data, but to do this continuously, I have to loop the writes, which causes the gui to hang. Since I have never dealt with threading, I tried to get rid of these hangs using <code>QCoreApplication.processEvents().</code> The radio needs to sleep between transmissions, though, so the gui still hangs based on how long these sleeps last. </p>
<p>Is there a simple way to fix this using QThread? I have looked for tutorials on how to implement multithreading with PyQt, but most of them deal with setting up servers and are much more advanced than I need them to be. I honestly don't even really need my thread to update anything while it is running, I just need to start it, have it transmit in the background, and stop it.</p> | 6,789,205 | 7 | 0 | null | 2011-07-21 21:43:03.167 UTC | 115 | 2022-08-09 01:03:00.67 UTC | 2012-10-02 10:02:02.403 UTC | null | 634,124 | null | 274,853 | null | 1 | 90 | python|multithreading|pyqt|pyqt4|qthread | 176,433 | <p>I created a little example that shows 3 different and simple ways of dealing with threads. I hope it will help you find the right approach to your problem.</p>
<pre><code>import sys
import time
from PyQt5.QtCore import (QCoreApplication, QObject, QRunnable, QThread,
QThreadPool, pyqtSignal)
# Subclassing QThread
# http://qt-project.org/doc/latest/qthread.html
class AThread(QThread):
def run(self):
count = 0
while count < 5:
time.sleep(1)
print("A Increasing")
count += 1
# Subclassing QObject and using moveToThread
# http://blog.qt.digia.com/blog/2007/07/05/qthreads-no-longer-abstract
class SomeObject(QObject):
finished = pyqtSignal()
def long_running(self):
count = 0
while count < 5:
time.sleep(1)
print("B Increasing")
count += 1
self.finished.emit()
# Using a QRunnable
# http://qt-project.org/doc/latest/qthreadpool.html
# Note that a QRunnable isn't a subclass of QObject and therefore does
# not provide signals and slots.
class Runnable(QRunnable):
def run(self):
count = 0
app = QCoreApplication.instance()
while count < 5:
print("C Increasing")
time.sleep(1)
count += 1
app.quit()
def using_q_thread():
app = QCoreApplication([])
thread = AThread()
thread.finished.connect(app.exit)
thread.start()
sys.exit(app.exec_())
def using_move_to_thread():
app = QCoreApplication([])
objThread = QThread()
obj = SomeObject()
obj.moveToThread(objThread)
obj.finished.connect(objThread.quit)
objThread.started.connect(obj.long_running)
objThread.finished.connect(app.exit)
objThread.start()
sys.exit(app.exec_())
def using_q_runnable():
app = QCoreApplication([])
runnable = Runnable()
QThreadPool.globalInstance().start(runnable)
sys.exit(app.exec_())
if __name__ == "__main__":
#using_q_thread()
#using_move_to_thread()
using_q_runnable()
</code></pre> |
6,835,682 | How to Disable GUI Button in Java | <p>so I have this small piece of code for my GUI:</p>
<pre><code>import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.BoxLayout;
import javax.swing.JSeparator;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class IPGUI extends JFrame implements ActionListener
{
private static JPanel contentPane;
private static boolean btn1Clicked = false;
private static boolean btn2Clicked = false;
private static boolean btn3Clicked = false;
private static boolean btn4Clicked = false;
//Create the frame
public IPGUI()
{
//Sets frame properties
setTitle("IP Extractor");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 250, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
//Creates new JPanel with boxlayout
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
//////////////////New Button//////////////////
JButton btnConvertDocuments = new JButton("1. Convert Documents");
btnConvertDocuments.setAlignmentX(Component.CENTER_ALIGNMENT);
btnConvertDocuments.setMaximumSize(new Dimension(160, 0));
btnConvertDocuments.setPreferredSize(new Dimension(0, 50));
panel.add(btnConvertDocuments);
btnConvertDocuments.setActionCommand("w");
btnConvertDocuments.addActionListener((ActionListener) this);
if (btn1Clicked == true)
{
btnConvertDocuments.setEnabled(false);
}
JSeparator separator_3 = new JSeparator();
panel.add(separator_3);
//////////////////New Button//////////////////
JButton btnExtractImages = new JButton("2. Extract Images");
btnExtractImages.setAlignmentX(Component.CENTER_ALIGNMENT);
btnExtractImages.setMaximumSize(new Dimension(160, 0));
btnExtractImages.setPreferredSize(new Dimension(0, 50));
panel.add(btnExtractImages);
btnExtractImages.setActionCommand("x");
btnExtractImages.addActionListener((ActionListener) this);
if (btn2Clicked == true)
{
btnExtractImages.setEnabled(false);
}
JSeparator separator_2 = new JSeparator();
panel.add(separator_2);
//////////////////New Button//////////////////
JButton btnParseRIDValues = new JButton("3. Parse rId Values");
btnParseRIDValues.setAlignmentX(Component.CENTER_ALIGNMENT);
btnParseRIDValues.setMaximumSize(new Dimension(160, 0));
btnParseRIDValues.setPreferredSize(new Dimension(0, 50));
panel.add(btnParseRIDValues);
btnParseRIDValues.setActionCommand("y");
btnParseRIDValues.addActionListener((ActionListener) this);
if (btn3Clicked == true)
{
btnParseRIDValues.setEnabled(false);
}
JSeparator separator_1 = new JSeparator();
panel.add(separator_1);
//////////////////New Button//////////////////
JButton btnParseImageInfo = new JButton("4. Parse Image Info.");
btnParseImageInfo.setAlignmentX(Component.CENTER_ALIGNMENT);
btnParseImageInfo.setMaximumSize(new Dimension(160, 0));
btnParseImageInfo.setPreferredSize(new Dimension(0, 50));
panel.add(btnParseImageInfo);
btnParseImageInfo.setActionCommand("z");
btnParseImageInfo.addActionListener((ActionListener) this);
if (btn4Clicked == true)
{
btnParseImageInfo.setEnabled(false);
}
}
public void actionPerformed(ActionEvent event)
{
String command = event.getActionCommand();
if (command.equals("w"))
{
FileConverter fc = new FileConverter();
btn1Clicked = true;
}
else if (command.equals("x"))
{
ImageExtractor ie = new ImageExtractor();
btn2Clicked = true;
}
else if (command.equals("y"))
{
XMLIDParser xip = new XMLIDParser();
btn3Clicked = true;
}
else if (command.equals("z"))
{
XMLTagParser xtp = new XMLTagParser();
btn4Clicked = true;
}
}
}
</code></pre>
<p>The part I want to focus specifically, is this conditional:</p>
<pre><code> if (btn1Clicked == true)
{
btnConvertDocuments.setEnabled(false);
}
</code></pre>
<p>So my belief is that what that command should do is this: once the button is clicked and the action performed method is called, btnClicked should be set to true, thus that button should then become disabled.</p>
<p>Can someone explain where am I going wrong here, or if I have the right idea here? Thank you in advance for any input!</p> | 6,835,781 | 8 | 2 | null | 2011-07-26 19:49:03.187 UTC | 1 | 2019-01-04 13:53:40.63 UTC | 2019-01-04 13:53:40.63 UTC | null | 8,458,892 | null | 810,860 | null | 1 | 4 | java|user-interface|jbutton|actionlistener | 128,444 | <p>You should put the statement <code>btnConvertDocuments.setEnabled(false);</code> in the <code>actionPerformed(ActionEvent event)</code> method. Your conditional above only get call once in the constructor when IPGUI object is being instantiated.</p>
<pre><code>if (command.equals("w")) {
FileConverter fc = new FileConverter();
btn1Clicked = true;
btnConvertDocuments.setEnabled(false);
}
</code></pre> |
45,677,774 | char vs wchar_t when to use which data type | <p>I want to understand the difference between <code>char</code> and <code>wchar_t</code> ? I understand that <code>wchar_t</code> uses more bytes but can I get a clear cut example to differentiate when I would use <code>char</code> vs <code>wchar_t</code> </p> | 45,678,211 | 3 | 6 | null | 2017-08-14 15:17:29.997 UTC | 9 | 2021-06-11 19:19:39.897 UTC | 2017-08-14 15:33:27.73 UTC | null | 3,459,185 | null | 8,351,550 | null | 1 | 21 | c++ | 12,613 | <p>Fundamentally, use <code>wchar_t</code> when the encoding has more symbols than a <code>char</code> can contain. </p>
<p><strong>Background</strong><br>
The <code>char</code> type has enough capacity to hold any character (encoding) in the ASCII character set. </p>
<p>The issue is that many languages require more encodings than the ASCII accounts for. So, instead of 127 possible encodings, more are needed. Some languages have more than 256 possible encodings. A <code>char</code> type does not guarantee a range greater than 256. Thus a new data type is required. </p>
<p>The <code>wchar_t</code>, a.k.a. wide characters, provides more room for encodings. </p>
<p><strong>Summary</strong><br>
Use <code>char</code> data type when the range of encodings is 256 or less, such as ASCII. Use <code>wchar_t</code> when you need the capacity for more than 256. </p>
<p>Prefer Unicode to handle large character sets (such as emojis). </p> |
41,583,088 | HTTP to HTTPS Nginx too many redirects | <p>I have a website running on a LEMP stack. I have enabled cloudflare with the website. I am using the cloudflare flexible SSL certificate for https. When i open the website in chrome it shows website redirected you too many times and in firefox has detected that the server is redirecting the request for this address in a way that will never complete. I have tried to see answers of other questions but none of them seem to solve the problem. NGINX conf file:-</p>
<pre><code>server {
listen 80 default_server;
listen [::]:80 default_server;
server_name mydomain.com www.mydomain.com;
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl http2 default_server;
listen [::]:443 ssl http2 default_server;
root /var/www/html;
index index.php index.html index.htm index.nginx-debian.html;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}
location ~ /\.ht {
deny all;
}
}
</code></pre>
<p>I would be highly grateful if anyone can point out what I am doing wrong.</p> | 41,584,708 | 4 | 1 | null | 2017-01-11 05:06:04.723 UTC | 10 | 2022-01-07 15:45:40.603 UTC | 2021-03-05 16:34:32.893 UTC | null | 2,415,524 | null | 6,039,938 | null | 1 | 28 | ssl|nginx|https | 60,339 | <p>Since you are using cloudflare flexible SSL your nginx config file wll look like this:-</p>
<pre><code>server {
listen 80 default_server;
listen [::]:80 default_server;
server_name mydomain.com www.mydomain.com;
if ($http_x_forwarded_proto = "http") {
return 301 https://$server_name$request_uri;
}
root /var/www/html;
index index.php index.html index.htm index.nginx-debian.html;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}
location ~ /\.ht {
deny all;
}
}
</code></pre> |
15,853,204 | How to login and then download a file from aspx web pages with R | <p>I'm trying to automate the download of the <em>Panel Study of Income Dynamics</em> files available on <a href="http://simba.isr.umich.edu/Zips/ZipMain.aspx" rel="nofollow noreferrer">this web page</a> using R. Clicking on any of those files takes the user through to <a href="http://simba.isr.umich.edu/u/Login.aspx" rel="nofollow noreferrer">this login/authentication page</a>. After authentication, it's easy to download the files with your web browser. Unfortunately, the <code>httr</code> code below does not appear to be maintaining the authentication. I have tried inspecting the <code>Headers</code> in Chrome for the Login.aspx page (<a href="https://stackoverflow.com/questions/10213194/use-rcurl-to-bypass-disclaimer-page-then-do-the-web-scrapping">as described here</a>), but it doesn't appear to maintain the authentication even when I believe I'm passing in all the correct values. I don't care if it's done with <code>httr</code> or <code>RCurl</code> or something else, I'd just like something that works inside R so I don't need to have users of this script have to download the files manually or with some completely separate program. One of my attempts at this is below, but it doesn't work. Any help would be appreciated. Thanks!! :D</p>
<pre><code>require(httr)
values <-
list(
"ctl00$ContentPlaceHolder3$Login1$UserName" = "[email protected]" ,
"ctl00$ContentPlaceHolder3$Login1$Password" = "somepassword" ,
"ctl00$ContentPlaceHolder3$Login1$LoginButton" = "Log In" ,
"_LASTFOCUS" = "" ,
"_EVENTTARGET" = "" ,
"_EVENTARGUMENT" = ""
)
POST( "http://simba.isr.umich.edu/u/Login.aspx?redir=http%3a%2f%2fsimba.isr.umich.edu%2fZips%2fZipMain.aspx" , body = values )
resp <- GET( "http://simba.isr.umich.edu/Zips/GetFile.aspx" , query = list( file = "1053" ) )
</code></pre> | 15,897,960 | 1 | 2 | null | 2013-04-06 16:25:04.083 UTC | 11 | 2013-04-09 09:14:31.277 UTC | 2017-05-23 11:46:43.07 UTC | null | -1 | null | 1,759,499 | null | 1 | 14 | asp.net|r|download|rcurl|httr | 8,649 | <p>Beside storing the cookie after authentication (see my above comment) there was another problematic point in your solution: the ASP.net site sets a <code>VIEWSTATE</code> key-value pair in the cookie which is to be reserved in your queries - if you check, you could not even login in your example (the result of the <code>POST</code> command holds info about how to login, just check it out).</p>
<p><strong>An outline of a possible solution:</strong></p>
<ol>
<li><p>Load <code>RCurl</code> package:</p>
<pre><code>> library(RCurl)
</code></pre></li>
<li><p>Set some handy <code>curl</code> options:</p>
<pre><code>> curl = getCurlHandle()
> curlSetOpt(cookiejar = 'cookies.txt', followlocation = TRUE, autoreferer = TRUE, curl = curl)
</code></pre></li>
<li><p>Load the page for the first time to capture <code>VIEWSTATE</code>:</p>
<pre><code>> html <- getURL('http://simba.isr.umich.edu/u/Login.aspx', curl = curl)
</code></pre></li>
<li><p>Extract <code>VIEWSTATE</code> with a regular expression or any other tool:</p>
<pre><code>> viewstate <- as.character(sub('.*id="__VIEWSTATE" value="([0-9a-zA-Z+/=]*).*', '\\1', html))
</code></pre></li>
<li><p>Set the parameters as your username, password <em>and the <code>VIEWSTATE</code></em>:</p>
<pre><code>> params <- list(
'ctl00$ContentPlaceHolder3$Login1$UserName' = '<USERNAME>',
'ctl00$ContentPlaceHolder3$Login1$Password' = '<PASSWORD>',
'ctl00$ContentPlaceHolder3$Login1$LoginButton' = 'Log In',
'__VIEWSTATE' = viewstate
)
</code></pre></li>
<li><p>Log in at last:</p>
<pre><code>> html = postForm('http://simba.isr.umich.edu/u/Login.aspx', .params = params, curl = curl)
</code></pre>
<p>Congrats, now you are logged in and <code>curl</code> holds the cookie verifying that!</p></li>
<li><p>Verify if you are logged in:</p>
<pre><code>> grepl('Logout', html)
[1] TRUE
</code></pre></li>
<li><p>So you can go ahead and download any file - just be sure to pass <code>curl = curl</code> in all your queries.</p></li>
</ol> |
15,972,404 | Symfony2 Validation Datetime 1 should be before Datetime 2 | <p>I'm looking through the Symfony2 Validation Reference but I'm not finding what I need.</p>
<p>I have a class Employment with a <strong>StartDate</strong> and <strong>EndDate</strong>.
I would like to add an \@Assert() where it verifies that <em>StartDate is always BEFORE EndDate</em>.
Is there a standard way of comparing class attributes as a Validation Constraint or should I create a custom validation constraint?</p>
<pre><code>class Employment {
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
* @Expose()
*/
protected $id;
/**
* @ORM\Column(type="datetime")
* @Expose()
* @Assert\DateTime()
*/
protected $startDate;
/**
* @ORM\Column(type="datetime", nullable=TRUE)
* @Expose()
* @Assert\DateTime()
*/
protected $endDate;
...
}
</code></pre> | 15,972,624 | 3 | 0 | null | 2013-04-12 13:16:24.643 UTC | 9 | 2018-07-10 13:11:53.817 UTC | 2018-07-10 13:11:53.817 UTC | null | 1,405,981 | null | 1,237,621 | null | 1 | 20 | php|symfony|validation|doctrine-orm|assert | 10,787 | <p>You could write a custom DateRangeValidator.</p>
<pre><code>class DateRange extends Constraint {
public $message = "daterange.violation.crossing";
public $emptyStartDate = "daterange.violation.startDate";
public $emptyEndDate = "daterange.violation.endDate";
public $hasEndDate = true;
public function getTargets() {
return self::CLASS_CONSTRAINT;
}
public function validatedBy() {
return 'daterange_validator';
}
}
class DateRangeValidator extends ConstraintValidator
{
public function isValid($entity, Constraint $constraint)
{
$hasEndDate = true;
if ($constraint->hasEndDate !== null) {
$hasEndDate = $constraint->hasEndDate;
}
if ($entity->getStartDate() !== null) {
if ($hasEndDate) {
if ($entity->getEndDate() !== null) {
if ($entity->getStartDate() > $entity->getEndDate()) {
$this->setMessage($constraint->message);
return false;
}
return true;
} else {
$this->setMessage($constraint->emptyEndDate);
return false;
}
} else {
if ($entity->getEndDate() !== null) {
if ($entity->getStartDate() > $entity->getEndDate()) {
$this->setMessage($constraint->message);
return false;
}
}
return true;
}
} else {
$this->setMessage($constraint->emptyStartDate);
return false;
}
}
</code></pre>
<p>register it as a service:</p>
<pre><code>parameters:
register.daterange.validator.class: XXX\FormExtensionsBundle\Validator\Constraints\DateRangeValidator
services:
daterange.validator:
class: %register.daterange.validator.class%
tags:
- { name: validator.constraint_validator, alias: daterange_validator }
</code></pre>
<p>And use it in your Entity:</p>
<pre><code>use XXX\FormExtensionsBundle\Validator\Constraints as FormAssert;
/**
*
* @FormAssert\DateRange()
*/
class Contact extends Entity
{
private $startDate;
private $endDate;
}
</code></pre>
<p>Eventhough it seems a bit much for a simple thing like that, but experience shows, that one needs a date range validator more often than just once.</p> |
15,720,593 | python: Two modules and classes with the same name under different packages | <p>I have started to learn python and writing a practice app. The directory structure looks like</p>
<pre><code>src
|
--ShutterDeck
|
--Helper
|
--User.py -> class User
--Controller
|
--User.py -> class User
</code></pre>
<p>The <code>src</code> directory is in <code>PYTHONPATH</code>. In a different file, lets say <code>main.py</code>, I want to access both <code>User</code> classes. How can I do it.</p>
<p>I tried using the following but it fails:</p>
<pre><code>import cherrypy
from ShutterDeck.Controller import User
from ShutterDeck.Helper import User
class Root:
@cherrypy.expose
def index(self):
return 'Hello World'
u1=User.User()
u2=User.User()
</code></pre>
<p>That's certainly ambiguous. The other (c++ way of doing it) way that I can think of is </p>
<pre><code>import cherrypy
from ShutterDeck import Controller
from ShutterDeck import Helper
class Root:
@cherrypy.expose
def index(self):
return 'Hello World'
u1=Controller.User.User()
u2=Helper.User.User()
</code></pre>
<p>But when above script is run, it gives the following error</p>
<pre><code>u1=Controller.User.User()
AttributeError: 'module' object has no attribute 'User'
</code></pre>
<p>I'm not able to figure out why is it erroring out? The directories <code>ShutterDeck</code>, <code>Helper</code> and <code>Controller</code> have <code>__init__.py</code> in them.</p> | 15,720,621 | 3 | 0 | null | 2013-03-30 16:06:31.073 UTC | 15 | 2016-02-04 22:14:36.857 UTC | 2016-02-04 22:14:36.857 UTC | null | 119,527 | null | 733,213 | null | 1 | 30 | python|python-3.x|package|python-import | 48,948 | <p>You want to import the <code>User</code> modules in the package <code>__init__.py</code> files to make them available as attributes.</p>
<p>So in both <code>Helper/__init_.py</code> and <code>Controller/__init__.py</code> add:</p>
<pre><code>from . import User
</code></pre>
<p>This makes the module an attribute of the package and you can now refer to it as such.</p>
<p>Alternatively, you'd have to import the modules themselves in full:</p>
<pre><code>import ShutterDeck.Controller.User
import ShutterDeck.Helper.User
u1=ShutterDeck.Controller.User.User()
u2=ShutterDeck.Helper.User.User()
</code></pre>
<p>so refer to them with their full names.</p>
<p>Another option is to rename the imported name with <code>as</code>:</p>
<pre><code>from ShutterDeck.Controller import User as ControllerUser
from ShutterDeck.Helper import User as HelperUser
u1 = ControllerUser.User()
u2 = HelperUser.User()
</code></pre> |
15,763,325 | Which parameter set has been used? | <p>I've used advanced parameter handling to support multiple parameter sets. Is there any pre-defined variable or way to determine which parameter set has been used to call the script?</p>
<p>e.g. something like</p>
<pre><code>if($parameterSet -eq "set1") { ... } elseif ($parameterSet -eq "set2") { ... }
</code></pre>
<p>?</p> | 15,763,532 | 2 | 0 | null | 2013-04-02 11:47:59.007 UTC | 6 | 2013-04-02 11:59:58.94 UTC | null | null | null | null | 1,400,869 | null | 1 | 64 | powershell|parameters|optional-parameters | 15,979 | <p>Check the $PSCmdlet variable:</p>
<pre><code>$PSCmdlet.ParameterSetName
</code></pre> |
33,010,594 | Why do I need a functional Interface to work with lambdas? | <p>I think this question is already somewhere out there, but I wasn't able to find it.</p>
<p>I don't understand, why it's necessary to have a functional interface to work with lambdas. Consider the following example:</p>
<pre><code>public class Test {
public static void main(String...args) {
TestInterface i = () -> System.out.println("Hans");
// i = (String a) -> System.out.println(a);
i.hans();
// i.hans("Hello");
}
}
public interface TestInterface {
public void hans();
// public void hans(String a);
}
</code></pre>
<p>This works without problems, but if you uncomment the commented lines, it doesn't. Why? In my understanding, the compiler should be able to distinguish the two methods, since they have different input-parameters. Why do I need a functional interface and blow up my code?</p>
<p>EDIT: The linked duplicates didn't answer my question because I'm asking about different method-parameters. But I got some really useful answers here, thanks to everyone who helped! :)</p>
<p>EDIT2: Sorry, I'm obviously not a native speaker, but to precise myself:</p>
<pre><code>public interface TestInterface {
public void hans(); //has no input parameters</br>
public void hans(String a); //has 1 input parameter, type String</br>
public void hans(String a, int b); //has 2 input parameters, 1. type = String, 2. type = int</br>
public void hans(int a, int b); //has also 2 input parameters, but not the same and a different order than `hans(String a, int a);`, so you could distinguish both
}
public class Test {
public static void main(String...args) {
TestInterface i = () -> System.out.println("Hans");
i = (String a) -> System.out.println(a);
i = (String a, int b) -> System.out.println(a + b);
i = (int a, int b) -> System.out.println(a);
i.hans(2, 3); //Which method would be called? Of course the one that would take 2 integer arguments. :)
}
}
</code></pre>
<p>All I'm asking is about the arguments. The method name doesn't matter, but each method takes an unique order of different arguments and because of that, Oracle could have implemented this feature instead just making a single method possible per "Lambda-Interface".</p> | 33,010,712 | 7 | 7 | null | 2015-10-08 08:34:23.337 UTC | 19 | 2021-01-20 10:34:16.02 UTC | 2018-10-06 09:14:05.85 UTC | null | 2,311,557 | null | 2,311,557 | null | 1 | 44 | java|lambda|java-8|functional-interface | 38,877 | <p>When you write :</p>
<pre><code>TestInterface i = () -> System.out.println("Hans");
</code></pre>
<p>You give an implementation to the <code>void hans()</code> method of the <code>TestInterface</code>.</p>
<p>If you could assign a lambda expression to an interface having more than one abstract method (i.e. a non functional interface), the lambda expression could only implement one of the methods, leaving the other methods unimplemented.</p>
<p>You can't solve it by assigning two lambda expressions having different signatures to the same variable (Just like you can't assign references of two objects to a single variable and expect that variable to refer to both objects at once).</p> |
10,831,565 | How do I split long lines in a .vimrc file? | <p>I've got a line in my <code>.vimrc</code> that is more than 80 chars long:</p>
<pre><code>autocmd FileType python set smartindent cinwords=if,elif,else,for,while,try,except,finally,def,class,with
</code></pre>
<p>I find this rather annoying, so I want to break it into multiple lines, but I don't know how to do that. I tried <code>\</code> since that does the trick in Python and the Bourne shell, but apparently that's not valid syntax in Vim:</p>
<pre><code>autocmd FileType python set smartindent \
cinwords=if,elif,else,for,while,try,except,finally,def,class,with
</code></pre>
<p>gives</p>
<pre><code>E492: Not an editor command
</code></pre>
<p>Can anyone tell me how to split this line?</p>
<p>(Bonus points if someone can tell me how to add to <code>cinwords</code> instead of resetting it entirely; the only thing I wanted to achieve is add the <code>with</code> keyword to it.)</p> | 10,831,665 | 2 | 3 | null | 2012-05-31 10:11:35.36 UTC | 9 | 2012-05-31 11:29:32.727 UTC | 2012-05-31 11:29:32.727 UTC | null | 1,301,972 | null | 166,749 | null | 1 | 42 | vim | 11,837 | <pre><code>autocmd FileType python set smartindent
\ cinwords+=with
</code></pre> |
10,272,605 | Align two inline-blocks left and right on same line | <p>How can I align two inline-blocks so that one is left and the other is right on the same line? Why is this so hard? Is there something like LaTeX's \hfill that can consume the space between them to achieve this?</p>
<p><strong>I don't want to use floats</strong> because with inline-blocks I can line up the baselines. And when the window is too small for both of them, with inline-blocks I can just change the text-align to center and they will be centered one atop another. Relative(parent) + Absolute(element) positioning has the same problems as floats do.</p>
<p>The HTML5:</p>
<pre><code><header>
<h1>Title</h1>
<nav>
<a>A Link</a>
<a>Another Link</a>
<a>A Third Link</a>
</nav>
</header>
</code></pre>
<p>The css:</p>
<pre><code>header {
//text-align: center; // will set in js when the nav overflows (i think)
}
h1 {
display: inline-block;
margin-top: 0.321em;
}
nav {
display: inline-block;
vertical-align: baseline;
}
</code></pre>
<p>Thery're right next to each other, but I want the <code>nav</code> on the right.</p>
<p><img src="https://i.stack.imgur.com/z88r1.png" alt="a diagram"></p> | 10,277,235 | 9 | 3 | null | 2012-04-22 22:17:17.737 UTC | 30 | 2020-07-05 13:35:05.833 UTC | 2012-04-23 00:34:54.49 UTC | null | 168,868 | null | 148,195 | null | 1 | 127 | css|html | 216,734 | <p><strong>Edit:</strong> 3 years has passed since I answered this question and I guess a more modern solution is needed, although the current one does the thing :)</p>
<p>1.<a href="https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes" rel="noreferrer"><strong>Flexbox</strong></a></p>
<p>It's by far the shortest and most flexible. Apply <code>display: flex;</code> to the parent container and adjust the placement of its children by <code>justify-content: space-between;</code> like this:</p>
<pre><code>.header {
display: flex;
justify-content: space-between;
}
</code></pre>
<p>Can be seen online here - <a href="http://jsfiddle.net/skip405/NfeVh/1073/" rel="noreferrer">http://jsfiddle.net/skip405/NfeVh/1073/</a></p>
<p>Note however that <a href="http://caniuse.com/#feat=flexbox" rel="noreferrer">flexbox support</a> is IE10 and newer. If you need to support IE 9 or older, use the following solution:</p>
<p>2.You can use the <code>text-align: justify</code> technique here.</p>
<pre><code>.header {
background: #ccc;
text-align: justify;
/* ie 7*/
*width: 100%;
*-ms-text-justify: distribute-all-lines;
*text-justify: distribute-all-lines;
}
.header:after{
content: '';
display: inline-block;
width: 100%;
height: 0;
font-size:0;
line-height:0;
}
h1 {
display: inline-block;
margin-top: 0.321em;
/* ie 7*/
*display: inline;
*zoom: 1;
*text-align: left;
}
.nav {
display: inline-block;
vertical-align: baseline;
/* ie 7*/
*display: inline;
*zoom:1;
*text-align: right;
}
</code></pre>
<p>The working example can be seen here: <a href="http://jsfiddle.net/skip405/NfeVh/4/" rel="noreferrer">http://jsfiddle.net/skip405/NfeVh/4/</a>. This code works from IE7 and above</p>
<p>If inline-block elements in HTML are not separated with space, this solution won't work - see example <a href="http://jsfiddle.net/NfeVh/1408/" rel="noreferrer">http://jsfiddle.net/NfeVh/1408/</a> . This might be a case when you insert content with Javascript.</p>
<p>If we don't care about IE7 simply omit the star-hack properties. The working example using your markup is here - <a href="http://jsfiddle.net/skip405/NfeVh/5/" rel="noreferrer">http://jsfiddle.net/skip405/NfeVh/5/</a>. I just added the <code>header:after</code> part and justified the content.</p>
<p>In order to solve the issue of the extra space that is inserted with the <code>after</code> pseudo-element one can do a trick of setting the <code>font-size</code> to 0 for the parent element and resetting it back to say 14px for the child elements. The working example of this trick can be seen here: <a href="http://jsfiddle.net/skip405/NfeVh/326/" rel="noreferrer">http://jsfiddle.net/skip405/NfeVh/326/</a></p> |
13,602,965 | Center align multiple child DIV | <p>I am finding it bit confusing working around this problem.</p>
<p>I have parent DIV and 3/more Child DIV.</p>
<p>Parent DIV is center aligned and child DIV should be floating left but should be aligned center.</p>
<p><strong>CSS</strong> contains,</p>
<pre><code>.center {
float:left;
height:250px;
width:15%;
margin: 0 auto;
border: 1px solid black;
}
</code></pre>
<p><a href="http://jsfiddle.net/wpXTr/">I have a sample of the code link here...</a></p> | 13,603,017 | 4 | 0 | null | 2012-11-28 10:31:46.783 UTC | 1 | 2021-05-17 12:59:41.763 UTC | 2012-11-28 10:40:33.973 UTC | null | 1,517,743 | null | 2,437,138 | null | 1 | 21 | css|css-float | 55,203 | <p>If you want to horizontally align your elements centrally, then don't float them.</p>
<p>Change the way they are displayed to <code>inline-block</code> and align them in the center by changing the <code>text-align</code> style of their parent:</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#parent {
text-align:center;
height:450px;
width:75%;
border:1px solid blue;
}
.center {
display:inline-block;
height:250px;
width:15%;
margin: 0 auto;
border: 1px solid black;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="parent">
<div id="child1" class="center"></div><!--
--><div id="child2" class="center"></div><!--
--><div id="child3" class="center"></div>
</div></code></pre>
</div>
</div>
</p>
<p>Be sure to have no white-space or newlines between your children <code><div></code>s (in your HTML, that is) or comment it out. Now that these are <em>inline</em> elements, this white-space will be interpreted as a space.</p> |
13,470,830 | How to change TIMEZONE for a java.util.Calendar/Date | <p>I would like to change the TIMEZONE value in a Java Calendar instance at runtime.
I tried below. But the output is the same in both instances:</p>
<pre><code> Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
System.out.println(cSchedStartCal.getTime().getTime());
cSchedStartCal.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
System.out.println(cSchedStartCal.getTime().getTime());
</code></pre>
<p>OUTPUT:<BR>
1353402486773 <BR>
1353402486773</p>
<p>I have tried this also but the output is still the same:</p>
<pre><code> Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
System.out.println(cSchedStartCal.getTime());
Calendar cSchedStartCal1 = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
cSchedStartCal1.setTime(cSchedStartCal.getTime());
System.out.println(cSchedStartCal.getTime());
</code></pre>
<p>In the API I am seeing the below comment but I am not able to understand much of it:</p>
<pre><code> * calls: cal.setTimeZone(EST); cal.set(HOUR, 1); cal.setTimeZone(PST).
* Is cal set to 1 o'clock EST or 1 o'clock PST? Answer: PST. More
* generally, a call to setTimeZone() affects calls to set() BEFORE AND
* AFTER it up to the next call to complete().
</code></pre>
<p>Could you please help me?</p>
<p><B>One Possible Solution : </B></p>
<pre><code> Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
long gmtTime = cSchedStartCal.getTime().getTime();
long timezoneAlteredTime = gmtTime + TimeZone.getTimeZone("Asia/Calcutta").getRawOffset();
Calendar cSchedStartCal1 = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
cSchedStartCal1.setTimeInMillis(timezoneAlteredTime);
</code></pre>
<p>Is this solution ok?</p> | 13,472,173 | 3 | 3 | null | 2012-11-20 10:07:35.197 UTC | 17 | 2022-07-14 07:06:33.75 UTC | 2015-08-27 13:06:56.04 UTC | null | 3,891,896 | null | 912,319 | null | 1 | 48 | java|datetime|calendar | 174,934 | <p>In Java, Dates are internally represented in UTC milliseconds since the epoch (so timezones are not taken into account, that's why you get the same results, as <code>getTime()</code> gives you the mentioned milliseconds).<br>
In your solution:</p>
<pre><code>Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
long gmtTime = cSchedStartCal.getTime().getTime();
long timezoneAlteredTime = gmtTime + TimeZone.getTimeZone("Asia/Calcutta").getRawOffset();
Calendar cSchedStartCal1 = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
cSchedStartCal1.setTimeInMillis(timezoneAlteredTime);
</code></pre>
<p>you just add the offset from GMT to the specified timezone ("Asia/Calcutta" in your example) in milliseconds, so this should work fine. </p>
<p>Another possible solution would be to utilise the static fields of the <code>Calendar</code> class:</p>
<pre><code>//instantiates a calendar using the current time in the specified timezone
Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
//change the timezone
cSchedStartCal.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
//get the current hour of the day in the new timezone
cSchedStartCal.get(Calendar.HOUR_OF_DAY);
</code></pre>
<p>Refer to <a href="https://stackoverflow.com/questions/7695859/how-to-convert-a-data-from-1-timezone-to-another-timezone">stackoverflow.com/questions/7695859/</a> for a more in-depth explanation.</p> |
24,407,716 | how to add a property to existing node neo4j cypher? | <p>i have created a new node labeled User </p>
<pre><code>CREATE (n:User)
</code></pre>
<p>i want to add a name property to my User node i tried it by </p>
<pre><code>MATCH (n { label: 'User' })
SET n.surname = 'Taylor'
RETURN n
</code></pre>
<p>but seems it is not affecting .</p>
<p>how can i add properties to a already created node .</p>
<p>Thank you very much.</p> | 24,407,850 | 1 | 2 | null | 2014-06-25 11:41:21.217 UTC | 6 | 2016-09-26 04:43:52.583 UTC | 2016-09-26 04:43:52.583 UTC | null | 4,111,842 | null | 733,287 | null | 1 | 29 | neo4j|cypher|graph-databases | 32,968 | <p>Your matching by label is incorrect, the query should be:</p>
<pre><code>MATCH (n:User)
SET n.surname = 'Taylor'
RETURN n
</code></pre>
<p>What you wrote is: "match a user whose label <em>property</em> is User".
Label isn't a property, this is a notion apart.</p>
<p>As Michael mentioned, if you want to match a node with a specific property, you've got two alternatives:</p>
<pre><code>MATCH (n:User {surname: 'Some Surname'})
</code></pre>
<p>or:</p>
<pre><code>MATCH (n:User)
WHERE n.surname = 'Some Surname'
</code></pre>
<p>Now the combo:</p>
<pre><code>MATCH (n:User {surname: 'Some Surname'})
SET n.surname = 'Taylor'
RETURN n
</code></pre> |
9,061,325 | FragmentPagerAdapter is not removing items (Fragments) correctly | <p>I have implemented the <code>FragmentPagerAdapter</code> and and using a <code>List<Fragment></code> to hold all fragments for my <code>ViewPager</code> to display. On <code>addItem()</code> I simply add an instantiated <code>Fragment</code> and then call <code>notifyDataSetChanged()</code>. I am not sure if this is necessary or not. </p>
<p>My problem simply...
start with fragment 1 </p>
<pre><code>[Fragment 1]
</code></pre>
<p>add new Fragment 2 </p>
<pre><code>[Fragment 1] [Fragment 2]
</code></pre>
<p>remove Fragment 2 </p>
<pre><code>[Fragment 1]
</code></pre>
<p>add new Fragment 3 </p>
<pre><code>[Fragment 1] [Fragment 2]
</code></pre>
<p>When adding new fragments everything seems great. Once I remove a fragment and then add a newly instantiated fragment the old fragment is still displayed. When i go a <code>.getClass.getName()</code> it is giving me Fragment 3's name however I still see Fragment 2. </p>
<p>I believe this might be an issue with <code>instantiateItem()</code> or such but I thought the adapter was to handle that for us. Any suggestions would be great. </p>
<p>adapter code...</p>
<pre><code>public class MyPagerAdapter extends FragmentPagerAdapter {
public final ArrayList<Fragment> screens2 = new ArrayList<Fragment>();
private Context context;
public MyPagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
public void removeType(String name){
for(Fragment f: screens2){
if(f.getClass().getName().contains(name)){ screens2.remove(f); return; }
}
this.notifyDataSetChanged();
}
public boolean addSt(String tag, Class<?> clss, Bundle args){
if(clss==null) return false;
if(!clss.getName().contains("St")) return false;
if(!args.containsKey("cId")) return false;
boolean has = false;
boolean hasAlready = false;
for(Fragment tab: screens2){
if(tab.getClass().getName().contains("St")){
has = true;
if(tab.getArguments().containsKey("cId"))
if(tab.getArguments().getLong("cId") == args.getLong("cId")){
hasAlready = true;
}
if(!hasAlready){
// exists but is different so replace
screens2.remove(tab);
this.addScreen(tag, clss, args, C.PAGE_ST);
// if returned true then it notifies dataset
return true;
}
}
hasAlready = false;
}
if(!has){
// no st yet exist in adapter
this.addScreen(tag, clss, args, C.PAGE_ST);
return true;
}
return false;
}
public boolean removeCCreate(){
this.removeType("Create");
return false;
}
@Override
public int getItemPosition(Object object) {
return POSITION_NONE; //To make notifyDataSetChanged() do something
}
public void addCCreate(){
this.removeCCreate();
Log.w("addding c", " ");
this.addScreen("Create C", CreateCFragment.class, null, C.PAGE_CREATE_C);
}
public void addScreen(String tag, Class<?> clss, Bundle args, int type){
if(clss!=null){
screens2.add(Fragment.instantiate(context, clss.getName(), args));
}
}
@Override
public int getCount() {
return screens2.size();
}
@Override
public Fragment getItem(int position) {
return screens2.get(position);
}
}
</code></pre>
<p>I realize the code uses some "ghetto" means of determining the fragment type however I wrote this code strictly for testing functionality. Any help or ideas would be great as it seems that not many people ventured into the world of <code>FragmentPagerAdapter</code>s.</p> | 10,298,847 | 9 | 2 | null | 2012-01-30 08:50:26.51 UTC | 23 | 2019-08-23 13:22:48.063 UTC | 2017-10-27 16:00:23.673 UTC | null | 1,708,390 | null | 778,158 | null | 1 | 44 | android|android-fragments|android-viewpager | 37,710 | <p>I got same problem,and my solution was overring the method "destroyItem" as following.</p>
<pre><code>@Override
public void destroyItem(ViewGroup container, int position, Object object) {
FragmentManager manager = ((Fragment)object).getFragmentManager();
FragmentTransaction trans = manager.beginTransaction();
trans.remove((Fragment)object);
trans.commit();
}
</code></pre>
<p>It's work for me,does anybody have another solutions?</p>
<p><strong>Updated:</strong></p>
<p>I found those code made Fragment removed unnecessary,so I added a condition to avoid it.</p>
<pre><code>@Override
public void destroyItem(ViewGroup container, int position, Object object) {
if (position >= getCount()) {
FragmentManager manager = ((Fragment) object).getFragmentManager();
FragmentTransaction trans = manager.beginTransaction();
trans.remove((Fragment) object);
trans.commit();
}
}
</code></pre> |
29,345,841 | Laravel: SQLSTATE[28000] [1045] Access denied for user 'homestead'@'localhost' | <p>I just installed laravel and made a migration. But when i try to run it i get this error:</p>
<pre><code>[PDOException]
SQLSTATE[28000] [1045] Access denied for user 'homestead'@'localhost' (using password: YES)
</code></pre>
<p>Can anyone tell me what is wrong? I think the Database.php file looks different than normal. Is this something new in the new Laravel?</p>
<p>My Database config:</p>
<pre><code>'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'LaraBlog'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', 'root'),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
</code></pre>
<p>Hope someone can help me :)</p> | 45,078,612 | 7 | 3 | null | 2015-03-30 12:07:21.84 UTC | 4 | 2019-03-07 07:43:17.2 UTC | 2018-10-11 12:21:58.42 UTC | null | 9,331,166 | null | 1,575,198 | null | 1 | 11 | laravel|pdo | 43,470 | <p>Try to check out the ".env" file in your root directory. These values are taken first. Yours are just the defaults if there are none given in the .env file.</p>
<pre><code>DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Your_Database_Name
DB_USERNAME=Your_UserName
DB_PASSWORD=Your_Password
</code></pre> |
16,466,516 | Notify user within app that a new version is available | <p>I have an android app in the market and I've noticed that it can take quite a while for the app to be updated when I release a new version. </p>
<p>What I was hoping is something like what Google do with their Google Chrome app (may only be the beta version that does it not sure). </p>
<p>What I want to do is when the user launches my app, it can do a check to see if there is a new version available, and if so, just display a small message at the bottom to inform the user that there is a new version available for download. If they click it then the user will be taken straight to the app within the play store so they can commence the update. </p>
<p>How is this done? I've not managed to find anything for android, I've found a couple of things relating to iOS but obviously no good to me.</p>
<p>Thanks for any help you can provide.</p> | 16,466,649 | 10 | 1 | null | 2013-05-09 16:24:49.91 UTC | 3 | 2021-11-15 11:27:11.49 UTC | null | null | null | null | 499,448 | null | 1 | 13 | android|google-play | 43,399 | <p>There is no API or service by when you can check with Google Play what the latest version of your app is.</p>
<p>Instead, you should maintain the latest version code on your server, and have your app check it periodically against its own version code. If the version code is higher on the server, then your app needs to be updated and you can tell the user accordingly.</p> |
29,271,251 | Put Navigation Drawer Under Status Bar | <p>I'm trying to make my navigation drawer go under the status bar. I've read extensively about the ScrimInsetsFrameLayout view and I tried implementing it, but for some reason it won't go under.</p>
<p>Here's the code that I used/wrote.</p>
<p>XML DrawerLayout:</p>
<pre><code><android.support.v4.widget.DrawerLayout
android:id="@+id/drawer_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<include layout="@layout/toolbar" />
</FrameLayout>
<com.andrewq.planets.util.ScrimInsetsFrameLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/linearLayout"
android:layout_width="304dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:insetForeground="#4000">
<ListView
android:id="@+id/left_drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:choiceMode="singleChoice" />
</com.andrewq.planets.util.ScrimInsetsFrameLayout>
</android.support.v4.widget.DrawerLayout>
</code></pre>
<p>ScrimInsetsFrameLayout.java:</p>
<pre><code>package com.andrewq.planets.util;
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.widget.FrameLayout;
import com.andrewq.planets.R;
/**
* A layout that draws something in the insets passed to {@link #fitSystemWindows(Rect)}, i.e. the area above UI chrome
* (status and navigation bars, overlay action bars).
*/
public class ScrimInsetsFrameLayout extends FrameLayout {
private Drawable mInsetForeground;
private Rect mInsets;
private Rect mTempRect = new Rect();
private OnInsetsCallback mOnInsetsCallback;
public ScrimInsetsFrameLayout(Context context) {
super(context);
init(context, null, 0);
}
public ScrimInsetsFrameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, 0);
}
public ScrimInsetsFrameLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs, defStyle);
}
private void init(Context context, AttributeSet attrs, int defStyle) {
final TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.ScrimInsetsView, defStyle, 0);
if (a == null) {
return;
}
mInsetForeground = a.getDrawable(R.styleable.ScrimInsetsView_insetForeground);
a.recycle();
setWillNotDraw(true);
}
@Override
protected boolean fitSystemWindows(Rect insets) {
mInsets = new Rect(insets);
setWillNotDraw(mInsetForeground == null);
ViewCompat.postInvalidateOnAnimation(this);
if (mOnInsetsCallback != null) {
mOnInsetsCallback.onInsetsChanged(insets);
}
return true; // consume insets
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
int width = getWidth();
int height = getHeight();
if (mInsets != null && mInsetForeground != null) {
int sc = canvas.save();
canvas.translate(getScrollX(), getScrollY());
// Top
mTempRect.set(0, 0, width, mInsets.top);
mInsetForeground.setBounds(mTempRect);
mInsetForeground.draw(canvas);
// Bottom
mTempRect.set(0, height - mInsets.bottom, width, height);
mInsetForeground.setBounds(mTempRect);
mInsetForeground.draw(canvas);
// Left
mTempRect.set(0, mInsets.top, mInsets.left, height - mInsets.bottom);
mInsetForeground.setBounds(mTempRect);
mInsetForeground.draw(canvas);
// Right
mTempRect.set(width - mInsets.right, mInsets.top, width, height - mInsets.bottom);
mInsetForeground.setBounds(mTempRect);
mInsetForeground.draw(canvas);
canvas.restoreToCount(sc);
}
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (mInsetForeground != null) {
mInsetForeground.setCallback(this);
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (mInsetForeground != null) {
mInsetForeground.setCallback(null);
}
}
/**
* Allows the calling container to specify a callback for custom processing when insets change (i.e. when
* {@link #fitSystemWindows(Rect)} is called. This is useful for setting padding on UI elements based on
* UI chrome insets (e.g. a Google Map or a ListView). When using with ListView or GridView, remember to set
* clipToPadding to false.
*/
public void setOnInsetsCallback(OnInsetsCallback onInsetsCallback) {
mOnInsetsCallback = onInsetsCallback;
}
public static interface OnInsetsCallback {
public void onInsetsChanged(Rect insets);
}
}
</code></pre>
<p>And finally, here's my styles.xml for values-v21:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppThemeNavDrawer" parent="Theme.AppCompat.NoActionBar">
<item name="colorAccent">#F8F8F8</item>
<item name="android:windowTranslucentStatus">true</item>
<item name="windowActionBar">false</item>
<item name="windowActionModeOverlay">true</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">@android:color/transparent</item>
</style>
</resources>
</code></pre>
<p>I've looked at the 2014 I/O app source code as well as <a href="https://stackoverflow.com/questions/26745300/navigation-drawer-semi-transparent-over-status-bar-not-working">this</a> question, and I don't know what is so different.</p>
<p>Here's a screenshot of what I have so far minus the drawer under the status bar:
<img src="https://i.stack.imgur.com/3NuQA.png" alt="Screenshot"></p>
<p>I've got everything else working perfectly and this is the last thing I need to do. Help is greatly appreciated!</p>
<h2>Edit:</h2>
<p>To clarify, I want to have the image be tinted under the status bar just like in most of the Google Apps and Google Now.</p> | 29,283,413 | 5 | 6 | null | 2015-03-26 04:43:17.97 UTC | 9 | 2017-05-31 01:16:10.76 UTC | 2017-05-23 11:54:46.987 UTC | null | -1 | null | 2,844,992 | null | 1 | 20 | android | 30,929 | <p>There are different approaches to get to the desired result. You can enable translucent via style or via code. </p>
<p>I've created a MaterialDrawer (which follows the Android Material Design Guidelines) which implements all of this and handles everything for you. Read more here: <a href="https://github.com/mikepenz/MaterialDrawer/" rel="noreferrer">https://github.com/mikepenz/MaterialDrawer/</a></p>
<p>If you want to create it on your own you always have to decide which is the lowest api you want to support and/or if you have to split up your styles. </p>
<p>So to enable translucentStatusbar you have to be at least on API v19 or you create a separat style for v19+ <code>values-v19</code>
This will look somehow like this</p>
<pre><code><style name="YourTheme.TranslucentStatus" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:windowTranslucentStatus">true</item>
</style>
</code></pre>
<p>So now this will move your complete layout below the statusbar. In almost all cases you will now want to add the padding on the top of the drawer content and your normal view content.</p>
<p>You can do this by adding <code>24dp</code> padding.</p>
<p>This is not a really nice implementation. So there's a different approach by using the ScrimInsetsLayout which is used in the Google IO 2014 app. <a href="https://github.com/google/iosched/blob/master/android/src/main/java/com/google/samples/apps/iosched/ui/widget/ScrimInsetsFrameLayout.java" rel="noreferrer">https://github.com/google/iosched/blob/master/android/src/main/java/com/google/samples/apps/iosched/ui/widget/ScrimInsetsFrameLayout.java</a></p>
<p>This will be your contents layout and you can set the color for the statusbar on it. You can find a detailed instruction, on how you can use it, here: <a href="https://stackoverflow.com/a/26932228">https://stackoverflow.com/a/26932228</a></p>
<p>It requires some time to get used to the styles and / or the <code>ScrimInsetsLayout</code>.</p>
<p><strong>EDIT:</strong></p>
<p>A more complex sample on how you can handle this programmatically:</p>
<pre><code>if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 21) {
//enable translucent statusbar via flags
setTranslucentStatusFlag(true);
}
if (Build.VERSION.SDK_INT >= 19) {
mActivity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
if (Build.VERSION.SDK_INT >= 21) {
//we don't need the translucent flag this is handled by the theme
setTranslucentStatusFlag(false);
//set the statusbarcolor transparent to remove the black shadow
mActivity.getWindow().setStatusBarColor(Color.TRANSPARENT);
}
//add a padding to the content of the drawer (25dp on devices starting with api v19)
mDrawerContentRoot.setPadding(0, mActivity.getResources().getDimensionPixelSize(R.dimen.tool_bar_top_padding), 0, 0);
// define the statusBarColor
mDrawerContentRoot.setInsetForeground(mStatusBarColor);
private void setTranslucentStatusFlag(boolean on) {
if (Build.VERSION.SDK_INT >= 19) {
Window win = mActivity.getWindow();
WindowManager.LayoutParams winParams = win.getAttributes();
final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
if (on) {
winParams.flags |= bits;
} else {
winParams.flags &= ~bits;
}
win.setAttributes(winParams);
}
}
</code></pre>
<p><strong>EDIT2:</strong></p>
<p>The complete solution to fix this issue was to clean up all the layouts which were in the project. some combination of the layouts and styles were causing the troubles. </p>
<p>The complete changes can be found in this pull request:
<a href="https://github.com/Andrew-Quebe/Planets-Gradle/commit/83e28c09253af6e807b6f4e94baca8fbca3fc7c8" rel="noreferrer">https://github.com/Andrew-Quebe/Planets-Gradle/commit/83e28c09253af6e807b6f4e94baca8fbca3fc7c8</a></p> |
60,601,438 | Xcode stuck in "Uploading package to the App Store" stage while uploading | <p>I have tried to upload an application to Test Flight. The app is successfully validated.</p>
<p>However, when distributing, Xcode is stuck in the "Uploading" stage as shown below:</p>
<blockquote>
<p>Uploading<br />
Uploading package to the App Store...</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/yUYbP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/yUYbP.png" alt="Uploading package to the App Store..." /></a></p>
<p>I have waited 2 hours and nothing has changed.</p>
<p>I am using Xcode 11.1. Is there any solution for this problem?</p> | 61,256,205 | 14 | 5 | null | 2020-03-09 13:19:36.563 UTC | 7 | 2022-06-17 18:37:55.863 UTC | 2020-09-22 18:56:06.803 UTC | null | 1,265,393 | null | 2,079,356 | null | 1 | 84 | ios|swift|xcode | 26,852 | <p>I faced the same problem, and first what I tried was to check my traffic. So I found a process called <code>java</code> (ironic).</p>
<p>The process has since been renamed to <code>com.apple.dt.Xcode.ITunesSoftwareService</code></p>
<p><img src="https://i.stack.imgur.com/V3ejH.png" alt="Activity monitor" /></p>
<p>If you will check info about this process there will be tab <code>Open Files and Ports</code> and there in the bottom of the log window, you will see <code>%YourApp%.ipa</code>. And in general if <code>Sent Packets</code> & <code>Sent Bytes</code> increasing that's mean uploading is not stuck it's just can be one of many issues such as:</p>
<ul>
<li>Bad connection</li>
<li>Slow upload speed</li>
<li>Accepting capacity of Apple servers</li>
<li>Highload network</li>
<li>etc.</li>
</ul>
<p><em>To open Activity Monitor: Open <code>Spotlight</code>(cmd+space or ctrl+space) -> Type <code>Activity Monitor</code> -> open tab <code>Network</code></em></p>
<p><strong>Summary:</strong> Don't worry, and take your time :)</p>
<p>P.S. For increasing speed of upload you can not include <code>bitcode</code>.</p>
<p>P.S.S. Try also to use the <code>Transporter</code> app, sometimes it helps to speed up uploading. (<a href="https://apps.apple.com/in/app/transporter/id1450874784?mt=12" rel="nofollow noreferrer">https://apps.apple.com/in/app/transporter/id1450874784?mt=12</a>)</p> |
22,003,833 | Groovy initialization of array of objects | <p>I am looking for the most compact syntax to initialize an array of objects in Groovy.
Given:</p>
<pre><code>class Program {
String id = ""
String title = ""
String genre = ""
}
</code></pre>
<p>I am currently doing this:</p>
<pre><code>Program[] programs = [
new Program([id:"prog1", title:"CSI", genre:"Drama"]),
new Program([id:"prog2", title:"NCIS", genre:"Drama"]),
new Program([id:"prog3", title:"Criminal Minds", genre:"Crime drama"]),
] as Program[]
</code></pre>
<p>I seem to recall that in Java there is a more compact syntax, possibly not requiring to use the new keyword. What is the most compact Groovy syntax to accomplish this?</p> | 22,005,177 | 1 | 2 | null | 2014-02-25 03:12:22.363 UTC | 2 | 2014-02-25 15:50:46.98 UTC | 2014-02-25 15:50:46.98 UTC | null | 856,974 | null | 856,974 | null | 1 | 21 | arrays|object|groovy|initialization | 54,192 | <pre><code>@groovy.transform.Canonical
class Program {
String id = ""
String title = ""
String genre = ""
}
Program[] programs = [
["prog1", "CSI", "Drama"],
["prog2", "NCIS", "Drama"],
["prog3", "Criminal Minds", "Crime drama"]
]
println programs
</code></pre>
<p>Please also answer @Igor's question.</p> |
17,254,839 | Eclipse on-click deploy to remote Tomcat | <p>I've been looking for this all-over the internet and somehow I can't find a easy way to do it. </p>
<p>What I need is really simple and I believe that many of you probably do it already:
- I develop Java Web Apps in Eclipse and so does my team;
- we have a tomcat7 server running on a Ubuntu machine which works as a centralized Dev environment;
- I would like to click a deploy button and send the new data to the server and deploy it (reload it), instead of exporting a war every time and manually upload it to server.</p>
<p>Up till now seems like the only way to do it is with Maven plugin for eclipse, which uses the manager/HTML interface of tomcat.</p>
<p>Problem: I just can't get it to work. But somehow I can't find a simple walk through that explains how to do it. I'm not too experienced with eclipse or Linux but the configuration of local tomcat servers seems pretty straightforward. I don't understand why is so hard to install a remote one.</p>
<p>Could you please help me out by explaining in detail how to do it? Thank you in advance for you patience.</p> | 17,266,749 | 1 | 0 | null | 2013-06-22 20:08:47.677 UTC | 11 | 2015-06-18 13:20:14.59 UTC | 2015-06-18 13:20:14.59 UTC | null | 2,277,817 | null | 2,511,493 | null | 1 | 21 | eclipse|tomcat|deployment | 19,839 | <p>Yes, you can use Tomcat7 Maven Plugin. Here is the steps:</p>
<p>1) Install Maven Integration for Eclipse (m2eclipse) to your eclipse from Eclipse Marketplace etc.</p>
<p>1.1) Navigate to Help -> Eclipse Marketplace and search "Maven Integration for Eclipse".</p>
<p>2) From eclipse, create a maven project.</p>
<p>2.1) Navigate to File -> New -> Project... -> Maven -> Maven Project.</p>
<p>2.2) Click Next (Leave all fields with default).</p>
<p>2.3) Select "maven-archetype-webapp" and click Next.</p>
<p>2.4) Enter arbitrary value on Group Id and Artifact Id. (e.g. "org.myorg" for Groupd Id and "myapp" for Artifact Id) and click Finish. (You will see pom.xml in your project's root.)</p>
<p>3) Edit pom.xml like this: (Replace <code>yourhost</code> below with your hostname or ip address.)</p>
<pre><code><project ...>
...
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<url>http://yourhost:8080/manager/text</url>
</configuration>
</plugin>
</plugins>
</build>
</project>
</code></pre>
<p>4) Add following lines to your CATALINA_BASE/conf/tomcat-users.xml and restart your tomcat.</p>
<pre><code><tomcat-users>
...
<role rolename="manager-script"/>
<user username="admin" password="" roles="manager-script"/>
</tomcat-users>
</code></pre>
<p>5) From eclipse, run tomcat7:redeploy goal.</p>
<p>5.1) Right click your project and navigate to Run As -> "Maven build...".</p>
<p>5.2) Enter <code>tomcat7:redeploy</code> to Goals and click Run.</p>
<p>6) Once you create the run configuration setting above, you can run tomcat7:redeploy goal from Run -> Run Configurations.</p>
<p>Please refer to the following documents for details:</p>
<p><a href="http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html#Configuring_Manager_Application_Access">http://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html#Configuring_Manager_Application_Access</a></p>
<p><a href="http://tomcat.apache.org/maven-plugin-2.1/index.html">http://tomcat.apache.org/maven-plugin-2.1/index.html</a></p>
<p><a href="http://tomcat.apache.org/maven-plugin-2.0/tomcat7-maven-plugin/plugin-info.html">http://tomcat.apache.org/maven-plugin-2.0/tomcat7-maven-plugin/plugin-info.html</a></p>
<p>If you use another user instead of admin with empty password (which is plug-in's default), you need to create %USERPROFILE%.m2\settings.xml and edit pom.xml like below:</p>
<p>%USERPROFILE%.m2\settings.xml:</p>
<pre><code><settings>
<servers>
<server>
<id>tomcat7</id>
<username>tomcat</username>
<password>tomcat</password>
</server>
</servers>
</settings>
</code></pre>
<p>%USERPROFILE% is your home folder. (e.g. C:\Users\yourusername)</p>
<p>pom.xml:</p>
<pre><code><configuration>
<server>tomcat7</server>
<url>http://localhost:8080/manager/text</url>
</configuration>
</code></pre>
<p>Add <code>server</code> tag.</p> |
17,666,075 | python pandas groupby() result | <p>I have the following python pandas data frame:</p>
<pre><code>df = pd.DataFrame( {
'A': [1,1,1,1,2,2,2,3,3,4,4,4],
'B': [5,5,6,7,5,6,6,7,7,6,7,7],
'C': [1,1,1,1,1,1,1,1,1,1,1,1]
} );
df
A B C
0 1 5 1
1 1 5 1
2 1 6 1
3 1 7 1
4 2 5 1
5 2 6 1
6 2 6 1
7 3 7 1
8 3 7 1
9 4 6 1
10 4 7 1
11 4 7 1
</code></pre>
<p>I would like to have another column storing a value of a sum over C values for fixed (both) A and B. That is, something like:</p>
<pre><code> A B C D
0 1 5 1 2
1 1 5 1 2
2 1 6 1 1
3 1 7 1 1
4 2 5 1 1
5 2 6 1 2
6 2 6 1 2
7 3 7 1 2
8 3 7 1 2
9 4 6 1 1
10 4 7 1 2
11 4 7 1 2
</code></pre>
<p>I have tried with pandas <code>groupby</code> and it kind of works:</p>
<pre><code>res = {}
for a, group_by_A in df.groupby('A'):
group_by_B = group_by_A.groupby('B', as_index = False)
res[a] = group_by_B['C'].sum()
</code></pre>
<p>but I don't know how to 'get' the results from <code>res</code> into <code>df</code> in the orderly fashion. Would be very happy with any advice on this. Thank you. </p> | 17,666,287 | 4 | 1 | null | 2013-07-16 00:24:25.113 UTC | 5 | 2021-09-21 19:41:55.11 UTC | null | null | null | null | 2,107,632 | null | 1 | 25 | python|group-by|pandas | 48,611 | <p>Here's one way (though it feels this should work in one go with an apply, I can't get it).</p>
<pre><code>In [11]: g = df.groupby(['A', 'B'])
In [12]: df1 = df.set_index(['A', 'B'])
</code></pre>
<p>The <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#aggregation"><code>size</code></a> groupby function is the one you want, we have to match it to the 'A' and 'B' as the index:</p>
<pre><code>In [13]: df1['D'] = g.size() # unfortunately this doesn't play nice with as_index=False
# Same would work with g['C'].sum()
In [14]: df1.reset_index()
Out[14]:
A B C D
0 1 5 1 2
1 1 5 1 2
2 1 6 1 1
3 1 7 1 1
4 2 5 1 1
5 2 6 1 2
6 2 6 1 2
7 3 7 1 2
8 3 7 1 2
9 4 6 1 1
10 4 7 1 2
11 4 7 1 2
</code></pre> |
30,298,041 | Capture close event on Bootstrap Modal | <p>I have a Bootstrap Modal to select events.
If the user clicks on the X button or outside the modal, I would like to send them to the default event.
How can I capture these events?</p>
<p>This is my HTML code:</p>
<pre><code><div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content event-selector">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
<center><h1 class="modal-title event-selector-text">Select an Event</h1><center>
</div>
<div class="container"></div>
<div class="modal-body">
<div class="event-banner">
<a href="/?event=1">
<img src="<?php echo IMAGES_EVENT1_LOGO; ?>" width="100%">
</a>
</div>
<div class="event-banner">
<a href="/?event=2">
<img src="<?php echo IMAGES_EVENT2_LOGO; ?>" width="100%">
</a>
</div>
</div>
</div>
</div>
</div>
</code></pre>
<p></p> | 30,303,312 | 8 | 2 | null | 2015-05-18 08:09:11.427 UTC | 8 | 2022-06-16 15:29:42.837 UTC | 2019-11-06 11:00:46.37 UTC | null | 2,615,246 | user411103 | null | null | 1 | 94 | twitter-bootstrap|events|bootstrap-modal | 220,124 | <p>This is very similar to another stackoverflow article, <strong><a href="https://stackoverflow.com/questions/8363802/bind-a-function-to-twitter-bootstrap-modal-close">Bind a function to Twitter Bootstrap Modal Close</a></strong>. Assuming you are using some version of Bootstap v3 or v4, you can do something like the following:</p>
<pre><code>$("#myModal").on("hidden.bs.modal", function () {
// put your default event here
});
</code></pre> |
5,161,502 | Indirect function call in JavaScript | <p>There are things like</p>
<pre><code>f.call(...)
f.apply(...)
</code></pre>
<p>But then there's this</p>
<pre><code>(1, alert)('Zomg what is this????!!!11')
</code></pre>
<p>"1" does not seem to mean much in this context, the following works just fine:</p>
<pre><code>(null, alert)('Zomg what is this????!!!11')
(1, null, alert)('Zomg what is this????!!!11')
(undefined, alert)('Zomg what is this????!!!11')
</code></pre>
<p>Could you point to a specific part of ECMAScript which describes that syntax?</p> | 5,161,574 | 3 | 1 | null | 2011-03-01 23:05:18.247 UTC | 17 | 2011-09-05 15:14:45.967 UTC | 2011-09-05 15:14:45.967 UTC | null | 764,846 | null | 62,194 | null | 1 | 26 | javascript|ecma262 | 5,405 | <p>You are just using <a href="http://es5.github.com/#x11.14" rel="noreferrer">The Comma Operator</a>.</p>
<p>This operator only evaluates its operands from left to right, and returns the value from the second one, for example:</p>
<pre><code>(0, 1); // 1
('foo', 'bar'); // 'bar'
</code></pre>
<p>In the context of calling a function, the evaluation of the operand will simply get a value, not a reference, this causes that the <code>this</code> value inside the invoked function point to the global object (or it will be <code>undefined</code> in the new ECMAScript 5 Strict Mode).</p>
<p>For example:</p>
<pre><code>var foo = 'global.foo';
var obj = {
foo: 'obj.foo',
method: function () {
return this.foo;
}
};
obj.method(); // "obj.foo"
(1, obj.method)(); // "global.foo"
</code></pre>
<p>As you can see, the first call, which is a direct call, the <code>this</code> value inside the <code>method</code> will properly refer to <code>obj</code> (returning <code>"obj.foo"</code>), the second call, the evaluation made by the comma operator will make the <code>this</code> value to point to the global object (yielding <code>"global.foo"</code>).</p>
<p>That pattern has been getting quite popular these days, to make indirect <a href="http://es5.github.com/#x15.1.2.1.1" rel="noreferrer">calls to <code>eval</code></a>, this can be useful under ES5 strict mode, to get a reference to the global object, for example, (imagine you are in a non-browser environment, <code>window</code> is not available):</p>
<pre><code>(function () {
"use strict";
var global = (function () { return this || (1,eval)("this"); })();
})();
</code></pre>
<p>In the above code, the inner anonymous function will execute within a strict mode code unit, that will result on having the <code>this</code> value as <code>undefined</code>.</p>
<p>The <code>||</code> operator will now take the second operand, the <code>eval</code> call, which is an indirect call, and it will evaluate the code on the global lexical and variable environment.</p>
<p>But personally, in this case, under strict mode I prefer using the <code>Function</code> constructor to get the global object:</p>
<pre><code>(function () {
"use strict";
var global = Function('return this')();
})();
</code></pre>
<p>Functions that are created with the <code>Function</code> constructor are strict only if they start with a Use Strict Directive, they don't "inherit" the strictness of the current context as Function Declarations or Function Expressions do.</p> |
25,829,143 | Trim whitespace from a String | <p>I know there are several ways to do this in Java and C that are nice, but in C++ I can't seem to find a way to easily implement a string trimming function.</p>
<p>This is what I currently have:</p>
<pre><code>string trim(string& str)
{
size_t first = str.find_first_not_of(' ');
size_t last = str.find_last_not_of(' ');
return str.substr(first, (last-first+1));
}
</code></pre>
<p>but whenever I try and call </p>
<pre><code>trim(myString);
</code></pre>
<p>I get the compiler error </p>
<pre><code>/tmp/ccZZKSEq.o: In function `song::Read(std::basic_ifstream<char,
std::char_traits<char> >&, std::basic_ifstream<char, std::char_traits<char> >&, char const*, char const*)':
song.cpp:(.text+0x31c): undefined reference to `song::trim(std::string&)'
collect2: error: ld returned 1 exit status
</code></pre>
<p>I am trying to find a simple and standard way of trimming leading and trailing whitespace from a string without it taking up 100 lines of code, and I tried using regex, but could not get that to work as well.</p>
<p><strong>I also cannot use Boost.</strong></p> | 25,829,178 | 6 | 3 | null | 2014-09-14 00:54:46.217 UTC | 13 | 2021-03-28 17:04:36.477 UTC | 2017-10-23 20:40:49.447 UTC | null | 577,167 | null | 3,784,049 | null | 1 | 29 | c++|string|whitespace|trim | 131,573 | <p>Your code is fine. What you are seeing is a linker issue.</p>
<p>If you put your code in a single file like this:</p>
<pre><code>#include <iostream>
#include <string>
using namespace std;
string trim(const string& str)
{
size_t first = str.find_first_not_of(' ');
if (string::npos == first)
{
return str;
}
size_t last = str.find_last_not_of(' ');
return str.substr(first, (last - first + 1));
}
int main() {
string s = "abc ";
cout << trim(s);
}
</code></pre>
<p>then do <code>g++ test.cc</code> and run a.out, you will see it works.</p>
<p>You should check if the file that contains the <code>trim</code> function is included in the link stage of your compilation process. </p> |
18,564,942 | Clean way to programmatically use CSS transitions from JS? | <p>As the title implies, is there a proper way to set some initial CSS properties (or class) and tell the browser to transition these to another value?</p>
<p>For example (<a href="http://jsfiddle.net/Jhuy6/" rel="noreferrer">fiddle</a>):</p>
<pre class="lang-js prettyprint-override"><code>var el = document.querySelector('div'),
st = el.style;
st.opacity = 0;
st.transition = 'opacity 2s';
st.opacity = 1;
</code></pre>
<p>This will not animate the opacity of the element in Chrome 29/Firefox 23. This is because (<a href="http://blog.alexmaccaw.com/css-transitions" rel="noreferrer">source</a>):</p>
<blockquote>
<p>[...] you’ll find that if you apply both sets of properties, one immediately
after the other, then the browser tries to optimize the property
changes, ignoring your initial properties and preventing a transition.
Behind the scenes, browsers batch up property changes before painting
which, while usually speeding up rendering, can sometimes have adverse
affects.</p>
<p>The solution is to force a redraw between applying the two sets of
properties. A simple method of doing this is just by accessing a DOM
element’s <code>offsetHeight</code> property [...]</p>
</blockquote>
<p>In fact, the hack does work in the current Chrome/Firefox versions. Updated code (<a href="http://jsfiddle.net/Jhuy6/1/" rel="noreferrer">fiddle</a> - click <code>Run</code> after opening the fiddle to run animation again):</p>
<pre class="lang-js prettyprint-override"><code>var el = document.querySelector('div'),
st = el.style;
st.opacity = 0;
el.offsetHeight; //force a redraw
st.transition = 'opacity 2s';
st.opacity = 1;
</code></pre>
<p>However, this is rather hackish and is reported to not work on some android devices.</p>
<p>Another <a href="https://stackoverflow.com/a/8213003/1331430">answer</a> suggests using <code>setTimeout</code> so the browser has time to perform a redraw, but it also fails in that we don't know how long it will take for a redraw to take place. Guessing a decent number of milliseconds (30-100?) to ensure that a redraw occurred means sacrificing performance, unnecessarily idling in the hopes that the browser performs some magic in that little while.</p>
<p>Through testing, I've found yet another solution which has been working great on latest Chrome, using <a href="https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame" rel="noreferrer"><code>requestAnimationFrame</code></a> (<a href="http://jsfiddle.net/Jhuy6/2/" rel="noreferrer">fiddle</a>):</p>
<pre class="lang-js prettyprint-override"><code>var el = document.querySelector('div'),
st = el.style;
st.opacity = 0;
requestAnimationFrame(function() {
st.transition = 'opacity 2s';
st.opacity = 1;
});
</code></pre>
<p>I assume that <code>requestAnimationFrame</code> waits until right before the beginning of the next repaint before executing the callback, hence the browser does not batch up the property changes. Not entirely sure here, but works nicely on Chrome 29.</p>
<p><strong>Update:</strong> after further testing, the <code>requestAnimationFrame</code> method does not work very well on Firefox 23 - it seems to fail most of the time. (<a href="http://jsfiddle.net/Jhuy6/13/" rel="noreferrer">fiddle</a>)</p>
<p>Is there a proper or recommended (cross-browser) way of achieving this?</p> | 31,862,081 | 5 | 12 | null | 2013-09-02 02:32:51.173 UTC | 8 | 2017-10-28 14:46:39.527 UTC | 2017-05-23 12:10:38.81 UTC | null | -1 | null | 1,331,430 | null | 1 | 29 | javascript|css|css-transitions|transition | 7,780 | <p>There isn't a clean way at this moment (without using CSS Animations -- see <a href="https://stackoverflow.com/a/21283499/1026">the nearby answer by James Dinsdale</a> for an example using CSS Animations). There is a <a href="https://www.w3.org/Bugs/Public/show_bug.cgi?id=14617" rel="noreferrer">spec bug 14617</a>, which unfortunately wasn't acted upon since it was filed in 2011.</p>
<p><code>setTimeout</code> does not work reliably in Firefox (<a href="https://bugzilla.mozilla.org/show_bug.cgi?id=701626" rel="noreferrer">this is by design</a>).</p>
<p>I'm not sure about <code>requestAnimationFrame</code> -- an edit to the original question says it doesn't work reliably either, but I did not investigate. (Update: it looks like <code>requestAnimationFrame</code> <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1187571#c3" rel="noreferrer">is considered at least by one Firefox core developer to be the place where you can make more changes, not necessarily see the effect of the previous changes</a>.)</p>
<p>Forcing reflow (e.g. by accessing <code>offsetHeight</code>) is a possible solution, but for transitions to work it should be <strong>enough to force restyle (i.e. <code>getComputedStyle</code>)</strong>: <a href="https://timtaubert.de/blog/2012/09/css-transitions-for-dynamically-created-dom-elements/" rel="noreferrer">https://timtaubert.de/blog/2012/09/css-transitions-for-dynamically-created-dom-elements/</a></p>
<pre><code>window.getComputedStyle(elem).opacity;
</code></pre>
<p>Note that just running <code>getComputedStyle(elem)</code> is not enough, since it's computed lazily. I believe it doesn't matter which property you ask from the getComputedStyle, the restyle will still happen. Note that asking for geometry-related properties might cause a more expensive reflow.</p>
<p>More information on reflow/restyle/repaint: <a href="http://www.phpied.com/rendering-repaint-reflowrelayout-restyle/" rel="noreferrer">http://www.phpied.com/rendering-repaint-reflowrelayout-restyle/</a></p> |
18,484,509 | How I can index the array starting from 1 instead of zero? | <pre><code>for (int i = 0; i < reports.length; i++) {
Products[] products = reports[i].getDecisions;
for (int j = 0; j < products.length; j++) {
}
}
</code></pre>
<p>Here I want to index the inner for loop starting from 1 , but it is not working as expected, I also changed the j | 18,484,558 | 6 | 6 | null | 2013-08-28 09:46:16.823 UTC | 3 | 2021-11-24 13:21:00.037 UTC | 2013-08-28 09:50:10.7 UTC | null | 2,500,405 | null | 2,500,405 | null | 1 | 0 | java | 54,687 | <p>Java arrays are always 0-based. You can't change that behavior. You can fill or use it from another index, but you can't change the base index.</p>
<p>It's defined in <a href="https://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html#jls-10.4" rel="noreferrer">JLS §10.4</a>, if you are interested in it.</p>
<blockquote>
<p>A component of an array is accessed by an array access expression (§15.13) that consists of an expression whose value is an array reference followed by an indexing expression enclosed by [ and ], as in A[i].</p>
<p>All arrays are 0-origin. An array with length n can be indexed by the integers 0 to n-1.</p>
</blockquote> |
18,395,725 | Test if numpy array contains only zeros | <p>We initialize a numpy array with zeros as bellow:</p>
<pre><code>np.zeros((N,N+1))
</code></pre>
<p>But how do we check whether all elements in a given n*n numpy array matrix is zero.<br>
The method just need to return a True if all the values are indeed zero.</p> | 18,395,906 | 7 | 0 | null | 2013-08-23 05:55:33.213 UTC | 15 | 2021-06-02 05:27:43.063 UTC | null | null | null | null | 1,483,620 | null | 1 | 138 | python|numpy | 168,844 | <p>Check out <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.count_nonzero.html#numpy.count_nonzero" rel="noreferrer">numpy.count_nonzero</a>.</p>
<pre><code>>>> np.count_nonzero(np.eye(4))
4
>>> np.count_nonzero([[0,1,7,0,0],[3,0,0,2,19]])
5
</code></pre> |
20,003,870 | How do I create a regular expression of minimum 8, maximum 16, alphabetic, numbers and NO space? | <p>I am trying to check text with a regular expression in iOS, and below is my code. My regular expression is accepting one word or number which it should be minimum 8 and maximum 16 with numbers or alphabetic.</p>
<pre><code>if (![self validate:txtPass.text regex:@"^[a-zA-Z0-9]+$"]){
NSLOG(@"Check value");
}
</code></pre>
<p>What should I change in my regular expression?</p> | 20,003,896 | 4 | 3 | null | 2013-11-15 14:54:00.323 UTC | 3 | 2020-02-19 06:43:58.75 UTC | 2019-07-31 15:02:52.63 UTC | null | 63,550 | null | 1,104,515 | null | 1 | 14 | regex | 53,302 | <p><code>^[a-zA-Z0-9]{8,16}$</code></p>
<p>You can specify the minimum/maximum gathered using {X,Y} as the boundaries.</p>
<p>Other examples:<br>
<code>^[a-zA-Z0-9]{8,}$</code> #8 or more characters<br>
<code>^[a-zA-Z0-9]{,16}$</code> #Less than or equal to 16 characters<br>
<code>^[a-zA-Z0-9]{8}$</code> #Exactly 8 characters </p>
<p><a href="http://krijnhoetmer.nl/stuff/regex/cheat-sheet/" rel="noreferrer">Regex cheatsheet</a></p> |
15,450,897 | How to extend enum class from abstract class? | <p>Having something like this:</p>
<pre><code>public enum Token
{
FOO("foo", "f"),
QUIT("quit", "q"),
UNKNOWN("", "");
...
public parse(String s) {
for (Token token : values()) {
...
return token;
}
return UNKNOWN;
}
}
</code></pre>
<p>An abstract class:</p>
<pre><code>abstract class Base
{
private boolean run;
Base() {
run = true;
while (run) {
inp = getInput();
act(inp);
}
}
public boolean act(String s) {
boolean OK = true;
switch (Token.parse(inp)) { /* Enum */
case FOO:
do_foo();
break;
case QUIT:
run = false;
break;
case UNKNOWN:
print "Unknown" + inp;
OK = false;
break;
}
}
return OK;
}
}
</code></pre>
<p>And the extender:</p>
<pre><code>class Major extends Base
{
}
</code></pre>
<p>What I want is to extend <code>act</code> as in if <code>super</code> does not handle it then try to handle it in <code>Major</code>. E.g. add <code>PRINT_STAT("print-statistics", "ps")</code> - but at the same time let the <code>Base</code> class handle defaults like <code>QUIT</code>.</p>
<p>Is this a completely wrong approach?</p>
<p>What I have done so far is add an interface Typically:</p>
<pre><code>public interface BaseFace
{
public boolean act_other(String inp);
}
</code></pre>
<p>And in class <code>Base implements BaseFace</code>:</p>
<pre><code> case UNKNOWN:
OK = act_other(inp);
</code></pre>
<p>And in class <code>Major</code>:</p>
<pre><code> public boolean act_other(String inp) {
if (inp.equals("blah")) {
do_blah();
return true;
}
return false;
}
</code></pre>
<p>Does this look like a usable design? </p>
<p><strong>And, major question:</strong></p>
<p>Is there some good way to extend the <code>Token</code> class such that I can use the same switch approach in <code>Major</code> as in <code>Base</code>? What I wonder is if there for one is a better design and second if I have to make a new Token class for <code>Major</code> or if I somehow can extend or otherwise re-use the existing.</p>
<hr>
<p>Edit: Point of concept is to have the <code>Base</code> class that I can easily re-use in different projects handling various types of input.</p> | 15,450,935 | 4 | 0 | null | 2013-03-16 15:12:34.28 UTC | 9 | 2017-05-03 22:19:12.6 UTC | null | null | null | null | 2,148,245 | null | 1 | 42 | java | 55,247 | <p>All enums implicity extend Enum. In Java, a class can extend at most one other class. </p>
<p>You can, however, have your enum class <strong>implement an interface</strong>. </p>
<p>From <a href="http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html" rel="noreferrer">this Java tutorial on Enum Types</a>:</p>
<blockquote>
<p>Note: All enums implicitly extend java.lang.Enum. Because a class can only extend one parent (see Declaring Classes), the Java language does not support multiple inheritance of state (see Multiple Inheritance of State, Implementation, and Type), and therefore an enum cannot extend anything else.</p>
</blockquote>
<p><strong>Edit for Java 8:</strong></p>
<p>As of Java 8, an interface can include <a href="https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html" rel="noreferrer">default methods</a>. This allows you to include method implementations (but not state) in interfaces. Although the primary purpose of this capability is to allow evolution of public interfaces, you could use this to inherit a custom method defining a common behavior among multiple enum classes. </p>
<p>However, this could be brittle. If a method with the same signature were later added to the <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Enum.html" rel="noreferrer">java.lang.Enum</a> class, it would override your default methods . (When a method is defined both in a class's superclass and interfaces, the class implementation always wins.) </p>
<p>For example:</p>
<pre><code>interface IFoo {
public default String name() {
return "foo";
}
}
enum MyEnum implements IFoo {
A, B, C
}
System.out.println( MyEnum.A.name() ); // Prints "A", not "foo" - superclass Enum wins
</code></pre> |
15,027,255 | Eclipse + Java 8 support? | <p>How can I get Java 8 to work with Eclipse? </p>
<p>I have followed <a href="http://tuhrig.de/?p=921">this guide</a> but doesn't work. I've also seen <a href="http://wiki.eclipse.org/JDT_Core/Java8">the Eclipse Java 8 wiki page</a>, but they don't explain what to do with the checked out git repositories. </p> | 22,899,605 | 7 | 2 | null | 2013-02-22 15:15:02.627 UTC | 8 | 2016-02-18 10:08:40.503 UTC | 2014-04-30 15:33:24.813 UTC | null | 474,189 | null | 961,018 | null | 1 | 43 | java|eclipse|eclipse-jdt|java-8 | 47,907 | <p>For Kepler SR2 (4.3.2) a feature patch needs to be installed in order to get JAVA 8 support. Follow these steps: </p>
<ul>
<li><p>Eclipse - Help (MENU) > Install New Software...</p></li>
<li><p>enter the following URL into the 'Work with' field: <br />
<a href="http://download.eclipse.org/eclipse/updates/4.3-P-builds/">http://download.eclipse.org/eclipse/updates/4.3-P-builds/</a></p></li>
<li><p>press 'Enter' <br /></p></li>
<li>select category 'Eclipse Java 8 Support (for Kepler SR2)' <br /></li>
<li>click 'Next' <br /></li>
<li>click 'Next' <br /></li>
<li>accept the license</li>
<li>click 'Finish' <br /> <br /></li>
<li>restart Eclipse when asked</li>
</ul>
<p>source: <a href="https://wiki.eclipse.org/JDT/Eclipse_Java_8_Support_For_Kepler">link</a></p>
<p>@Elisabeth</p>
<p>In order to have the desired JRE/ JDK on BuildPath, follow these steps.</p>
<ul>
<li>Right click on Project from Package Explorer</li>
<li>Select <strong>BuildPath</strong> and then select <strong>Configure Builpath</strong></li>
<li>Select <strong>Libraries</strong> Tab from the popped up Properties window</li>
<li>Select the current <strong>JRE System Library</strong></li>
<li>Click <strong>Remove</strong> button</li>
<li>Click on <strong>Add Library</strong> button</li>
<li>Select <strong>JRE System Library</strong></li>
<li>There you will be able to add your desired JRE/ JDK version using 3 different methods.</li>
</ul>
<p>If you don't find your desired version of JRE/ JDK there in those 3 options, then you will have to install that first. The following link helps you in detail with screen shots to do the same. Hope it helps. </p>
<p>source: <a href="http://im-a-developer-too.blogspot.ca/2014/04/configuring-java-environment-jre-jdk-in.html">link</a> </p> |
38,136,013 | Simulate slow network on Android simulator | <p>I'm building an app that uses AsyncTask to display a progress bar when it's performing network operation (Google translate).
However, the problem is that I can't tell if it's working since the network is too fast and it finishes running the operation as soon as I start it.
So is there a way to simulate a slow network so that I can tell if the progress bar will actually run (visible) when it's waiting for the operation to be completed? I have come across network options when creating an Android emulator. However, there are so many abbreviations that I still have trouble understanding what indicates slow network connection and I'm still not sure if that is how I should set a slow network connection.</p>
<p>Thanks in advance!</p> | 38,136,750 | 4 | 3 | null | 2016-07-01 02:17:32.093 UTC | 2 | 2020-08-15 02:08:22.25 UTC | null | null | null | null | 4,766,340 | null | 1 | 29 | android|android-asynctask|android-emulator | 18,997 | <p>The emulator lets you simulate various network conditions. You can approximate the network speed for different network protocols, or you can specify Full, which transfers data as quickly as your computer allows. </p>
<p>Specifying a network protocol is always slower than Full. You can also specify the voice and data network status, such as roaming. The defaults are set in the AVD.</p>
<p>Select a Network type:</p>
<ul>
<li>GSM - Global System for Mobile Communications </li>
<li>HSCSD - High-Speed Circuit-Switched Data</li>
<li>GPRS - Generic Packet Radio Service</li>
<li>EDGE - Enhanced Data rates for GSM Evolution</li>
<li>UMTS - Universal Mobile Telecommunications System</li>
<li>HSPDA - High-Speed Downlink Packet Access</li>
<li>Full (default)</li>
</ul>
<p><strong>Speeds for reference in increasing kbps:</strong></p>
<pre><code> UP DOWN
-------- ----------
gsm GSM/CSD 14.4 14.4
hscsd HSCSD 14.4 57.6
gprs GPRS 28.8 57.6
umts UMTS/3G 384.0 384.0
edge EDGE/EGPRS 473.6 473.6
hsdpa HSDPA 5760.0 13,980.0
lte LTE 58,000.0 173,000.0
evdo EVDO 75,000.0 280,000.0
full No limit ∞ ∞
</code></pre>
<p>Select a Voice status, Data status, or both:</p>
<ul>
<li>Home (default)</li>
<li>Roaming</li>
<li>Searching</li>
<li>Denied (emergency calls only)</li>
<li>Unregistered (off)</li>
</ul>
<p>For more information see <a href="https://developer.android.com/studio/run/emulator.html#extended" rel="noreferrer">https://developer.android.com/studio/run/emulator.html#extended</a></p> |
28,299,830 | Executing a batch file in a remote machine through PsExec | <p>I am trying to run a batch file (in the batch file I have just written 'notepad') on a remote PC through PSExec. The psexec command below runs in my laptop but fails to do anything on the remote PC. I don't even see 'notepad' running on the list of processes in the remote machine. </p>
<hr>
<pre><code>c:\Program Files (x86)\PSTools>psexec -u administrator -p force \\135.20.230.160 -s -d cmd.exe /c -c "C:\Amtra\bogus.bat"
PsExec v2.11 - Execute processes remotely
Copyright (C) 2001-2014 Mark Russinovich
Sysinternals - www.sysinternals.com
cmd.exe started on 135.24.237.167 with process ID 1520.
</code></pre>
<hr>
<p>Anyone can help me where I am going wrong here?</p>
<p>Thanks,</p> | 28,300,048 | 2 | 2 | null | 2015-02-03 13:12:57.533 UTC | 4 | 2017-07-31 14:45:31.127 UTC | 2017-07-31 14:45:31.127 UTC | null | 1,702,943 | null | 3,565,150 | null | 1 | 6 | windows|powershell-3.0|psexec|sysinternals | 120,295 | <p>You have an extra <code>-c</code> you need to get rid of:</p>
<pre><code>psexec -u administrator -p force \\135.20.230.160 -s -d cmd.exe /c "C:\Amitra\bogus.bat"
</code></pre> |
27,956,638 | How to append a text to file succinctly | <p>Instead of writing</p>
<pre><code>File.open("foo.txt", "w"){|f| f.write("foo")}
</code></pre>
<p>We can write it </p>
<pre><code>File.write("foo.txt", "foo")
</code></pre>
<p>Is there simpler way to write this one?</p>
<pre><code>File.open("foo.txt", "a"){|f| f.write("foo")}
</code></pre> | 71,481,898 | 5 | 3 | null | 2015-01-15 04:04:09.6 UTC | 5 | 2022-05-12 14:24:46.927 UTC | 2015-01-16 03:45:14.853 UTC | null | 1,536,527 | null | 1,536,527 | null | 1 | 28 | ruby | 19,733 | <p>Yes. It's poorly documented, but you can use:</p>
<pre class="lang-rb prettyprint-override"><code>File.write('foo.txt', 'some text', mode: 'a+')
</code></pre> |
9,140,873 | How to use Activator to create an instance of a generic Type and casting it back to that type? | <p>I have a generic type <code>Store<T></code> and use <code>Activator</code> to make an instance of this type. Now how, after using the Activator, can I cast the resulted object of type <code>object</code> back to the instantiated type? I know the type that I used to instantiate the generic. Please see the following code:</p>
<pre><code>class Store<T> where T : IStorable
{}
class Beer : IStorable
{}
class BeerStore : Store<Beer>
{}
Type storeType = someObjectThatImplementsIStorable.GetType();
Type classType = typeof(Store<>);
Type[] typeParams = new Type[] { storeType };
Type constructedType = classType.MakeGenericType(typeParams);
object x = Activator.CreateInstance(constructedType, new object[] { someParameter });
</code></pre>
<p>What I would like to do is something like this:</p>
<pre><code>var store = (Store<typeof(objectThatImplementsIStorable)>)x;
</code></pre>
<p>but that doesn't work for obvious reasons. As an alternative I tried:</p>
<pre><code>var store = (Store<IStorable>)x;
</code></pre>
<p>which could possibly work in my opinion, but gives an <code>InvalidCastException</code>.</p>
<p>How do I get access again to the <code>Store<T></code> methods that I know are in the object <code>x</code>?</p> | 9,140,979 | 5 | 7 | null | 2012-02-04 12:30:05.523 UTC | 11 | 2021-08-19 03:24:11.757 UTC | 2012-02-04 12:35:28.563 UTC | null | 196,679 | null | 196,679 | null | 1 | 49 | c#|generics|reflection|activator | 45,295 | <p>Since the actual type <code>T</code> is available to you only through reflection, you would need to access methods of <code>Store<T></code> through reflection as well:</p>
<pre><code>Type constructedType = classType.MakeGenericType(typeParams);
object x = Activator.CreateInstance(constructedType, new object[] { someParameter });
var method = constructedType.GetMethod("MyMethodTakingT");
var res = method.Invoke(x, new object[] {someObjectThatImplementsStorable});
</code></pre>
<p><strong>EDIT</strong> You could also define an additional <code>IStore</code> interface that does not use generics, and uses <code>IStorable</code> instead:</p>
<pre><code>interface IStore {
int CountItems(IStorable item);
}
class Store<T> : IStore where T : IStorable {
int CountItems(IStorable item) {
return count;
}
}
</code></pre>
<p>Your <code>Store<T></code> would remain generic, but you would get access to its <code>CountItems</code> by casting to <code>IStore</code>:</p>
<pre><code>var x = (IStore)Activator.CreateInstance(constructedType, new object[] { someParameter });
var count = x.CountItems((IStorable)someObjectThatImplementsStorable);
</code></pre> |
23,523,597 | Split string into repeated characters | <p>I want to split the string "aaaabbbccccaaddddcfggghhhh" into "aaaa", "bbb", "cccc". "aa", "dddd", "c", "f" and so on.</p>
<p>I tried this:</p>
<pre><code>String[] arr = "aaaabbbccccaaddddcfggghhhh".split("(.)(?!\\1)");
</code></pre>
<p>But this eats away one character, so with the above regular expression I get "aaa" while I want it to be "aaaa" as the first string.</p>
<p>How do I achieve this?</p> | 23,523,874 | 3 | 6 | null | 2014-05-07 16:44:11.78 UTC | 9 | 2019-03-30 01:33:20.81 UTC | 2019-03-30 01:33:20.81 UTC | null | 201,359 | null | 628,242 | null | 1 | 23 | java|regex|string|split | 8,601 | <p>Try this:</p>
<pre><code>String str = "aaaabbbccccaaddddcfggghhhh";
String[] out = str.split("(?<=(.))(?!\\1)");
System.out.println(Arrays.toString(out));
=> [aaaa, bbb, cccc, aa, dddd, c, f, ggg, hhhh]
</code></pre>
<p>Explanation: we want to split the string at groups of same chars, so we need to find out the "boundary" between each group. I'm using Java's syntax for positive look-behind to pick the previous char and then a negative look-ahead with a back reference to verify that the next char is not the same as the previous one. No characters were actually consumed, because only two look-around assertions were used (that is, the regular expresion is zero-width).</p> |
19,715,144 | How to convert char* to LPCWSTR? | <p>I know this has already been discussed in several questions on SO, but none of those solutions have worked for me.</p>
<p>I start with a <code>char*</code> because this is for a DLL that will be called from VBA, and <code>char*</code> is necessary for VBA to pass a string to the DLL.</p>
<p>I need to return a <code>LPCWSTR</code> because that's the input parameter for the API function I'm trying to call, and I can't enable casting by switching from Unicode to multi-byte character set in the Properties window, because the API has this code:</p>
<pre><code>#if !defined(UNICODE) && !defined(NOUNICODE)
#error UNICODE is not defined. UNICODE must be defined for correct API arguments.
#endif
</code></pre>
<p>I tried this:</p>
<pre><code>LPCWSTR convertCharArrayToLPCWSTR(char* charArray)
{
const char* cs=charArray;
wchar_t filename[4096] = {0};
MultiByteToWideChar(0, 0, cs[1], strlen(cs[1]), filename, strlen(cs[1]));
}
</code></pre>
<p>which gave these errors:</p>
<pre><code>error C2664: 'strlen' : cannot convert parameter 1 from 'const char' to 'const char *'
error C2664: 'MultiByteToWideChar' : cannot convert parameter 3 from 'const char' to 'LPCCH'
</code></pre>
<p>I tried this (same function header), loosely adapted from <a href="https://stackoverflow.com/a/6858692/619177">this post</a>:</p>
<pre><code>size_t retVal;
const char * cs = charArray;
size_t length=strlen(cs);
wchar_t * buf = new wchar_t[length](); // value-initialize to 0 (see below)
size_t wn = mbsrtowcs_s(&retVal,buf,20, &cs, length + 1, NULL);
return buf;
</code></pre>
<p>This compiled ok, but when I passed it an example string of "xyz.xlsx", <code>mbsrtowcs_s()</code> set <code>buf</code> to an empty string: <code>L""</code></p>
<p>So, how do I make this conversion?</p> | 19,715,260 | 2 | 9 | null | 2013-10-31 19:35:01.967 UTC | 3 | 2013-10-31 22:50:39.853 UTC | 2017-05-23 12:17:29.747 UTC | null | -1 | null | 619,177 | null | 1 | 12 | c++|visual-c++|visual-studio-2012 | 86,379 | <p>Since <code>cs</code> is a <code>const char*</code>, <code>cs[1]</code> is a <code>const char</code>. C++ won't convert it to a pointer for you, because in most cases that doesn't make sense.</p>
<p>You could instead say <code>&cs[1]</code> or <code>cs+1</code> if the intent is to skip the first char. (That's what you're doing when you pass a pointer to the 1th element; in C++, indexes start at 0.) If the intent is to pass the whole string, then just pass <code>cs</code>.</p> |
67,146,654 | How to compile Python + Electron JS into desktop app (exe) | <p>I created a desktop application using <strong>python as the backend</strong> and <strong>Electron JS integrated with Node JS as the front end</strong>.</p>
<p>The image below is the file tree for my project.</p>
<p><a href="https://i.stack.imgur.com/D0n0N.png" rel="noreferrer"><img src="https://i.stack.imgur.com/D0n0N.png" alt="enter image description here" /></a></p>
<p>I was able to link up both the python with Electron JS using the <code>renderer.js</code> file and my app functions as expected.</p>
<p>But my question is, how should I compile this <strong>Python + Electron JS</strong> app into an <code>exe</code>. I am aware that <strong><code>pyinstaller</code></strong> can be used to compile python files to <code>exe</code>. Please let me know how to compile this <code>python + electron JS</code> app.</p>
<p>Thanks in advance.</p> | 67,220,101 | 2 | 3 | null | 2021-04-18 08:41:56.763 UTC | 9 | 2022-01-13 19:38:30.793 UTC | 2021-04-22 14:46:23.877 UTC | null | 12,874,556 | null | 12,874,556 | null | 1 | 16 | python|compilation|electron|exe | 5,518 | <p>So after a bit of research, I was able to find out the solution myself.</p>
<h1><strong>Step 1: Compile the python file to an <code>exe</code></strong></h1>
<p>First, you need to convert the <code>python</code> file to a single <code>exe</code> using <code>pyinstaller</code>. The command is</p>
<pre><code>pyinstaller --onefile engine.py
</code></pre>
<p>You will find <code>engine.exe</code> inside the <code>dist</code> folder. Copy the <code>exe</code> to the main directory where you have the <code>renderer.js</code>. Delete all the other python related folders.</p>
<h1>Step 2: Making modifications to the <code>renderer.js</code> file</h1>
<p>Initially, I had a <code>renderer.js</code> file with the following code. <em><strong>Note:</strong></em> The following code was there to run my python script using <code>sys.argv</code> for the input and get the output using <code>stdout</code>.</p>
<pre class="lang-js prettyprint-override"><code>function sendToPython() {
var python = require("child_process").spawn("python", [
"./py/engine.py",
input.value,
]);
python.stdout.on("data", function (data) {
// Do some process here
});
python.stderr.on("data", (data) => {
console.error(`stderr: ${data}`);
console.log(`stderr: ${data}`);
});
python.on("close", (code) => {
console.log(`child process exited with code ${code}`);
});
}
</code></pre>
<p>But now that we have generated the <code>exe</code> file, we need to make some modifications to get this working. We need to simply change the line.</p>
<pre><code>var python = require("child_process").spawn("python", ["./py/engine.py", input.value]);
</code></pre>
<p>Following is the amended version of the line.</p>
<pre><code>var python = require("child_process").execFile("engine.exe", [input.value]);
</code></pre>
<p>In short, what this does is that, it executes our <code>engine.exe</code> with command line arguments without spawning a python shell.</p>
<h1>Step 3: Using <code>electron-packager</code> to package our app</h1>
<p>Open a terminal in your project folder and run the following commands (one after the other) to install <code>electron-packager</code> globally using <code>npm</code>.</p>
<pre><code>npm install --save-dev electron
npm install electron-packager -g
</code></pre>
<p>Once that is installed, we can use the following command to package our app.</p>
<pre><code>electron-packager . pythonElectronApp --arch=x64 --asar
</code></pre>
<p><em><strong>Note:</strong></em> <code>pythonElectronApp</code> is the name of the project (you can name it according to your wish), <code>--arch=x64</code> means 64-bit architecture.</p>
<p><code>--asar</code> packages your project in a way that it stops a most people from viewing your source code. Anyways, almost all can see the source by inspecting the <code>asar</code> file that Electron dumps out. You can try methods like code obfuscation to slow down a attacker from reverse engineering.</p>
<p><em><strong>Useful resource regarding code obfuscation</strong></em> - <a href="https://stackoverflow.com/questions/58103656/how-to-perform-obfuscation-of-source-code-and-protect-source-in-electron-js">How to perform obfuscation of source code and protect source in electron js</a></p>
<p><em><strong>Similar issue reported in github</strong></em> - <a href="https://github.com/electron/electron-packager/issues/152" rel="nofollow noreferrer">https://github.com/electron/electron-packager/issues/152</a></p>
<h1>Step 4: Placing our <code>engine.exe</code> at the correct directory</h1>
<p>Copy the <code>engine.exe</code> that we created earlier and paste it inside the folder where your electron app was created. In my case it is, <code>pythonElectronApp-win32-x64</code></p>
<p>Now you can open up your fully functional <code>python+electron</code> app. In my case the name is <code>pythonElectronApp.exe</code></p>
<h1>Step 5: Create a main installer file <code>.msi</code></h1>
<p>As you saw earlier in the previous image, there are a lot dependencies and folders. To create one standalone installer like a <code>.msi</code> for windows, you can use a software like <a href="https://jrsoftware.org/isinfo.php" rel="nofollow noreferrer">Inno Setup</a> to do it for you.</p> |
8,594,707 | Jersey Exception : SEVERE: A message body reader for Java class | <p>I have a Jersey based Rest WS which outputs JSON. I am implementing a Jersey Client to invoke the WS and consume the JSON response. The client code I have is below</p>
<pre>
WebResource r = restClient.resource(UriBuilder.fromUri("http://localhost/").port(8080).build());
String resp = r.path("/user").accept(MediaType.APPLICATION_JSON).get(String.class);
User[] users = r.path("/user").accept(MediaType.APPLICATION_JSON).get(User[].class);
</pre>
<p>The 2nd line outputs the JSON string response correctly, however the 3rd line to marshal JSON to the POJO is not happening and I get the following exception stacktrace</p>
<pre>
SEVERE: A message body reader for Java class [Lorg.shoppingsite.model.entity.jpa.User;, and Java type class [Lorg.shoppingsite.model.entity.jpa.User;, and MIME media type application/json was not found
Dec 21, 2011 11:32:01 AM com.sun.jersey.api.client.ClientResponse getEntity
SEVERE: The registered message body readers compatible with the MIME media type are:
*/* ->
com.sun.jersey.core.impl.provider.entity.FormProvider
com.sun.jersey.core.impl.provider.entity.StringProvider
com.sun.jersey.core.impl.provider.entity.ByteArrayProvider
com.sun.jersey.core.impl.provider.entity.FileProvider
com.sun.jersey.core.impl.provider.entity.InputStreamProvider
com.sun.jersey.core.impl.provider.entity.DataSourceProvider
com.sun.jersey.core.impl.provider.entity.XMLJAXBElementProvider$General
com.sun.jersey.core.impl.provider.entity.ReaderProvider
com.sun.jersey.core.impl.provider.entity.DocumentProvider
com.sun.jersey.core.impl.provider.entity.SourceProvider$StreamSourceReader
com.sun.jersey.core.impl.provider.entity.SourceProvider$SAXSourceReader
com.sun.jersey.core.impl.provider.entity.SourceProvider$DOMSourceReader
com.sun.jersey.core.impl.provider.entity.XMLRootElementProvider$General
com.sun.jersey.core.impl.provider.entity.XMLListElementProvider$General
com.sun.jersey.core.impl.provider.entity.XMLRootObjectProvider$General
com.sun.jersey.core.impl.provider.entity.EntityHolderReader
</pre>
<p>I have the correct MIME TYPES in my request. My POJO has been annotated with XMLRootElement. What am I missing. </p>
<p>Thank you</p> | 8,594,810 | 15 | 3 | null | 2011-12-21 18:40:31.743 UTC | 2 | 2020-06-05 10:14:24 UTC | 2011-12-21 18:48:31.02 UTC | null | 162,758 | null | 162,758 | null | 1 | 40 | java|json|rest|jersey | 106,547 | <p>I was able to fix the issue by adding the maven dependency for jersey-json.</p> |
8,825,956 | Assert.AreEqual() with System.Double getting really confusing | <h3>Description</h3>
<p>This is not a real world example! Please don't suggest using <code>decimal</code> or something else. </p>
<p>I am only asking this because I really want to know why this happens.</p>
<p>I recently saw the awesome Tekpub Webcast <strong>Mastering C# 4.0 with Jon Skeet</strong> again. </p>
<p>On episode <strong>7 - Decimals and Floating Points</strong> it is going really weird and even our
<strong>Chuck Norris of Programming (aka Jon Skeet)</strong> does not have a real answer to my question.
Only a <em>might be</em>.</p>
<h3>Question: Why did <code>MyTestMethod()</code> fail and <code>MyTestMethod2()</code> pass?</h3>
<h3>Example 1</h3>
<pre><code>[Test]
public void MyTestMethod()
{
double d = 0.1d;
d += 0.1d;
d += 0.1d;
d += 0.1d;
d += 0.1d;
d += 0.1d;
d += 0.1d;
d += 0.1d;
d += 0.1d;
d += 0.1d;
Console.WriteLine("d = " + d);
Assert.AreEqual(d, 1.0d);
}
</code></pre>
This results in
<blockquote>
<p>d = 1</p>
<p>Expected: 0.99999999999999989d
But was: 1.0d</p>
</blockquote>
<h3>Example 2</h3>
<pre><code>[Test]
public void MyTestMethod2()
{
double d = 0.1d;
d += 0.1d;
d += 0.1d;
d += 0.1d;
d += 0.1d;
Console.WriteLine("d = " + d);
Assert.AreEqual(d, 0.5d);
}
</code></pre>
This results in success
<blockquote>
<p>d = 0,5</p>
</blockquote>
<p>But why ?</p>
<h3>Update</h3>
<p>Why doesn't <code>Assert.AreEqual()</code> cover that? </p> | 8,858,164 | 7 | 4 | null | 2012-01-11 20:13:22.64 UTC | 5 | 2017-01-04 21:00:19.763 UTC | 2017-01-04 21:00:19.763 UTC | null | 1,087,335 | null | 479,659 | null | 1 | 28 | c#|.net|c#-4.0|floating-point|clr | 25,645 | <p>Okay, I haven't checked what <code>Assert.AreEqual</code> does... but I suspect that by default it's <em>not</em> applying any tolerance. I wouldn't <em>expect</em> it to behind my back. So let's look for another explanation...</p>
<p>You're basically seeing a coincidence - the answer after four additions <em>happens</em> to be the exact value, probably because the lowest bit gets lost somewhere when the magnitude changes - I haven't looked at the bit patterns involved, but if you use <code>DoubleConverter.ToExactString</code> (my own code) you can see <em>exactly</em> what the value is at any point:</p>
<pre><code>using System;
public class Test
{
public static void Main()
{
double d = 0.1d;
Console.WriteLine("d = " + DoubleConverter.ToExactString(d));
d += 0.1d;
Console.WriteLine("d = " + DoubleConverter.ToExactString(d));
d += 0.1d;
Console.WriteLine("d = " + DoubleConverter.ToExactString(d));
d += 0.1d;
Console.WriteLine("d = " + DoubleConverter.ToExactString(d));
d += 0.1d;
Console.WriteLine("d = " + DoubleConverter.ToExactString(d));
}
}
</code></pre>
<p>Results (on my box):</p>
<pre><code>d = 0.1000000000000000055511151231257827021181583404541015625
d = 0.200000000000000011102230246251565404236316680908203125
d = 0.3000000000000000444089209850062616169452667236328125
d = 0.40000000000000002220446049250313080847263336181640625
d = 0.5
</code></pre>
<p>Now if you start with a different number, it doesn't work itself out in the same way:</p>
<p>(Starting with d=10.1)</p>
<pre><code>d = 10.0999999999999996447286321199499070644378662109375
d = 10.199999999999999289457264239899814128875732421875
d = 10.2999999999999989341858963598497211933135986328125
d = 10.39999999999999857891452847979962825775146484375
d = 10.4999999999999982236431605997495353221893310546875
</code></pre>
<p>So basically you happened to get lucky or unlucky with your test - the errors cancelled themselves out.</p> |
8,698,303 | How do I discover the quarter of a given date | <p>The following are the Quarters for a financial year </p>
<pre><code>April to June - Q1
July to Sep - Q2
Oct to Dec - Q3
Jan to March - Q4
</code></pre>
<p>If the month of an input date lies as above I need the output for in terms of Quarter number.</p>
<p>For Example,</p>
<p>If I give an input date (say <strong>january 2nd</strong>) , I need the output as <code>Q4</code>.</p>
<p>If I give input as (<strong>Jun 5</strong>), output should give <code>Q1</code>.</p>
<p>Based on input date I need the Quarter number.</p> | 8,698,345 | 15 | 4 | null | 2012-01-02 07:10:45.08 UTC | 9 | 2022-01-10 20:23:25.697 UTC | 2018-09-09 16:17:06.55 UTC | null | 107,625 | null | 239,991 | null | 1 | 51 | c# | 80,780 | <p>You can simply write an extension method to DateTime</p>
<pre><code>public static int GetQuarter(this DateTime date)
{
if (date.Month >= 4 && date.Month <= 6)
return 1;
else if (date.Month >= 7 && date.Month <= 9)
return 2;
else if (date.Month >= 10 && date.Month <= 12)
return 3;
else
return 4;
}
</code></pre>
<p>and use it as </p>
<pre><code>DateTime dt = DateTime.Now;
dt.GetQuarter();
</code></pre> |
5,475,473 | How to rename a view in MySQL? | <p>I have created a view <code>vw_extr</code>. </p>
<p>Now I want to rename it <code>vw_my</code>. </p>
<p>How can a view be renamed in MySQL?</p> | 5,475,511 | 4 | 0 | null | 2011-03-29 16:03:19.013 UTC | 4 | 2020-03-09 17:18:25.313 UTC | 2011-03-29 16:07:02.82 UTC | null | 23,199 | null | 571,832 | null | 1 | 44 | mysql | 29,105 | <p>You can use <code>RENAME TABLE</code> for that:</p>
<pre><code>RENAME TABLE vw_extr to vw_my
</code></pre> |
5,275,924 | What SVN command can I use to see the branch I'm currently using? | <p>I generally use Subclipse, but there's some wonkiness in my code right now and I want to do some sanity checks from the command line. Thanks to Subclipse, I can usually see the branches I'm using in Eclipse's Package Explorer window.</p>
<p><img src="https://i.stack.imgur.com/AXfEd.png" alt="screenshot of branch information in Eclipse"></p>
<p><strong>What command can I use from the command line to see the branch I'm currently using?</strong></p>
<p>Resources I tried before Stack Overflow include <a href="http://svnbook.red-bean.com/en/1.5/svn.branchmerge.whatis.html" rel="noreferrer">the SVN book</a>, <a href="https://www.forge.funambol.org/scdocs/ddUsingSVN_command-line" rel="noreferrer">this list of commands</a> and <a href="http://www.yolinux.com/TUTORIALS/Subversion.html" rel="noreferrer">this other list of commands</a>. I didn't find anything that would let me passively look at branch information (as opposed to making some sort of active branch modification, which is not what I want).</p> | 5,275,959 | 4 | 0 | null | 2011-03-11 17:00:47.747 UTC | 6 | 2020-02-18 16:03:47.62 UTC | null | null | null | null | 122,607 | null | 1 | 51 | svn | 48,593 | <p>Try the following:</p>
<pre><code>svn info
</code></pre>
<p>This will give you the URL your workspace is a checkout of, relative to where you are in the workspace. You should be able to see the branch in the URL.</p> |
5,560,602 | Add/Delete UITableViewCell with animation? | <p>I know this might sound like a dumb question, but I have looked every where. How can I do this?</p>
<p>I know how to do this with a swype-to-delete method, but how cam I do it outside that function?</p>
<p>Please post some code samples.</p>
<p>Thanks!<br>Coulton</p> | 5,564,842 | 4 | 0 | null | 2011-04-06 01:40:52.587 UTC | 16 | 2018-06-09 11:48:23.197 UTC | null | null | null | null | 613,860 | null | 1 | 55 | objective-c|ios4|uitableview | 51,191 | <pre><code>[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationFade];
[self.tableView deleteRowsAtIndexPaths:deleteIndexPaths withRowAnimation:UITableViewRowAnimationFade];
[self.tableView endUpdates];
</code></pre>
<p><code>insertIndexPaths</code> is an array of NSIndexPaths to be inserted to your table. </p>
<p><code>deleteIndexPaths</code> is a array of NSIndexPaths to be deleted from your table. </p>
<p>Example array format for index paths : </p>
<pre><code>NSArray *insertIndexPaths = [[NSArray alloc] initWithObjects:
[NSIndexPath indexPathForRow:0 inSection:0],
[NSIndexPath indexPathForRow:1 inSection:0],
[NSIndexPath indexPathForRow:2 inSection:0],
nil];
</code></pre> |
5,110,706 | How does extern work in C#? | <p>Whenever I look deeply enough into reflector I bump into <code>extern</code> methods with no source. I read the msdn documentation at <a href="http://msdn.microsoft.com/en-us/library/e59b22c5(v=vs.80).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/e59b22c5(v=vs.80).aspx</a>. What I got from that article is that methods with the <code>extern</code> modifier have to be injected. I interpreted this to mean it works something like an abstract factory pattern. I also noticed that I've never seen a non-static extern method. Is static declaration a requirement (I could see how this would make sense)? I'm still guessing here and I'm not sure how it actually works. It seems to me like the compiler must recognize certain attributes that mitigate processing, but I don't know what the attributes are other than ones I've come across like <code>MethodImplAttribute</code> and <code>DllImportAttribute</code> from the MSDN example. How does someone leverage the <code>extern</code> attribute? It said that in many instances this can increase performance. Also, how would I go about looking into the source of <code>extern</code> methods like <code>Object.InternalGetEquals()</code>? </p> | 5,110,832 | 4 | 2 | null | 2011-02-24 21:30:08.62 UTC | 18 | 2017-09-19 20:00:31.663 UTC | null | null | null | null | 344,211 | null | 1 | 76 | c#|.net|performance|extern|modifier | 57,557 | <p>Consider reading section 10.6.7 of the C# specification, which answers many of your questions. I reproduce part of it here for your convenience:</p>
<hr>
<blockquote>
<p>When a method declaration includes an
extern modifier, that method is said
to be an external method. External
methods are implemented externally,
typically using a language other than
C#. Because an external method
declaration provides no actual
implementation, the method-body of an
external method simply consists of a
semicolon. An external method may not
be generic. The extern modifier is
typically used in conjunction with a
DllImport attribute,
allowing external methods to be
implemented by DLLs (Dynamic Link
Libraries). The execution environment
may support other mechanisms whereby
implementations of external methods
can be provided. When an external
method includes a DllImport attribute,
the method declaration must also
include a static modifier.</p>
</blockquote>
<hr>
<blockquote>
<p>How does someone leverage the extern attribute?</p>
</blockquote>
<ul>
<li>Write your code in the unmanaged language of your choice. </li>
<li>Compile it into a DLL, exporting the entry point of your code.</li>
<li>Make an interop library that defines the method as an extern method in the given DLL.</li>
<li>Call it from C#.</li>
<li>Profit!</li>
</ul>
<blockquote>
<p>How would I go about looking into the source of extern methods like Object.InternalGetEquals()? </p>
</blockquote>
<p>Go to <a href="https://github.com/dotnet/coreclr/tree/master/src/vm" rel="noreferrer">https://github.com/dotnet/coreclr/tree/master/src/vm</a></p> |
5,376,193 | style a <thead> | <p>I have the following :</p>
<pre><code><table style="border:solid 1px; border-color:black">
<thead style="border:solid 2px; border-color:black">
<tr>
<th>
<p>Document Date</p>
</th>
<th>
<p>Buy-from Vendor No.</p>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<p>18/03/11</p>
</td>
<td>
<p>C01753</p>
</td>
</tr>
</tbody>
<tbody>
<tr>
<td>
<p>18/03/11</p>
</td>
<td>
<p>C00522</p>
</td>
</tr>
</tbody>
</table>
</code></pre>
<p>I'd like to add a border around the whole table and one around the whole header. The table border is showing nicely (Internet Explorer), but the header border is not.</p>
<p>PS: I use inline styles because it's meant for a HTML body in a mail message.</p>
<p><strong>EDIT</strong></p>
<p>The following gave me what I wanted in Firefox, not in IE though</p>
<pre><code><table style="border: 1px solid black; border-collapse: collapse;">
<thead>
<tr style="border: 1px solid black">
...
</code></pre>
<p><strong>EDIT</strong></p>
<p>Added coloring</p>
<pre><code><table style="border: 2px solid black; border-collapse: collapse;">
<thead>
<tr style="border: 1px solid black; background-color: #EEE;">
...
</code></pre> | 5,376,287 | 5 | 2 | null | 2011-03-21 10:13:22.86 UTC | 1 | 2013-08-19 12:02:45.57 UTC | 2012-01-04 15:19:39.3 UTC | null | 861,565 | null | 544,863 | null | 1 | 8 | html|css | 58,778 | <p>Use <code>rules="groups"</code> and change your structure a bit:</p>
<pre><code><table style="border: 1px solid black; border-collapse: collapse;" rules="groups">
<thead style="border: 2px solid black;">
<tr>
<th>
<p>Document Date</p>
</th>
<th>
<p>Buy-from Vendor No.</p>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<p>18/03/11</p>
</td>
<td>
<p>C01753</p>
</td>
</tr>
<tr>
<td>
<p>18/03/11</p>
</td>
<td>
<p>C00522</p>
</td>
</tr>
</tbody>
</table>
</code></pre>
<hr>
<p><strong>EDIT</strong>: Well, that doesn's seem to work in IE. In that case, I'd suggest:</p>
<pre><code><table style="border: 1px solid black; border-collapse: collapse;">
<thead>
<tr style="background-color: black; color: white;">
<!-- ... -->
</code></pre> |
5,289,328 | WPF MessageBox window style | <p>How to apply the default Windows style to the standard <code>MessageBox</code> in WPF?</p>
<p>For example, when I execute next code:</p>
<pre><code>MessageBox.Show("Hello Stack Overflow!", "Test", MessageBoxButton.OKCancel,
MessageBoxImage.Exclamation);
</code></pre>
<p>I'm getting message box:</p>
<p><img src="https://i.stack.imgur.com/gbd7z.png" alt="enter image description here"></p>
<p>But in WinForms everything is OK with style:</p>
<pre><code>MessageBox.Show("Hello Stack Overflow!", "Test", MessageBoxButtons.OKCancel,
MessageBoxIcon.Exclamation);
</code></pre>
<p><img src="https://i.stack.imgur.com/TRROw.png" alt="enter image description here"></p> | 5,289,462 | 5 | 0 | null | 2011-03-13 12:27:38.93 UTC | 22 | 2020-11-26 01:08:04.747 UTC | 2013-08-25 19:10:05.323 UTC | null | 438,180 | null | 438,180 | null | 1 | 50 | c#|wpf|messagebox | 38,281 | <p>According to <a href="http://www.nbdtech.com/Blog/archive/2008/05/28/Why-am-I-Getting-Old-Style-File-Dialogs-and-Message.aspx" rel="noreferrer">this</a> page, WPF picks up the old styles for some of the controls. </p>
<p>To get rid of it, you have to create a custom app.manifest file (Add -> New item -> Application Manifest File) and paste the following code in it (right after the /trustInfo - Tag ): </p>
<pre class="lang-xml prettyprint-override"><code><!-- Activate Windows Common Controls v6 usage (XP and Vista): -->
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="*"
publicKeyToken="6595b64144ccf1df"
language="*"/>
</dependentAssembly>
</dependency>
</code></pre>
<p>Then you have to compile your solution with this app.manifest (set it in the project properties -> Application -> Point to the new manifest in "Icons and manifest").</p>
<p>If you start your application now it should look like the WinForms- MessageBox.</p> |
5,323,146 | MySQL integer field is returned as string in PHP | <p>I have a table field in a MySQL database: </p>
<pre><code>userid INT(11)
</code></pre>
<p>So I am calling it to my page with this query:</p>
<pre><code>"SELECT userid FROM DB WHERE name='john'"
</code></pre>
<p>Then for handling the result I do: </p>
<pre><code>$row=$result->fetch_assoc();
$id=$row['userid'];
</code></pre>
<p>Now if I do:</p>
<pre><code>echo gettype($id);
</code></pre>
<p><strong>I get a string. Shouldn't this be an integer?</strong></p> | 5,323,169 | 16 | 5 | null | 2011-03-16 09:20:08.667 UTC | 29 | 2022-04-26 22:33:26.737 UTC | 2018-02-10 14:41:26.927 UTC | null | 4,284,627 | null | 505,762 | null | 1 | 151 | php|mysql|types|int|gettype | 135,201 | <p>When you select data from a MySQL database using PHP the datatype will always be converted to a string. You can convert it back to an integer using the following code:</p>
<pre><code>$id = (int) $row['userid'];</code></pre>
<p>Or by using the function <code>intval()</code>:</p>
<pre><code>$id = intval($row['userid']);</code></pre> |
16,596,520 | Android Studio start fails on Windows 8 64bit | <p>Installation works fine, JDK was also found without problems. After installation the program does not start. Double clicking the icon results in nothing happening. Starting as admin or installing "just for me" or for all users makes no difference.
I am out of answers.. Is this maybe a common issue?</p> | 16,598,949 | 5 | 3 | null | 2013-05-16 20:08:24.48 UTC | 1 | 2015-06-18 06:01:29.177 UTC | 2013-05-16 20:08:54.15 UTC | null | 115,145 | null | 923,441 | null | 1 | 3 | android|windows|android-studio | 39,302 | <p>After download and install Java SE Development Kit 7 - <code>"jdk-7u21-windows-x64.exe"</code> from <a href="http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html" rel="nofollow">Oracle site</a>
then adds <code>JAVA_HOME (value = c:\program Files\Java\jdk1.7.0_21)</code> to environment variables. It works fine with me on Windows 8.</p> |
12,335,747 | C++ - Too Many Initializers for Arrays | <p>I have made an array like this but then it keeps saying I had too many initializers. How can I fix this error?</p>
<pre><code> int people[6][9] = {{0,0,0,0,0,0},
{0,0,0,0,0,0},
{0,0,0,0,0,0},
{0,0,0,0,0,0},
{0,0,0,0,0,0},
{0,0,0,0,0,0},
{0,0,0,0,0,0},
{0,0,0,0,0,0},
{0,0,0,0,0,0}};
</code></pre> | 12,335,831 | 3 | 0 | null | 2012-09-09 01:07:05.463 UTC | 4 | 2014-10-21 18:03:53.213 UTC | 2014-10-21 18:03:53.213 UTC | null | 1,238,478 | null | 1,477,913 | null | 1 | 12 | c++|c|multidimensional-array|initialization | 52,792 | <pre><code>int people[6][9] =
{
{0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0},
};
</code></pre>
<p>Arrays in C are in the order rows then columns, so there are 6 rows of 9 integers, not 9 rows of 6 integers in the initializer for the array you defined.</p> |
12,231,644 | JS replace not working on string | <p>Trying to replace all instances of # in a string with a variable. It's not working but not retuning any error either.</p>
<pre><code>answer_form = '<textarea name="answer_#" rows="5"></textarea>'+
'<input type="file" name="img_#" />';
question_num = 5;
answer_form.replace(/#/g, question_num);
</code></pre>
<p>The hashes remain.</p>
<p>Not sure what I'm missing?</p> | 12,231,651 | 2 | 0 | null | 2012-09-01 21:41:29.963 UTC | 9 | 2012-09-01 21:53:41.487 UTC | null | null | null | null | 1,284,793 | null | 1 | 46 | javascript|jquery | 113,619 | <p><code>.replace()</code> returns a new string (it does not modify the existing string) so you would need:</p>
<pre><code>answer_form = answer_form.replace(/#/g, question_num);
</code></pre>
<p>You probably should also make <code>question_num</code> a string though auto type conversions probably handle that for you.</p>
<p>Working example: <a href="http://jsfiddle.net/jfriend00/4cAz5/" rel="noreferrer">http://jsfiddle.net/jfriend00/4cAz5/</a></p>
<p>FYI, in Javascript, strings are immutable - an existing string is never modified. So any method which makes a modification to the string (like <code>concat</code>, <code>replace</code>, <code>slice</code>, <code>substr</code>, <code>substring</code>, <code>toLowerCase</code>, <code>toUpperCase</code>, etc...) ALWAYS returns a new string.</p> |
12,250,024 | How to obtain sheet names from XLS files without loading the whole file? | <p>I'm currently using pandas to read an Excel file and present its sheet names to the user, so he can select which sheet he would like to use. The problem is that the files are really big (70 columns x 65k rows), taking up to 14s to load on a notebook (the same data in a CSV file is taking 3s).</p>
<p>My code in panda goes like this:</p>
<pre><code>xls = pandas.ExcelFile(path)
sheets = xls.sheet_names
</code></pre>
<p>I tried xlrd before, but obtained similar results. This was my code with xlrd:</p>
<pre><code>xls = xlrd.open_workbook(path)
sheets = xls.sheet_names
</code></pre>
<p>So, can anybody suggest a faster way to retrieve the sheet names from an Excel file than reading the whole file?</p> | 12,250,416 | 7 | 2 | null | 2012-09-03 14:44:51.63 UTC | 22 | 2022-07-08 22:56:13.383 UTC | 2016-01-26 19:52:37.443 UTC | null | 1,677,912 | null | 1,643,926 | null | 1 | 61 | python|excel|pandas|xlrd | 138,692 | <p>you can use the <a href="http://pypi.python.org/pypi/xlrd">xlrd</a> library and open the workbook with the "on_demand=True" flag, so that the sheets won't be loaded automaticaly.</p>
<p>Than you can retrieve the sheet names in a similar way to pandas:</p>
<pre><code>import xlrd
xls = xlrd.open_workbook(r'<path_to_your_excel_file>', on_demand=True)
print xls.sheet_names() # <- remeber: xlrd sheet_names is a function, not a property
</code></pre> |
12,532,339 | No appenders could be found for logger(log4j)? | <p>I have put log4j to my buildpath, but I get the following message when I run my application:</p>
<pre><code>log4j:WARN No appenders could be found for logger (dao.hsqlmanager).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
</code></pre>
<p>What do these warnings mean? Whats the appender here?</p> | 12,532,442 | 32 | 5 | null | 2012-09-21 14:17:21.42 UTC | 122 | 2021-09-08 20:20:11.483 UTC | 2015-10-28 10:34:24.527 UTC | null | 212,378 | null | 1,248,720 | null | 1 | 458 | java|eclipse|log4j | 861,264 | <p>This <a href="http://logging.apache.org/log4j/1.2/manual.html" rel="noreferrer">Short introduction to log4j</a> guide is a little bit old but still valid.</p>
<p>That guide will give you some information about how to use loggers and appenders.</p>
<hr>
<p>Just to get you going you have two simple approaches you can take.</p>
<p>First one is to just add this line to your main method:</p>
<pre class="lang-java prettyprint-override"><code>BasicConfigurator.configure();
</code></pre>
<p>Second approach is to add this standard <code>log4j.properties</code> (taken from the above mentioned guide) file to your classpath:</p>
<pre class="lang-none prettyprint-override"><code># Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG, A1
# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender
# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
</code></pre> |
3,261,228 | Convert flat array to the multi-dimensional | <p>I have an array with tree data (by parent id). I want to convert it to multidimensional array. What is the best way to achieve that? Is there any short function for that?</p>
<p>Source array:</p>
<pre><code>$source = array(
'0' => array(
'Menu' => array(
'id' => 45
'name' => 'Home'
'parent_id' => 1
)
)
'1' => array(
'Menu' => array(
'id' => 47
'name' => 'Get started'
'parent_id' => 1
)
)
'2' => array(
'Menu' => array(
'id' => 72
'name' => 'Attributes'
'parent_id' => 71
)
)
'3' => array(
'Menu' => array(
'id' => 73
'name' => 'Headings'
'parent_id' => 71
)
)
'4' => array(
'Menu' => array(
'id' => 75
'name' => 'Links'
'parent_id' => 71
)
)
'5' => array(
'Menu' => array(
'id' => 59
'name' => 'Images'
'parent_id' => 75
)
)
'6' => array(
'Menu' => array(
'id' => 65
'name' => 'Lists'
'parent_id' => 75
)
)
);
</code></pre>
<p>Some parents are missing from the source array. I would like the items with missing parent to be root. Result array:</p>
<pre><code>$result = array(
'0' => array(
'Menu' => array(
'id' => 45
'name' => 'Home'
'parent_id' => 1
)
'Children' => array()
)
'1' => array(
'Menu' => array(
'id' => 47
'name' => 'Get started'
'parent_id' => 1
)
'Children' => array()
)
'2' => array(
'Menu' => array(
'id' => 72
'name' => 'Attributes'
'parent_id' => 71
)
'Children' => array()
)
'3' => array(
'Menu' => array(
'id' => 73
'name' => 'Headings'
'parent_id' => 71
)
'Children' => array()
)
'4' => array(
'Menu' => array(
'id' => 75
'name' => 'Links'
'parent_id' => 71
)
'Children' => array(
'0' => array(
'Menu' => array(
'id' => 59
'name' => 'Images'
'parent_id' => 75
)
'Children' => array()
)
'1' => array(
'Menu' => array(
'id' => 65
'name' => 'Lists'
'parent_id' => 75
)
'Children' => array()
)
)
)
);
</code></pre>
<p>Update: removed square brackets.</p> | 3,261,351 | 3 | 5 | null | 2010-07-16 01:03:27.483 UTC | 13 | 2017-07-29 08:42:55.307 UTC | 2017-07-29 08:42:55.307 UTC | null | 1,033,581 | null | 316,041 | null | 1 | 7 | php|arrays|multidimensional-array|nested|hierarchical-data | 6,106 | <p>I don't think there is a built-in function in PHP that does this.</p>
<p>I tried the following code, and it seems to work to prepare the nested array the way you describe:</p>
<pre><code>$nodes = array();
$tree = array();
foreach ($source as &$node) {
$node["Children"] = array();
$id = $node["Menu"]["id"];
$parent_id = $node["Menu"]["parent_id"];
$nodes[$id] =& $node;
if (array_key_exists($parent_id, $nodes)) {
$nodes[$parent_id]["Children"][] =& $node;
} else {
$tree[] =& $node;
}
}
var_dump($tree);
</code></pre>
<p>I wrote a similar algorithm in a PHP class I wrote for my presentation <a href="http://www.slideshare.net/billkarwin/models-for-hierarchical-data" rel="noreferrer">Hierarchical Models in SQL and PHP</a>, but I was using objects instead of plain arrays. </p> |
3,592,475 | how to get <head> content of the current page with jquery or JS | <p>how to get <code><head></code> content of the current page</p> | 3,592,527 | 3 | 0 | null | 2010-08-28 21:09:40.187 UTC | 5 | 2016-08-01 11:36:44.863 UTC | 2013-12-03 14:16:46.567 UTC | null | 638,471 | null | 423,903 | null | 1 | 43 | javascript|jquery|head | 70,665 | <p>You could use the javascript DOM API like this:</p>
<pre><code>var headContent = document.getElementsByTagName('head')[0].innerHTML;
</code></pre> |
3,919,798 | How to check if a cmdlet exists in PowerShell at runtime via script | <p>I have a PowerShell script that needs to run under multiple hosts (PowerGUI, <a href="https://technet.microsoft.com/en-us/library/dd315244.aspx" rel="noreferrer">PowerShell ISE</a>, etc...), but I am having an issue where sometimes a cmdlet doesn't exist under one of the hosts. Is there a way to check to see if a cmdlet exists so that I can wrap the code in an if block and do something else when it does not exist?</p>
<p>I know I could use the <code>$host.name</code> to section the code that is suppose to run on each host, but I would prefer to use <a href="http://msdn.microsoft.com/en-us/library/ms537509(VS.85).aspx#DetectFtr" rel="noreferrer">Feature Detection</a> instead in case the cmdlet ever gets added in the future.</p>
<p>I also could use a try/catch block, but since it runs in managed code I assume there is away to detect if a cmdlet is installed via code.</p> | 3,919,904 | 3 | 0 | null | 2010-10-12 23:21:29.817 UTC | 11 | 2020-11-09 10:51:47.997 UTC | 2015-09-24 21:05:16.02 UTC | null | 63,550 | null | 17,373 | null | 1 | 71 | powershell|powershell-2.0 | 45,594 | <p>Use the <code>Get-Command</code> cmdlet to test for the existence of a cmdlet:</p>
<pre><code>if (Get-Command $cmdName -errorAction SilentlyContinue)
{
"$cmdName exists"
}
</code></pre>
<p>And if you want to ensure it is a cmdlet (and not an exe or function or script) use the <code>-CommandType</code> parameter e.g <code>-CommandType Cmdlet</code></p> |
22,581,248 | Is there a package to marshal in and out of x-www-form-urlencoding in golang | <p>I would like to marshal in and out of x-www-form-urlencoding similar to how you can do it with json or xml. Is there an existing package to do this, or are there any documents on how to implement one myself if none exist?</p> | 22,584,892 | 4 | 10 | null | 2014-03-22 17:46:05.663 UTC | 9 | 2021-04-06 20:04:59.503 UTC | null | null | null | null | 1,269,969 | null | 1 | 31 | go|marshalling|urlencode|unmarshalling | 16,229 | <p><a href="http://www.gorillatoolkit.org/pkg/schema" rel="noreferrer">gorilla/schema</a> is popular and well maintained:</p>
<p>e.g.</p>
<pre><code>func FormHandler(w http.RequestWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
// handle error
}
person := new(Person) // Person being a struct type
decoder := schema.NewDecoder()
err = decoder.Decode(person, r.Form)
if err != nil {
// handle error
}
}
</code></pre>
<p><a href="https://github.com/absoludity/goforms" rel="noreferrer">goforms</a> is also an alternative. </p>
<p><strong>Update May 23rd 2015:</strong></p>
<ul>
<li>gorilla/schema is still my pick as one of the most-supported map-to-struct packages, with POST form values being a common use-case.</li>
<li><a href="https://github.com/goji/param" rel="noreferrer">goji/param</a> is also fairly solid and has many of the same features.</li>
<li><a href="https://github.com/mholt/binding" rel="noreferrer">mholt/binding</a> is a little more feature packed at the (IMO) expense of a slightly more complex API.</li>
</ul>
<p>I've been using gorilla/schema for a couple of years now and haven't had any major issues with it. I use it in conjunction with <a href="https://github.com/kat-co/vala" rel="noreferrer">vala</a> for validating inputs (not nil, too short, too long, etc) before they hit the DB.</p> |
18,769,758 | How to detect the colour of an iPhone 5c? | <p>After iPhone 5c announcement, i'm curious if anybody knows an API how to get an iPhone 5c colour? I'm sure everyone will find it convenient loading a corresponding UI colour scheme to the device colour. </p>
<p>I'm thinking about wrapping it in something like the UIDevice category, which will return a UIColor.</p>
<p><strong>Update:</strong>
@ColinE and @Ortwin Gentz
has indicated the availability of private UIDevice instance method calls for it.</p>
<p><strong>Please note, that in case of iPhone 5c, what you are really looking for is deviceEnclosureColor, as deviceColor will always return #3b3b3c, as it is a front colour.</strong></p>
<p>method signature:</p>
<pre><code>-(id)_deviceInfoForKey:(struct __CFString { }*)arg1
</code></pre>
<p>UIDevice category for it:</p>
<pre><code>@interface UIDevice (deviceColour)
- (id)_deviceInfoForKey:(struct __CFString { }*)arg1;
- (NSString*)deviceColourString_UntilAppleMakesItPublic;
- (NSString*)deviceEnclosureColour_UntilAppleMakesItPublic;
@end
@implementation UIDevice (deviceColour)
- (NSString*)deviceColourString_UntilAppleMakesItPublic
{
return [self _deviceInfoForKey:@"DeviceColor"];
}
- (NSString*)deviceEnclosureColour_UntilAppleMakesItPublic
{
return [self _deviceInfoForKey:@"DeviceEnclosureColor"];
}
@end
</code></pre> | 19,356,301 | 4 | 14 | null | 2013-09-12 16:36:02.207 UTC | 17 | 2015-10-16 08:49:53.997 UTC | 2015-10-16 08:49:53.997 UTC | null | 916,299 | null | 2,380,455 | null | 1 | 40 | ios|objective-c|iphone|cocoa-touch|ios7 | 8,718 | <p>There's a private API to retrieve both the <code>DeviceColor</code> and the <code>DeviceEnclosureColor</code>. In case of the iPhone 5c, the interesting part is the enclosure color (the device color = front color is always #3b3b3c).</p>
<pre><code>UIDevice *device = [UIDevice currentDevice];
SEL selector = NSSelectorFromString(@"deviceInfoForKey:");
if (![device respondsToSelector:selector]) {
selector = NSSelectorFromString(@"_deviceInfoForKey:");
}
if ([device respondsToSelector:selector]) {
NSLog(@"DeviceColor: %@ DeviceEnclosureColor: %@", [device performSelector:selector withObject:@"DeviceColor"], [device performSelector:selector withObject:@"DeviceEnclosureColor"]);
}
</code></pre>
<p>I've blogged about this and provide a sample app:</p>
<p><a href="http://www.futuretap.com/blog/device-colors/">http://www.futuretap.com/blog/device-colors/</a></p>
<p><strong>Warning: As mentioned, this is a private API. Don't use this in App Store builds.</strong></p> |
8,701,754 | How to disable scroll without hiding it? | <p>I'm trying to disable the html/body scrollbar of the parent while I'm using a lightbox. The main word here is <em>disable</em>. I do <em>not</em> want to hide it with <code>overflow: hidden;</code>.</p>
<p>The reason for this is that <code>overflow: hidden</code> makes the site jump and take up the area where the scroll was.</p>
<p>I want to know if its possible to disable a scrollbar while still showing it.</p> | 8,701,977 | 23 | 12 | null | 2012-01-02 14:01:46.06 UTC | 78 | 2022-04-27 11:43:22.067 UTC | 2021-08-02 09:29:48.763 UTC | null | 15,366,635 | null | 148,601 | null | 1 | 249 | javascript|jquery|html|css | 243,850 | <p>If the page under the overlayer can be "fixed" at the top, when you open the overlay you can set</p>
<pre><code>body { position: fixed; overflow-y:scroll }
</code></pre>
<p>you should still see the right scrollbar but the content is not scrollable. When you close the overlay just revert these properties with</p>
<pre><code>body { position: static; overflow-y:auto }
</code></pre>
<p>I just proposed this way only because you wouldn't need to change any scroll event</p>
<p><strong>Update</strong></p>
<p>You could also do a slight improvement: if you get the <code>document.documentElement.scrollTop</code> property via javascript just before the layer opening, you could dynamically assign that value as <code>top</code> property of the body element: with this approach the page will stand in its place, no matter if you're on top or if you have already scrolled. </p>
<p><strong>Css</strong></p>
<pre><code>.noscroll { position: fixed; overflow-y:scroll }
</code></pre>
<p><strong>JS</strong></p>
<pre><code>$('body').css('top', -(document.documentElement.scrollTop) + 'px')
.addClass('noscroll');
</code></pre> |
26,323,215 | Do any languages / compilers utilize the x86 ENTER instruction with a nonzero nesting level? | <p>Those familiar with x86 assembly programming are very used to the typical function prologue / epilogue:</p>
<pre><code>push ebp ; Save old frame pointer.
mov ebp, esp ; Point frame pointer to top-of-stack.
sub esp, [size of local variables]
...
mov esp, ebp ; Restore frame pointer and remove stack space for locals.
pop ebp
ret
</code></pre>
<p>This same sequence of code can also be implemented with the <code>ENTER</code> and <code>LEAVE</code> instructions:</p>
<pre><code>enter [size of local variables], 0
...
leave
ret
</code></pre>
<p>The <code>ENTER</code> instruction's second operand is the <em>nesting level</em>, which allows multiple parent frames to be accessed from the called function.</p>
<p>This is not used in C because there are no nested functions; local variables have only the scope of the function they're declared in. This construct does not exist (although sometimes I wish it did):</p>
<pre class="lang-c prettyprint-override"><code>void func_a(void)
{
int a1 = 7;
void func_b(void)
{
printf("a1 = %d\n", a1); /* a1 inherited from func_a() */
}
func_b();
}
</code></pre>
<p>Python however <em>does</em> have nested functions which behave this way:</p>
<pre class="lang-python prettyprint-override"><code>def func_a():
a1 = 7
def func_b():
print 'a1 = %d' % a1 # a1 inherited from func_a()
func_b()
</code></pre>
<p>Of course Python code isn't translated directly to x86 machine code, and thus would be unable (unlikely?) to take advantage of this instruction.</p>
<p><strong>Are there any languages which compile to x86 and provide nested functions? Are there compilers which will emit an <code>ENTER</code> instruction with a nonzero second operand?</strong></p>
<p>Intel invested a nonzero amount of time/money into that nesting level operand, and basically I'm just curious if anyone uses it :-)</p>
<p>References:</p>
<ul>
<li><a href="http://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-software-developer-instruction-set-reference-manual-325383.pdf" rel="noreferrer">Intel® 64 and IA-32 Architectures Software Developer’s Manual Vol 2: Instruction Set Reference</a> </li>
<li><a href="http://www.posix.nl/linuxassembly/nasmdochtml/nasmdoca.html#section-A.27" rel="noreferrer">NASM Manual - ENTER: Create Stack Frame</a></li>
</ul> | 26,323,663 | 4 | 12 | null | 2014-10-12 08:20:45.65 UTC | 10 | 2018-09-20 23:12:34.397 UTC | 2018-09-20 23:12:34.397 UTC | null | -1 | null | 119,527 | null | 1 | 58 | assembly|x86 | 10,871 | <p><code>enter</code> is avoided in practice as it performs quite poorly - see the answers at <a href="https://stackoverflow.com/questions/5959890/enter-vs-push-ebp-mov-ebp-esp-sub-esp-imm-and-leave-vs-mov-esp-ebp">"enter" vs "push ebp; mov ebp, esp; sub esp, imm" and "leave" vs "mov esp, ebp; pop ebp"</a>. There are a bunch of x86 instructions that are obsolete but are still supported for backwards compatibility reasons - <code>enter</code> is one of those. (<code>leave</code> is OK though, and compilers are happy to emit it.) </p>
<p>Implementing nested functions in full generality as in Python is actually a considerably more interesting problem than simply selecting a few frame management instructions - search for 'closure conversion' and 'upwards/downwards funarg problem' and you'll find many interesting discussions.</p>
<p>Note that the x86 was originally designed as a Pascal machine, which is why there are instructions to support nested functions (<code>enter</code>, <code>leave</code>), the <code>pascal</code> calling convention in which the callee pops a known number of arguments from the stack (<code>ret K</code>), bounds checking (<code>bound</code>), and so on. Many of these operations are now obsolete.</p> |
11,071,211 | Convert JTextField input into an Integer | <p>I am new to JAVA, I am trying to convert an input from a JTextField into an integer, I have tried loads of options but nothing is working, the eclipse is always giving me an error and the errors are not making sense to me.</p>
<p>import java.awt.Graphics;
import java.awt.Color;</p>
<pre><code>public class circle extends Shape{
public int x;
public int y;
public int Radius;
public circle (int Radius, int x, int y, Color c){
super(c);
this.x = x;
this.y = y;
this.Radius = Radius;
}
public void draw(Graphics g){
g.setColor(super.getColor());
g.fillOval(x-Radius, y-Radius, Radius * 2, Radius * 2);
}
}
</code></pre> | 11,071,273 | 4 | 4 | null | 2012-06-17 12:16:00.243 UTC | 4 | 2012-07-17 09:51:17.91 UTC | 2012-07-17 09:51:17.91 UTC | null | 1,460,412 | null | 1,460,412 | null | 1 | 5 | java|string|parsing|jtextfield|japplet | 88,871 | <p>In place of:</p>
<pre><code>JTextField f1 = new JTextField("-5");
//xaxis1 = Integer.parseInt(f1);
</code></pre>
<p>try this:</p>
<pre><code>JTextField f1 = new JTextField("-5");
String text = f1.getText();
int xaxis1 = Integer.parseInt(text);
</code></pre>
<p>You cannot parse <code>TextField</code> to <code>Integer</code>, but <strong>you can parse</strong> its <strong>value</strong> contained - text.</p> |
11,222,007 | How do I get the value of drop down list on page load with jQuery | <p>Using jQuery, how can I get the selected item's value in a select when the page loads?
I can do it onChange etc but cant figure out the way on page load.</p>
<p>Here's my code:</p>
<pre><code><select name="symb" id="symb">
<option value="1#10#6">Basic Personal</option>
<option selected="selected" value="2#20#6">Basic Family</option>
<option value="7#90#12">Advanced Personal</option>
<option value="8#120#12">Advanced Family</option>
<option value="9#130#12">Optimum Personal</option>
<option value="10#170#12">Optimum Family</option>
</select>
</code></pre>
<p>This is the script I'm using for getting the option value onchange:</p>
<pre><code>$(document).ready(function() {
$("#symb").change(function() {
var val = $(this).symbCost(0);
})
$.fn.symbCost = function(pos) {
var total = parseInt($("option:selected").val().split('#')[pos]);
return total;
}
});
</code></pre> | 11,222,059 | 4 | 0 | null | 2012-06-27 08:16:20.52 UTC | 1 | 2021-07-30 19:05:58.53 UTC | 2021-07-30 19:05:58.53 UTC | null | 14,367,332 | null | 511,488 | null | 1 | 5 | jquery|drop-down-menu|onload | 42,081 | <pre><code>$(document).ready(function() {
alert($("#symb").val());
});
</code></pre> |
11,386,147 | Display the value of a variable property in LLDB debugger? | <p>I'm using a breakpoint with Action "Log Message", and I want to print the row of an NSIndexPath. So I tried: <code>cell row @indexPath.row@</code> but nothing gets printed. I also tried using a debugger command: <code>expr (void)NSLog(@"indexPath row:%i", indexPath.row)</code> but I get an error: <code>error: property 'row' not found on object of type 'NSIndexPath *'</code></p>
<p>What am I doing wrong?</p> | 11,386,218 | 3 | 0 | null | 2012-07-08 19:51:23.407 UTC | 9 | 2013-09-03 14:24:10.18 UTC | null | null | null | null | 458,960 | null | 1 | 13 | xcode|lldb | 25,310 | <p>The dot syntax is just syntactic sugar added by the compiler. I've always disagreed with adding it to Objective-C, but some people love it. What you have to remember is that these dots are getting converted into method calls by the compiler, so when you message something directly, like in the debugger, you must use the actual method call. Try rewriting your expression:</p>
<pre><code>expr (void)NSLog(@"indexPath row: %ld", (long int)[indexPath row])
</code></pre>
<p>I'm not sure if the debugger's basic log method will execute method calls like this, so you may have to use the expression type.</p> |
11,180,125 | Repeating a repeated sequence | <p>We want to get an array that looks like this:</p>
<pre><code>1,1,1,2,2,2,3,3,3,4,4,4,1,1,1,2,2,2,3,3,3,4,4,4,1,1,1,2,2,2,3,3,3,4,4,4
</code></pre>
<p>What is the easiest way to do it?</p> | 11,181,273 | 5 | 1 | null | 2012-06-24 18:32:00.847 UTC | 7 | 2022-01-04 21:55:33.133 UTC | 2012-06-24 20:51:52.08 UTC | null | 602,276 | null | 1,403,232 | null | 1 | 21 | r|sequence|replicate | 40,812 | <p>You can do it with a single <code>rep</code> call. The <code>each</code> and <code>times</code> parameters are evaluated sequentially with the <code>each</code> being done first.</p>
<pre><code>rep(1:4, times=3, each=3) # 'each' done first regardless of order of named parameters
#[1] 1 1 1 2 2 2 3 3 3 4 4 4 1 1 1 2 2 2 3 3 3 4 4 4 1 1 1 2 2 2 3 3 3 4 4 4
</code></pre> |
11,351,135 | Create ul and li elements in javascript. | <p>I am trying to create ul and li element in my codes by using javascript. I have following:</p>
<pre><code>var test=document.createElement('section');
test.setAttribute('id','test');
var ul=document.createElement('ul');
document.body.appendChild(test);
test.appendChild(ul);
for (var i=0; i<array.length; i++){
var li=document.createElement('li');
ul.appendChild(li);
li.innerHTML=li.innerHTML + array[i];
}
</code></pre>
<p>My array is parsed using json_encode from php</p>
<pre><code>array[0]='aaa';
array[1]='bbb';
array[2]='ccc';
</code></pre>
<p>CSS</p>
<pre><code>section {
display: block;
width: 200px;
margin: 50px auto;
border: 3px solid red;
}
</code></pre>
<p>Everything works fine except the list style dot is outside of my section tag. </p>
<p>It displays like this in Chrome and IE but firefox work fine.</p>
<pre><code> -------------
*| aaa |
*| bbb |
*| ccc |
-------------
</code></pre>
<p>I want my dot inside my section tag. Anyone idea? Thanks a lot.</p> | 11,351,198 | 4 | 4 | null | 2012-07-05 19:22:38.403 UTC | 12 | 2019-08-07 08:04:23.953 UTC | null | null | null | null | 1,174,696 | null | 1 | 29 | javascript | 165,451 | <p>Use the <code>CSS</code> property <code>list-style-position</code> to position the bullet:</p>
<pre><code>list-style-position:inside /* or outside */;
</code></pre> |
10,970,958 | Get a color component from an rgb string in Javascript? | <p>I'm using Javascript and Canvas to make a painting app and was using strings in this format to designate chosen colors:</p>
<p><code>"rgb(255,0,0)"</code></p>
<p>Because the canvas context fillStyle property takes in strings of that format.</p>
<p>However, I now need to obtain individual components from this string and was wondering if there was a way to do it without messy string manipulation. Possibly some built in way to convert that string to a sort of color object and then access its r, g, and b components?</p>
<p>Thanks.</p> | 10,971,090 | 9 | 1 | null | 2012-06-10 17:54:16.177 UTC | 10 | 2022-01-04 12:45:32.077 UTC | null | null | null | null | 962,155 | null | 1 | 42 | javascript|html|canvas|colors | 41,489 | <p><strong>NOTE</strong> - We're all on board with the <em>regex ate my brains and kicked my dog</em> attitude, but the regex version just seems the better method. My opinion. Check it out.</p>
<p>Non-regex method:</p>
<pre><code>var rgb = 'rgb(200, 12, 53)';
rgb = rgb.substring(4, rgb.length-1)
.replace(/ /g, '')
.split(',');
console.log(rgb);
</code></pre>
<p><a href="http://jsfiddle.net/userdude/Fg9Ba/" rel="noreferrer">http://jsfiddle.net/userdude/Fg9Ba/</a></p>
<p>Outputs:</p>
<pre><code>["200", "12", "53"]
</code></pre>
<p>Or... A really simple regex:</p>
<p>EDIT: Ooops, had an <code>i</code> in the regex for some reason.</p>
<pre><code>var rgb = 'rgb(200, 12, 53)';
rgb = rgb.replace(/[^\d,]/g, '').split(',');
console.log(rgb);
</code></pre>
<p><a href="http://jsfiddle.net/userdude/Fg9Ba/2" rel="noreferrer">http://jsfiddle.net/userdude/Fg9Ba/2</a></p> |
10,953,326 | What is a concise way to create inline elements in Jade | <p>I like to put all my inline elements in a single line. </p>
<pre><code><ul>
<li><a>click<span>here</span><strong>!</strong></a></li>
</code></pre>
<p>Wondering if there's a better way to create inline elements in Jade than this:</p>
<pre><code>ul
li
a(href="#") click
span here
strong !
</code></pre>
<p>This get's a little closer but I'm not sure how to add the span and strong tags without breaking the lines.</p>
<pre><code>ul
li: a(href='#') click
span ...
</code></pre>
<p>This obviously isn't a super big problem but it's a little annoying that I can't put inline elements inline. Thanks for the help</p> | 23,082,806 | 3 | 0 | null | 2012-06-08 17:21:49.473 UTC | 14 | 2015-06-10 15:04:29.43 UTC | 2014-02-24 16:26:39.987 UTC | null | 203,708 | null | 203,708 | null | 1 | 62 | node.js|pug | 23,031 | <p><a href="https://github.com/visionmedia/jade/pull/1323">Since version 1.0</a>, jade supports inline tags:</p>
<pre><code>#[tag(attribute='value') inner stuff]
</code></pre>
<p>In your case that would be:</p>
<pre><code>ul
li #[a(href="#") click #[span here #[strong !]]]
</code></pre> |
10,985,950 | How do you insert a template into another template? | <p>I have a very basic template (basic_template.html), and want to fill in the with data formatted using another partial template. The basic_template.html might contain several things formatted using the partial template.</p>
<p>How should I structure the code in views.py?</p>
<p>The reason I am doing this is that later on the will be filled using Ajax. Am I doing this right?</p> | 10,985,987 | 4 | 0 | null | 2012-06-11 18:58:44.153 UTC | 17 | 2019-04-29 12:54:43.357 UTC | 2013-12-19 16:09:48.73 UTC | null | 1,267,329 | null | 643,084 | null | 1 | 86 | html|django|django-templates | 73,499 | <p>You can do:</p>
<pre><code><div class="basic">
{% include "main/includes/subtemplate.html" %}
</div>
</code></pre>
<p>where <code>subtemplate.html</code> is another Django template. In this <code>subtemplate.html</code> you can put the HTML that would be obtained with Ajax.</p>
<p>You can also include the template multiple times:</p>
<pre><code><div class="basic">
{% for item in items %}
{% include "main/includes/subtemplate.html" %}
{% endfor %}
</div>
</code></pre> |
11,421,741 | MySQL WHERE: how to write "!=" or "not equals"? | <p>I need to do this</p>
<pre><code>DELETE FROM konta WHERE taken != ''
</code></pre>
<p>But != doesn't exist in mysql.
Anyone know how to do this?</p> | 11,421,762 | 3 | 0 | null | 2012-07-10 20:51:55.167 UTC | 12 | 2015-08-22 22:15:16.477 UTC | 2015-08-22 22:15:16.477 UTC | user166390 | 4,370,109 | null | 1,377,311 | null | 1 | 109 | mysql|sql-delete | 152,304 | <pre><code>DELETE FROM konta WHERE taken <> '';
</code></pre> |
12,875,682 | Initialize database on Jersey webapp startup | <p>I've read <a href="https://stackoverflow.com/questions/7424465/jersey-app-run-initialization-code-on-startup-to-initialize-application">this</a> but I don't quite understand how it works. I want to load a properties file and set up my connection pool when my web application starts. Obviously I want to do this only once and in a single place so I can change it if needs be. With regular servlets, I would simply put my initialization code in the servlet's init() method, but you don't have access to it with a Jersey servlet. So where do I do it? How do the listeners in the link above work?</p> | 12,875,920 | 2 | 0 | null | 2012-10-13 18:21:26.697 UTC | 9 | 2019-01-09 12:38:14.223 UTC | 2018-08-23 18:33:56.137 UTC | null | 438,154 | null | 438,154 | null | 1 | 14 | java|web-applications|initialization|jersey | 16,671 | <p>All you need to do is write a java class that implements the ServletContextListener interface. This class must implement two method contextInitialized method which is called when the web application is first created and contextDestroyed which will get called when it is destroyed. The resource that you want to be initialized would be instantiated in the contextInitialized method and the resource freed up in the contextDestroyed class. The application must be configured to call this class when it is deployed which is done in the web.xml descriptor file.</p>
<pre><code>public class ServletContextClass implements ServletContextListener
{
public static Connection con;
public void contextInitialized(ServletContextEvent arg0)
{
con.getInstance ();
}//end contextInitialized method
public void contextDestroyed(ServletContextEvent arg0)
{
con.close ();
}//end constextDestroyed method
}
</code></pre>
<p>The web.xml configuration </p>
<pre class="lang-xml prettyprint-override"><code><listener>
<listener-class>com.nameofpackage.ServletContextClass</listener-class>
</listener>
</code></pre>
<p>This now will let the application call the ServletContextClass when the application is deployed and instantiate the Connection or any other resource place in the contextInitialized method some what similar to what the Servlet init method does.</p> |
13,034,746 | If I declare a fragment in an XML layout, how do I pass it a Bundle? | <p>I've got an activity that I've replaced with a fragment. The activity took an Intent that had some extra information on what data the activity was supposed to display.</p>
<p>Now that my Activity is just a wrapper around a Fragment that does the same work, how do I get that bundle to the Fragment if I declare the fragment in XML with the tag?</p>
<p>If I were to use a FragmentTransaction to put the Fragment into a ViewGroup, I'd get a chance to pass this info along in the Fragment constructor, but I'm wondering about the situation where the fragment is defined in XML.</p> | 13,034,812 | 8 | 2 | null | 2012-10-23 16:07:03.473 UTC | 6 | 2022-09-06 11:11:07.8 UTC | null | null | null | null | 652,466 | null | 1 | 79 | java|android|xml|fragment | 28,283 | <blockquote>
<p>Now that my Activity is just a wrapper around a Fragment that does the same work, how do I get that bundle to the Fragment if I declare the fragment in XML with the tag?</p>
</blockquote>
<p>You can't.</p>
<p>However, you are welcome to call <code>findFragmentById()</code> on your <code>FragmentManager</code> to retrieve the fragment post-inflation, then call some method on the fragment to associate data with it. While apparently that cannot be <code>setArguments()</code>, your fragment could arrange to hold onto the data itself past a configuration change by some other means (<code>onSaveInstanceState()</code>, <code>setRetainInstance(true)</code>, etc.).</p> |
13,042,008 | java.util.NoSuchElementException - Scanner reading user input | <p>I'm new to using Java, but I have some previous experience with C#. The issue I'm having comes with reading user input from console.</p>
<p>I'm running into the "java.util.NoSuchElementException" error with this portion of code:</p>
<pre><code>payment = sc.next(); // PromptCustomerPayment function
</code></pre>
<p>I have two functions that get user input:</p>
<ul>
<li>PromptCustomerQty</li>
<li>PromptCustomerPayment</li>
</ul>
<p>If I don't call PromptCustomerQty then I don't get this error, which leads me to believe I am doing something wrong with scanner. Below is my full code sample. I appreciate any help.</p>
<pre><code>public static void main (String[] args) {
// Create a customer
// Future proofing the possabiltiies of multiple customers
Customer customer = new Customer("Will");
// Create object for each Product
// (Name,Code,Description,Price)
// Initalize Qty at 0
Product Computer = new Product("Computer","PC1003","Basic Computer",399.99);
Product Monitor = new Product("Monitor","MN1003","LCD Monitor",99.99);
Product Printer = new Product("Printer","PR1003x","Inkjet Printer",54.23);
// Define internal variables
// ## DONT CHANGE
ArrayList<Product> ProductList = new ArrayList<Product>(); // List to store Products
String formatString = "%-15s %-10s %-20s %-10s %-10s %n"; // Default format for output
// Add objects to list
ProductList.add(Computer);
ProductList.add(Monitor);
ProductList.add(Printer);
// Ask users for quantities
PromptCustomerQty(customer, ProductList);
// Ask user for payment method
PromptCustomerPayment(customer);
// Create the header
PrintHeader(customer, formatString);
// Create Body
PrintBody(ProductList, formatString);
}
public static void PromptCustomerQty(Customer customer, ArrayList<Product> ProductList) {
// Initiate a Scanner
Scanner scan = new Scanner(System.in);
// **** VARIABLES ****
int qty = 0;
// Greet Customer
System.out.println("Hello " + customer.getName());
// Loop through each item and ask for qty desired
for (Product p : ProductList) {
do {
// Ask user for qty
System.out.println("How many would you like for product: " + p.name);
System.out.print("> ");
// Get input and set qty for the object
qty = scan.nextInt();
}
while (qty < 0); // Validation
p.setQty(qty); // Set qty for object
qty = 0; // Reset count
}
// Cleanup
scan.close();
}
public static void PromptCustomerPayment (Customer customer) {
// Initiate Scanner
Scanner sc = new Scanner(System.in);
// Variables
String payment = "";
// Prompt User
do {
System.out.println("Would you like to pay in full? [Yes/No]");
System.out.print("> ");
payment = sc.next();
} while ((!payment.toLowerCase().equals("yes")) && (!payment.toLowerCase().equals("no")));
// Check/set result
if (payment.toLowerCase().equals("yes")) {
customer.setPaidInFull(true);
}
else {
customer.setPaidInFull(false);
}
// Cleanup
sc.close();
}
</code></pre> | 13,042,296 | 5 | 0 | null | 2012-10-24 02:04:45.32 UTC | 28 | 2022-03-14 03:16:10.047 UTC | 2021-11-30 17:18:27.543 UTC | null | 1,393,766 | null | 1,769,999 | null | 1 | 83 | java|input|java.util.scanner | 137,752 | <p><strong>This has really puzzled me for a while but this is what I found in the end.</strong></p>
<p>When you call, <code>sc.close()</code> in first method, it not only closes your scanner but closes your <code>System.in</code> input stream as well. You can verify it by printing its status at very top of the second method as :</p>
<pre><code> System.out.println(System.in.available());
</code></pre>
<p>So, now when you re-instantiate, <code>Scanner</code> in second method, it doesn't find any open <code>System.in</code> stream and hence the exception.</p>
<p>I doubt if there is any way out to reopen <code>System.in</code> because:</p>
<p><code>public void close() throws IOException --> Closes this input stream and releases any system resources associated with this stream. The general contract of close is that it closes the input stream. A closed stream cannot perform input operations and **cannot be reopened.**</code></p>
<p>The only good solution for your problem is to initiate the <code>Scanner</code> in your main method, pass that as argument in your two methods, and close it again in your main method e.g.:</p>
<p><code>main</code> method related code block:</p>
<pre><code>Scanner scanner = new Scanner(System.in);
// Ask users for quantities
PromptCustomerQty(customer, ProductList, scanner );
// Ask user for payment method
PromptCustomerPayment(customer, scanner );
//close the scanner
scanner.close();
</code></pre>
<p>Your Methods:</p>
<pre><code> public static void PromptCustomerQty(Customer customer,
ArrayList<Product> ProductList, Scanner scanner) {
// no more scanner instantiation
...
// no more scanner close
}
public static void PromptCustomerPayment (Customer customer, Scanner sc) {
// no more scanner instantiation
...
// no more scanner close
}
</code></pre>
<p>Hope this gives you some insight about the failure and possible resolution.</p> |
12,737,293 | How do I resolve the "java.net.BindException: Address already in use: JVM_Bind" error? | <p>In Eclipse, I got this error:</p>
<pre><code>run:
[java] Error creating the server socket.
[java] Oct 04, 2012 5:31:38 PM cascadas.ace.AceFactory bootstrap
[java] SEVERE: Failed to create world : java.net.BindException: Address already in use: JVM_Bind
[java] Java Result: -1
BUILD SUCCESSFUL
Total time: 10 seconds
</code></pre>
<p>I'm not sure why it came up now, but it ran fine just a few hours ago. Do I need to restart my machine? How do i get to the bottom of it? I appreciate any tips or advice.</p> | 12,737,775 | 22 | 2 | null | 2012-10-04 23:07:16.603 UTC | 69 | 2022-04-12 13:06:03.767 UTC | null | null | null | null | 763,029 | null | 1 | 249 | java|eclipse|networking|serversocket | 824,522 | <p>Yes you have another process bound to the same port.</p>
<p><a href="http://technet.microsoft.com/en-us/sysinternals/bb897437">TCPView</a> (Windows only) from <a href="http://technet.microsoft.com/en-US/sysinternals">Windows Sysinternals</a> is my favorite app whenever I have a JVM_BIND error. It shows which processes are listening on which port. It also provides a convenient context menu to either kill the process or close the connection that is getting in the way. </p> |
16,743,611 | Setting a div to display:none; using javascript or jQuery | <p>I have a really quick question that should be an easy answer.</p>
<p>I have a mobile navigation menu that uses jQuery to "drill down" menu levels. Each time a level is loaded, the jQuery determines the menu's height, and sets it accordingly.</p>
<p>I am using the following script on a button to toggle show and hide the main menu based on the current page:</p>
<pre><code><script type="text/javascript">
(function ($) {
$("a.BNnavTrigger").click(function (event) {
event.preventDefault();
$("div.drill-down-wrapper").slideToggle("9000");
});
})(jQuery);
</script>
</code></pre>
<p>In order for the menu to start "closed" on certain pages, I know that I must give the css value of <code>display:none;</code> to the containing div. This is all working fine with one small problem.</p>
<p>When I initially hide the menu, the jQuery drilldown menu plugin detects that it is hidden, and sets the menu height to 0px. When I toggle the menu on a page that had the menu initially hidden, all the other content in the pane toggles correctly, but the menu itself is stuck at a 0 height.</p>
<p>In my brain, the obvious answer to this problem would be to hide the containing menu div ,via javascript, after the menu has been loaded and it's height set. Does this sound correct?</p>
<p>Could anyone provide me with a little script to do this? I am a complete and utter noob with js. Does anyone else have a different recommendation as to how to handle this issue?</p>
<p>Thanks for your time!
Alex</p>
<p><strong>UPDATE!</strong></p>
<p><strong>JS fiddle for the issue here:</strong> <a href="http://jsfiddle.net/fyyG2/17/" rel="noreferrer">http://jsfiddle.net/fyyG2/17/</a>*</p> | 16,800,957 | 5 | 15 | null | 2013-05-24 21:02:07.517 UTC | 1 | 2020-04-10 15:37:06.88 UTC | 2017-02-09 20:33:47.177 UTC | null | 13,302 | null | 1,774,754 | null | 1 | 13 | javascript|jquery|css|mobile | 78,481 | <p>On <strong>document ready</strong> do <code>$("#yourId").hide();</code>.</p>
<p>For example:</p>
<pre><code>$(document).ready(function () {
$("div.drill-down-wrapper").hide();
var $drillDown = $("#drilldown");
// (what ever your code is)
});
</code></pre> |
17,057,809 | D3.js: what is 'g' in .append("g") D3.js code? | <p>I am new to <code>D3.js</code>, started learning today only</p>
<p>I looked the the <a href="http://bl.ocks.org/mbostock/3887193" rel="noreferrer">donut example</a> and found this code</p>
<pre><code>var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
</code></pre>
<p>I searched for <a href="https://github.com/mbostock/d3/wiki/Selections#wiki-append" rel="noreferrer">documentation</a>, but did not understood what <code>.append("g")</code> is appending</p>
<p>Is it even <code>D3</code> specific?</p>
<p>Looking for guidance here</p> | 17,058,707 | 2 | 1 | null | 2013-06-12 04:44:25.85 UTC | 25 | 2018-08-18 15:55:07.56 UTC | null | null | null | null | 379,235 | null | 1 | 149 | javascript|d3.js | 85,897 | <p>It appends a <a href="http://www.w3.org/TR/SVG/struct.html#Groups" rel="noreferrer">'g' element</a> to the SVG. <code>g</code> element <a href="http://tutorials.jenkov.com/svg/g-element.html" rel="noreferrer">is used to group SVG shapes together</a>, so no it's not d3 specific.</p> |
16,709,373 | AngularJS. How to call controller function from outside of controller component | <p>How I can call function defined under controller from any place of web page (outside of controller component)?</p>
<p>It works perfectly when I press "get" button. But I need to call it from outside of div controller. The logic is: by default my div is hidden. Somewhere in navigation menu I press a button and it should show() my div and execute "get" function. How I can achieve this?</p>
<p>My web page is:</p>
<pre><code><div ng-controller="MyController">
<input type="text" ng-model="data.firstname" required>
<input type='text' ng-model="data.lastname" required>
<form ng-submit="update()"><input type="submit" value="update"></form>
<form ng-submit="get()"><input type="submit" value="get"></form>
</div>
</code></pre>
<p>My js:</p>
<pre><code> function MyController($scope) {
// default data and structure
$scope.data = {
"firstname" : "Nicolas",
"lastname" : "Cage"
};
$scope.get = function() {
$.ajax({
url: "/php/get_data.php?",
type: "POST",
timeout: 10000, // 10 seconds for getting result, otherwise error.
error:function() { alert("Temporary error. Please try again...");},
complete: function(){ $.unblockUI();},
beforeSend: function(){ $.blockUI()},
success: function(data){
json_answer = eval('(' + data + ')');
if (json_answer){
$scope.$apply(function () {
$scope.data = json_answer;
});
}
}
});
};
$scope.update = function() {
$.ajax({
url: "/php/update_data.php?",
type: "POST",
data: $scope.data,
timeout: 10000, // 10 seconds for getting result, otherwise error.
error:function() { alert("Temporary error. Please try again...");},
complete: function(){ $.unblockUI();},
beforeSend: function(){ $.blockUI()},
success: function(data){ }
});
};
}
</code></pre> | 16,737,459 | 10 | 2 | null | 2013-05-23 08:45:00.467 UTC | 69 | 2019-10-18 13:43:23.72 UTC | 2016-02-26 22:22:16.493 UTC | null | 659,634 | null | 2,243,874 | null | 1 | 195 | angularjs | 380,272 | <p>Here is a way to call controller's function from outside of it: </p>
<pre><code>angular.element(document.getElementById('yourControllerElementID')).scope().get();
</code></pre>
<p>where <code>get()</code> is a function from your controller.</p>
<p>You can switch </p>
<pre><code>document.getElementById('yourControllerElementID')`
</code></pre>
<p>to </p>
<pre><code>$('#yourControllerElementID')
</code></pre>
<p>If you are using jQuery.</p>
<p>Also, if your function means changing anything on your View, you should call </p>
<pre><code>angular.element(document.getElementById('yourControllerElementID')).scope().$apply();
</code></pre>
<p>to apply the changes.</p>
<p>One more thing, you should note is that scopes are initialized after the page is loaded, so calling methods from outside of scope should always be done after the page is loaded. Else you will not get to the scope at all.</p>
<p><strong>UPDATE:</strong></p>
<p>With the latest versions of angular, you should use</p>
<pre><code>angular.element(document.getElementById('yourControllerElementID')).injector().get('$rootScope')
</code></pre>
<p>And yes, this is, in fact, <strong>a bad practice</strong>, but sometimes you just need things done quick and dirty.</p> |
50,709,625 | Link with target="_blank" and rel="noopener noreferrer" still vulnerable? | <p>I see people recommending that whenever one uses <code>target="_blank"</code> in a link to open it in a different window, they should put <code>rel="noopener noreferrer"</code>. I wonder how does this prevent me from using Developer Tools in Chrome, for example, and removing the rel attribute. Then clicking the link...</p>
<p>Is that an easy way to still keep the vulnerability?</p> | 50,709,724 | 7 | 3 | null | 2018-06-05 22:08:25.717 UTC | 51 | 2022-01-09 17:18:00.23 UTC | 2020-06-12 14:44:35.803 UTC | null | 1,919,959 | null | 311,063 | null | 1 | 228 | html | 191,873 | <p>You may be misunderstanding the vulnerability. You can read more about it here: <a href="https://www.jitbit.com/alexblog/256-targetblank---the-most-underestimated-vulnerability-ever/" rel="noreferrer">https://www.jitbit.com/alexblog/256-targetblank---the-most-underestimated-vulnerability-ever/</a></p>
<p>Essentially, adding <code>rel="noopener noreferrer"</code> to links protects your site's users against having the site you've <em>linked to</em> potentially hijacking the browser (via rogue JS).</p>
<p>You're asking about removing that attribute via Developer Tools - that would only potentially expose <em>you</em> (the person tampering with the attribute) to the vulnerability.</p>
<p><strong>Update as of 2021:</strong> All current versions of major browsers now automatically use the behavior of <code>rel="noopener"</code> for any <code>target="_blank"</code> link, nullifying this issue. See more at <a href="https://chromestatus.com/feature/6140064063029248" rel="noreferrer">chromestatus.com</a>.</p> |
26,822,277 | Return HTML from ASP.NET Web API | <p>How to return HTML from ASP.NET MVC Web API controller?</p>
<p>I tried the code below but got compile error since Response.Write is not defined:</p>
<pre><code>public class MyController : ApiController
{
[HttpPost]
public HttpResponseMessage Post()
{
Response.Write("<p>Test</p>");
return Request.CreateResponse(HttpStatusCode.OK);
}
}
</code></pre> | 26,822,588 | 2 | 4 | null | 2014-11-08 21:25:29.057 UTC | 31 | 2019-09-24 22:10:48.377 UTC | 2016-04-27 11:39:52.15 UTC | null | 2,061,604 | null | 742,402 | null | 1 | 154 | c#|html|asp.net-mvc|asp.net-mvc-4|asp.net-web-api | 153,424 | <h2>ASP.NET Core. Approach 1</h2>
<p>If your Controller extends <code>ControllerBase</code> or <code>Controller</code> you can use <code>Content(...)</code> method:</p>
<pre><code>[HttpGet]
public ContentResult Index()
{
return base.Content("<div>Hello</div>", "text/html");
}
</code></pre>
<h2>ASP.NET Core. Approach 2</h2>
<p>If you choose not to extend from <code>Controller</code> classes, you can create new <code>ContentResult</code>:</p>
<pre><code>[HttpGet]
public ContentResult Index()
{
return new ContentResult
{
ContentType = "text/html",
Content = "<div>Hello World</div>"
};
}
</code></pre>
<h2>Legacy ASP.NET MVC Web API</h2>
<p>Return string content with media type <code>text/html</code>:</p>
<pre><code>public HttpResponseMessage Get()
{
var response = new HttpResponseMessage();
response.Content = new StringContent("<div>Hello World</div>");
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
return response;
}
</code></pre> |
10,033,555 | Pass a JSP variable as parameter to javascript function | <p>I have a function defined inside the script tags of head.(in a JSP)
I want to declare a string variable in the JSP and pass it as a parameter to this function</p>
<pre><code><% String uname ="multiple"; %>
<form action="ExampleServlet" method="post" onclick="pagetype(${uname});"><br>
<input type="submit" name="Log in" value="Login" />
</form>
</code></pre>
<p>But this doesn't work.
need Help</p> | 10,033,621 | 2 | 0 | null | 2012-04-05 17:59:04.373 UTC | 1 | 2018-09-26 08:35:26.597 UTC | 2012-04-06 18:16:01.25 UTC | null | 587,642 | null | 1,284,949 | null | 1 | 8 | jsp | 50,127 | <p>You have to use like this</p>
<pre><code><% String uname ="multiple"; %>
<form action="ExampleServlet" method="post" onclick="pagetype('<%=uname%>');"><br>
<input type="submit" name="Log in" value="Login" />
</form>
</code></pre> |
10,043,760 | Count number of columns in a table row | <p>I have a table similar to:</p>
<pre><code><table id="table1">
<tr>
<td><input type="text" value="" /></td>
<td><input type="text" value="" /></td>
<td><input type="text" value="" /></td>
<td><input type="text" value="" /></td>
</tr>
<tr>
<td><input type="text" value="" /></td>
<td><input type="text" value="" /></td>
<td><input type="text" value="" /></td>
<td><input type="text" value="" /></td>
</tr>
<table>
</code></pre>
<p>I want to count the number of td element in a row. I am trying: </p>
<pre><code>document.getElementById('').cells.length;
document.getElementById('').length;
document.getElementById('').getElementsByTagName('td').length;
</code></pre>
<p>It did not show actual result.</p> | 10,043,799 | 10 | 2 | null | 2012-04-06 12:54:31.94 UTC | 12 | 2021-04-19 15:00:43.87 UTC | 2018-09-10 20:22:20.057 UTC | null | 4,370,109 | null | 420,613 | null | 1 | 45 | javascript|html-table | 128,592 | <pre><code>document.getElementById('table1').rows[0].cells.length
</code></pre>
<p>cells is not a property of a table, rows are. Cells is a property of a row though</p> |
9,815,612 | Should I stick only to AWS RDS Automated Backup or DB Snapshots? | <p>I am using AWS RDS for MySQL. When it comes to backup, I understand that Amazon provides two types of backup - automated backup and database (DB) snapshot. The difference is explained <a href="http://aws.amazon.com/rds/faqs/#23">here</a>. However, I am still confused: should I stick to automated backup only or both automated and manual (db snapshots)?</p>
<p>What do you think guys? What's the setup of your own? I heard from others that automated backup is not reliable due to some unrecoverable database when the DB instance is crashed so the DB snapshots are the way to rescue you. If I am to do daily DB snapshots as similar settings to automated backup, I am gonna pay much bunch of bucks.</p>
<p>Hope anyone could enlighten me or advise me the right set up.</p> | 9,827,303 | 3 | 0 | null | 2012-03-22 02:26:13.107 UTC | 11 | 2022-03-23 14:49:06.54 UTC | 2013-07-23 21:53:23.837 UTC | null | 759,866 | null | 1,256,458 | null | 1 | 56 | mysql|amazon-web-services|amazon-rds | 26,050 | <p>From personal experience, I recommend doing both. I have the automated backup set to 8 days, and then I also have a script that will take a snapshot once per day and delete snapshots older than 7 days. The reason is because from what I understand, there are certain situations where you could not restore from the automated backup. For example, if you accidentally deleted your RDS instance and did not take a final snapshot, you would not be able to access the automated backups that were done. But it is also good to have the automated backups turned on because that will provide you the point-in-time restore.</p>
<p>Hope this helps.</p>
<p><strong>EDIT</strong></p>
<p>To answer your comment, I use a certain naming convention when my script creates the snapshots. Something like:</p>
<p>autosnap-<em>instancename</em>-2012-03-23</p>
<p>When it goes to do the cleanup, it retrieves all the snapshots, looks for that naming convention, parses the date, and deletes any older than a certain date.</p>
<p>I think you could also look at the snapshot creation date, but this is just how I ended up doing it.</p> |
28,259,636 | Is this a bug in Files.lines(), or am I misunderstanding something about parallel streams? | <p>Environment: Ubuntu x86_64 (14.10), Oracle JDK 1.8u25</p>
<p>I try and use a parallel stream of <a href="http://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#lines-java.nio.file.Path-java.nio.charset.Charset-" rel="nofollow noreferrer"><code>Files.lines()</code></a> but I want to <a href="http://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#skip-long-" rel="nofollow noreferrer"><code>.skip()</code></a> the first line (it's a CSV file with a header). Therefore I try and do this:</p>
<pre><code>try (
final Stream<String> stream = Files.lines(thePath, StandardCharsets.UTF_8)
.skip(1L).parallel();
) {
// etc
}
</code></pre>
<p>But then one column failed to parse to an int...</p>
<p>So I tried some simple code. The file is question is dead simple:</p>
<pre><code>$ cat info.csv
startDate;treeDepth;nrMatchers;nrLines;nrChars;nrCodePoints;nrNodes
1422758875023;34;54;151;4375;4375;27486
$
</code></pre>
<p>And the code is equally simple:</p>
<pre><code>public static void main(final String... args)
{
final Path path = Paths.get("/home/fge/tmp/dd/info.csv");
Files.lines(path, StandardCharsets.UTF_8).skip(1L).parallel()
.forEach(System.out::println);
}
</code></pre>
<p>And I <em>systematically</em> get the following result (OK, I have only run it something around 20 times):</p>
<pre><code>startDate;treeDepth;nrMatchers;nrLines;nrChars;nrCodePoints;nrNodes
</code></pre>
<p>What am I missing here?</p>
<hr>
<p><strong>EDIT</strong> It seems like the problem, or misunderstanding, is much more rooted than that (the two examples below were cooked up by a fellow on FreeNode's ##java):</p>
<pre><code>public static void main(final String... args)
{
new BufferedReader(new StringReader("Hello\nWorld")).lines()
.skip(1L).parallel()
.forEach(System.out::println);
final Iterator<String> iter
= Arrays.asList("Hello", "World").iterator();
final Spliterator<String> spliterator
= Spliterators.spliteratorUnknownSize(iter, Spliterator.ORDERED);
final Stream<String> s
= StreamSupport.stream(spliterator, true);
s.skip(1L).forEach(System.out::println);
}
</code></pre>
<p>This prints:</p>
<pre><code>Hello
Hello
</code></pre>
<p>Uh.</p>
<p>@Holger suggested that this happens for any stream which is <code>ORDERED</code> and not <code>SIZED</code> with this other sample:</p>
<pre><code>Stream.of("Hello", "World")
.filter(x -> true)
.parallel()
.skip(1L)
.forEach(System.out::println);
</code></pre>
<p>Also, it stems from all the discussion which already took place that the problem (if it is one?) is with <code>.forEach()</code> (as <a href="https://stackoverflow.com/questions/28259636/is-this-a-bug-in-files-lines-or-am-i-misunderstanding-something-about-paralle#comment44876969_28259636">@SotiriosDelimanolis first pointed out</a>).</p> | 32,611,920 | 5 | 10 | null | 2015-02-01 04:56:01.617 UTC | 15 | 2016-02-10 13:12:15.78 UTC | 2017-05-23 11:54:47.53 UTC | null | -1 | null | 1,093,528 | null | 1 | 36 | java|parallel-processing|java-8|java-stream | 3,359 | <p>Since the current state of the issue is quite the opposite of the earlier statements made here, it should be noted, that there is now an <a href="https://stackoverflow.com/a/30916033/2711488">explicit statement by Brian Goetz</a> about the back-propagation of the unordered characteristic past a <code>skip</code> operation is considered a bug. <a href="https://stackoverflow.com/questions/30843279/stream-skip-behavior-with-unordered-terminal-operation?lq=1#comment49971789_30916033">It’s also stated</a> that it is now considered to have no back-propagation of the ordered-ness of a terminal operation at all.</p>
<p>There is also a <a href="https://bugs.openjdk.java.net/browse/JDK-8129120" rel="noreferrer">related bug report, JDK-8129120</a> whose status is “fixed in Java 9” and it’s <a href="https://bugs.openjdk.java.net/browse/JDK-8129945" rel="noreferrer">backported to Java 8, update 60</a></p>
<p>I did some tests with <code>jdk1.8.0_60</code> and it seems that the implementation now indeed exhibits the more intuitive behavior.</p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.