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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
579,374 | What does the dot-slash do to PHP include calls? | <p>A. What does this do?</p>
<pre><code>require ("./file.php");
</code></pre>
<p>B. in comparison to this?</p>
<pre><code>require ("file.php");
</code></pre>
<hr>
<p>(Its <strong>not</strong> up-one-directory.. which would be)</p>
<pre><code>require ("../file.php");
</code></pre> | 579,398 | 7 | 0 | null | 2009-02-23 21:11:20.083 UTC | 8 | 2022-09-22 19:38:30.077 UTC | null | null | null | Jeremy Rudd | 41,021 | null | 1 | 40 | php|url|include|relative-path | 15,633 | <p><code>./</code> is the <em>current</em> directory. It is largely the same as just <code>file.php</code>, but in many cases (this one included) it doesn't check any standard places PHP might look for a file, instead checking <em>only</em> the current directory.</p>
<p>From the <a href="http://us.php.net/manual/en/function.include.php" rel="noreferrer">PHP documentation</a> (notice the last sentence):</p>
<blockquote>
<p>Files for including are first looked for in each include_path entry relative to the current working directory, and then in the directory of current script. E.g. if your include_path is libraries, current working directory is /www/, you included include/a.php and there is include "b.php" in that file, b.php is first looked in /www/libraries/ and then in /www/include/. If filename begins with ./ or ../, it is looked only in the current working directory.</p>
</blockquote> |
713,918 | Replace multiple characters in a string in Objective-C? | <p>In PHP I can do this:</p>
<pre><code>$new = str_replace(array('/', ':', '.'), '', $new);
</code></pre>
<p>...to replace all instances of the characters / : . with a blank string (to remove them)</p>
<p>Can I do this easily in Objective-C? Or do I have to roll my own?</p>
<p>Currently I am doing multiple calls to <code>stringByReplacingOccurrencesOfString</code>:</p>
<pre><code>strNew = [strNew stringByReplacingOccurrencesOfString:@"/" withString:@""];
strNew = [strNew stringByReplacingOccurrencesOfString:@":" withString:@""];
strNew = [strNew stringByReplacingOccurrencesOfString:@"." withString:@""];
</code></pre>
<p>Thanks,<br>
matt</p> | 714,009 | 8 | 0 | null | 2009-04-03 13:32:33.837 UTC | 14 | 2017-06-07 14:26:14.57 UTC | null | null | null | matt | 28,290 | null | 1 | 48 | iphone|objective-c|string|replace | 78,755 | <p>A somewhat inefficient way of doing this:</p>
<pre><code>NSString *s = @"foo/bar:baz.foo";
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"/:."];
s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""];
NSLog(@"%@", s); // => foobarbazfoo
</code></pre>
<p>Look at <code>NSScanner</code> and <code>-[NSString rangeOfCharacterFromSet: ...]</code> if you want to do this a bit more efficiently.</p> |
272,360 | Does opacity:0 have exactly the same effect as visibility:hidden | <p>If so, does it effectively deprecate the <code>visibility</code> property?</p>
<p>(I realize that Internet Explorer does not yet support this CSS2 property.)
<br/>
<a href="http://en.wikipedia.org/wiki/Comparison_of_layout_engines_(CSS)#Properties" rel="noreferrer">Comparisons of layout engines</a></p>
<p><a href="https://stackoverflow.com/questions/133051/what-is-the-difference-between-visibilityhidden-and-displaynone">See also: What is the difference between visibility:hidden and display:none</a></p> | 273,076 | 9 | 3 | null | 2008-11-07 15:10:44.613 UTC | 61 | 2020-06-11 02:27:56.78 UTC | 2017-05-23 12:34:42.373 UTC | Chris Noe | -1 | Chris Noe | 14,749 | null | 1 | 131 | html|css | 68,570 | <p>Here is a compilation of verified information from the various answers.</p>
<p>Each of these CSS properties is unique. In addition to rendering an element not visible, they have the following additional effect(s):</p>
<ol>
<li><strong>Collapses</strong> the space that the element would normally occupy</li>
<li>Responds to <strong>events</strong> (e.g., click, keypress)</li>
<li>Participates in the <strong>taborder</strong></li>
</ol>
<pre>
collapse events taborder
opacity: 0 No Yes Yes
visibility: hidden No No No
visibility: collapse Yes* No No
display: none Yes No No
* Yes inside a table element, otherwise No.
</pre> |
621,577 | How do I monitor clipboard changes in C#? | <p>Is there a clipboard changed or updated event that i can access through C#?</p> | 621,582 | 10 | 4 | null | 2009-03-07 09:18:04.397 UTC | 62 | 2022-01-14 15:36:41.037 UTC | 2021-02-26 18:39:33.963 UTC | Nick | 3,195,477 | Sevki | 68,438 | null | 1 | 97 | c#|events|clipboard | 75,922 | <p>I think you'll have to use some p/invoke:</p>
<pre><code>[DllImport("User32.dll", CharSet=CharSet.Auto)]
public static extern IntPtr SetClipboardViewer(IntPtr hWndNewViewer);
</code></pre>
<p>See <a href="https://web.archive.org/web/20131104125500/http://www.radsoftware.com.au/articles/clipboardmonitor.aspx" rel="noreferrer">this article on how to set up a clipboard monitor in c#</a></p>
<p>Basically you register your app as a clipboard viewer using</p>
<pre><code>_ClipboardViewerNext = SetClipboardViewer(this.Handle);
</code></pre>
<p>and then you will recieve the <code>WM_DRAWCLIPBOARD</code> message, which you can handle by overriding <code>WndProc</code>:</p>
<pre><code>protected override void WndProc(ref Message m)
{
switch ((Win32.Msgs)m.Msg)
{
case Win32.Msgs.WM_DRAWCLIPBOARD:
// Handle clipboard changed
break;
// ...
}
}
</code></pre>
<p>(There's more to be done; passing things along the clipboard chain and unregistering your view, but you can get that from <a href="https://web.archive.org/web/20131104125500/http://www.radsoftware.com.au/articles/clipboardmonitor.aspx" rel="noreferrer">the article</a>)</p> |
285,289 | Exit codes in Python | <p>I got a message saying <code>script xyz.py returned exit code 0</code>. What does this mean?</p>
<p>What do the exit codes in Python mean? How many are there? Which ones are important?</p> | 285,326 | 13 | 2 | null | 2008-11-12 20:43:08.51 UTC | 51 | 2020-12-20 22:31:50.063 UTC | 2012-10-15 09:11:50.5 UTC | EnderMB | 225,037 | sundeep | 19,731 | null | 1 | 303 | python|exit-code | 664,107 | <p>You're looking for calls to <a href="https://docs.python.org/2/library/sys.html#sys.exit" rel="noreferrer"><code>sys.exit()</code></a> in the script. The argument to that method is returned to the environment as the exit code.</p>
<p>It's fairly likely that the script is never calling the <em>exit</em> method, and that 0 is the default exit code.</p> |
1,308,194 | Determine credit card type by number? | <p>Can credit card type be determined solely from the credit card number?</p>
<p>Is this recommended or should we always ask client for the type of credit card they're using?</p>
<p>I Googled about it and found this algorithm: <a href="http://cuinl.tripod.com/Tips/o-1.htm" rel="nofollow noreferrer">http://cuinl.tripod.com/Tips/o-1.htm</a> , is this reliable?</p> | 1,308,203 | 15 | 2 | null | 2009-08-20 19:03:07.927 UTC | 28 | 2019-04-10 10:32:00 UTC | 2019-04-10 10:32:00 UTC | null | 141,661 | null | 35,634 | null | 1 | 67 | e-commerce|credit-card | 54,481 | <p>Yes, the site you mentioned is correct. Many sites, incl. Google Checkout I believe, rely on automatic detection of the card type. It's convenient, makes the UI less cluttered (one less input box) and saves time. Go ahead!</p> |
772,388 | C# How can I test a file is a jpeg? | <p>Using C# how can I test a file is a jpeg? Should I check for a .jpg extension?</p>
<p>Thanks</p> | 772,492 | 16 | 0 | null | 2009-04-21 12:45:03.507 UTC | 18 | 2019-02-11 20:17:29.01 UTC | null | null | null | Scott | null | null | 1 | 36 | c#|jpeg | 37,905 | <p>Several options:</p>
<p>You can check for the file extension:</p>
<pre><code>static bool HasJpegExtension(string filename)
{
// add other possible extensions here
return Path.GetExtension(filename).Equals(".jpg", StringComparison.InvariantCultureIgnoreCase)
|| Path.GetExtension(filename).Equals(".jpeg", StringComparison.InvariantCultureIgnoreCase);
}
</code></pre>
<p>or check for the correct <a href="https://web.archive.org/web/20100212180433/http://www.obrador.com/essentialjpeg/headerinfo.htm" rel="noreferrer">magic number</a> in the header of the file:</p>
<pre><code>static bool HasJpegHeader(string filename)
{
using (BinaryReader br = new BinaryReader(File.Open(filename, FileMode.Open, FileAccess.Read)))
{
UInt16 soi = br.ReadUInt16(); // Start of Image (SOI) marker (FFD8)
UInt16 marker = br.ReadUInt16(); // JFIF marker (FFE0) or EXIF marker(FFE1)
return soi == 0xd8ff && (marker & 0xe0ff) == 0xe0ff;
}
}
</code></pre>
<p>Another option would be to load the image and check for the correct type. However, this is less efficient (unless you are going to load the image anyway) but will probably give you the most reliable result (Be aware of the additional cost of loading and decompression as well as possible exception handling):</p>
<pre><code>static bool IsJpegImage(string filename)
{
try
{
using (System.Drawing.Image img = System.Drawing.Image.FromFile(filename))
{
// Two image formats can be compared using the Equals method
// See http://msdn.microsoft.com/en-us/library/system.drawing.imaging.imageformat.aspx
//
return img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
catch (OutOfMemoryException)
{
// Image.FromFile throws an OutOfMemoryException
// if the file does not have a valid image format or
// GDI+ does not support the pixel format of the file.
//
return false;
}
}
</code></pre> |
233,596 | Best Practice for Forcing Garbage Collection in C# | <p>In my experience it seems that most people will tell you that it is unwise to force a garbage collection but in some cases where you are working with large objects that don't always get collected in the 0 generation but where memory is an issue, is it ok to force the collect? Is there a best practice out there for doing so?</p> | 233,647 | 17 | 0 | null | 2008-10-24 13:49:43.64 UTC | 39 | 2022-07-01 15:28:00.833 UTC | null | null | null | Echostorm | 12,862 | null | 1 | 122 | c#|.net|garbage-collection | 159,391 | <p>The best practise is to not force a garbage collection.</p>
<p>According to MSDN:</p>
<blockquote>
<p>"It is possible to force garbage
collection by calling Collect, but
most of the time, this should be
avoided because it may create
performance issues. "</p>
</blockquote>
<p>However, if you can reliably test your code to confirm that calling Collect() won't have a negative impact then go ahead...</p>
<p>Just try to make sure objects are cleaned up when you no longer need them. If you have custom objects, look at using the "using statement" and the IDisposable interface.</p>
<p>This link has some good practical advice with regards to freeing up memory / garbage collection etc:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/66x5fx1b.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/66x5fx1b.aspx</a></p> |
1,005,473 | Must Dependency Injection come at the expense of Encapsulation? | <p>If I understand correctly, the typical mechanism for Dependency Injection is to inject either through a class' constructor or through a public property (member) of the class. </p>
<p>This exposes the dependency being injected and violates the OOP principle of encapsulation.</p>
<p>Am I correct in identifying this tradeoff? How do you deal with this issue? </p>
<p><em>Please also see my answer to my own question below.</em></p> | 1,800,843 | 21 | 5 | null | 2009-06-17 06:58:01.643 UTC | 54 | 2018-03-22 19:16:06.217 UTC | 2009-06-28 16:13:32.543 UTC | null | 33,404 | null | 33,404 | null | 1 | 139 | oop|dependency-injection|inversion-of-control|encapsulation | 12,228 | <p>There is another way of looking at this issue that you might find interesting.</p>
<p>When we use IoC/dependency injection, we're not using OOP concepts. Admittedly we're using an OO language as the 'host', but the ideas behind IoC come from component-oriented software engineering, not OO.</p>
<p>Component software is all about managing dependencies - an example in common use is .NET's Assembly mechanism. Each assembly publishes the list of assemblies that it references, and this makes it much easier to pull together (and validate) the pieces needed for a running application.</p>
<p>By applying similar techniques in our OO programs via IoC, we aim to make programs easier to configure and maintain. Publishing dependencies (as constructor parameters or whatever) is a key part of this. Encapsulation doesn't really apply, as in the component/service oriented world, there is no 'implementation type' for details to leak from.</p>
<p>Unfortunately our languages don't currently segregate the fine-grained, object-oriented concepts from the coarser-grained component-oriented ones, so this is a distinction that you have to hold in your mind only :)</p> |
614,671 | Commands out of sync; you can't run this command now | <p>I am trying to execute my PHP code, which calls two MySQL queries via mysqli, and get the error "Commands out of sync; you can't run this command now".</p>
<p>Here is the code I am using</p>
<pre><code><?php
$con = mysqli_connect("localhost", "user", "password", "db");
if (!$con) {
echo "Can't connect to MySQL Server. Errorcode: %s\n". Mysqli_connect_error();
exit;
}
$con->query("SET NAMES 'utf8'");
$brand ="o";
$countQuery = "SELECT ARTICLE_NO FROM AUCTIONS WHERE upper(ARTICLE_NAME) LIKE % ? %";
if ($numRecords = $con->prepare($countQuery)) {
$numRecords->bind_param("s", $brand);
$numRecords->execute();
$data = $con->query($countQuery) or die(print_r($con->error));
$rowcount = $data->num_rows;
$rows = getRowsByArticleSearch("test", "Auctions", " ");
$last = ceil($rowcount/$page_rows);
} else {
print_r($con->error);
}
foreach ($rows as $row) {
$pk = $row['ARTICLE_NO'];
echo '<tr>' . "\n";
echo '<td><a href="#" onclick="updateByPk(\'Layer2\', \'' . $pk . '\')">'.$row['USERNAME'].'</a></td>' . "\n";
echo '<td><a href="#" onclick="updateByPk(\'Layer2\', \'' . $pk . '\')">'.$row['shortDate'].'</a></td>' . "\n";
echo '<td><a href="#" onclick="deleterec(\'Layer2\', \'' . $pk . '\')">DELETE RECORD</a></td>' . "\n";
echo '</tr>' . "\n";
}
function getRowsByArticleSearch($searchString, $table, $max) {
$con = mysqli_connect("localhost", "user", "password", "db");
$recordsQuery = "SELECT ARTICLE_NO, USERNAME, ACCESSSTARTS, ARTICLE_NAME, date_format(str_to_date(ACCESSSTARTS, '%d/%m/%Y %k:%i:%s'), '%d %m %Y' ) AS shortDate FROM AUCTIONS WHERE upper(ARTICLE_NAME) LIKE '%?%' ORDER BY str_to_date(ACCESSSTARTS, '%d/%m/%Y %k:%i:%s')" . $max;
if ($getRecords = $con->prepare($recordsQuery)) {
$getRecords->bind_param("s", $searchString);
$getRecords->execute();
$getRecords->bind_result($ARTICLE_NO, $USERNAME, $ACCESSSTARTS, $ARTICLE_NAME, $shortDate);
while ($getRecords->fetch()) {
$result = $con->query($recordsQuery);
$rows = array();
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
}
}
</code></pre>
<p>I have tried reading up on this, but I am unsure of what to do. I have read about store result and free result, however these have made no difference when using them. I am unsure at exactly which point this error is being caused, and would like to know why it is being caused, and how to fix it.</p>
<p>Going by my debug statements, the first if loop for countQuery is not even being entered, because of an error in my sql syntax near near <code>'% ? %'</code>. However if I just select <code>*</code> instead of trying to limit based on a LIKE clause, I still get the command out of sync error.</p> | 614,741 | 23 | 0 | null | 2009-03-05 13:05:32.323 UTC | 22 | 2022-03-19 04:48:32.447 UTC | 2012-10-23 13:01:44.197 UTC | Iraimbilanja | 815,724 | user1253538 | 1,246,613 | null | 1 | 113 | php|sql|mysql|mysqli | 250,492 | <p>You can't have two simultaneous queries because mysqli uses unbuffered queries by default (for prepared statements; it's the opposite for vanilla <code>mysql_query</code>). You can either fetch the first one into an array and loop through that, or tell mysqli to buffer the queries (using <a href="http://php.net/manual/en/mysqli-stmt.store-result.php" rel="noreferrer"><code>$stmt->store_result()</code></a>).</p>
<p>See <a href="http://php.net/mysqli_query" rel="noreferrer">here</a> for details.</p> |
222,598 | How do I clone a generic list in C#? | <p>I have a generic list of objects in C#, and wish to clone the list. The items within the list are cloneable, but there doesn't seem to be an option to do <code>list.Clone()</code>.</p>
<p>Is there an easy way around this?</p> | 222,640 | 28 | 7 | null | 2008-10-21 16:47:05.823 UTC | 133 | 2022-02-17 15:14:07.1 UTC | 2012-12-03 06:26:03.35 UTC | null | 63,550 | null | 30,025 | null | 1 | 714 | c#|generics|list|clone | 802,675 | <p>You can use an extension method.</p>
<pre><code>static class Extensions
{
public static IList<T> Clone<T>(this IList<T> listToClone) where T: ICloneable
{
return listToClone.Select(item => (T)item.Clone()).ToList();
}
}
</code></pre> |
6,834,037 | Initialize a long in Java | <p><a href="http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html" rel="noreferrer">Primitive Data Types - oracle doc</a> says the range of <strong><code>long</code></strong> in Java is <code>-9,223,372,036,854,775,808</code> to <code>9,223,372,036,854,775,807</code>.
But when I do something like this in my eclipse</p>
<pre><code>long i = 12345678910;
</code></pre>
<p>it shows me "<code>The literal 12345678910 of type int is out of range</code>" error.</p>
<p><strong>There are 2 questions.</strong></p>
<p>1) How do I initialize the <strong><code>long</code></strong> with the value <code>12345678910</code>?</p>
<p>2) Are all numeric literals by default of type <strong><code>int</code></strong>? </p> | 6,834,049 | 4 | 2 | null | 2011-07-26 17:28:11.303 UTC | 29 | 2017-03-20 22:28:52.247 UTC | 2014-06-02 05:45:25.947 UTC | null | 432,903 | null | 863,968 | null | 1 | 239 | java|long-integer | 496,069 | <ol>
<li>You should add <code>L</code>: <code>long i = 12345678910L;</code>.</li>
<li>Yes.</li>
</ol>
<p>BTW: it doesn't have to be an upper case L, but lower case is confused with <code>1</code> many times :).</p> |
6,471,549 | Avoiding "MySQL server has gone away" on infrequently used Python / Flask server with SQLAlchemy | <p>How can Flask / SQLAlchemy be configured to create a new database connection if one is not present?</p>
<p>I have an infrequently visited Python / Flask server which uses SQLAlchemy. It gets visited every couple of days, and on the first visit it often throws a "MySQL server has gone away" error. Subsequent page views are fine, but it looks unprofessional to have this initial error.</p>
<p>I'd like to know the correct way to handle this - advice like "make a really long time out", which would be about 4 days long in this case, doesn't seem correct. How can I test for the lack of a database connection and create one if needed?</p> | 6,473,271 | 7 | 0 | null | 2011-06-24 17:34:12.683 UTC | 28 | 2019-11-12 15:03:07.34 UTC | 2013-09-04 17:11:54.657 UTC | null | 2,165,163 | null | 160,406 | null | 1 | 65 | python|mysql|sqlalchemy|flask|database-connection | 34,208 | <p>I've had trouble with this before, and found that the way to handle it is by not keeping sessions around. The trouble is you are trying to keep a connection open for way too long. Instead, use a thread local scoped session like so either in <code>__init__.py</code> or in a utility package that you import everywhere:</p>
<pre><code>from sqlalchemy.orm import scoped_session, sessionmaker
Session = scoped_session( sessionmaker() )
</code></pre>
<p>Then set up your engines and metadata once. This allows you to skip configuration mechanics every time you connect/disconnect. After that, you can do your db work like this:</p>
<pre><code>session = Session()
someObject = session.query( someMappedClass ).get( someId )
# use session like normal ...
session.close()
</code></pre>
<p>If you want to hold on to old objects and you don't want to leave your session open, then you can use the above pattern and reuse old objects like this:</p>
<pre><code>session = Session()
someObject = session.merge( someObject )
# more db stuff
session.close()
</code></pre>
<p>The point is, you want to open your session, do your work, then close your session. This avoids timeouts very well. There are lots of options for .merge and .add that allow you to either include changes you've made to detached objects or to load new data from the db. The docs are very verbose, but once you know what you are looking for it might be a little easier to find.</p>
<p>To actually get all the way there and prevent the MySQL from "going away", you need to solve the issue of your connection pool keeping connections open too long and checking out an old connection for you. </p>
<p>To get a fresh connection, you can set the <code>pool_recycle</code> option in your <code>create_engine</code> call. Set this <code>pool_recycle</code> to the number of seconds of time in the connection pool between checkouts that you want a new connection to be created instead of an existing connection to be returned.</p> |
41,657,428 | Getting null with @pathparam and @requestmapping | <p>I am using spring-boot 1.4.3.RELEASE for creating web services, whereas, while giving the request with <code>http://localhost:7211/person/get/ram</code>, I am getting null for the id property</p>
<pre><code>@RequestMapping(value="/person/get/{id}", method=RequestMethod.GET, produces="application/json")
public @ResponseBody Person getPersonById(@PathParam("id") String id) {
return personService.getPersonById(id);
}
</code></pre>
<p>Can you please suggest me, is there anything I missed.</p> | 41,657,460 | 4 | 1 | null | 2017-01-15 03:12:33.28 UTC | 3 | 2020-04-24 09:55:22.377 UTC | null | null | null | null | 4,242,765 | null | 1 | 23 | spring-boot | 43,677 | <p>The annotation to get path variable is <strong>@PathVariable</strong>. It looks like you have used @PathParam instead which is incorrect. </p>
<p>Check this out for more details:</p>
<p><a href="https://stackoverflow.com/a/13718502/3494368">requestparam-vs-pathvariable</a></p> |
15,811,411 | High CPU Utilization in java application - why? | <p>I have a Java Application (web-based) that at times shows very high CPU Utilization (almost 90%) for several hours. Linux <code>TOP</code> command shows this. On application restart, the problem goes away.</p>
<p><strong><em>So to investigate</em></strong>:</p>
<p>I take Thread Dump to find what threads are doing. Several Threads are found in <code>'RUNNABLE'</code> state, some in few other states. On taking repeated Thread Dumps, i do see some threads that are always present in <code>'RUNNABLE'</code> state. So, they appear to be the culprit.</p>
<p>But I am unable to tell for sure, which Thread is hogging the CPU or has gone into a infinite loop (thereby causing high CPU util).</p>
<p>Logs don't necessarily help, as the offending code may not be logging anything.</p>
<p><strong><em>How do I investigate - What part of the application or what-thread is causing High CPU Utilization? - Any other ideas?</em></strong> </p> | 15,815,829 | 7 | 4 | null | 2013-04-04 12:38:11.207 UTC | 32 | 2021-02-20 15:11:04.56 UTC | 2017-05-28 10:25:03.713 UTC | null | 3,118,209 | null | 974,169 | null | 1 | 57 | java|multithreading|performance|web-applications|cpu-usage | 120,722 | <p>If a profiler is not applicable in your setup, you may try to identify the thread following steps in <a href="http://web.archive.org/web/20190403090107/http://code.nomad-labs.com/2010/11/18/identifying-which-java-thread-is-consuming-most-cpu/" rel="noreferrer">this post</a>.</p>
<p>Basically, there are three steps:</p>
<ol>
<li>run <code>top -H</code> and get PID of the thread with highest CPU.</li>
<li>convert the PID to hex.</li>
<li>look for thread with the matching HEX PID in your thread dump.</li>
</ol> |
15,808,719 | Controlling the camera to take pictures in portrait doesn't rotate the final images | <p>I'm trying to controlling the Android camera to take pictures in a portrait app, but when I save the picture, it's in landscape. I've rotated the image 90 grades with <a href="http://developer.android.com/reference/android/hardware/Camera.html#setDisplayOrientation%28int%29" rel="noreferrer"><code>setCameraDisplayOrientation()</code></a> method, but doesn't work.</p>
<p>Then I've found this <a href="https://stackoverflow.com/questions/11023696/setrotation90-to-take-picture-in-portrait-mode-does-not-work-on-samsung-device">post</a> but the <code>TAG_ORIENTATION</code> is <code>0</code> (undefined). If I catch this value and apply a rotation value, doesn't work either. </p>
<p>How I can take a photo in portrait and save it with a good orientation?</p>
<pre><code> /** Initializes the back/front camera */
private boolean initPhotoCamera() {
try {
camera = getCameraInstance(selected_camera);
Camera.Parameters parameters = camera.getParameters();
// parameters.setPreviewSize(width_video, height_video);
// parameters.set("orientation", "portrait");
// parameters.set("rotation", 1);
// camera.setParameters(parameters);
checkCameraFlash(parameters);
// camera.setDisplayOrientation( 0);
setCameraDisplayOrientation(selected_camera, camera);
surface_view.getHolder().setFixedSize(width_video, height_video);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(width_video, height_video);
surface_view.setLayoutParams(lp);
camera.lock();
surface_holder = surface_view.getHolder();
surface_holder.addCallback(this);
surface_holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
setPreviewCamera();
} catch (Exception e) {
Log.v("RecordVideo", "Could not initialize the Camera");
return false;
}
return true;
}
public void setCameraDisplayOrientation(int cameraId, Camera camera) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(cameraId, info);
int rotation = getWindowManager().getDefaultDisplay().getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0: degrees = 0; break;
case Surface.ROTATION_90: degrees = 90; break;
case Surface.ROTATION_180: degrees = 180; break;
case Surface.ROTATION_270: degrees = 270; break;
}
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (info.orientation - degrees + 360) % 360;
}
camera.setDisplayOrientation(result);
}
public static Bitmap rotate(Bitmap bitmap, int degree) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Matrix mtx = new Matrix();
// mtx.postRotate(degree);
mtx.setRotate(degree);
return Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
}
@Override
public void onPictureTaken(byte[] data, Camera camera) {
String timeStamp = Calendar.getInstance().getTime().toString();
output_file_name = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + File.separator + timeStamp + ".jpeg";
File pictureFile = new File(output_file_name);
if (pictureFile.exists()) {
pictureFile.delete();
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
Bitmap realImage = BitmapFactory.decodeFile(output_file_name);
ExifInterface exif=new ExifInterface(pictureFile.toString());
Log.d("EXIF value", exif.getAttribute(ExifInterface.TAG_ORIENTATION));
if(exif.getAttribute(ExifInterface.TAG_ORIENTATION).equalsIgnoreCase("6")){
realImage= rotate(realImage, 90);
} else if(exif.getAttribute(ExifInterface.TAG_ORIENTATION).equalsIgnoreCase("8")){
realImage= rotate(realImage, 270);
} else if(exif.getAttribute(ExifInterface.TAG_ORIENTATION).equalsIgnoreCase("3")){
realImage= rotate(realImage, 180);
} else if(exif.getAttribute(ExifInterface.TAG_ORIENTATION).equalsIgnoreCase("0")){
realImage= rotate(realImage, 45);
}
boolean bo = realImage.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
Log.d("Info", bo + "");
} catch (FileNotFoundException e) {
Log.d("Info", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("TAG", "Error accessing file: " + e.getMessage());
}
}
</code></pre> | 15,812,722 | 9 | 1 | null | 2013-04-04 10:32:39.333 UTC | 34 | 2022-04-05 10:58:22.63 UTC | 2017-05-23 12:10:11.31 UTC | null | -1 | null | 916,366 | null | 1 | 60 | android|android-camera|android-orientation | 59,917 | <p>The problem is when I saved the image I didn't do well.</p>
<pre><code>@Override
public void onPictureTaken(byte[] data, Camera camera) {
String timeStamp = new SimpleDateFormat( "yyyyMMdd_HHmmss").format( new Date( ));
output_file_name = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + File.separator + timeStamp + ".jpeg";
File pictureFile = new File(output_file_name);
if (pictureFile.exists()) {
pictureFile.delete();
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
Bitmap realImage = BitmapFactory.decodeByteArray(data, 0, data.length);
ExifInterface exif=new ExifInterface(pictureFile.toString());
Log.d("EXIF value", exif.getAttribute(ExifInterface.TAG_ORIENTATION));
if(exif.getAttribute(ExifInterface.TAG_ORIENTATION).equalsIgnoreCase("6")){
realImage= rotate(realImage, 90);
} else if(exif.getAttribute(ExifInterface.TAG_ORIENTATION).equalsIgnoreCase("8")){
realImage= rotate(realImage, 270);
} else if(exif.getAttribute(ExifInterface.TAG_ORIENTATION).equalsIgnoreCase("3")){
realImage= rotate(realImage, 180);
} else if(exif.getAttribute(ExifInterface.TAG_ORIENTATION).equalsIgnoreCase("0")){
realImage= rotate(realImage, 90);
}
boolean bo = realImage.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
((ImageView) findViewById(R.id.imageview)).setImageBitmap(realImage);
Log.d("Info", bo + "");
} catch (FileNotFoundException e) {
Log.d("Info", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("TAG", "Error accessing file: " + e.getMessage());
}
}
public static Bitmap rotate(Bitmap bitmap, int degree) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Matrix mtx = new Matrix();
// mtx.postRotate(degree);
mtx.setRotate(degree);
return Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
}
</code></pre> |
10,854,119 | calculate business days including holidays | <p>i need to calculate the business days between two dates.
ex : we have holiday(in USA) on july4th. so if my dates are
date1 = 07/03/2012
date2 = 07/06/2012</p>
<p>no of business days b/w these dates should be 1 since july4th is holiday.</p>
<p>i have a below method to calclulate the business days which will only counts week ends but not holidays.
is there any way to calculate holidays also....please help me on this.</p>
<pre><code> public static int getWorkingDaysBetweenTwoDates(Date startDate, Date endDate) {
Calendar startCal;
Calendar endCal;
startCal = Calendar.getInstance();
startCal.setTime(startDate);
endCal = Calendar.getInstance();
endCal.setTime(endDate);
int workDays = 0;
//Return 0 if start and end are the same
if (startCal.getTimeInMillis() == endCal.getTimeInMillis()) {
return 0;
}
if (startCal.getTimeInMillis() > endCal.getTimeInMillis()) {
startCal.setTime(endDate);
endCal.setTime(startDate);
}
do {
startCal.add(Calendar.DAY_OF_MONTH, 1);
if (startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY
&& startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
++workDays;
}
} while (startCal.getTimeInMillis() < endCal.getTimeInMillis());
return workDays;
}
</code></pre> | 10,854,403 | 5 | 4 | null | 2012-06-01 16:31:04.3 UTC | 4 | 2020-06-26 20:30:00.993 UTC | null | null | null | null | 766,816 | null | 1 | 11 | java|date|calendar | 41,149 | <p>Let's pretend you have a list containing all the holidays, as you mentioned.</p>
<pre><code>ArrayList<Integer> holidays = ...
</code></pre>
<p>Just add a condition to your <code>if</code> condition in your <code>do-while</code>:</p>
<pre><code>do {
startCal.add(Calendar.DAY_OF_MONTH, 1);
if (startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY
&& startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY
&& !holidays.contains((Integer) startCal.get(Calendar.DAY_OF_YEAR))) {
++workDays;
}
} while (startCal.getTimeInMillis() < endCal.getTimeInMillis());
</code></pre>
<p>For simplicity's sake, I've assumed <code>holiday</code> contains dates in the format identical to <code>Calendar.DAY_OF_YEAR</code>.</p> |
31,924,396 | Why shared_from_this can't be used in constructor from technical standpoint? | <p>In <a href="https://rads.stackoverflow.com/amzn/click/com/0321623215" rel="noreferrer" rel="nofollow noreferrer">the book <em>The C++ Standard Library</em></a> at page 91 I have read this about <code>shared_from_this()</code>:</p>
<blockquote>
<p>The problem is that <code>shared_ptr</code> stores itself in a private member of
<code>Person</code>’s base class, <code>enable_shared_from_this<></code>, <strong>at the end</strong> of
the construction of the Person.</p>
</blockquote>
<p>The relevant code snippet from the book is:</p>
<pre><code>class Person : public std::enable_shared_from_this<Person> {
...
};
</code></pre>
<p>I don't understand two things here: </p>
<ol>
<li>who is this <code>shared_ptr</code> which stores itself?</li>
<li>how he can store itself anywhere at the end of the construction of <code>Person</code>? I think construction of <code>Person</code> ends up with the last statement of its constructor which written by me.</li>
</ol>
<p>I understand that there is <code>weak_ptr</code> which hasn't been initialized yet.</p>
<p>EDIT:
Thanks to Angew! <code>shared_from_this</code> will work only after first <code>shared_ptr</code> to <code>Person</code> was created. This <code>shared_ptr</code> will check if <code>Person</code> class inherited from <code>enable_shared_from_this</code>, and if yes then initialize its internal <code>weak_ptr</code>.</p> | 31,924,590 | 1 | 2 | null | 2015-08-10 16:14:13.967 UTC | 6 | 2020-11-19 12:29:35.983 UTC | 2017-07-11 08:56:22.69 UTC | null | 1,898,563 | null | 312,896 | null | 1 | 46 | c++|constructor|shared-ptr | 17,390 | <p>The reason is simple: in object <code>X</code>, <code>enable_shared_from_this</code> works by initialising a hidden <code>weak_ptr</code> with a copy of the first <code>shared_ptr</code> which points to object <code>X</code>. However, for a <code>shared_ptr</code> to be able to point to <code>X</code>, <code>X</code> must already exist (it must be already constructed). Therefore, while the constructor of <code>X</code> is running, there is yet no <code>shared_ptr</code> which <code>enable_shared_from_this</code> could use.</p>
<p>Take this piece of code:</p>
<pre><code>std::shared_ptr<Person> p(new Person());
</code></pre>
<p>Before the constructor of <code>p</code> (of the <code>shared_ptr</code>) is even called, its argument must be evaluated. That argument is the expression <code>new Person()</code>. Therefore, the constructor of <code>Person</code> runs before the constructor of <code>p</code> has even begun—before there is any <code>shared_ptr</code> object to which <code>enable_shared_from_this</code> could bind.</p> |
33,793,211 | TableView rounded corners and shadow | <p>I have a tableview with three rows. I am trying to make the table rows have rounded corners and also a shadow effect around the entire tableview. For some reason, I cannot make the tableview both have the rounded corners and shadow effect but I could do them separately if I comment out the code responsible for one of the features. Here is the code I am using:</p>
<pre><code>//this is for shadow effect
tableView.backgroundColor = UIColor.clearColor()
tableView.layer.shadowColor = UIColor.darkGrayColor().CGColor
tableView.layer.shadowOffset = CGSize(width: 2.0, height: 2.0
tableView.layer.shadowOpacity = 1.0
tableView.layer.shadowRadius = 2
// This is for rounded corners
tableView.layer.cornerRadius = 10
tableView.layer.masksToBounds = true
</code></pre> | 33,794,065 | 4 | 10 | null | 2015-11-19 00:31:54.14 UTC | 12 | 2020-02-11 11:33:18.547 UTC | 2016-04-22 08:51:57.513 UTC | null | 2,227,743 | null | 3,500,130 | null | 1 | 18 | ios|swift|uitableview|storyboard|tableview | 26,467 | <p>You can add your table view to a container view and add drop shadow to that container view:</p>
<pre><code>let containerView:UIView = UIView(frame:CGRect(x: 10, y: 100, width: 300, height: 400))
self.tableView = UITableView(frame: containerView.bounds), style: .Plain)
containerView.backgroundColor = UIColor.clearColor()
containerView.layer.shadowColor = UIColor.darkGrayColor().CGColor
containerView.layer.shadowOffset = CGSize(width: 2.0, height: 2.0)
containerView.layer.shadowOpacity = 1.0
containerView.layer.shadowRadius = 2
// This is for rounded corners
self.tableView.layer.cornerRadius = 10
self.tableView.layer.masksToBounds = true
self.view.addSubview(containerView)
containerView.addSubview(self.tableView)
</code></pre>
<h2>Edit</h2>
<p>Swift 3.0:</p>
<pre><code>let containerView:UIView = UIView(frame:CGRect(x: 10, y: 100, width: 300, height: 400))
self.tableView = UITableView(frame: containerView.bounds, style: .plain)
containerView.backgroundColor = UIColor.clear
containerView.layer.shadowColor = UIColor.darkGray.cgColor
containerView.layer.shadowOffset = CGSize(width: 2.0, height: 2.0)
containerView.layer.shadowOpacity = 1.0
containerView.layer.shadowRadius = 2
self.tableView.layer.cornerRadius = 10
self.tableView.layer.masksToBounds = true
self.view.addSubview(containerView)
containerView.addSubview(self.tableView)
</code></pre>
<p><a href="https://i.stack.imgur.com/fIlBB.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/fIlBB.gif" alt="enter image description here" /></a></p> |
22,513,355 | Input::file() returning null Laravel | <p>I've been writing an uploading script and even though I'm using the Laravel built in function Input::file() it still returns null.
I am going to post my Home Controller code. </p>
<pre><code>public function handleUpload()
{
$user = Auth::user();
$username = $user->username;
$userId = $user->id;
$path_to_users = "users";
$user_profile_img = 'users/'.$username.$userId.'/'.$username.'image001.jpg';
$user_path_profile = "users/$username$userId";
$user_image_name = $username.'image001.jpg';
if(file_exists($path_to_users))
{
if(file_exists("$user_path_profile")){
$file = Input::file('profile')->move("$user_path_profile/", $user_image_name);
} else {
mkdir("$user_path_profile");
$file = Input::file('profile')->move("$user_path_profile/", $user_image_name);
}
} else {
mkdir("users");
mkdir("$user_path_profile");
$file = Input::file('profile')->move("$user_path_profile/", $user_image_name);
}
}
</code></pre>
<p>When I die(var_dump(Input::file('profile'))) returns null which means it is basically not taking in my file as an actual file. When I do die(var_dump(Input::get('profile'))) it returns the image name meaning that my uploading script is working but the Laravel backend is failing. Is this true, or am I just missing something?</p>
<p>Here is my HTML form stuff:</p>
<pre><code>@if($user->id == $userProf->id)
<div class="fileUpload button-success pure-button">
<span>Upload</span>
<form action="{{action('HomeController@handleUpload')}}" method="POST" enctype="multipart/form-data">
<input type="file" name="profile" class="upload" />
</form>
</div>
@endif
</code></pre> | 25,184,177 | 4 | 2 | null | 2014-03-19 17:15:10.66 UTC | 13 | 2021-01-26 23:32:44.853 UTC | 2014-05-20 03:32:00.133 UTC | null | 1,317,935 | null | 2,880,726 | null | 1 | 26 | php|laravel|laravel-4 | 38,387 | <p>I had the same problem in a normal form. I forgot to add:</p>
<pre><code>enctype="multipart/form-data"
</code></pre> |
22,502,606 | why is std::lock_guard not movable? | <p>Why is <code>std::lock_guard</code> not movable, it would make code so much nicer:</p>
<pre><code>auto locked = lock_guard(mutex);
</code></pre>
<p>instead of</p>
<pre><code>std::lock_guard<std::mutex> locked(mutex);
</code></pre>
<p>Is there something wrong with creating your own version, like:</p>
<pre><code>template <typename T> class lock_guard_
{
T* Mutex_;
lock_guard_(const lock_guard_&) = delete;
lock_guard_& operator=(const lock_guard_&) = delete;
public:
lock_guard_(T& mutex) : Mutex_(&mutex)
{
Mutex_->lock();
}
~lock_guard_()
{
if(Mutex_!=nullptr)
Mutex_->unlock();
}
lock_guard_(lock_guard_&& guard)
{
Mutex_ = guard.Mutex_;
guard.Mutex_ = nullptr;
}
};
template <typename T> lock_guard_<T> lock_guard(T& mutex)
{
return lock_guard_<T>(mutex);
}
</code></pre>
<p>?</p>
<p>Any fundamental reason it would be a bad idea to make it movable?</p> | 22,504,231 | 2 | 3 | null | 2014-03-19 10:18:24.3 UTC | 7 | 2018-11-21 11:46:50.697 UTC | 2018-11-21 11:46:50.697 UTC | null | 1,625,187 | null | 2,423,171 | null | 1 | 29 | c++|multithreading|c++11|standards|movable | 7,508 | <p><code>lock_guard</code> is <em>always</em> engaged; it always holds a reference to a mutex and always unlocks it in its destructor. If it was movable then it would need to hold a pointer instead of a reference, and test the pointer in its destructor. This might seem a trivial cost, but it is C++ philosophy that you don't pay for what you don't use.</p>
<p>If you want a movable (and releaseable) lock you can use <code>unique_lock</code>.</p>
<p>You might be interested in <a href="http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2013/n3602.html" rel="noreferrer">n3602 Template parameter deduction for constructors</a>, which removes the need for <code>make_</code> functions. It won't be in C++14 but we can hope for C++17.</p> |
22,585,621 | The FileReader cannot find my text file | <p>I have a simple text file and for some reason, it cannot be found. I don't see anything wrong with the code because I got it from a site, and I am starting to think that I didn't place the text file in the right place. Any suggestion please?</p>
<h2>Code:</h2>
<pre><code>import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.nio.file.Path;
import java.nio.file.Paths;
public class MainFavorites {
public static void main(String[] args) throws IOException {
/**
* finds pathway to the file
*/
// File file = new File("icecreamTopping.txt");
// System.out.println(file.getCanonicalPath());
BufferedReader reader = null;
ArrayList <String> myFileLines = new ArrayList <String>();
try {
String sCurrentLine;
reader = new BufferedReader(new FileReader("icecreamTopping.txt"));
while ((sCurrentLine = reader.readLine()) != null) {
//System.out.println(sCurrentLine);
myFileLines.add(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
System.out.print(e.getMessage());
} finally {
try {
if (reader != null)reader.close();
} catch (IOException ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
int numElements = myFileLines.size();
System.out.println ("there are n lines in the file:" + numElements);
for (int counter = numElements-1; counter >= 0; counter--) {
String mylineout = myFileLines.get(counter);
System.out.println (mylineout);
}
}
}
</code></pre>
<h2>File content:</h2>
<pre><code>1- Blueberry
2- Banana Buzz
3- Cookie Batter
</code></pre>
<p>My stack trace is this:</p>
<pre><code>java.io.FileNotFoundException: C:\Users\homar_000\workspace\RankFavorites\icecreamTopping.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at MainFavorites.main(MainFavorites.java:28)
</code></pre> | 22,618,107 | 5 | 3 | null | 2014-03-23 00:44:52.183 UTC | 4 | 2022-04-15 00:05:31.403 UTC | 2014-03-23 06:54:46.43 UTC | null | 207,421 | null | 2,843,235 | null | 1 | 2 | java|filereader|java-io | 69,320 | <p>Found out what was the problem. It was unnecessary for me to put the file extension so I removed the .txt because when I kept it, it read it as "icecreamTopping.txt.txt"</p> |
13,438,369 | java.lang.IllegalArgumentException: argument type mismatch while using Reflection | <p>Below is my code from which I am using reflection to call a method but I am always getting
exception</p>
<pre><code>List<PdAttrKey> attrKeys = new ArrayList<PdAttrKey>();
Properties adapterProps = new Properties();
PdReadRequest pdReadRequest = new PdReadRequest(1L, 1L, (short) 0, new Date(),
dataDurationSec, 2L, 3L, attrKeys, null, adapterProps);
PdAdapterUserReadOnlyGemsReader adapter1 = new PdAdapterUserReadOnlyGemsReader();
PdReader reader = adapter1.acquireReader(pdReadRequest);
UserCacheDoImpl userDos = Some Value;
Method method = getClassMethod("createPdRecordFromUserDO");
// This line is throwing me exception. And I don't know why?
PdRecord onePdsxRecord = (PdRecord) method.invoke(reader, userDos);
</code></pre>
<p>This is the below method from which I am getting all the method names of a class.</p>
<pre><code> private Method getClassMethod(String methodName) {
Method method = null;
Method[] methodList = PdAdapterUserReadOnlyGemsReader.PdUserReadOnlyGemsReader.class
.getDeclaredMethods();
for (Method m : methodList) {
if (m.getName().equals(methodName)) {
method = m;
method.setAccessible(true);
break;
}
}
return method;
}
</code></pre>
<p>Some More Code:-</p>
<pre><code>private PdRecord createPdRecordFromUserDO(UserCacheDoImpl userCache) {
// Some code here
}
</code></pre>
<p>This is the exception I am getting. Any idea why?</p>
<pre><code>java.lang.IllegalArgumentException: argument type mismatch
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:599)
</code></pre>
<p>Any suggestions will be of great help.</p> | 13,440,739 | 1 | 5 | null | 2012-11-18 07:42:09.087 UTC | 1 | 2012-11-18 13:46:11.863 UTC | 2012-11-18 07:57:44.43 UTC | null | 663,148 | null | 663,148 | null | 1 | 8 | java|reflection | 96,058 | <p>Please check if more than one method with name "createPdRecordFromUserDO" exists.
It looks like there are more than one, but with different arguments.</p>
<p>Your method getClassMethod returns the first method it finds, but that could be the wrong one.
Check if methodList.length > 1, then this is the cause of the bug.</p>
<p>Rethink what you want to do if multiple methods with the given name are found.</p> |
13,687,233 | Where is bootstrap-responsive.css? | <p>I know that by default the bootstrap doesn't come with the file, but after I customized (I've selected all the responsive features!) I still can't see the file. At the docs, it says that I should do this on head tag:</p>
<pre><code><meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
</code></pre>
<p>But the truth is that I don't even have the folder assets. What I do have is:</p>
<pre><code>\bootstrap
\img
\css
\js
</code></pre>
<p>Can anyone help me?</p> | 18,800,441 | 6 | 0 | null | 2012-12-03 16:11:48.033 UTC | 10 | 2016-10-18 21:07:24.927 UTC | 2016-10-18 21:07:24.927 UTC | null | 881,229 | null | 1,860,606 | null | 1 | 58 | twitter-bootstrap | 96,462 | <p>Since Bootstrap 3 you don't need responsive.css anymore. Because it is inside default bootstrap.css.</p>
<p>Related: <a href="https://stackoverflow.com/a/16379181/429938">https://stackoverflow.com/a/16379181/429938</a></p> |
39,754,070 | How to solve Facebook tools:replace="android:theme"? | <p>I have</p>
<pre><code>compile 'com.facebook.android:facebook-android-sdk:4.16.0'
</code></pre>
<p>My manifest:</p>
<pre><code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
...
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AutoTheme"
tools:replace="android:theme">
</code></pre>
<p>How to solve compile error:</p>
<pre><code>Error:Execution failed for task ':app:processDebugManifest'.
> Manifest merger failed : Attribute activity#com.facebook.FacebookActivity@theme value=(@android:style/Theme.Translucent.NoTitleBar) from AndroidManifest.xml:69:13-72
is also present at [com.facebook.android:facebook-android-sdk:4.16.0] AndroidManifest.xml:32:13-63 value=(@style/com_facebook_activity_theme).
Suggestion: add 'tools:replace="android:theme"' to <activity> element at AndroidManifest.xml:66:9-70:47 to override.
</code></pre> | 39,786,339 | 5 | 4 | null | 2016-09-28 17:28:49.887 UTC | 9 | 2021-02-13 18:01:52.963 UTC | 2021-02-13 18:01:52.963 UTC | null | 2,425,851 | null | 2,425,851 | null | 1 | 57 | android|facebook|facebook-android-sdk | 28,027 | <p>1) Add <code>xmlns:tools="http://schemas.android.com/tools"</code> to <code><manifest></code> element at AndroidManifest</p>
<p>2) Add <code>tools:replace="android:theme"</code> to (facebook activity) <code><activity></code></p>
<p>Here is my manifest file</p>
<pre><code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.company.product" xmlns:tools="http://schemas.android.com/tools">
...
<application
android:allowBackup="true"
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher"
android:theme="@style/AppTheme"
android:name="MyApplication">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize">
<intent-filter>
...
</intent-filter>
</activity>
<!--FacebookActivity-->
<activity
tools:replace="android:theme"
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="@string/app_name"
android:theme="@android:style/Theme.Translucent.NoTitleBar"/>
...
</application>
</manifest>
</code></pre> |
20,881,213 | Converting JavaScript object with numeric keys into array | <p>I have an object like this coming back as a JSON response from the server:</p>
<pre class="lang-js prettyprint-override"><code>{
"0": "1",
"1": "2",
"2": "3",
"3": "4"
}
</code></pre>
<p>I want to convert it into a JavaScript array like this:</p>
<pre><code>["1","2","3","4"]
</code></pre>
<p>Is there a best way to do this? Wherever I am reading, people are using complex logic using loops. So are there alternative methods to doing this?</p> | 20,881,336 | 17 | 2 | null | 2014-01-02 10:48:40.997 UTC | 73 | 2021-12-11 18:03:37.223 UTC | 2021-06-03 10:24:31.427 UTC | null | 3,082,296 | null | 2,218,452 | null | 1 | 178 | javascript|jquery|arrays|json|javascript-objects | 677,029 | <p>It's actually very straight forward with jQuery's <a href="http://api.jquery.com/jquery.map/" rel="noreferrer"><strong><code>$.map</code></strong></a></p>
<pre><code>var arr = $.map(obj, function(el) { return el });
</code></pre>
<p><a href="http://jsfiddle.net/8TT4p/" rel="noreferrer"><strong>FIDDLE</strong></a></p>
<p>and almost as easy without jQuery as well, converting the keys to an array and then mapping back the values with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map" rel="noreferrer"><strong><code>Array.map</code></strong></a></p>
<pre><code>var arr = Object.keys(obj).map(function(k) { return obj[k] });
</code></pre>
<p><a href="http://jsfiddle.net/8TT4p/67/" rel="noreferrer"><strong>FIDDLE</strong></a></p>
<p>That's assuming it's already parsed as a javascript object, and isn't actually JSON, which is a string format, in that case a run through <code>JSON.parse</code> would be necessary as well.</p>
<p>In ES2015 there's <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values" rel="noreferrer"><code>Object.values</code></a> to the rescue, which makes this a breeze</p>
<pre><code>var arr = Object.values(obj);
</code></pre> |
24,429,976 | pass parameter from jenkins parameterized build to windows batch command | <p>I am starting to use Jenkins, which is a really great tool. We are using parameterized build, we define parameter such as branch name ${Branch} (e.g. dev, release, main etc).</p>
<p>In the build config, I can add a windows batch command, is there a way I can pass down these parameters to the batch command?</p>
<p>I tried to pass like "%${Branch}%" or "%Branch%", but seems not working.</p>
<p>Can anyone help?</p>
<p>Many Thanks</p> | 24,436,799 | 2 | 2 | null | 2014-06-26 12:00:33.143 UTC | 4 | 2021-01-02 19:32:31.04 UTC | 2019-01-17 17:04:27.68 UTC | null | 4,707,189 | null | 1,223,876 | null | 1 | 18 | batch-file|jenkins|cmd | 45,770 | <p>Using <strong>Parameterized Build</strong>, you need to define parameters. The value of these will be prompted to you when you click "Build" link.</p>
<p>The name of the parameters should be a <strong>plain name</strong>, preferably without spaces, like <code>Branch</code>. Do not add any <code>${}</code> or <code>%%</code> to definition of the parameter name.</p>
<p>In the <strong>build steps</strong>, like <strong>Execute Windows Batch Command</strong>, you can reference the parameter with regular batch syntax, like <code>%Branch%</code>.</p>
<p>If you would be on a *nix machine, you would use <strong>Execute shell</strong> build step and reference the parameter with regular bash syntax, like <code>${Branch}</code></p>
<p>Note that even when running on Windows, a lot of Jenkins plugins themselves take the parameters in *nix syntax, however the <strong>Execute Windows Batch Command</strong> will be batch-like, i.e. <code>%Branch%</code>.</p>
<p>So, you can try typing:<br>
<code>echo %Branch%</code></p>
<p>I also suggest putting just <code>set</code> command on a line by itself, and it will show you all environment variables available to you during the build process, which is quite useful.</p> |
3,978,429 | Eclipse publishing to Tomcat | <p>I recently came back to using Eclipse after 2 years of IntelliJ. Things have changed.</p>
<p>Now when I try to run Tomcat, it tries to <strong>publish</strong> my project to it. What the hell is publish? </p>
<p>What ever happened to pushing a war into the webapps directory and letting Tomcat deploy it?</p>
<p>Right now my deployment is broken because of compilation errors. I have a feeling that Eclipse is taking my project and copying it to webapps dir without first building it properly. </p>
<p>Can someone explain to me what exactly publishing does, and also how to turn it off and use Tomcat like normal people?</p> | 3,978,514 | 2 | 0 | null | 2010-10-20 13:37:46.607 UTC | 9 | 2012-03-02 09:20:09.767 UTC | 2012-03-02 09:20:09.767 UTC | null | 505,893 | null | 26,188 | null | 1 | 18 | eclipse|tomcat|war | 31,757 | <p>A the "Servers" view, you can double click on your Tomcat instance, to open the server settings editor.</p>
<p>There, at the upper right corner, you can find the <em>Publishing</em> options. Check the "Never publish automatically" option, and save.</p>
<p>With this it should be enough.</p>
<p>Oh, and by "Publishing", they kind of mean "Deploying", or "Copying to the deploy directory", depending on what server you are using.</p> |
9,050,066 | Eclipse error: "Editor does not contain a main type" | <p>I can't seem to run the following code in Eclipse. I do have a main method and this is the currently opened file. I even tried the "Run As" option but I keep getting this error: "editor does not contain a main type". What am I doing wrong here?</p>
<pre><code> public class cfiltering {
/**
* @param args
*/
//remember this is just a reference
//this is a 2d matrix i.e. user*movie
private static int user_movie_matrix[][];
//remember this is just a reference
//this is a 2d matrix i.e. user*user and contains
//the similarity score for every pair of users.
private float user_user_matrix[][];
public cfiltering()
{
//this is default constructor, which just creates the following:
//ofcourse you need to overload the constructor so that it takes in the dimensions
//this is 2d matrix of size 1*1
user_movie_matrix=new int[1][1];
//this is 2d matrix of size 1*1
user_user_matrix=new float[1][1];
}
public cfiltering(int height, int width)
{
user_movie_matrix=new int[height][width];
user_user_matrix=new float[height][height];
}
public static void main(String[] args) {
//1.0 this is where you open/read file
//2.0 read dimensions of number of users and number of movies
//3.0 create a 2d matrix i.e. user_movie_matrix with the above dimensions.
//4.0 you are welcome to overload constructors i.e. create new ones.
//5.0 create a function called calculate_similarity_score
//you are free to define the signature of the function
//The above function calculates similarity score for every pair of users
//6.0 create a new function that prints out the contents of user_user_matrix
try
{
//fileinputstream just reads in raw bytes.
FileInputStream fstream = new FileInputStream("inputfile.txt");
//because fstream is just bytes, and what we really need is characters, we need
//to convert the bytes into characters. This is done by InputStreamReader.
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
int numberOfUsers=Integer.parseInt(br.readLine());
int numberOfMovies=Integer.parseInt(br.readLine());
//Now you have numberOfUsers and numberOfMovies to create your first object.
//this object will initialize the user_movie_matrix and user_user_matrix.
new cfiltering(numberOfUsers, numberOfMovies);
//this is a blankline being read
br.readLine();
String row;
int userNo = 0;
while ((row = br.readLine()) != null)
{
//now lets read the matrix from the file
String allRatings[]=row.split(" ");
int movieNo = 0;
for (String singleRating:allRatings)
{
int rating=Integer.parseInt(singleRating);
//now you can start populating your user_movie_matrix
System.out.println(rating);
user_movie_matrix[userNo][movieNo]=rating;
++ movieNo;
}
++ userNo;
}
}
catch(Exception e)
{
System.out.print(e.getMessage());
}
}
}
</code></pre> | 9,050,130 | 3 | 2 | null | 2012-01-29 01:03:38.033 UTC | 4 | 2014-12-17 05:26:16.013 UTC | 2014-12-17 05:26:16.013 UTC | user4356732 | null | null | 1,082,226 | null | 1 | 20 | java|eclipse | 123,046 | <p>Try closing and reopening the file, then press <code>Ctrl+F11</code>.</p>
<p>Verify that the name of the file you are running is the same as the name of the project you are working in, and that the name of the public class in that file is the same as the name of the project you are working in as well.</p>
<p>Otherwise, restart Eclipse. Let me know if this solves the problem! Otherwise, comment, and I'll try and help.</p> |
16,567,121 | More than 2 columns in a CONCAT function | <p>In SQL Server 2012 I want to <code>concat</code> 5 columns into 1 but in the query it works but when I put in in a view it gives me an error like </p>
<blockquote>
<p>Msg 174, Level 15, State 1, Line 3<br>
The CONCAT function requires 2 argument(s).</p>
</blockquote>
<p>What's the problem so I can fix it because <code>concat</code> is a good function for <code>concatenate</code> more than 1 column because if its null they make it empty..</p>
<p>CODE:</p>
<pre><code>SELECT
'Aan ' + A.Name AS 'Naam',
{ fn CONCAT('T.a.v. ', C.Salutation + ' ', C.FirstName + ' ', C.MiddleName + ' ', C.LastName) } AS 'T.a.v.',
ISNULL(ISNULL(A.Address1_Line2, A.Address1_Line1),
C.Address1_Line2) AS 'Adres',
ISNULL(A.Address1_PostalCode + ' ' + A.Address1_City, A.Address2_PostalCode + ' ' + A.Address2_City) AS 'Woonplaats',
'heer' + ' ' + ISNULL(C.MiddleName + ' ', N'') + ISNULL(C.LastName, N'') AS 'Aanhef'
FROM
dbo.Account AS A
FULL OUTER JOIN
dbo.Contact AS C ON A.Name = C.AccountIdName
WHERE
(C.Salutation = 'Dhr.') AND (A.Name IS NOT NULL) AND (A.StatusCode = 1)
AND (ISNULL(C.StatusCode, 1) = 1) OR (C.Salutation = 'dhr.') AND (A.Name IS NOT NULL) AND (A.StatusCode = 1) AND (ISNULL(C.StatusCode, 1) = 1)
</code></pre> | 16,567,450 | 8 | 4 | null | 2013-05-15 13:59:39.52 UTC | 1 | 2021-11-12 13:54:33.28 UTC | 2013-05-15 14:32:20.433 UTC | null | 694,852 | null | 2,289,664 | null | 1 | 17 | sql-server|sql-server-2012|concat | 40,114 | <p>There must be an error somewhere else in your view!!</p>
<p>Ok, then what I did with your code was to change this line </p>
<pre><code>{ fn CONCAT('T.a.v. ', C.Salutation + ' ', C.FirstName + ' ', C.MiddleName + ' ', C.LastName) } AS 'T.a.v.'
</code></pre>
<p>to this</p>
<pre><code>CONCAT('T.a.v. ', C.Salutation + ' ', C.FirstName + ' ', C.MiddleName + ' ', C.LastName) AS 'T.a.v.'
</code></pre>
<p>Edit:</p>
<p>Just to explain the difference in code, is that the one with { fn ....} is a Canonical function and microsoft promise that it will work on all ODBC connections.</p>
<p>From MSDN:</p>
<p>Canonical functions are functions that are supported by all data providers, and can be used by all querying technologies. Canonical functions cannot be extended by a provider.</p> |
16,210,822 | Angular.JS: views sharing same controller, model data resets when changing view | <p>I'm getting started with Angular.JS.</p>
<p>I have a number of views that share the same controller. Each view is a step in collecting data that is stored in the controller:</p>
<pre><code>$routeProvider.when('/', {
templateUrl: 'partials/text.html',
controller: 'itemSubmitter'
});
$routeProvider.when('/nextThing', {
templateUrl: 'partials/nextthing.html',
controller: 'itemSubmitter'
});
</code></pre>
<p>The itemSubmitter controller:</p>
<pre><code>$scope.newitem = {
text: null
}
</code></pre>
<p>Here's the first view:</p>
<pre><code><textarea ng-model="newitem.text" placeholder="Enter some text"></textarea>
<p>Your text is:
{{ newitem.text }}</p>
</code></pre>
<p>This works, live updating the 'Your text is:' paragraph.</p>
<p>However when the next view is loaded, <code>{{ newitem.text }}</code> is reset to its default value. How can I make values stored in a controller instance persist across views?</p> | 16,213,055 | 1 | 3 | null | 2013-04-25 09:12:38.87 UTC | 12 | 2013-07-30 12:10:56.473 UTC | 2013-04-25 16:29:10.243 UTC | null | 168,868 | null | 123,671 | null | 1 | 36 | javascript|angularjs | 31,348 | <p>Controllers are disposed when changing routes. This is good behavior since you should not rely on controllers to carry data between views. It's best to create a service to handle that data.</p>
<p>See the angular docs on how to use controllers correctly.
<a href="http://docs.angularjs.org/guide/dev_guide.mvc.understanding_controller">http://docs.angularjs.org/guide/dev_guide.mvc.understanding_controller</a></p>
<p><em>To quote from the docs:</em></p>
<blockquote>
<h2>Using Controllers Correctly</h2>
<p>In general, a controller shouldn't try to do too much. It should contain only the business logic needed for a single view.</p>
<p>The most common way to keep controllers slim is by encapsulating work that doesn't belong to controllers into services and then using these services in controllers via dependency injection. This is discussed in the Dependency Injection Services sections of this guide.</p>
<p>Do not use controllers for:</p>
<ul>
<li>Any kind of DOM manipulation — Controllers should contain only business logic. DOM manipulation—the presentation logic of an application—is well known for being hard to test. Putting any presentation logic into controllers significantly affects testability of the business logic. Angular offers databinding for automatic DOM manipulation. If you have to perform your own manual DOM manipulation, encapsulate the presentation logic in directives.</li>
<li>Input formatting — Use angular form controls instead.</li>
<li>Output filtering — Use angular filters instead.</li>
<li>To run stateless or stateful code shared across controllers — Use angular services instead.</li>
<li>To instantiate or manage the life-cycle of other components (for example, to create service instances).</li>
</ul>
</blockquote> |
16,084,741 | How do I set resources allocated to a container using docker? | <p>As the title of this question suggests I'm wanting to set max disk/memory and cpu usage for a container using docker (docker.io).</p>
<p>Is there a way to do this using just docker?</p> | 25,153,501 | 6 | 0 | null | 2013-04-18 13:46:55.09 UTC | 26 | 2017-02-13 15:10:36.303 UTC | 2016-05-27 21:10:21.567 UTC | null | 437,763 | null | 1,659,519 | null | 1 | 66 | docker | 55,325 | <p><strong>Memory/CPU</strong></p>
<p>Docker now supports more resource allocation options:</p>
<ul>
<li>CPU shares, via -c flag</li>
<li>Memory limit, via -m flag</li>
<li>Specific CPU cores, via --cpuset flag</li>
</ul>
<p>Have a look at <code>docker run --help</code> for more details.</p>
<p>If you use lxc backend (<code>docker -d --exec-driver=lxc</code>), more fine grained resource allocation schemes can be specified, e.g.:</p>
<pre><code>docker run --lxc-conf="lxc.cgroup.cpuset.cpus = 0,1"\
--lxc-conf="lxc.cgroup.cpu.shares = 1234"
</code></pre>
<p><strong>Storage</strong></p>
<p>Limiting storage is a bit trickier at the moment. Please refer to the following links for more details:</p>
<ul>
<li><a href="http://jpetazzo.github.io/2014/01/29/docker-device-mapper-resize/" rel="noreferrer">Resizing Docker containers with the Device Mapper plugin</a></li>
<li><a href="https://github.com/docker/docker/issues/471" rel="noreferrer">Question on Resource Limits?</a></li>
<li><a href="https://github.com/snitm/docker/blob/master/daemon/graphdriver/devmapper/README.md" rel="noreferrer">devicemapper - a storage backend based on Device Mapper</a></li>
</ul> |
16,232,572 | Distributed task queues (Ex. Celery) vs crontab scripts | <p>I'm having trouble understanding the purpose of 'distributed task queues'. For example, python's <a href="http://www.celeryproject.org/" rel="noreferrer">celery library</a>. </p>
<p>I know that in celery, the python framework, you can set timed windows for functions to get executed. However, that can also be easily done in a linux crontab directed at a python script. </p>
<p>And as far as I know, and shown from my own django-celery webapps, celery consumes much more RAM memory than just setting up a raw crontab. Few hundred MB difference for a relatively small app.</p>
<p>Can someone please help me with this distinction? Perhaps a high level explanation of how task queues / crontabs work in general would be nice also.</p>
<p>Thank you.</p> | 16,234,656 | 1 | 0 | null | 2013-04-26 09:04:04.3 UTC | 39 | 2013-04-26 10:50:13.043 UTC | 2013-04-26 09:36:06.41 UTC | null | 1,660,802 | null | 1,660,802 | null | 1 | 112 | python|django|celery | 17,370 | <p>It depends what you want your tasks to be doing, if you need to distribute them, and how you want to manage them.</p>
<p>A crontab is capable of executing a script every N intervals. It runs, and then returns. Essentially you get a single execution each interval. You could just direct a crontab to execute a django management command and get access to the entire django environment, so celery doesn't really help you there.</p>
<p>What celery brings to the table, with the help of a message queue, is distributed tasks. Many servers can join the pool of workers and each receive a work item without fear of double handling. It's also possible to execute a task as soon as it is ready. With cron, you're limited to a minimum of one minute.</p>
<p>As an example, imagine you've just launched a new web application and you're receiving hundreds of sign ups that require an email to be sent to each user. Sending an email may take a long time (comparatively) so you decide that you'll handle activation emails via tasks.</p>
<p>If you were using cron, you'd need to ensure that every minute cron is able to process all of the emails that need to be sent. If you have several servers you now need to make sure that you aren't sending multiple activation emails to the same user - you need some kind of synchronization.</p>
<p>With celery, you add a task to the queue. You may have several workers per server so you've already scaled ahead of a cronjob. You may also have several servers allowing you to scale even more. Synchronization is handled as part of the 'queue'.</p>
<p>You <em>can</em> use celery as a cron replacement but that's not really its primary use. It is used for farming out asynchronous tasks across a distributed cluster.</p>
<p>And of course, celery has a <a href="http://docs.celeryproject.org/en/master/getting-started/introduction.html#features" rel="noreferrer">big list of features</a> that cron does not.</p> |
21,489,701 | O(n log n) vs O(n) -- practical differences in time complexity | <p><code>n log n > n</code> -- but this is like a <code>pseudo-linear</code> relationship. If <code>n=1 billion</code>, log n ~ 30;</p>
<p>So <code>n log n</code> will be <code>30 billion</code>, which is <code>30 X n</code>, order of <code>n</code>.
I am wondering if this time complexity difference between <code>n log n and n</code> are significant in real life.</p>
<p>Eg: A <code>quick select</code> on finding kth element in an unsorted array is <code>O(n)</code> using quickselect algorithm.</p>
<p>If I sort the array and find the kth element, it is <code>O(n log n)</code>. To sort an array with <code>1 trillion</code> elements, I will be <code>60 times</code> slower if I do <code>quicksort</code> and <code>index it</code>. </p> | 21,489,964 | 5 | 9 | null | 2014-01-31 20:43:31.053 UTC | 24 | 2019-02-26 07:59:02.74 UTC | 2018-12-01 19:20:33.673 UTC | null | 6,644,851 | null | 1,988,876 | null | 1 | 56 | algorithm|big-o|time-complexity | 98,066 | <p>The main purpose of the Big-O notation is to let you do the estimates like the ones you did in your post, and decide for yourself if spending your effort coding a typically more advanced algorithm is worth the additional CPU cycles that you are going to buy with that code improvement. Depending on the circumstances, you may get a different answer, even when your data set is relatively small:</p>
<ul>
<li>If you are running on a mobile device, and the algorithm represents a significant portion of the execution time, cutting down the use of CPU translates into extending the battery life</li>
<li>If you are running in an all-or-nothing competitive environment, such as a high-frequency trading system, a micro-optimization may differentiate between making money and losing money</li>
<li>When your profiling shows that the algorithm in question dominates the execution time in a server environment, switching to a faster algorithm may improve performance for all your clients.</li>
</ul>
<p>Another thing the Big-O notation hides is the constant multiplication factor. For example, Quick Select has very reasonable multiplier, making the time savings from employing it on extremely large data sets well worth the trouble of implementing it.</p>
<p>Another thing that you need to keep in mind is the space complexity. Very often, algorithms with <code>O(N*Log N)</code> time complexity would have an <code>O(Log N)</code> space complexity. This may present a problem for extremely large data sets, for example when a recursive function runs on a system with a limited stack capacity.</p> |
26,900,080 | How to do a script for odd and even numbers from 1 to 1000 in Javascript? | <p>I am studying a book of Javascript with solved examples but there is one example without solution. I would like to know how to do it ...</p>
<p>In javascript (in browser) I should do is write even numbers from 1-1000 and after it is finished write odd numbers from 1-1000 ... I am not sure how to add there very small "pause" between number writing and how to know if first cycle is over and start writing odd numbers?</p>
<p>Here is How I started:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Test</title>
</head>
<body>
<script type="text/javascript">
/* <![CDATA[ */
var i;
for (i = 0; i < 1000; i++)
if ((i % 2) == 0)
document.writeln(i);
/* ]]> */
</script>
</body>
</html>
</code></pre> | 26,900,201 | 8 | 3 | null | 2014-11-13 01:56:33.843 UTC | 1 | 2016-12-29 13:22:30.893 UTC | null | null | null | null | 559,792 | null | 1 | 3 | javascript|loops|numbers | 80,273 | <p>Give this a try:</p>
<pre><code> function partA() {
for (var i = 0; i < 1000; i++){
if ((i % 2) == 0) document.write(i + ' ');
}
window.setTimeout(partB,1000)
}
function partB() {
for (var i = 0; i < 1000; i++){
if ((i % 2) !== 0) document.write(i + ' ');
}
}
partA();
</code></pre>
<hr>
<p>SIDENOTE:</p>
<p>Use <code>document.write</code> for testing only.
If you execute it, on a loaded HTML document, all HTML elements will be overwritten. ( As you can see in my example )</p> |
26,453,916 | Passing data from Django to D3 | <p>I'm trying to write a very basic bar graph using Django and D3.js. I have an object called play with a datetime field called date. What I want to do is show number of plays over time grouped by month. Basically I have two questions:</p>
<ol>
<li>How do I get these grouped by month with a count of the number of plays in that month</li>
<li>What is the best way to get this information from Django into something usable by D3.</li>
</ol>
<p>Now I have looked at some other answers on here and have tried </p>
<pre><code>json = (Play.objects.all().extra(select={'month': "extract(month FROM date)"})
.values('month').annotate(count_items=Count('date')))
</code></pre>
<p>This gets close to trhe information I want but when I try to output it in the template it comes out as the following (with Ls) on the end of the months. This means that obviously it isn't valid js (no qoutes) and I don't really want the Ls on the end there anyway.</p>
<p>Template:</p>
<pre><code> <script>
var test ={{ json|safe }};
alert("test");
</script>
</code></pre>
<p>output:</p>
<pre><code>var test = [{'count_items': 10, 'month': 1L}, {'count_items': 5, 'month': 2L}];
</code></pre>
<p>I have also tried json.dumps on this data but I get told it isn't valid JSON. This feels like it should be a lot more straightforward to do in Django so maybe I am headed down the worng path entirely.</p> | 26,455,798 | 2 | 3 | null | 2014-10-19 18:27:43.97 UTC | 37 | 2018-11-30 20:54:03.893 UTC | null | null | null | null | 4,159,383 | null | 1 | 28 | javascript|python|json|django|d3.js | 38,033 | <p>Since D3.js v3 has a nice collection of <a href="https://github.com/d3/d3-3.x-api-reference/blob/master/API-Reference.md#loading-external-resources" rel="noreferrer">methods to load data from external resources</a>¹, It's better to you not embed data into your page, you just load it.</p>
<p>This will be an answer by example.</p>
<p>Let's start with a model definition:</p>
<pre><code># models.py
from django.db import models
class Play(models.Model):
name = models.CharField(max_length=100)
date = models.DateTimeField()
</code></pre>
<p>A urlconf:</p>
<pre><code># urls.py
from django.conf.urls import url
from .views import graph, play_count_by_month
urlpatterns = [
url(r'^$', graph),
url(r'^api/play_count_by_month', play_count_by_month, name='play_count_by_month'),
]
</code></pre>
<p>We are using two urls, one to return the html (view <code>graph</code>), and the other url (view <code>play_count_by_month</code>) as an api to return only data as JSON.</p>
<p>And finally our views:</p>
<pre><code># views.py
from django.db import connections
from django.db.models import Count
from django.http import JsonResponse
from django.shortcuts import render
from .models import Play
def graph(request):
return render(request, 'graph/graph.html')
def play_count_by_month(request):
data = Play.objects.all() \
.extra(select={'month': connections[Play.objects.db].ops.date_trunc_sql('month', 'date')}) \
.values('month') \
.annotate(count_items=Count('id'))
return JsonResponse(list(data), safe=False)
</code></pre>
<p>Here we defined an view to return our data as JSON, note that I changed extra to be database agnostic, since I did tests with SQLite.</p>
<p>And follows our <code>graph/graph.html</code> template that shows a graph of play counts by month:</p>
<pre><code><!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.x.axis path {
display: none;
}
.line {
fill: none;
stroke: steelblue;
stroke-width: 1.5px;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.js"></script>
<script>
var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var parseDate = d3.time.format("%Y-%m-%d").parse; // for dates like "2014-01-01"
//var parseDate = d3.time.format("%Y-%m-%dT00:00:00Z").parse; // for dates like "2014-01-01T00:00:00Z"
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var line = d3.svg.line()
.x(function(d) { return x(d.month); })
.y(function(d) { return y(d.count_items); });
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.json("{% url "play_count_by_month" %}", function(error, data) {
data.forEach(function(d) {
d.month = parseDate(d.month);
d.count_items = +d.count_items;
});
x.domain(d3.extent(data, function(d) { return d.month; }));
y.domain(d3.extent(data, function(d) { return d.count_items; }));
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Play count");
svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);
});
</script>
</body>
</html>
</code></pre>
<p>This will return a nice graph like this (random data):
<img src="https://i.stack.imgur.com/3JW8K.png" alt="Graph of Play counts by month"></p>
<p><strong>Update 1</strong>: D3 v4 will move the code to load external data to a dedicated lib, please see <a href="https://github.com/d3/d3/blob/master/API.md#requests-d3-request" rel="noreferrer">d3-request</a>.
<strong>Update 2</strong>: In order to help, I've put all files together into an example project, on github: <a href="https://github.com/fgmacedo/django-d3-example" rel="noreferrer">github.com/fgmacedo/django-d3-example</a></p> |
19,458,960 | MySQL Error Code: 1205. Lock wait timeout during update with inner join | <p>I am trying to update the <code>Time_Stamp</code> field in my table, <code>simple_pack_data</code>, to match the values in the similarly titled field in my <code>temp_data</code> table. The tables each have fields called <code>Test_Number</code> and <code>Time_Marker</code>, which I'm using to <code>INNER JOIN</code> the tables. <code>Time_Marker</code> is like a reading count, where <code>Time_Stamp</code> is an actual time from the start of the test. </p>
<p>I want to update the <code>Time_Stamp</code> one test at a time, so the code I have been trying is: </p>
<pre><code>UPDATE simple_pack_data s
INNER JOIN (
SELECT *
FROM temp_data t
WHERE t.Test = "3"
) AS tmp
ON s.Test_Number = tmp.Test_Number AND s.Time_Marker = tmp.Time_Marker
SET s.Time_Stamp = tmp.Time_Stamp
WHERE s.Test_Number = "3";
</code></pre>
<p>When I run this it takes over 50 seconds and I get the 1205 error. If I run a similarly structured select statement:</p>
<pre><code>SELECT *
FROM simple_pack_data s
INNER JOIN (
SELECT *
FROM temp_data t
WHERE t.Test = "3"
) AS tmp
ON s.Test_Number = tmp.Test AND s.Time_Marker = tmp.Time_Marker
WHERE s.Test_Number = "3";
</code></pre>
<p>It takes much less than a second and I know join is working fine. Is the update really taking that long? If so, is there any way to change the timeout value so it can get through it?</p> | 19,523,828 | 2 | 4 | null | 2013-10-18 20:59:46.76 UTC | 4 | 2021-06-02 19:26:59.507 UTC | null | null | null | null | 2,896,292 | null | 1 | 11 | mysql|sql|mysql-workbench|mysql-error-1205 | 41,692 | <p>This error is entirely MySQL not doing as it should. The best solution is to get off of MySQL, but lacking that ability, this <a href="http://mysqlperformanceblog.com/2012/03/27/innodbs-gap-locks" rel="nofollow noreferrer">performance blog post</a> has helped me get around this in the past.</p>
<p>MySQL has a lot of these little gotchas. It's like working in Access, half the time the program is going to do the wrong thing and not raise an error.</p> |
17,152,760 | How to restore a builtin that I overwrote by accident? | <p>I accidentally overwrote <code>set</code> by using it as a variable name in an interactive python session - is there any way that I can get access to the original <code>set</code> function without just restarting my session? </p>
<p>(I have so much stuff in that session that I'd rather not have to do that, although of course I can if necessary.)</p> | 17,152,796 | 3 | 0 | null | 2013-06-17 16:50:20.053 UTC | 8 | 2019-11-21 04:19:47.27 UTC | null | null | null | null | 456,876 | null | 1 | 45 | python|built-in | 14,941 | <p>Just delete the name that is masking the builtin:</p>
<pre><code>>>> set = 'oops'
>>> set
'oops'
>>> del set
>>> set
<type 'set'>
</code></pre>
<p>You can always still access the original built-in through the <a href="https://docs.python.org/3/library/builtins.html" rel="noreferrer"><code>builtins</code></a> module (<a href="https://docs.python.org/2/library/__builtin__.html" rel="noreferrer"><code>__builtin__</code></a> on Python 2, with underscores and no <code>s</code>); use this if you want to override the built-in but want to defer to the original still from the override:</p>
<pre><code>>>> import builtins
>>> builtins.set
<type 'set'>
</code></pre>
<p>If you have trouble locating where the masking name is defined, do check all namespaces from your current one up to the built-ins; see <a href="https://stackoverflow.com/questions/291978/short-description-of-scoping-rules">Short description of the scoping rules?</a> for what scopes may apply to your current situation.</p> |
17,615,414 | How to convert 'binary string' to normal string in Python3? | <p>For example, I have a string like this(return value of <code>subprocess.check_output</code>):</p>
<pre><code>>>> b'a string'
b'a string'
</code></pre>
<p>Whatever I did to it, it is always printed with the annoying <code>b'</code> before the string:</p>
<pre><code>>>> print(b'a string')
b'a string'
>>> print(str(b'a string'))
b'a string'
</code></pre>
<p>Does anyone have any ideas about how to use it as a normal string or convert it into a normal string? </p> | 17,615,424 | 3 | 2 | null | 2013-07-12 12:55:06.807 UTC | 56 | 2020-06-02 17:52:23.247 UTC | null | null | null | null | 1,272,683 | null | 1 | 386 | python|string|python-3.x|binary | 521,457 | <p>Decode it.</p>
<pre><code>>>> b'a string'.decode('ascii')
'a string'
</code></pre>
<p>To get bytes from string, encode it.</p>
<pre><code>>>> 'a string'.encode('ascii')
b'a string'
</code></pre> |
5,247,383 | How to run ASP.NET 4.0 website on Apache server? | <p>I understood that I need to use «mod_aspdotnet», but I can't find this module for ASP.NET 4.0: only for 2.0.</p>
<p>Please, help me.</p> | 5,247,445 | 3 | 0 | null | 2011-03-09 14:43:12 UTC | 7 | 2016-08-26 04:47:10.423 UTC | 2016-02-25 23:40:40.337 UTC | null | 490,018 | null | 648,137 | null | 1 | 14 | asp.net|apache | 96,837 | <p>Try to look at the <a href="http://www.mono-project.com/Main_Page" rel="noreferrer">Mono Project</a>.</p>
<p>They have a module for the Apache server called «mod_mono».</p>
<p>Hope this helps.</p> |
5,511,990 | How to create a facet in ggplot, except with different variables | <p>I have a data frame with 3 variables, which are all wind speeds. I want to check how well the hardware was calibrated by plotting all the variables against each other. Although there are three in this instance, it may be that there are up to 6.</p>
<p>This would result in 3 different graphs, where the <code>x</code> and <code>y</code> parameters keep changing. I'd really like to plot these using facets- or something with the same appearance.</p>
<p>Here is some sample data, in a data frame called <code>wind</code>:</p>
<pre><code>wind <- structure(list(speed_60e = c(3.029, 3.158, 2.881, 2.305, 2.45,
2.358, 2.325, 2.723, 2.567, 1.972, 2.044, 1.745, 2.1, 2.08, 1.914,
2.44, 2.356, 1.564, 1.942, 1.413, 1.756, 1.513, 1.263, 1.301,
1.403, 1.496, 1.828, 1.8, 1.841, 2.014), speed_60w = c(2.981,
3.089, 2.848, 2.265, 2.406, 2.304, 2.286, 2.686, 2.511, 1.946,
2.004, 1.724, 2.079, 2.058, 1.877, 2.434, 2.375, 1.562, 1.963,
1.436, 1.743, 1.541, 1.256, 1.312, 1.402, 1.522, 1.867, 1.837,
1.873, 2.055), speed_40 = c(2.726, 2.724, 2.429, 2.028, 1.799,
1.863, 1.987, 2.445, 2.282, 1.938, 1.721, 1.466, 1.841, 1.919,
1.63, 2.373, 2.22, 1.576, 1.693, 1.185, 1.274, 1.421, 1.071,
1.163, 1.166, 1.504, 1.77, 1.778, 1.632, 1.545)), .Names = c("speed_60e",
"speed_60w", "speed_40"), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",
"14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24",
"25", "26", "27", "28", "29", "30"))
R> head(wind)
speed_60e speed_60w speed_40
1 3.029 2.981 2.726
2 3.158 3.089 2.724
3 2.881 2.848 2.429
4 2.305 2.265 2.028
5 2.450 2.406 1.799
6 2.358 2.304 1.863
</code></pre>
<p>I wish to plot three square graphs. An individual one can be plotted by calling</p>
<pre><code>ggplot() + geom_point(data=wind, aes(wind[,1],wind[,3]), alpha=I(1/30),
shape=I(20), size=I(1))
</code></pre>
<p>Any idea how I can do this?</p> | 5,512,160 | 3 | 1 | null | 2011-04-01 10:17:07.793 UTC | 9 | 2013-03-27 05:32:29.483 UTC | 2011-04-01 10:24:06.223 UTC | null | 429,846 | null | 323,225 | null | 1 | 18 | r|ggplot2 | 9,042 | <p>Will something like this do?</p>
<pre><code>plotmatrix(data = wind) + geom_smooth(method="lm")
</code></pre>
<p>Which gives:</p>
<p><img src="https://i.stack.imgur.com/eKLpV.png" alt="pairs plotting in ggplot"></p>
<p>Hadley calls this a "Crude experimental scatterplot matrix", but it might suffice for your needs?</p>
<p><strong>Edit:</strong> Currently, <code>plotmatrix()</code> isn't quite flexible enough to handle all of @Chris' requirements regarding specification of the <code>geom_point()</code> layer. However, we can cut the guts out of <code>plotmatrix()</code> as use Hadley's nice code to create the data structure needed for plotting, but plot it however we like using standard <code>ggplot()</code> calls. This function also drops the densities but you can look into the code for <code>plotmatrix()</code> to see how to get them.</p>
<p>First, a function that expands the data from the wide format to the repeated format required for a pairs plot where we plot each variables against every other, but not itself.</p>
<pre><code>Expand <- function(data) {
grid <- expand.grid(x = 1:ncol(data), y = 1:ncol(data))
grid <- subset(grid, x != y)
all <- do.call("rbind", lapply(1:nrow(grid), function(i) {
xcol <- grid[i, "x"]
ycol <- grid[i, "y"]
data.frame(xvar = names(data)[ycol], yvar = names(data)[xcol],
x = data[, xcol], y = data[, ycol], data)
}))
all$xvar <- factor(all$xvar, levels = names(data))
all$yvar <- factor(all$yvar, levels = names(data))
all
}
</code></pre>
<p><strong>Note:</strong> <em>all</em> this does is steal Hadley's code from <code>plotmatrix()</code> - I have done nothing fancy here.</p>
<p>Expand the data:</p>
<pre><code>wind2 <- Expand(wind)
</code></pre>
<p>Now we can plot this as any other long-format data object required by <code>ggplot()</code>:</p>
<pre><code>ggplot(wind2, aes(x = x, y = y)) +
geom_point(alpha = I(1/10), shape = I(20), size = I(1)) +
facet_grid(xvar ~ yvar, scales = "free")
</code></pre>
<p>If you want the densities, then we can pull out that bit of code two into a helper function:</p>
<pre><code>makeDensities <- function(data) {
densities <- do.call("rbind", lapply(1:ncol(data), function(i) {
data.frame(xvar = names(data)[i], yvar = names(data)[i],
x = data[, i])
}))
densities
}
</code></pre>
<p>Then compute the densities for the <strong>original</strong> data:</p>
<pre><code>dens <- makeDensities(wind)
</code></pre>
<p>and then add then using the same bit of code from <code>plotmatrix()</code>:</p>
<pre><code>ggplot(wind2, aes(x = x, y = y)) +
geom_point(alpha = I(1/10), shape = I(20), size = I(1)) +
facet_grid(xvar ~ yvar, scales = "free")+
stat_density(aes(x = x, y = ..scaled.. * diff(range(x)) + min(x)),
data = dens, position = "identity", colour = "grey20",
geom = "line")
</code></pre>
<p>A complete version of the original figure I showed above but using the extracted code would be:</p>
<pre><code>ggplot(wind2, aes(x = x, y = y)) +
geom_point(alpha = I(1/10), shape = I(20), size = I(1)) +
facet_grid(xvar ~ yvar, scales = "free")+
stat_density(aes(x = x, y = ..scaled.. * diff(range(x)) + min(x)),
data = dens, position = "identity", colour = "grey20",
geom = "line") +
geom_smooth(method="lm")
</code></pre>
<p>giving:</p>
<p><img src="https://i.stack.imgur.com/PX4E5.png" alt="custom version of the pairs plot"></p> |
5,242,880 | android 9-patch graphic doesn't scale in image view | <p>I have</p>
<pre><code><LinearLayout android:id="@+id/LinearLayout01"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView android:layout_height="wrap_content"
android:layout_width="wrap_content" android:id="@+id/ImageView01"
android:src="@drawable/phone80"></ImageView>
<ImageView android:id="@+id/ImageView02"
android:layout_height="wrap_content" android:src="@drawable/underline"
android:layout_width="fill_parent" android:layout_gravity="fill_vertical|fill_horizontal"></ImageView>
</LinearLayout>
</code></pre>
<p>The first image is a fixed size image which shouldn't scale at all. The image right of it should scale horizontally to the maximum space. The source points to a valid .9.png file. Unfortunatly it always only shows up in its original size. What property to I have to set? Is ImageView the right object at all?</p>
<p>Thanks,
A.</p> | 5,242,897 | 4 | 0 | null | 2011-03-09 08:00:49.417 UTC | 9 | 2015-10-16 07:36:01.05 UTC | null | null | null | null | 481,493 | null | 1 | 8 | android|imageview|nine-patch | 20,371 | <p>Use <code>android:background</code> instead. And if it is just an underline, you can use a <code>View</code> and not an <code>ImageView</code>. As for filling the remainder of the screen, you may want to use a <code>TableLayout</code> instead.</p>
<p>Also, make sure your 9-patch is correct. The 1px sides must be black. #000</p> |
43,221,847 | Cannot call this method while RecyclerView is computing a layout or scrolling when try remove item from recyclerview | <p>I am Trying to remove my item from recyclerview, but i always getting error </p>
<blockquote>
<p>java.lang.IllegalStateException: Cannot call this method while
RecyclerView is computing a layout or scrolling</p>
</blockquote>
<p>i am using notify datasetchanged, can i solve this?</p>
<pre><code>public class AdapterIntransit extends RecyclerView.Adapter<AdapterIntransit.ViewHolder> {
private Context context;
List<DataIntransit> data;
public AdapterIntransit(Context context, List<DataIntransit> data) {
this.context = context;
this.data = data;
}
@Override
public AdapterIntransit.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardintransit, parent, false);
return new ViewHolder(itemView);
}
@Override
public void onBindViewHolder(AdapterIntransit.ViewHolder holder, int position) {
if (data.get(position).getJml1() - data.get(position).getJml2() <= 0) {
data.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, getItemCount());
notifyDataSetChanged();
} else {
holder.kode.setText(data.get(position).getKode());
holder.nama.setText(data.get(position).getNama());
holder.jumlah.setText(String.valueOf(data.get(position).getJml1() - data.get(position).getJml2()));
}
}
@Override
public int getItemCount() {
return data.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView kode, nama, jumlah;
public ViewHolder(View itemView) {
super(itemView);
kode = (TextView)itemView.findViewById(R.id.kode);
nama = (TextView)itemView.findViewById(R.id.nama);
jumlah = (TextView)itemView.findViewById(R.id.jumlah);
}
}
}
</code></pre> | 45,182,852 | 10 | 3 | null | 2017-04-05 04:30:36.31 UTC | 12 | 2022-05-23 07:27:39.64 UTC | 2017-04-05 04:41:39.03 UTC | null | 7,777,753 | null | 7,777,753 | null | 1 | 107 | android|android-recyclerview | 83,611 | <p><em><strong>Below answer worked for me</strong></em></p>
<p>This is just <code>workaround</code> for the problem.</p>
<p>This usually occurs when you are calling <code>notifyDataSetChanged()</code> on the <code>background thread</code>. So just move notify to <code>UI thread</code></p>
<pre><code>recyclerView.post(new Runnable()
{
@Override
public void run() {
myadapter.notifyDataSetChanged();
}
});
</code></pre>
<blockquote>
<p>You use your <code>RecyclerView</code> instance and inside the post method a new Runnable added to the message queue. The runnable will be run on the user interface thread. This is a limit for Android to access the <code>UI</code> thread from background (e.g. inside a method which will be run in a background thread).
for more you run it on <code>UI</code> thread if you needed.</p>
</blockquote>
<p>For more you can run it on <code>UI</code> thread, if you needed</p>
<pre><code> runOnUiThread(new Runnable(){
public void run() {
// UI code goes here
}
});
</code></pre> |
25,583,428 | ipython: how to set terminal width | <p>When I use <code>ipython terminal</code> and want to print a <code>numpy.ndarray</code> which has many columns, the lines are automatically broken somewhere around 80 characters (i.e. the width of the lines is cca 80 chars):</p>
<pre><code>z = zeros((2,20))
print z
</code></pre>
<p>Presumably, ipython expects that my terminal has 80 columns. In fact however, my terminal has width of 176 characters and I would like to use the full width.</p>
<p>I have tried changing the following parameter, but this has no effect:</p>
<pre><code>c.PlainTextFormatter.max_width = 160
</code></pre>
<p><strong>How can I tell <code>ipython</code> to use full width of my terminal ?</strong></p>
<p>I am using <code>ipython 1.2.1</code> on Debian Wheezy</p> | 25,619,121 | 4 | 3 | null | 2014-08-30 14:28:11.38 UTC | 9 | 2020-09-29 16:05:49.573 UTC | 2014-10-04 02:34:34.717 UTC | null | 2,223,706 | null | 2,693,551 | null | 1 | 30 | python|numpy|ipython | 15,159 | <p>After some digging through the code, it appears that the variable you're looking for is <code>numpy.core.arrayprint._line_width</code>, which is 75 by default. Setting it to 160 worked for me:</p>
<pre><code>>>> numpy.zeros((2, 20))
array([[ 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>The function used by default for array formatting is <code>numpy.core.numeric.array_repr</code>, although you can change this with <code>numpy.core.numeric.set_string_function</code>.</p> |
23,314,054 | Distinct random time generation in the fixed interval | <p>I'm trying to generate a random time between 8:00 AM and 8:00 PM <em>for each row</em> that is selected from a data set, however, I always get the <strong><em>same</strong> random value for each row</em> – I want it to be <strong><em>different</strong> for each row</em>.</p>
<p><em>Table schema & data:</em></p>
<pre class="lang-none prettyprint-override"><code>╔══════╦════════════════╗
║ ID ║ CREATED_DATE ║
╠══════╬════════════════╣
║ ID/1 ║ 26/04/2014 ║
║ ID/2 ║ 26/04/2014 ║
║ ID/3 ║ 26/04/2014 ║
║ ID/4 ║ 26/04/2014 ║
║ ID/5 ║ 26/04/2014 ║
╚══════╩════════════════╝
</code></pre>
<p><em>Сurrent SQL statement:</em></p>
<pre class="lang-sql prettyprint-override"><code>SELECT [ID]
, MyFunction.dbo.AddWorkDays(14, [CREATED_DATE]) AS [New Date]
, CONVERT(VARCHAR, DATEADD(MILLISECOND, CAST(43200000 * RAND() AS INT), CONVERT(TIME, '08:00')), 114) AS [New Time]
FROM [RandomTable]
</code></pre>
<p><em>Current results (<strong>same</strong> time for each row in the <code>[New Time]</code> column):</em></p>
<pre class="lang-none prettyprint-override"><code>╔══════╦════════════════╦════════════════╗
║ ID ║ New Date ║ New Time ║
╠══════╬════════════════╬════════════════╣
║ ID/1 ║ 10/05/2014 ║ 09:41:43 ║
║ ID/2 ║ 10/05/2014 ║ 09:41:43 ║
║ ID/3 ║ 10/05/2014 ║ 09:41:43 ║
║ ID/4 ║ 10/05/2014 ║ 09:41:43 ║
║ ID/5 ║ 10/05/2014 ║ 09:41:43 ║
╚══════╩════════════════╩════════════════╝
</code></pre>
<p><em>Desired results (<strong>different</strong> time for each row in the <code>[New Time]</code> column):</em></p>
<pre class="lang-none prettyprint-override"><code>╔══════╦════════════════╦════════════════╗
║ ID ║ New Date ║ New Time ║
╠══════╬════════════════╬════════════════╣
║ ID/1 ║ 10/05/2014 ║ 09:41:43 ║
║ ID/2 ║ 10/05/2014 ║ 15:05:23 ║
║ ID/3 ║ 10/05/2014 ║ 10:01:05 ║
║ ID/4 ║ 10/05/2014 ║ 19:32:45 ║
║ ID/5 ║ 10/05/2014 ║ 08:43:15 ║
╚══════╩════════════════╩════════════════╝
</code></pre>
<p>Any ideas on how to fix this? All of the above is just sample data – my real table has around 2800 records (<em>not sure if that will make a difference to anyone's suggestions</em>).</p> | 27,826,049 | 8 | 12 | null | 2014-04-26 17:04:16.633 UTC | 6 | 2021-06-14 05:35:45.89 UTC | 2018-05-20 00:46:24.527 UTC | null | 3,444,240 | null | 3,482,447 | null | 1 | 30 | sql|sql-server|sql-server-2008|tsql|random-time-generation | 13,109 | <h2>Interpretation of Original Question:</h2>
<p>The question states:</p>
<ul>
<li>Generate a <em>random</em> time between 8:00 AM and 8:00 PM (i.e. a 12-hour window)</li>
<li>It should be different <em>for each row</em> (i.e. unique across all rows)</li>
<li>The real table has around 2800 records</li>
</ul>
<p>Now factor in the following points:</p>
<ul>
<li>Sample data shows only a single date</li>
<li>There are 86,400 seconds in 24 hours, hence 43,200 seconds in 12 hours</li>
</ul>
<p>There is some ambiguity in the following areas:</p>
<ul>
<li>What exactly is random within the context of "different <em>for every row</em>", given that truly random values cannot be guaranteed to be different for every row. In fact, <em>truly</em> random numbers <em>could</em> theoretically be the <em>same</em> for every row. So is the emphasis on "random" or "different"? Or are we really talking about different but not sequentially ordered (to give the appearance of randomness without actually being random)?</li>
<li>What if there are ever more than 2800 rows? What if there are 1 million rows?</li>
<li>If there can be more than 43,200 rows, how to handle "different <em>for each row</em>" (since it is not possible to have unique across all rows)?</li>
<li>Will the date ever vary? If so, are we really talking about "different for each row <em>per date</em>"?</li>
<li>If "different for each row <em>per date</em>":
<ul>
<li>Can the times for each date follow the same, non-sequential pattern? Or does the pattern need to differ per each date?</li>
<li>Will there ever be more than 43,200 rows for any particular date? If so, the times can only be unique <em>per each set of 43,200 rows</em>.</li>
</ul></li>
</ul>
<p>Given the information above, there are a few ways to interpret the request:</p>
<ol>
<li><strong>Emphasis on "random":</strong> Dates and number of rows don't matter. Generate truly random times that are highly likely, but not <em>guaranteed</em>, to be unique using one of the three methods shown in the other answers:
<ul>
<li>@notulysses: <code>RAND(CAST(NEWID() AS VARBINARY)) * 43200</code></li>
<li>@Steve Ford: <code>ABS(CHECKSUM(NewId()) % 43201)</code></li>
<li>@Vladimir Baranov : <code>CAST(43200000 * (CAST(CRYPT_GEN_RANDOM(4) as int) / 4294967295.0 + 0.5) as int)</code></li>
</ul></li>
<li><strong>Emphasis on "different for each row", always <= 43,200 rows:</strong> If the number of rows never exceeds the number of available seconds, it is easy to guarantee unique times across all rows, regardless of same or different dates, and appear to be randomly ordered.</li>
<li><strong>Emphasis on "different for each row", could be > 43,200 rows:</strong> If the number of rows can exceed the number of available seconds, then it is not possible to guarantee uniqueness across <em>all</em> rows, but it would be possible to still guarantee uniqueness across rows of any particular date, provided that no particular date has > 43,200 rows.</li>
</ol>
<p>Hence, I based my answer on the idea that:</p>
<ul>
<li>Even if the number of rows for the O.P. never exceeds 2800, it is more likely that most others who are encountering a similar need for randomness would have a larger data set to work with (i.e. there could easily be 1 million rows, for any number of dates: 1, 5000, etc.)</li>
<li>Either the sample data is overly simplistic in using the same date for all 5 rows, or even if the date is the same for all rows in this particular case, in most other cases that is less likely to happen</li>
<li>Uniqueness is to be favored over Randomness</li>
<li>If there is a pattern to the "seemingly random" ordering of the seconds for each date, there should at least be a varying offset to the start of the sequence across the dates (when the dates are ordered sequentially) to give the appearance of randomness between any small grouping of dates.</li>
</ul>
<hr>
<h2>Answer:</h2>
<p>If the situation requires unique times, that cannot be guaranteed with any method of generating truly random values. I really like the use of <code>CRYPT_GEN_RANDOM</code> by @Vladimir Baranov, but it is nearly impossible to get a unique set of values generated:</p>
<pre class="lang-sql prettyprint-override"><code>DECLARE @Table TABLE (Col1 BIGINT NOT NULL UNIQUE);
INSERT INTO @Table (Col1)
SELECT CONVERT(BIGINT, CRYPT_GEN_RANDOM(4))
FROM [master].sys.objects so
CROSS JOIN [master].sys.objects so2
CROSS JOIN [master].sys.objects so3;
-- 753,571 rows
</code></pre>
<p>Increasing the random value to 8 bytes does seem to work:</p>
<pre class="lang-sql prettyprint-override"><code>DECLARE @Table TABLE (Col1 BIGINT NOT NULL UNIQUE);
INSERT INTO @Table (Col1)
SELECT CONVERT(BIGINT, CRYPT_GEN_RANDOM(8))
FROM [master].sys.objects so
CROSS JOIN [master].sys.objects so2
CROSS JOIN [master].sys.objects so3;
-- 753,571 rows
</code></pre>
<p>Of course, if we are generating down to the second, then there are only 86,400 of those. Reducing the scope seems to help as the following does occasionally work:</p>
<pre class="lang-sql prettyprint-override"><code>DECLARE @Table TABLE (Col1 BIGINT NOT NULL UNIQUE);
INSERT INTO @Table (Col1)
SELECT TOP (86400) CONVERT(BIGINT, CRYPT_GEN_RANDOM(4))
FROM [master].sys.objects so
CROSS JOIN [master].sys.objects so2
CROSS JOIN [master].sys.objects so3;
</code></pre>
<p>However, things get a bit trickier if the uniqueness needs <em>per each day</em> (which seems like a reasonable requirement of this type of project, as opposed to unique across all days). But a random number generator isn't going to know to reset at each new day.</p>
<p>If it is acceptable to merely have the appearance of being random, then we can guarantee uniqueness per each date without:</p>
<ul>
<li>looping / cursor constructs</li>
<li>saving already used values in a table</li>
<li>using <code>RAND()</code>, <code>NEWID()</code>, or <code>CRYPT_GEN_RANDOM()</code></li>
</ul>
<p>The following solution uses the concept of <a href="http://ericlippert.com/2013/11/12/math-from-scratch-part-thirteen-multiplicative-inverses/" rel="noreferrer">Modular Multiplicative Inverses</a> (MMI) which I learned about in this answer: <a href="https://stackoverflow.com/questions/26967215/generate-seemingly-random-unique-numeric-id-in-sql-server">generate seemingly random unique numeric ID in SQL Server</a> . Of course, that question did not have a tightly-defined range of values like we have here with only 86,400 of them per day. So, I used a range of 86400 (as "Modulo") and tried a few "coprime" values (as "Integer") in an <a href="http://planetcalc.com/3311/" rel="noreferrer">online calculator</a> to get their MMIs:</p>
<ul>
<li>13 (MMI = 39877)</li>
<li>37 (MMI = 51373)</li>
<li>59 (MMI = 39539)</li>
</ul>
<p>I use <code>ROW_NUMBER()</code> in a CTE, partitioned (i.e. grouped) by <code>CREATED_DATE</code> as a means of assigning each second of the day a value.</p>
<p>But, while the values generated for seconds 0, 1, 2, ... and so on sequentially will appear random, across different days that particular second will map to the same value. So, the second CTE (named "WhichSecond") shifts the starting point for each date by converting the date to an INT (which converts dates to a sequential offset from 1900-01-01) and then multiply by 101.</p>
<pre class="lang-sql prettyprint-override"><code>DECLARE @Data TABLE
(
ID INT NOT NULL IDENTITY(1, 1),
CREATED_DATE DATE NOT NULL
);
INSERT INTO @Data (CREATED_DATE) VALUES ('2014-10-05');
INSERT INTO @Data (CREATED_DATE) VALUES ('2014-10-05');
INSERT INTO @Data (CREATED_DATE) VALUES ('2014-10-05');
INSERT INTO @Data (CREATED_DATE) VALUES ('2014-10-05');
INSERT INTO @Data (CREATED_DATE) VALUES ('2014-10-05');
INSERT INTO @Data (CREATED_DATE) VALUES ('2015-03-15');
INSERT INTO @Data (CREATED_DATE) VALUES ('2016-10-22');
INSERT INTO @Data (CREATED_DATE) VALUES ('2015-03-15');
;WITH cte AS
(
SELECT tmp.ID,
CONVERT(DATETIME, tmp.CREATED_DATE) AS [CREATED_DATE],
ROW_NUMBER() OVER (PARTITION BY tmp.CREATED_DATE ORDER BY (SELECT NULL))
AS [RowNum]
FROM @Data tmp
), WhichSecond AS
(
SELECT cte.ID,
cte.CREATED_DATE,
((CONVERT(INT, cte.[CREATED_DATE]) - 29219) * 101) + cte.[RowNum]
AS [ThisSecond]
FROM cte
)
SELECT parts.*,
(parts.ThisSecond % 86400) AS [NormalizedSecond], -- wrap around to 0 when
-- value goes above 86,400
((parts.ThisSecond % 86400) * 39539) % 86400 AS [ActualSecond],
DATEADD(
SECOND,
(((parts.ThisSecond % 86400) * 39539) % 86400),
parts.CREATED_DATE
) AS [DateWithUniqueTime]
FROM WhichSecond parts
ORDER BY parts.ID;
</code></pre>
<p>Returns:</p>
<pre class="lang-none prettyprint-override"><code>ID CREATED_DATE ThisSecond NormalizedSecond ActualSecond DateWithUniqueTime
1 2014-10-05 1282297 72697 11483 2014-10-05 03:11:23.000
2 2014-10-05 1282298 72698 51022 2014-10-05 14:10:22.000
3 2014-10-05 1282299 72699 4161 2014-10-05 01:09:21.000
4 2014-10-05 1282300 72700 43700 2014-10-05 12:08:20.000
5 2014-10-05 1282301 72701 83239 2014-10-05 23:07:19.000
6 2015-03-15 1298558 2558 52762 2015-03-15 14:39:22.000
7 2016-10-22 1357845 61845 83055 2016-10-22 23:04:15.000
8 2015-03-15 1298559 2559 5901 2015-03-15 01:38:21.000
</code></pre>
<hr>
<p>If we want to only generate times between 8:00 AM and 8:00 PM, we only need to make a few minor adjustments:</p>
<ol>
<li>Change the range (as "Modulo") from 86400 to half of it: 43200</li>
<li>Recalculate the MMI (can use the same "coprime" values as "Integer"): 39539 (same as before)</li>
<li>Add <code>28800</code> to the second parameter of the <code>DATEADD</code> as an 8 hour offset</li>
</ol>
<p>The result will be a change to just one line (since the others are diagnostic):</p>
<pre class="lang-sql prettyprint-override"><code>-- second parameter of the DATEADD() call
28800 + (((parts.ThisSecond % 43200) * 39539) % 43200)
</code></pre>
<hr>
<p>Another means of shifting each day in a less predictable fashion would be to make use of <code>RAND()</code> by passing in the INT form of <code>CREATED_DATE</code> in the "WhichSecond" CTE. This would give a stable offset per each date since <code>RAND(x)</code> will return the same value <code>y</code> for the same value of <code>x</code> passed in, but will return a different value <code>y</code> for a different value of <code>x</code> passed in. Meaning:</p>
<p>RAND(1) = y1<br>
RAND(2) = y2<br>
RAND(3) = y3<br>
RAND(2) = y2 </p>
<p>The second time <code>RAND(2)</code> was called, it still returned the same value of <code>y2</code> that it returned the first time it was called.</p>
<p>Hence, the "WhichSecond" CTE could be:</p>
<pre><code>(
SELECT cte.ID,
cte.CREATED_DATE,
(RAND(CONVERT(INT, cte.[CREATED_DATE])) * {some number}) + cte.[RowNum]
AS [ThisSecond]
FROM cte
)
</code></pre> |
18,675,557 | What is the maximum amount of RAM an app can use? | <p>I am quite curious about this question concerning the <strong>memory management of the Android operating system</strong> so I hope for a quite detailed answer on that topic.</p>
<p>What I would like to know:</p>
<ul>
<li>What is the <strong>maximum amount of memory</strong> (in <strong>megabytes</strong> / as
<strong>percentage</strong> of the total RAM) that an Android application (that is not a system app) can use?</li>
<li>Are there any differences between <strong>Android versions</strong>?</li>
<li>Are there any differences concerning the <strong>manufacturer</strong> of the device?</li>
</ul>
<p>And most importantly:</p>
<ul>
<li><strong>What</strong> is considered / <strong>what does it depend on</strong> when it comes to the system determining how much RAM an app can use at runtime (assuming that the memory maximum per app is not a static number)?</li>
</ul>
<p>What I have heard so far (up until 2013):</p>
<ul>
<li>Early Android devices had a per-app cap of 16MB</li>
<li>Later this cap increased to 24MB or 32MB</li>
</ul>
<p><strong>What makes me very curious:</strong></p>
<p>Both of these limits are very low.</p>
<p>I have just recently downloaded the <a href="https://play.google.com/store/apps/details?id=com.james.SmartTaskManager&hl=de" rel="noreferrer">Android Task Manager</a> to check my devices RAM. What I have noticed is that there are applications using around 40-50 megabytes of RAM, which is obvioulsy more than the mentioned maximum RAM usage of let's say 32 MB. So how does Android determine how much RAM an app can use? How is it possible that apps exceed that limit?</p>
<p>Furthermore, I noticed that some apps of mine crash (killed by the system?) with an <strong>OutOfMemoryException</strong> when using around 30-40 Megabytes. On the other hand, I have apps running on my phone using <strong>100 MB and more</strong> after some time (probably due to memory leaks) that do not crash or get killed off.
So <strong>it obviously also depends on the app itself</strong> when it comes to determining how much RAM can be spared. How is this possible?
(I conducted my tests with an HTC One S with 768 MB RAM)</p>
<p><em>Disclaimer: I am NOT affiliated with Android Task Manager app in any way.</em></p> | 18,675,698 | 5 | 0 | null | 2013-09-07 16:40:07.897 UTC | 60 | 2021-12-19 11:02:52.923 UTC | 2018-12-03 09:03:27.083 UTC | null | 1,590,502 | null | 1,590,502 | null | 1 | 161 | android|memory|memory-management|out-of-memory|android-memory | 90,182 | <blockquote>
<p>What is the maximum amount of memory (in Megabytes / as percentage of the total RAM) that an Android application (that is not a system app) can use?</p>
</blockquote>
<p>That varies by device. <a href="http://developer.android.com/reference/android/app/ActivityManager.html#getMemoryClass%28%29" rel="noreferrer"><code>getMemoryClass()</code> on <code>ActivityManager</code></a> will give you the value for the device your code is running upon.</p>
<blockquote>
<p>Are there any differences between the Android versions?</p>
</blockquote>
<p>Yes, insofar as OS requirements have increased over the years, and devices have to adjust to match.</p>
<blockquote>
<p>Are there differences concerning the manufacturer of the device?</p>
</blockquote>
<p>Yes, insofar as manufacturers manufacture devices, and the size varies by device.</p>
<blockquote>
<p>Which "side factors" are taken into consideration when it comes to determining how much RAM an app can use?</p>
</blockquote>
<p>I have no idea what "side factors" means.</p>
<blockquote>
<p>Early devices had a per-app cap of 16MB; Later devices increased that to 24MB or 32MB</p>
</blockquote>
<p>That's about right. Screen resolution is a significant determinant, as larger resolutions mean larger bitmaps, and so tablets and high-resolution phones will tend to have higher values yet. For example, you will see devices with 48MB heaps, and I wouldn't be surprised if there are values higher than that.</p>
<blockquote>
<p>How is it possible that apps exceed that limit?</p>
</blockquote>
<p>You assume that the author of that app knows what (s)he is doing. Considering that <a href="https://stackoverflow.com/questions/2298208/how-to-discover-memory-usage-of-my-application-in-android/2299813#2299813">memory usage of an app is difficult for a core Android engineer to determine</a>, I would not assume that the app in question is necessarily providing particularly accurate results.</p>
<p>That being said, native code (NDK) is not subject to the heap limit. And, since Android 3.0, apps can request a "large heap", usually in the hundreds of MB range, but that's considered poor form for most apps.</p>
<blockquote>
<p>Furthermore, I noticed that some apps of mine crash with an OutOfMemoryException when using around 30-40 Megabytes.</p>
</blockquote>
<p>Bear in mind that the Android garbage collector is not a compacting garbage collector. The exception really should be <code>CouldNotFindSufficientlyLargeBlockOfMemoryException</code>, but that was probably deemed too wordy. <code>OutOfMemoryException</code> means that you <strong>could not allocate your requested block</strong>, not that you have exhausted your heap entirely.</p> |
18,444,840 | How to disable a pep8 error in a specific file? | <p>I tried with</p>
<pre><code>#:PEP8 -E223
</code></pre>
<p>or</p>
<pre><code># pep8: disable=E223
</code></pre>
<p>I thought the second would work but doesn't seems to work.</p>
<p>Do you have an idea how I can handle this ?</p> | 18,445,159 | 8 | 0 | null | 2013-08-26 13:03:23.097 UTC | 11 | 2021-03-18 10:48:10.223 UTC | 2017-06-13 13:55:29.913 UTC | null | 2,394,026 | null | 2,394,026 | null | 1 | 100 | python|pep8 | 81,053 | <p>As far as I know, you can't.
You can disable errors or warnings user wide, or per project. See <a href="http://pep8.readthedocs.org/en/latest/intro.html#configuration">the documentation</a>.</p>
<p>Instead, you can use the <code># noqa</code> comment at the end of a line, to skip that particular line (see <a href="https://github.com/jcrocholl/pep8/pull/136">patch 136</a>). Of course, that would skip all PEP8 errors.</p>
<p>The main author argues against <a href="https://github.com/jcrocholl/pep8/pull/27#issuecomment-11509431">source file noise</a>, so they suggested <code># pep8</code> comments don't get included.</p>
<hr>
<p>Note that there is also <code>nopep8</code>, which is the equivalent. <code>noqa</code> (which stands for <a href="https://github.com/PyCQA/pycodestyle/issues/476">No Quality Assurance</a> was added <a href="https://github.com/PyCQA/pycodestyle/blob/08f48912d88e4c8104813cc2834e634841f0301c/CHANGES.txt#L393">in version 1.4.1</a> to support people <a href="https://github.com/PyCQA/pycodestyle/issues/149">running <code>pyflakes</code> next to <code>pep8</code></a>.</p> |
18,410,922 | Bootstrap 3.0 Popovers and tooltips | <p>I am new to Bootstrap and I'm having trouble getting the popover and tooltip features to work. I had no problem with the drop downs and models but I seem to be missing something for the popover and tooltips. </p>
<p>I am getting tooltips to show up but they are not styled and located like the bootstrap examples. And the popover is not working at all.</p>
<p>Please take a look and let me know what I am missing.</p>
<pre><code> <!DOCTYPE html>
<html>
<head>
<title>Bootstrap 101 Template</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet" media="screen">
<link href="css/font-awesome.min.css" rel="stylesheet" media="screen">
<link href="css/index.css" rel="stylesheet" media="screen">
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="../../assets/js/html5shiv.js"></script>
<script src="../../assets/js/respond.min.js"></script>
<![endif]-->
</head>
<body>
<p id="tool"class="muted" style="margin-bottom: 0;">
Tight pants next level keffiyeh
<a href="#" data-toggle="tooltip" title="Default tooltip">you probably</a> haven't heard of them. Photo booth beard raw denim letterpress vegan messenger bag stumptown. Farm-to-table seitan, mcsweeney's fixie sustainable quinoa 8-bit american apparel <a href="#" data-toggle="tooltip" title="Another tooltip">have a</a> terry richardson vinyl chambray. Beard stumptown, cardigans banh mi lomo thundercats. Tofu biodiesel williamsburg marfa, four loko mcsweeney's cleanse vegan chambray. A really ironic artisan <a href="#" data-toggle="tooltip" title="Another one here too">whatever keytar</a>, scenester farm-to-table banksy Austin <a href="#" data-toggle="tooltip" title="The last tip!">twitter handle</a> freegan cred raw denim single-origin coffee viral.</p>
<h3>Live demo</h3>
<div style="padding-bottom: 24px;">
<a id="pop" href="#" class="btn btn-lg btn-danger" data-toggle="popover" title="A Title" data-content="And here's some amazing content. It's very engaging. right?">Click to toggle popover</a>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="http://code.jquery.com/jquery.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script type="text/javascript">
$(document).ready(function() {
$('.tool').tooltip();
$('.btn').popover();
}); //END $(document).ready()
</script>
<script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap.min.css"></script>
</body>
</html>
</code></pre> | 18,537,617 | 8 | 4 | null | 2013-08-23 20:01:15.607 UTC | 40 | 2015-05-04 05:41:57.95 UTC | 2014-08-18 18:26:24.123 UTC | null | 3,900,052 | null | 2,560,895 | null | 1 | 84 | javascript|jquery|css|twitter-bootstrap | 214,727 | <p>Turns out that <a href="https://stackoverflow.com/a/18411591/463065">Evan Larsen has the best answer</a>. Please upvote his answer (and/or select it as the correct answer) - it's brilliant.</p>
<p><a href="http://jsfiddle.net/LhZpX/" rel="noreferrer">Working jsFiddle here</a></p>
<p>Using Evan's trick, you can instantiate all tooltips with one line of code:</p>
<pre><code>$('[data-toggle="tooltip"]').tooltip({'placement': 'top'});
</code></pre>
<p>You will see that all tooltips in your long paragraph have working tooltips with just that one line.</p>
<p>In the jsFiddle example (link above), I also added a situation where one tooltip (by the Sign-In button) is ON by default. Also, the tooltip code is ADDED to the button in jQuery, not in the HTML markup.</p>
<hr>
<p>Popovers <em>do</em> work the same as the tooltips:</p>
<pre><code>$('[data-toggle="popover"]').popover({trigger: 'hover','placement': 'top'});
</code></pre>
<hr>
<p>And there you have it! Success at last.</p>
<p>One of the biggest problems in figuring this stuff out was making bootstrap work with jsFiddle... Here's what you must do:</p>
<ol>
<li>Get reference for Twitter Bootstrap CDN from here: <a href="http://www.bootstrapcdn.com/" rel="noreferrer">http://www.bootstrapcdn.com/</a><br></li>
<li>Paste each link into notepad and strip out ALL except the URL. For example:<br>
<strong>//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css</strong><br></li>
<li>In jsFiddle, on left side, open the External Resources accordion dropdown</li>
<li>Paste in each URL, pressing plus sign after each paste</li>
<li>Now, open the "Frameworks & Extensions" accordion dropdown, and select jQuery 1.9.1 (or whichever...)</li>
</ol>
<p>NOW you are ready to go.</p> |
20,150,527 | Concatenate two Dictionaries | <p>Given some Dictionaries</p>
<pre><code>Dictionary<string, string> GroupNames = new Dictionary<string, string>();
Dictionary<string, string> AddedGroupNames = new Dictionary<string, string>();
</code></pre>
<p>I am unable to merge them into one:</p>
<pre><code>GroupNames = GroupNames.Concat(AddedGroupNames);
</code></pre>
<p>because "the type can't be implicitly converted". I believe (and my code proves me true) their type is the same - what am I overlooking?</p> | 20,150,588 | 1 | 2 | null | 2013-11-22 17:08:29.53 UTC | 7 | 2013-11-22 17:11:48.55 UTC | null | null | null | null | 1,827,295 | null | 1 | 53 | c#|implicit-conversion | 68,009 | <p>I think you defined your <code>GroupNames</code> as <code>Dictionary<string,string></code>, so you need to add <code>ToDictionary</code> like this:</p>
<pre><code>GroupNames = GroupNames.Concat(AddedGroupNames)
.ToDictionary(x=>x.Key,x=>x.Value);
</code></pre>
<p>Note that 2 original dictionaries would have different keys, otherwise we need some rule to merge them correctly.</p> |
27,736,618 | Why are sem_init(), sem_getvalue(), sem_destroy() deprecated on Mac OS X — and what replaces them? | <p>When I compile a program using the POSIX <a href="http://pubs.opengroup.org/onlinepubs/9699919799/functions/sem_init.html" rel="noreferrer"><code>sem_init()</code></a> function, I get a compilation warning (error because I normally use <code>-Werror</code>) that the function has been deprecated when I compile on Mac OS X 10.10.1 (Yosemite) with GCC 4.9.1 or the version of Clang (<code>Apple LLVM version 6.0 (clang-600.0.56) (based on LLVM 3.5svn)</code>) from XCode 6.1.1. A quick look at <code>/usr/include/sys/semaphore.h</code> shows that the function does indeed have a <code>__deprecated</code> tag after its declaration, as do
<a href="http://pubs.opengroup.org/onlinepubs/9699919799/functions/sem_getvalue.html" rel="noreferrer"><code>sem_getvalue()</code></a> and
<a href="http://pubs.opengroup.org/onlinepubs/9699919799/functions/sem_destroy.html" rel="noreferrer"><code>sem_destroy()</code></a>.</p>
<p>Questions:</p>
<ol>
<li><p>Given that there is no hint of deprecation in the POSIX specification, why are these three functions singled out as deprecated on Mac OS X?</p></li>
<li><p>Given that they are deprecated, what is the replacement, and why is the replacement preferred?</p></li>
</ol>
<p>(<em>I did check <a href="https://apple.stackexchange.com/">Ask Different</a> first; there are no questions tagged <a href="/questions/tagged/c" class="post-tag" title="show questions tagged 'c'" rel="tag">c</a> and no questions that ask about deprecated system calls — only programs.</em>)</p> | 27,847,103 | 1 | 5 | null | 2015-01-02 02:08:23.627 UTC | 8 | 2022-02-20 22:58:16.753 UTC | 2017-04-13 12:45:06.893 UTC | null | -1 | null | 15,168 | null | 1 | 46 | c|macos|posix | 25,839 | <p>I ran into this problem myself when trying to port a library I was working on to OS X. I searched for a while without finding a great answer. When I did find the answer, I was a bit perturbed: the answer is effectively <a href="http://lists.apple.com/archives/darwin-kernel/2009/Apr/msg00010.html">"if Apple implemented POSIX unnamed semaphores, how many X Serves would you buy?"</a>.</p>
<p>To summarize the points of why they are deprecated and why some of the functionality remains unimplemented:</p>
<ul>
<li>Appendix 9 of the Single UNIX Specification states they are not mandatory interfaces</li>
<li>"Most portable code" uses SYSV semaphores</li>
<li>Backwards compatibility with POSIX named semaphores, which share the <code>sem_t</code> type is difficult</li>
</ul>
<p>As for what to do instead, I went with GCD semaphores. As to why the replacement is preferred: it's the only native unnamed semaphore interface available on vanilla OS X. Apparently GCD helped them sell more X Serves. I fear there's not a better answer.</p>
<p>However, hopefully some code will be helpful. The upshot of all of this is that you effectively have to implement your own portable semaphore interface:</p>
<pre><code>#ifdef __APPLE__
#include <dispatch/dispatch.h>
#else
#include <semaphore.h>
#endif
struct rk_sema {
#ifdef __APPLE__
dispatch_semaphore_t sem;
#else
sem_t sem;
#endif
};
static inline void
rk_sema_init(struct rk_sema *s, uint32_t value)
{
#ifdef __APPLE__
dispatch_semaphore_t *sem = &s->sem;
*sem = dispatch_semaphore_create(value);
#else
sem_init(&s->sem, 0, value);
#endif
}
static inline void
rk_sema_wait(struct rk_sema *s)
{
#ifdef __APPLE__
dispatch_semaphore_wait(s->sem, DISPATCH_TIME_FOREVER);
#else
int r;
do {
r = sem_wait(&s->sem);
} while (r == -1 && errno == EINTR);
#endif
}
static inline void
rk_sema_post(struct rk_sema *s)
{
#ifdef __APPLE__
dispatch_semaphore_signal(s->sem);
#else
sem_post(&s->sem);
#endif
}
</code></pre>
<p>This was the minimal set of functionality I cared about; your needs may vary. Hopefully this is helpful.</p> |
15,077,217 | Count only fields with text/data, not formulas | <p>I have a listing of headcount within a given month that I am comparing to budgeted headcount.
I have used a vlookup to match budget to actuals.
Then: =IF(ISNA(M66),K66," ") to return names that are not in budget, but in actuals (HR file) or else blank. </p>
<p>Now I would like to count the names returned in the column , but I'm having trouble with the count functions recognizing the formula in the cells even though they are blank.</p>
<p>Thanks for your time!</p> | 15,077,342 | 2 | 4 | null | 2013-02-25 21:53:10.043 UTC | 7 | 2019-01-29 23:49:20.693 UTC | 2013-02-25 21:55:38.857 UTC | null | 2,108,929 | null | 2,108,929 | null | 1 | 13 | excel|count | 86,782 | <p>[Edit - didn't notice the space in " " - remove that as Scott suggests then try below]</p>
<p>If range of data is A2:A100 try this formula to count text values but not ""</p>
<p><code>=COUNTIF(A2:A100,"?*")</code></p>
<p>or if you want to include numeric values too</p>
<p><code>=SUMPRODUCT((A2:A100<>"")+0)</code></p> |
15,322,917 | Clearing URL hash | <p>Visit <code>stackoverflow.com/#_=_</code> and <code>window.location.hash</code> evaluates to <code>#_=_</code>. Fine.</p>
<p>Now execute <code>window.location.hash = ''</code> to clear the hash, and the URL becomes <code>stackoverflow.com/#</code>. (Notice the trailing <code>#</code>.)</p>
<p>Why is the <code>#</code> in <code>window.location.hash</code> inconsistently included or excluded? How can the <code>#</code> be removed from the URL without reloading the page?</p>
<p>(<a href="https://developer.mozilla.org/en-US/docs/DOM/window.location">MDN</a> says</p>
<blockquote>
<p>[the hash is] the part of the URL that follows the # symbol, including the # symbol.</p>
</blockquote>
<p>but that is not true for in the case of an empty hash.)</p> | 15,323,220 | 3 | 6 | null | 2013-03-10 13:46:54.363 UTC | 9 | 2017-09-09 08:56:50.407 UTC | 2016-09-14 08:43:32.503 UTC | null | 3,576,214 | null | 707,381 | null | 1 | 30 | javascript|html|url-routing|window.location | 28,289 | <p>To answer the second question (removing the <code>#</code> without a page refresh):</p>
<pre><code>history.pushState('', document.title, window.location.pathname);
</code></pre> |
15,137,308 | AtomicInteger.incrementAndGet() vs. AtomicInteger.getAndIncrement() | <p>When return value is not of interest, is there any (even irrelevant in practice) difference between <a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/atomic/AtomicInteger.html#getAndIncrement%28%29" rel="noreferrer"><code>AtomicInteger.getAndIncrement()</code></a> and <a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/atomic/AtomicInteger.html#incrementAndGet%28%29" rel="noreferrer"><code>AtomicInteger.incrementAndGet()</code></a> methods, when return value is ignored?</p>
<p>I'm thinking of differences like which would be more idiomatic, as well as which would put less load in CPU caches getting synchronized, or anything else really, anything to help decide which one to use more rationally than tossing a coin.</p> | 15,154,441 | 5 | 4 | null | 2013-02-28 13:56:22.12 UTC | 2 | 2017-08-30 19:17:25.773 UTC | null | null | null | null | 1,717,300 | null | 1 | 56 | java|atomic|java.util.concurrent | 28,274 | <p>Since no answer to the actual question has been given, here's my personal opinion based on the other answers (thanks, upvoted) and Java convention:</p>
<pre><code>incrementAndGet()
</code></pre>
<p>is better, because method names should start with the verb describing the action, and intended action here is to increment only.</p>
<p>Starting with verb is the common Java convention, also described by official docs:</p>
<p><a href="http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367" rel="noreferrer">"Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized."</a></p> |
15,231,937 | heroku and github at the same time | <p>So I understand that heroku functions as a git repository, but let's say i want to use github as well as a repository. How do I set it up such that I have two repositories and both are in sync? </p> | 15,232,034 | 6 | 0 | null | 2013-03-05 19:01:14.577 UTC | 54 | 2019-08-31 19:33:31.91 UTC | null | null | null | null | 1,433,227 | null | 1 | 70 | git|heroku|github | 32,968 | <p>You can have multiple remotes on a git installation. You would have a github remote, and a heroku remote.</p>
<p>Assuming you already have github setup, then you probably push to github with something like:</p>
<p><code>git push origin master</code></p>
<p><code>origin</code> is your remote, and <code>master</code> is your branch.</p>
<p>Follow the instructions in <a href="https://devcenter.heroku.com/articles/quickstart">getting started with Heroku</a> choose your desired language and continue through the tutorial. This tutorial assumes that you already have github setup, and will show you how to create your <code>heroku</code> remote - via <code>heroku create</code>.</p>
<p>You then push to github as normal, and push to heroku via:</p>
<p><code>git push heroku master</code></p>
<p>The same format applies - <code>heroku</code> is your remote, and <code>master</code> is your branch. You are not overwriting your Github remote here, you are adding another, so you can still do both pushes via one commit with workflow such as:</p>
<pre><code>git add .
git commit -m "Going to push to Heroku and Git"
git push origin master -- push to Github Master branch
git push heroku master -- push to Heroku
</code></pre> |
45,070,661 | python+opencv - How to plot hsv range? | <p>To extract the color, we have this function</p>
<pre><code># define range of blue color in HSV
lower_blue = np.array([110,50,50])
upper_blue = np.array([130,255,255])
# Threshold the HSV image to get only blue colors
mask = cv2.inRange(hsv, lower_blue, upper_blue)
</code></pre>
<p>How do we actually visualize the range(lower_blue,upper_blue) I define on hsv space?
Also How do I actually plot a hsv color,but it is not working...?
I have this code:</p>
<pre><code>upper = np.array([60, 255, 255])
upper = cv2.cvtColor(upper, cv2.COLOR_HSV2BGR)
upper = totuple(upper/-255)
print(upper)
plt.imshow([[upper]])
</code></pre> | 45,071,147 | 1 | 7 | null | 2017-07-13 02:54:16.767 UTC | 8 | 2017-07-13 07:27:17.153 UTC | 2017-07-13 03:22:24.213 UTC | null | 7,567,502 | null | 7,567,502 | null | 1 | 5 | python|opencv | 13,132 | <h1>What are HSV colors</h1>
<p>HSV, like HSL (or in OpenCV, HLS), is one of the cylindrical colorspaces.</p>
<p><a href="https://i.stack.imgur.com/kbBMc.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/kbBMc.jpg" alt="cylindrical colorspaces"></a></p>
<p>The name is somewhat descriptive of how their values are referenced. </p>
<p>The hue is represented as degrees from 0 to 360 (in OpenCV, to fit into the an 8-bit unsigned integer format, they degrees are divided by two to get a number from 0 to 179; so 110 in OpenCV is 220 degrees). If you were to take a "range" of hue values, it's like cutting a slice from a cake. You're just taking some angle chunk of the cake.</p>
<p>The saturation channel is how far from the center you are---the radius you're at. The center has absolutely no saturation---only gray colors from black to white. If you took a range of these values, it is akin to shaving off the outside of the cylinder, or cutting out a circle from the center. For example, if the range is 0 to 255, then the range 0 to 127 would be a cylinder only extending to half the radius; the range 127 to 255 would be cutting an inner cylinder with half the radius out.</p>
<p>The value channel is a slightly confusing name; it's not exactly darkness-to-brightness because the highest value represents the direct color, while the lowest value is black. This is the height of the cylinder. Not too hard to imagine cutting a slice of the cylinder vertically. </p>
<h1>Ranges of HSV values</h1>
<p>The function <code>cv2.inRange(image, lower_bound, upper_bound)</code> finds all values of the image between <code>lower_bound</code> and <code>upper_bound</code>. For instance, if your image was a 3x3 image (just for simple demonstration purposes) with 3-channels, it might look something like this:</p>
<pre><code># h channel # s channel # v channel
100 150 250 150 150 100 50 75 225
50 100 125 75 25 50 255 100 50
0 255 125 100 200 250 50 75 100
</code></pre>
<p>If we wanted to select hues between 100 and 200, then our <code>lower_b</code> should be <code>[100, 0, 0]</code> and <code>upper_b</code> should be <code>[200, 255, 255]</code>. That way our mask would only take into account values in the hue channel, and not be affected by the saturation and value. That's why HSV is so popular---you can select colors by hue regardless of their brightness or darkness, so a dark red and bright red can be selected just by specifying the min and max of the hue channel.</p>
<p>But say we only wanted to select bright white colors. Take a look back at the cylinder model---we see that white is given at the top-center of the cylinder, so where <code>s</code> values are low, and <code>v</code> values are high, and the color angle doesn't matter. So the <code>lower_b</code> would look something like <code>[0, 0, 200]</code> and <code>upper_b</code> would look something like <code>[255, 50, 255]</code>. That means all <code>H</code> values will be included and won't affect our mask. But then only <code>S</code> values between 0 and 50 would be included (towards the center of the cylinder) and only <code>V</code> values from 200 to 255 will be included (towards the top of the cylinder).</p>
<h1>Visualizing a range of colors from HSV</h1>
<p>One way to visualize all the colors in a range is to create gradients going the length of both directions for each of two channels, and then animate over the changing third channel.</p>
<p>For instance, you could create a gradient of values from left to right for the range of <code>S</code> values, from top to bottom for the range of <code>V</code> values, and then loop over each <code>H</code> value. This whole program could look something like this:</p>
<pre><code>import numpy as np
import cv2
lower_b = np.array([110,50,50])
upper_b = np.array([130,255,255])
s_gradient = np.ones((500,1), dtype=np.uint8)*np.linspace(lower_b[1], upper_b[1], 500, dtype=np.uint8)
v_gradient = np.rot90(np.ones((500,1), dtype=np.uint8)*np.linspace(lower_b[1], upper_b[1], 500, dtype=np.uint8))
h_array = np.arange(lower_b[0], upper_b[0]+1)
for hue in h_array:
h = hue*np.ones((500,500), dtype=np.uint8)
hsv_color = cv2.merge((h, s_gradient, v_gradient))
rgb_color = cv2.cvtColor(hsv_color, cv2.COLOR_HSV2BGR)
cv2.imshow('', rgb_color)
cv2.waitKey(250)
cv2.destroyAllWindows()
</code></pre>
<p><a href="https://i.stack.imgur.com/ISFgH.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/ISFgH.gif" alt="Gif of range values"></a></p>
<p>Now this gif shows a new <code>H</code> value every frame. And from left to right we have the min to max <code>S</code> values, and from top to bottom we have the min to max <code>V</code> values. Every single one of the colors showing up in this animation will be selected from your image to be part of your <code>mask</code>.</p>
<h1>Make your own inRange() function</h1>
<p>To fully understand the OpenCV function, the easiest way is just to make your own function to complete the task. It's not difficult at all, and not very much code. </p>
<p>The idea behind the function is simple: find where the values of each channel fall between <code>min</code> and <code>max</code>, and then <code>&</code> all the channels together. </p>
<pre><code>def inRange(img, lower_b, upper_b):
ch1, ch2, ch3 = cv2.split(img)
ch1m = (lower_b[0] <= ch1) & (ch1 <= upper_b[0])
ch2m = (lower_b[1] <= ch2) & (ch2 <= upper_b[1])
ch3m = (lower_b[2] <= ch3) & (ch3 <= upper_b[2])
mask = ch1m & ch2m & ch3m
return mask.astype(np.uint8)*255
</code></pre>
<p>You can read the <a href="http://docs.opencv.org/3.0-beta/modules/core/doc/operations_on_arrays.html?#cv2.inRange" rel="noreferrer">OpenCV docs</a> to see that this is indeed the formula used. And we can verify it too.</p>
<pre><code>lower_b = np.array([200,200,200])
upper_b = np.array([255,255,255])
mask = cv2.inRange(img, lower_b, upper_b) # OpenCV function
mask2 = inRange(img, lower_b, upper_b) # above defined function
print((mask==mask2).all()) # checks that the masks agree on all values
# True
</code></pre>
<h1>How to find the right colors</h1>
<p>It can be a little tricky to find the <em>correct</em> values to use for a particular image. There is an easy way to experiment, though. You can create trackbars in OpenCV and use them to control the min and max for each channel and have the Python program update your mask every time you change the values. I made a program for this which you can grab on GitHub <a href="https://github.com/alkasm/cspaceThresh" rel="noreferrer">here</a>. Here's an animated <code>.gif</code> of it being used, to demonstrate:</p>
<p><a href="https://i.imgur.com/Kah3s7n.gif" rel="noreferrer"><img src="https://i.imgur.com/Kah3s7n.gif" alt="Gif of cspaceThresh program"></a></p> |
8,171,856 | MIMEText UTF-8 encode problems when sending email | <p>Here is a part of my code which sends an email:</p>
<pre><code>servidor = smtplib.SMTP()
servidor.connect(HOST, PORT)
servidor.login(user, usenha)
assunto = str(self.lineEdit.text())
para = str(globe_email)
texto = self.textEdit.toPlainText()
textos = str(texto)
corpo = MIMEText(textos.encode('utf-8'), _charset='utf-8')
corpo['From'] = user
corpo['To'] = para
corpo['Subject'] = assunto
servidor.sendmail(user, [para], corpo.as_string())
</code></pre>
<p>Everything is ok except the part of the Subject.
When I try to send a string with special characters (e.g. "ação") it raises this error:</p>
<pre><code>UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-2: ordinal not in range(128)
</code></pre>
<p>How can I send emails with special characters in the Subject of MIMEText?</p> | 8,173,543 | 2 | 0 | null | 2011-11-17 17:49:24 UTC | 9 | 2020-06-27 12:28:39.457 UTC | 2016-02-29 01:58:54.233 UTC | null | 984,421 | null | 798,758 | null | 1 | 19 | python|email|python-3.x|unicode|utf-8 | 34,792 | <p>It seems that, in python3, a <a href="http://docs.python.org/py3k/library/email.header.html#email.header.Header" rel="noreferrer"><code>Header</code></a> object is needed to encode a <code>Subject</code> as utf-8:</p>
<pre><code># -*- coding: utf-8 -*-
from email.mime.text import MIMEText
from email.header import Header
s = 'ação'
m = MIMEText(s, 'plain', 'utf-8')
m['Subject'] = Header(s, 'utf-8')
print(repr(m.as_string()))
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>'Content-Type: text/plain; charset="utf-8"\nMIME-Version: 1.0\nContent-Transfer-Encoding: base64\nSubject: =?utf-8?b?YcOnw6Nv?=\n\nYcOnw6Nv\n
</code></pre>
<p>So the original script would become:</p>
<pre><code>servidor = smtplib.SMTP()
servidor.connect(HOST, PORT)
servidor.login(user, usenha)
assunto = str(self.lineEdit.text())
para = str(globe_email)
texto = str(self.textEdit.toPlainText())
corpo = MIMEText(texto, 'plain', 'utf-8')
corpo['From'] = user
corpo['To'] = para
corpo['Subject'] = Header(assunto, 'utf-8')
servidor.sendmail(user, [para], corpo.as_string())
</code></pre> |
4,853,581 | Django - Get uploaded file type / mimetype | <p>Is there a way to get the content type of an upload file when overwriting the models save method? I have tried this:</p>
<pre><code>def save(self):
print(self.file.content_type)
super(Media, self).save()
</code></pre>
<p>But it did not work. In this example, self.file is a model.FileField:</p>
<pre><code>file = models.FileField(upload_to='uploads/%m-%Y/')
</code></pre>
<p>Edit: I want to be able to save the content type to the database, so I'll need it before the save is actually complete :)</p> | 4,855,340 | 4 | 5 | null | 2011-01-31 16:49:21.557 UTC | 11 | 2022-07-26 10:33:01.39 UTC | 2011-01-31 16:55:24.553 UTC | null | 170,488 | null | 170,488 | null | 1 | 26 | django | 42,244 | <pre><code>class MyForm(forms.ModelForm):
def clean_file(self):
file = self.cleaned_data['file']
try:
if file:
file_type = file.content_type.split('/')[0]
print file_type
if len(file.name.split('.')) == 1:
raise forms.ValidationError(_('File type is not supported'))
if file_type in settings.TASK_UPLOAD_FILE_TYPES:
if file._size > settings.TASK_UPLOAD_FILE_MAX_SIZE:
raise forms.ValidationError(_('Please keep filesize under %s. Current filesize %s') % (filesizeformat(settings.TASK_UPLOAD_FILE_MAX_SIZE), filesizeformat(file._size)))
else:
raise forms.ValidationError(_('File type is not supported'))
except:
pass
return file
</code></pre>
<p>settings.py</p>
<pre><code>TASK_UPLOAD_FILE_TYPES = ['pdf', 'vnd.oasis.opendocument.text','vnd.ms-excel','msword','application',]
TASK_UPLOAD_FILE_MAX_SIZE = "5242880"
</code></pre> |
5,237,989 | How is a non-breaking space represented in a JavaScript string? | <p>This apparently is not working:</p>
<pre><code>X = $td.text();
if (X == '&nbsp;') {
X = '';
}
</code></pre>
<p>Is there something about a non-breaking space or the ampersand that JavaScript doesn't like?</p> | 5,238,020 | 4 | 7 | null | 2011-03-08 20:32:13.267 UTC | 20 | 2018-11-15 17:38:01.69 UTC | 2018-11-15 17:38:01.69 UTC | null | 12,484 | null | 111,665 | null | 1 | 161 | javascript|jquery | 168,656 | <p><code>&nbsp;</code> is a HTML entity. When doing <code>.text()</code>, all HTML entities are decoded to their character values.</p>
<p>Instead of comparing using the entity, compare using the actual raw character:</p>
<pre><code>var x = td.text();
if (x == '\xa0') { // Non-breakable space is char 0xa0 (160 dec)
x = '';
}
</code></pre>
<p>Or you can also create the character from the character code manually it in its Javascript escaped form:</p>
<pre><code>var x = td.text();
if (x == String.fromCharCode(160)) { // Non-breakable space is char 160
x = '';
}
</code></pre>
<p>More information about <code>String.fromCharCode</code> is available here:</p>
<blockquote>
<p><a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/fromCharCode" rel="noreferrer">fromCharCode - MDC Doc Center</a></p>
</blockquote>
<p>More information about character codes for different charsets are available here:</p>
<blockquote>
<p><a href="http://en.wikipedia.org/wiki/Windows-1252" rel="noreferrer">Windows-1252 Charset</a><br>
<a href="http://en.wikipedia.org/wiki/UTF-8" rel="noreferrer">UTF-8 Charset</a></p>
</blockquote> |
5,120,171 | Extract links from a web page | <p>Using Java, how can I extract all the links from a given web page?</p> | 5,120,608 | 6 | 1 | null | 2011-02-25 16:57:53.11 UTC | 11 | 2016-10-05 23:16:27.18 UTC | 2014-11-19 18:48:52.517 UTC | null | 2,476,755 | null | 346,297 | null | 1 | 24 | java|hyperlink|package|extract | 56,526 | <p>download java file as plain text/html pass it through <a href="http://jsoup.org/cookbook/extracting-data/selector-syntax">Jsoup</a> or <em>html cleaner</em> both are similar and can be used to parse even malformed html 4.0 syntax and then you can use the popular HTML DOM parsing methods like getElementsByName("a") or in jsoup its even cool you can simply use </p>
<pre><code>File input = new File("/tmp/input.html");
Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/");
Elements links = doc.select("a[href]"); // a with href
Elements pngs = doc.select("img[src$=.png]");
// img with src ending .png
Element masthead = doc.select("div.masthead").first();
</code></pre>
<p>and find all links and then get the detials using </p>
<pre><code>String linkhref=links.attr("href");
</code></pre>
<p>Taken from <a href="http://jsoup.org/cookbook/extracting-data/selector-syntax">http://jsoup.org/cookbook/extracting-data/selector-syntax</a></p>
<p>The selectors have same syntax as <code>jQuery</code> if you know jQuery function chaining then you will certainly love it.</p>
<p>EDIT: In case you want more tutorials, you can try out this one made by mkyong.</p>
<p><a href="http://www.mkyong.com/java/jsoup-html-parser-hello-world-examples/">http://www.mkyong.com/java/jsoup-html-parser-hello-world-examples/</a></p> |
5,002,279 | Killing all threads that opened by application | <p>I have some really big application mixture of c# and j#.</p>
<p>Sometimes when I close it, there are some threads that are not closed and they are hanging in the task manager and it is impossible to kill them from there.</p>
<p>I have really problem to find all those threads and add them to the closing event .</p>
<p>Is there some way violently kill all threads that were opened by application in the closing event ?...</p>
<p>Thanks.</p>
<p>Is there maybe some Tool that can tell me what threads are opened while i close the application and who openned them ?</p> | 5,002,379 | 7 | 1 | null | 2011-02-15 10:12:33.05 UTC | 3 | 2018-12-12 08:21:34.81 UTC | 2011-02-15 10:18:41.25 UTC | null | 140,100 | null | 140,100 | null | 1 | 37 | c#|.net|j# | 83,521 | <p>This <em>shouldn't be happening</em>, and if it is, you're trying to address it the wrong way.</p>
<p>When your application exits, the .NET Framework will automatically kill any threads whose <a href="http://msdn.microsoft.com/en-us/library/system.threading.thread.isbackground.aspx" rel="noreferrer"><code>IsBackground</code> property</a> is set to "True". Designate each of your worker threads as background threads, and you won't have this problem anymore. Taking advantage of the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx" rel="noreferrer"><code>BackgroundWorker</code> class</a> and the <a href="http://msdn.microsoft.com/en-us/library/system.threading.threadpool.aspx" rel="noreferrer"><code>ThreadPool</code> class</a>, which automatically create background threads, is a much better option.</p>
<p>Otherwise, you need to clean up your foreground threads explicitly. A properly designed application will do its own bookkeeping and have a deterministic, structured way of ensuring that all its threads have been closed before exiting the <code>Main</code> method. This is what you should be doing <em>anyway</em> if your threads require a graceful termination.</p>
<p>Killing the process is a very bad idea, as is letting your threads run about willy-nilly in your application.</p> |
5,059,501 | Why is the probe method needed in Linux device drivers in addition to init? | <p>In the linux kernel, what does the <code>probe()</code> method, that the driver provides, do? How different is it from the driver's <code>init</code> function, i.e. why can't the <code>probe()</code> functions actions be performed in the driver's <code>init</code> function ?</p> | 5,069,325 | 7 | 0 | null | 2011-02-20 19:41:19.103 UTC | 26 | 2019-09-23 10:28:10.6 UTC | 2017-06-24 18:56:14.207 UTC | null | 895,245 | null | 581,003 | null | 1 | 59 | linux|operating-system|linux-kernel | 74,523 | <p>Different device types can have probe() functions. For example, PCI and USB devices both have probe() functions.</p>
<p>If you're talking about PCI devices, I would recommend you read chapter 12 of <a href="http://lwn.net/Kernel/LDD3/" rel="noreferrer">Linux Device Drivers</a>, which covers this part of driver initialization. USB is covered in chapter 13.</p>
<p>Shorter answer, assuming PCI: The driver's init function calls <code>pci_register_driver()</code> which gives the kernel a list of devices it is able to service, along with a pointer to the <code>probe()</code> function. The kernel then calls the driver's <code>probe()</code> function once for each device.</p>
<p>This probe function starts the per-device initialization: initializing hardware, allocating resources, and registering the device with the kernel as a block or network device or whatever it is.</p>
<p>That makes it easier for device drivers, because they never need to search for devices or worry about finding a device that was hot-plugged. The kernel handles that part and notifies the right driver when it has a device for you to handle.</p> |
4,884,882 | Is it possible to load a drawable from the assets folder? | <p>Can you load a drawable from a sub directory in the <code>assets</code> (not the drawable folder) folder?</p> | 5,082,672 | 8 | 0 | null | 2011-02-03 10:20:29.52 UTC | 11 | 2020-04-21 12:48:41.997 UTC | 2011-02-03 11:22:30.15 UTC | null | 418,183 | null | 601,327 | null | 1 | 46 | android|drawable|assets | 31,141 | <p>Hope this help: </p>
<pre><code>Drawable d = Drawable.createFromStream(getAssets().open("Cloths/btn_no.png"), null);
</code></pre> |
5,178,125 | How to place object files in separate subdirectory | <p>I'm having trouble with trying to use make to place object files in a separate subdirectory, probably a very basic technique. I have tried to use the information in this page:
<a href="http://www.gnu.org/software/hello/manual/make/Prerequisite-Types.html#Prerequisite-Types" rel="noreferrer">http://www.gnu.org/software/hello/manual/make/Prerequisite-Types.html#Prerequisite-Types</a></p>
<p>I get the following output from make:</p>
<pre><code>make: *** No rule to make target `ku.h', needed by `obj/kumain.o'. Stop.
</code></pre>
<p>However ku.h is a dependency not a target (although it's obviously #included within the c source files). When I don't try to use a subdirectory for object files (i.e. miss out the OBJDIR parts) it works fine. Why does make think ku.h is a target?</p>
<p>my makefile is this: (the style is after reading various sources of information)</p>
<pre><code>.SUFFIXES:
.SUFFIXES: .c .o
CC=gcc
CPPFLAGS=-Wall
LDLIBS=-lhpdf
VPATH=%.c src
VPATH=%.h src
VPATH=%.o obj
OBJDIR=obj
objects= $(addprefix $(OBJDIR)/, kumain.o kudlx.o kusolvesk.o kugetpuz.o kuutils.o \
kurand.o kuASCboard.o kuPDFs.o kupuzstrings.o kugensud.o \
kushapes.o )
ku : $(objects)
$(CC) $(CPPFLAGS) -o ku $(objects) $(LDLIBS)
$(objects) : ku.h kudefines.h kuglobals.h kufns.h | $(OBJDIR)
$(OBJDIR):
mkdir $(OBJDIR)
.PHONY: clean
clean :
rm $(objects)
</code></pre>
<p>Edit:
I applied the change to use the vpath directive. My version was a bad mixture of VPATH=xxx and vpath %.c xxx. However I now get another problem (which was the original problem before I added the wrong vpath). This is now the output:</p>
<pre><code> gcc -o ku -lhpdf obj/kumain.o obj/kudlx.o obj/kusolvesk.o ..etc
gcc: obj/kumain.o: No such file or directory
gcc: obj/kudlx.o: No such file or directory
gcc: obj/kusolvesk.o: No such file or directory
gcc: obj/kugetpuz.o: No such file or directory
gcc: obj/kuutils.o: No such file or directory
gcc: obj/kurand.o: No such file or directory
gcc: obj/kuASCboard.o: No such file or directory
gcc: obj/kuPDFs.o: No such file or directory
gcc: obj/kupuzstrings.o: No such file or directory
gcc: obj/kugensud.o: No such file or directory
gcc: obj/kushapes.o: No such file or directory
make: *** [ku] Error 1
</code></pre>
<p>It appears that make is not applying the implicit rule for an object file although the manual says
"Implicit rules tell make how to use customary techniques so that you do not have to specify them in detail when you want to use them. For example, there is an implicit rule for C compilation. File names determine which implicit rules are run. For example, C compilation typically takes a .c file and makes a .o file. So make applies the implicit rule for C compilation when it sees this combination of file name endings." and also "The search through the directories specified in VPATH or with vpath also happens during consideration of implicit rules (see Using Implicit Rules)."</p>
<p>Again here "For example, when a file foo.o has no explicit rule, make considers implicit rules, such as the built-in rule to compile foo.c if that file exists. If such a file is lacking in the current directory, the appropriate directories are searched for it. If foo.c exists (or is mentioned in the makefile) in any of the directories, the implicit rule for C compilation is applied."</p>
<p>Any assistance in getting implicit rules to work for my makefile would be greatly appreciated.</p>
<p>Edit no 2:
Thanks to Jack Kelly I have made an explicit rule to compile the .c files since I couldn't get anywhere trying to use implicit rules. Also thanks to al_miro for the vpath info.</p>
<p>Here is the working makfile:</p>
<pre><code>.SUFFIXES:
.SUFFIXES: .c .o
CC=gcc
CPPFLAGS=-Wall
LDLIBS=-lhpdf
OBJDIR=obj
vpath %.c src
vpath %.h src
objects = $(addprefix $(OBJDIR)/, kumain.o kudlx.o kusolvesk.o kugetpuz.o kuutils.o \
kurand.o kuASCboard.o kuPDFs.o kupuzstrings.o kugensud.o \
kushapes.o )
ku : $(objects)
$(CC) $(CPPFLAGS) -o ku $(objects) $(LDLIBS)
$(OBJDIR) obj/%.o : %.c ku.h kudefines.h kuglobals.h kufns.h
$(CC) -c $(CPPFLAGS) $< -o $@
.PHONY : clean
clean :
rm $(objects)
</code></pre> | 5,188,496 | 9 | 1 | null | 2011-03-03 08:10:13.1 UTC | 37 | 2020-06-25 12:52:59.527 UTC | 2018-12-10 00:04:38.003 UTC | null | 1,848,654 | null | 639,587 | null | 1 | 76 | makefile|gnu-make | 152,059 | <p>Since you're using GNUmake, use a pattern rule for compiling object files:</p>
<pre><code>$(OBJDIR)/%.o: %.c
$(CC) $(CFLAGS) $(CPPFLAGS) -c -o $@ $<
</code></pre> |
5,396,932 | Why are no Amazon S3 authentication handlers ready? | <p>I have my $AWS_ACCESS_KEY_ID and $AWS_SECRET_ACCESS_KEY environment variables set properly, and I run this code:</p>
<pre><code>import boto
conn = boto.connect_s3()
</code></pre>
<p>and get this error:</p>
<pre><code>boto.exception.NoAuthHandlerFound: No handler was ready to authenticate. 1 handlers were checked. ['HmacAuthV1Handler']
</code></pre>
<p>What's happening? I don't know where to start debugging.</p>
<hr>
<p>It seems boto isn't taking the values from my environment variables. If I pass in the key id and secret key as arguments to the connection constructor, this works fine.</p> | 5,831,211 | 12 | 0 | null | 2011-03-22 19:47:35.13 UTC | 12 | 2018-07-08 12:00:59.56 UTC | 2011-11-27 02:44:45.407 UTC | null | 1,288 | user334856 | null | null | 1 | 53 | amazon-s3|amazon-web-services|boto | 50,652 | <p>Boto <strong>will</strong> take your credentials from the environment variables.
I've tested this with V2.0b3 and it works fine. It will give precedence to credentials specified explicitly in the constructor, but it will pick up credentials from the environment variables too.</p>
<p>The simplest way to do this is to put your credentials into a text file, and specify the location of that file in the environment.</p>
<p>For example (on Windows: I expect it will work just the same on Linux but I have not personally tried that)</p>
<p>Create a file called "mycred.txt" and put it into C:\temp
This file contains two lines:</p>
<pre><code>AWSAccessKeyId=<your access id>
AWSSecretKey=<your secret key>
</code></pre>
<p>Define the environment variable <strong>AWS_CREDENTIAL_FILE</strong> to point at C:\temp\mycred.txt</p>
<pre><code>C:\>SET AWS_CREDENTIAL_FILE=C:\temp\mycred.txt
</code></pre>
<p>Now your code fragment above:</p>
<pre><code>import boto
conn = boto.connect_s3()
</code></pre>
<p>will work fine.</p> |
5,515,310 | Is there a standard function to check for null, undefined, or blank variables in JavaScript? | <p>Is there a universal JavaScript function that checks that a variable has a value and ensures that it's not <code>undefined</code> or <code>null</code>? I've got this code, but I'm not sure if it covers all cases:</p>
<pre><code>function isEmpty(val){
return (val === undefined || val == null || val.length <= 0) ? true : false;
}
</code></pre> | 5,515,349 | 47 | 13 | null | 2011-04-01 15:14:24.25 UTC | 825 | 2022-05-11 11:16:16.733 UTC | 2020-05-11 09:13:03.42 UTC | null | 860,099 | null | 177,416 | null | 1 | 2,881 | javascript|null|comparison|undefined | 2,614,002 | <p>You can just check if the <em>variable</em> has a <code>truthy</code> value or not. That means</p>
<pre><code>if( value ) {
}
</code></pre>
<p>will evaluate to <code>true</code> if <code>value</code> is <strong>not</strong>:</p>
<ul>
<li>null</li>
<li>undefined</li>
<li>NaN</li>
<li>empty string ("")</li>
<li>0</li>
<li>false</li>
</ul>
<p>The above list represents all possible <code>falsy</code> values in ECMA-/Javascript. Find it in the <a href="https://www.ecma-international.org/ecma-262/5.1/#sec-9.2" rel="noreferrer">specification</a> at the <code>ToBoolean</code> section.</p>
<p>Furthermore, if you do not <strong>know</strong> whether a variable exists (that means, if it was <em>declared</em>) you should check with the <code>typeof</code> operator. For instance</p>
<pre><code>if( typeof foo !== 'undefined' ) {
// foo could get resolved and it's defined
}
</code></pre>
<p>If you can be sure that a <em>variable</em> is declared at least, you should directly check if it has a <code>truthy</code> value like shown above.</p> |
12,290,456 | Efficiently Using SublimeText with SublimeClang for CMake/C++ Projects | <p>I have been trying to play with SublimeText2 for some time now. While it is very easy to work with Python in it almost out of the box, working with C++ is a bit more tricky. I can manage to set up a CMake build script by copying and modifying the existing Makefile script, but there are many things that just don't work as they do in a CMake supported IDE, like Eclipse CDT. SublimeText 2 does not seem to understand the concept of a separate build directory, it also cannot get me autocomplete through SublimeClang, if I include the libraries with reference to the directories added in CMake. SublimeClang keeps complaining that it cannot find the libraries, and when I try to <code>#include</code>, it cannot even offer me autocomplete on standard STL header file names, e.g., algorithm. If someone has a pipeline figured out, I would be obliged to hear about it.</p>
<p>I have asked this question in more general purpose usage-related forums before, where I did not get any response, which is why I thought of posting it here.</p> | 13,079,020 | 1 | 1 | null | 2012-09-05 22:05:16.097 UTC | 13 | 2012-10-25 23:55:15.287 UTC | null | null | null | null | 1,062,484 | null | 1 | 11 | c++|autocomplete|cmake|sublimetext2|sublimetext | 11,110 | <p>I use Sublime Text 2 with CMake and SublimeClang. I also use SublimeGDB. My build directory is under <code>[project root]/build</code>. Have a look at my project file and see if it helps you:</p>
<pre><code>{
"folders":
[
{
"path": "."
}
],
"build_systems":
[
{
"name": "Build",
"cmd": [ "make", "-C", "build" ],
"file_regex": "/([^/:]+):(\\d+):(\\d+): "
}
],
"settings":
{
"sublimegdb_commandline": "gdb --interpreter=mi myapp",
"sublimegdb_workingdir": "build",
"sublimeclang_options" :
[
"-Wno-reorder"
],
"sublimeclang_options_script": "${project_path:scripts/compileflags.rb} ${project_path:build}"
}
}
</code></pre>
<p>The <code>compileflags.rb</code>script is used to search for <code>flags.make</code> files in the CMake build tree which is where CMake keeps its compile flags. These flags are needed so that SublimeClang knows where to find your includes.</p>
<p>Here is that script, located under <code>scripts/</code>:</p>
<pre><code>#!/usr/bin/env ruby
# Searches for a flags.make in a CMake build tree and prints the compile flags.
def search_dir(dir, &block)
Dir.foreach(dir) do |filename|
next if (filename == ".") || (filename == "..")
path ="#{dir}/#{filename}"
if File.directory?(path)
search_dir(path, &block)
else
search_file(path, &block)
end
end
end
def search_file(filename)
return if File.basename(filename) != "flags.make"
File.open(filename) do |io|
io.read.scan(/[a-zA-Z]+_(?:FLAGS|DEFINES)\s*=\s*(.*)$/) do |match|
yield(match.first.split(/\s+/))
end
end
end
root = ARGV.empty? ? Dir.pwd : ARGV[0]
params = to_enum(:search_dir, root).reduce { |a, b| a | b }
puts params
</code></pre> |
12,225,715 | Update Statement using Join and Group By | <p>I have written the below Update Statement, but it shows the error such as "Incorrect syntax near the keyword 'GROUP'."</p>
<pre><code>UPDATE
J
SET
J.StatusID = CASE WHEN SUM(DUV.VendorDUQuantity) = SUM(RD.InvoiceQuantity) THEN 1 ELSE J.StatusID END
FROM
PLN_DU_Vendor DUV
INNER JOIN ENG_Release R ON R.ReleaseID = DUV.ReleaseID
INNER JOIN ENG_DU_Header H ON H.ReleaseID = R.ReleaseID AND DUV.DUID = H.DUID
INNER JOIN MKT_JobOrder J ON J.JobOrderID = R.JobOrderID
INNER JOIN MKT_CustomerOrder CO ON CO.OrderID = J.OrderID
LEFT JOIN PMT_RFDHeader RH ON RH.JobOrderID = J.JobOrderID
LEFT JOIN PMT_RFDDetail RD ON RD.RFDID = RH.RFDID AND RD.DUID = DUV.DUID
WHERE
CO.OrderID = 100
GROUP BY
J.JobOrderID
</code></pre>
<p>Instead of Update, Select is working perfectly for the above Query. What would be the problem and How to write the Query based on Join and Group By clause. </p> | 12,225,765 | 2 | 0 | null | 2012-09-01 07:09:14.337 UTC | 4 | 2019-10-01 08:02:17.137 UTC | null | null | null | null | 518,927 | null | 1 | 31 | sql|sql-server-2008|join|group-by|update-statement | 85,725 | <p>You can try putting the group by inside of a subquery, then join by the "JobOrderID", like this:</p>
<pre><code>UPDATE J
SET J.StatusID = A.statusId
FROM MKT_JobOrder J
INNER JOIN (
SELECT J.JobOrderID
, CASE
WHEN SUM(DUV.VendorDUQuantity) = SUM(RD.InvoiceQuantity)
THEN 1
ELSE J.StatusID
END AS statusId
FROM PLN_DU_Vendor DUV
INNER JOIN ENG_Release R ON R.ReleaseID = DUV.ReleaseID
INNER JOIN ENG_DU_Header H ON H.ReleaseID = R.ReleaseID
AND DUV.DUID = H.DUID
INNER JOIN MKT_JobOrder J ON J.JobOrderID = R.JobOrderID
INNER JOIN MKT_CustomerOrder CO ON CO.OrderID = J.OrderID
LEFT JOIN PMT_RFDHeader RH ON RH.JobOrderID = J.JobOrderID
LEFT JOIN PMT_RFDDetail RD ON RD.RFDID = RH.RFDID
AND RD.DUID = DUV.DUID
WHERE CO.OrderID = 100
GROUP BY J.JobOrderID
, J.StatusID
) A ON J.JobOrderID = A.JobOrderID
</code></pre> |
12,533,955 | String split on new line, tab and some number of spaces | <p>I'm trying to perform a string split on a set of somewhat irregular data that looks something like:</p>
<pre><code>\n\tName: John Smith
\n\t Home: Anytown USA
\n\t Phone: 555-555-555
\n\t Other Home: Somewhere Else
\n\t Notes: Other data
\n\tName: Jane Smith
\n\t Misc: Data with spaces
</code></pre>
<p>I'd like to convert this into a tuple/dict where I later will split on the colon <code>:</code>, but first I need to get rid of all the extra whitespace. I'm guessing a regex is the best way but I can't seem to get one that works, below is my attempt.</p>
<pre><code>data_string.split('\n\t *')
</code></pre> | 12,533,983 | 7 | 0 | null | 2012-09-21 15:54:34.7 UTC | 12 | 2022-04-10 16:45:13.247 UTC | null | null | null | null | 1,563,457 | null | 1 | 40 | python|regex|split | 137,374 | <p>Just use <a href="http://docs.python.org/library/stdtypes.html#str.strip" rel="noreferrer">.strip()</a>, it removes all whitespace for you, including tabs and newlines, while splitting. The splitting itself can then be done with <a href="http://docs.python.org/library/stdtypes.html#str.splitlines" rel="noreferrer"><code>data_string.splitlines()</code></a>:</p>
<pre><code>[s.strip() for s in data_string.splitlines()]
</code></pre>
<p>Output:</p>
<pre><code>>>> [s.strip() for s in data_string.splitlines()]
['Name: John Smith', 'Home: Anytown USA', 'Phone: 555-555-555', 'Other Home: Somewhere Else', 'Notes: Other data', 'Name: Jane Smith', 'Misc: Data with spaces']
</code></pre>
<p>You can even inline the splitting on <code>:</code> as well now:</p>
<pre><code>>>> [s.strip().split(': ') for s in data_string.splitlines()]
[['Name', 'John Smith'], ['Home', 'Anytown USA'], ['Phone', '555-555-555'], ['Other Home', 'Somewhere Else'], ['Notes', 'Other data'], ['Name', 'Jane Smith'], ['Misc', 'Data with spaces']]
</code></pre> |
12,534,836 | PHP multiline string with PHP | <p>I need to echo a lot of PHP and HTML.</p>
<p>I already tried the obvious, but it's not working:</p>
<pre><code><?php echo '
<?php if ( has_post_thumbnail() ) { ?>
<div class="gridly-image"><a href="<?php the_permalink() ?>"><?php the_post_thumbnail('summary-image', array('class' => 'overlay', 'title'=> the_title('Read Article ',' now',false) ));?></a>
</div>
<?php } ?>
<div class="date">
<span class="day">
<?php the_time('d') ?></span>
<div class="holder">
<span class="month">
<?php the_time('M') ?></span>
<span class="year">
<?php the_time('Y') ?></span>
</div>
</div>
<?php } ?>';
?>
</code></pre>
<p>How can I do it?</p> | 12,534,908 | 7 | 3 | null | 2012-09-21 16:55:47.227 UTC | 4 | 2021-03-03 08:57:27.81 UTC | 2016-02-13 11:13:23.863 UTC | null | 63,550 | null | 1,235,256 | null | 1 | 47 | php|html|multiline | 126,490 | <p>You don't need to output <code>php</code> tags:</p>
<pre><code><?php
if ( has_post_thumbnail() )
{
echo '<div class="gridly-image"><a href="'. the_permalink() .'">'. the_post_thumbnail('summary-image', array('class' => 'overlay', 'title'=> the_title('Read Article ',' now',false) )) .'</a></div>';
}
echo '<div class="date">
<span class="day">'. the_time('d') .'</span>
<div class="holder">
<span class="month">'. the_time('M') .'</span>
<span class="year">'. the_time('Y') .'</span>
</div>
</div>';
?>
</code></pre> |
12,246,627 | What is PurpleEventCallback? | <p>In the stack trace of my iPhone application, I see a call to something called <code>PurpleEventCallback</code>. I wasn't able to find any documentation for it. What is this?</p>
<p><img src="https://i.stack.imgur.com/x9uwi.png" alt="PurpleEventCallback"></p> | 12,247,281 | 2 | 0 | null | 2012-09-03 11:07:17.017 UTC | 4 | 2015-09-20 00:24:38.687 UTC | 2015-09-20 00:24:38.687 UTC | null | 560,648 | null | 141,220 | null | 1 | 52 | ios|iphone|xcode|stack-trace | 2,757 | <p>Project Purple was the codename for iOS back when it was basically a skunkworks project within Apple. This callback is basically just an event bridge between the <code>CoreFoundation</code> layer (ported from OS X) and the <code>UIKit</code> layer (the next-generation Cocoa framework).</p>
<ul>
<li><a href="http://allthingsd.com/20120803/apples-scott-forstall-on-how-project-purple-turned-into-the-iphone/" rel="noreferrer">"How Project Purple Turned into the iPhone"</a></li>
</ul> |
12,142,021 | How can I do something 0.5 seconds after text changed in my EditText control? | <p>I am filtering my list using an EditText control. I want to filter the list <strong>0.5 seconds after the user has finished typing in EditText</strong>. I used the <code>afterTextChanged</code> event of <code>TextWatcher</code> for this purpose. But this event rises for each character changes in EditText.</p>
<p>What should I do?</p> | 12,143,050 | 17 | 0 | null | 2012-08-27 12:31:27.72 UTC | 20 | 2021-03-17 12:53:58.567 UTC | 2021-01-28 11:54:45.133 UTC | null | 63,550 | null | 779,408 | null | 1 | 73 | android|filter|android-edittext|textwatcher|textchanged | 55,705 | <p>Use:</p>
<pre><code>editText.addTextChangedListener(
new TextWatcher() {
@Override public void onTextChanged(CharSequence s, int start, int before, int count) { }
@Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
private Timer timer = new Timer();
private final long DELAY = 1000; // Milliseconds
@Override
public void afterTextChanged(final Editable s) {
timer.cancel();
timer = new Timer();
timer.schedule(
new TimerTask() {
@Override
public void run() {
// TODO: Do what you need here (refresh list).
// You will probably need to use
// runOnUiThread(Runnable action) for some
// specific actions (e.g., manipulating views).
}
},
DELAY
);
}
}
);
</code></pre>
<p>The trick is in canceling and rescheduling <code>Timer</code> each time, when text in <code>EditText</code> gets changed.</p>
<p>For how long to set the delay, see <a href="https://ux.stackexchange.com/a/38545">this post</a>.</p> |
23,957,278 | How to add table of contents in Rmarkdown? | <p>I am using RStudio for writing markdown documents and want to add Table of Contents (TOC) at top of the documents so that the user could click the relevant section for reading. There were some relevant examples on rpubs but now I can't seem to find them. Please note that I don't use <code>pandoc</code> and am quite new to <code>Rmd</code> & <code>knitr</code>. Is there any way to add TOCs without using <code>pandoc</code>? If using <code>pandoc</code> is must then which functions are relevant?</p>
<h1>EDIT</h1>
<p>Here's a small sample page:</p>
<pre><code>---
title: "Sample Document"
output:
html_document:
toc: true
theme: united
---
Header 1
---------------
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
## Header 2
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r}
summary(cars)
```
You can also embed plots, for example:
```{r, echo=FALSE}
plot(cars)
```
### Header 3
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
</code></pre>
<p>I tried running this in RStudio v 0.98.864 and it worked! but sadly it didn't work on 0.98.501 and 0.98.507. I am working on my thesis in 0.98.501 and after updating RStudio, some of my analyses didn't work. So, I reverted back to 0.98.501.
What should I do now? I really want TOCs but without harming the outputs of other analyses.</p> | 23,963,277 | 3 | 11 | null | 2014-05-30 14:43:26.167 UTC | 33 | 2020-06-19 17:47:00.47 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 2,829,961 | null | 1 | 117 | r|rstudio|r-markdown | 114,733 | <p>The syntax is</p>
<pre><code>---
title: "Sample Document"
output:
html_document:
toc: true
theme: united
---
</code></pre>
<p>in <a href="http://rmarkdown.rstudio.com/" rel="noreferrer">the documentation</a>. Make sure this is at the beginning of your document. Also make sure your document actually has headers otherwise R can't tell what you want in the table of contents.</p> |
3,747,362 | php regex validation | <p>just a quick question am abit rubish with regex so thought I would post on here. The regex below is to validate a username.</p>
<ul>
<li><p>Must be between 4-26 characters long</p></li>
<li><p>Start with atleast 2 letters</p></li>
<li>Can only contain numbers and one
underscore and one dot</li>
</ul>
<p>I have this so far, but isn't working</p>
<pre><code><?php
$username=$_POST['username'];
if (!eregi("^([a-zA-Z][0-9_.]){4,26}$",$username))
{
return false;
}
else
{
echo "username ok";
}
?>
</code></pre>
<p>Thanks :)</p> | 3,747,506 | 3 | 3 | null | 2010-09-19 20:33:41.667 UTC | 2 | 2010-09-20 14:27:28.487 UTC | null | null | null | null | 99,329 | null | 1 | 19 | php|regex | 55,304 | <p>You could use the regex</p>
<pre><code>/^(?=[a-z]{2})(?=.{4,26})(?=[^.]*\.?[^.]*$)(?=[^_]*_?[^_]*$)[\w.]+$/iD
</code></pre>
<p>as in</p>
<pre><code><?php
$username=$_POST['username'];
if (!preg_match('/^(?=[a-z]{2})(?=.{4,26})(?=[^.]*\.?[^.]*$)(?=[^_]*_?[^_]*$)[\w.]+$/iD',
$username))
{
return false;
}
else
{
echo "username ok";
}
?>
</code></pre>
<ul>
<li>The <code>^(?=[a-z]{2})</code> ensure the string "Start with atleast 2 letters".</li>
<li>The <code>(?=.{4,26})</code> ensure it "Must be between 4-26 characters long".</li>
<li>The <code>(?=[^.]*\.?[^.]*$)</code> ensures the following characters contains at most one <code>.</code> until the end.</li>
<li>Similarly <code>(?=[^_]*_?[^_]*$)</code> ensures at most one <code>_</code>.</li>
<li>The <code>[\w.]+$</code> commits the match. It also ensures only alphanumerics, <code>_</code> and <code>.</code> will be involved.</li>
</ul>
<p>(Note: this regex assumes <code>hello_world</code> is a valid user name.)</p> |
20,579,185 | Is there a way to reuse builder code for retrofit | <p>I am using <a href="http://square.github.io/retrofit/">Retrofit</a> and in every task I have to do something like this:</p>
<pre><code>public class MyTask extends AsyncTask<String, String, String> {
private void someMethod() {
final RestAdapter restAdapter = new RestAdapter.Builder()
.setServer("http://10.0.2.2:8080")
.build();
final MyTaskService apiManager = restAdapter.create(MyTaskService.class);
}
// ...
}
</code></pre>
<p>What is a good way to make this code DRY?</p> | 20,609,674 | 3 | 4 | null | 2013-12-14 02:57:02.143 UTC | 14 | 2014-12-10 10:50:47.62 UTC | 2014-12-10 10:50:47.62 UTC | null | 356,895 | null | 131,194 | null | 1 | 21 | java|android|retrofit | 9,578 | <p>first you declare your parent class with all common behavior</p>
<pre><code>public abstract class MyAbstractTask extends AsyncTask<String, String, String> {
protected void someMethod() { //note that i change private to protected
final RestAdapter restAdapter = new RestAdapter.Builder().setServer("http://10.0.2.2:8080").build();
final MyTaskService apiManager = restAdapter.create(MyTaskService.class);
}
}
</code></pre>
<p>then, you extend it with every task</p>
<pre><code>public class MyTask extends MyAbstractTask {
//your someMethod() is available from everywhere in your class
}
public class MyOtherTask extends MyAbstractTask {
//your someMethod() is available from everywhere in your class
}
</code></pre>
<hr>
<p>but i dont know where you are using restAdapter and apiManager, and if the actually need to be created once per task, since probably you can create it outside of these tasks. </p>
<p>If you create them outside, and then you need to use something inside your task, it is also good to have in mind the <a href="http://en.wikipedia.org/wiki/Dependency_injection" rel="noreferrer">Dependency_injection</a> pattern.</p>
<hr>
<p>Also, you should avoid hardcoding values in your classes, like <code>http://10.0.2.2:8080</code> </p>
<p>You should use at least a <code>final static final String server= "http://10.0.2.2:8080"</code> and then use that, or better, use a setter or the constructor in the most inner class, and set tha values from the activity or the main controller. </p> |
22,186,467 | How to use JavaScript EventTarget? | <p>I would like to create a custom event emitter in my client-side programs. I am referencing this (sparse) documentation for <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget">EventTarget</a></p>
<p><strong>My implementation attempt</strong></p>
<pre><code>var Emitter = function Emitter() {
EventTarget.call(this);
};
Emitter.prototype = Object.create(EventTarget.prototype, {
constructor: {
value: Emitter
}
});
</code></pre>
<p><strong>My desired usage</strong></p>
<pre><code>var e = new Emitter();
e.addEventListener("hello", function() {
console.log("hello there!");
});
e.dispatchEvent(new Event("hello"));
// "hello there!"
</code></pre>
<p><strong>Where it fails</strong></p>
<pre><code>var e = new Emitter();
// TypeError: Illegal constructor
</code></pre>
<p>What am I doing wrong?</p>
<hr>
<p><strong>Update</strong></p>
<p>The following is possible, but it's a hack that depends on a dummy DOMElement</p>
<pre><code>var fake = document.createElement("phony");
fake.addEventListener("hello", function() { console.log("hello there!"); });
fake.dispatchEvent(new Event("hello"));
// "hello there!"
</code></pre>
<p>I'd like to know how to do this without having to use the dummy element</p> | 24,216,547 | 10 | 8 | null | 2014-03-05 01:03:20.87 UTC | 15 | 2020-05-01 16:48:24.777 UTC | 2014-03-05 02:13:17.387 UTC | null | 633,183 | null | 633,183 | null | 1 | 38 | javascript|events | 30,505 | <p>I gave up on this awhile ago, but recently needed it again. Here's what I ended up using.</p>
<blockquote>
<p>ES6</p>
</blockquote>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class Emitter {
constructor() {
var delegate = document.createDocumentFragment();
[
'addEventListener',
'dispatchEvent',
'removeEventListener'
].forEach(f =>
this[f] = (...xs) => delegate[f](...xs)
)
}
}
// sample class to use Emitter
class Example extends Emitter {}
// run it
var e = new Example()
e.addEventListener('something', event => console.log(event))
e.dispatchEvent(new Event('something'))</code></pre>
</div>
</div>
</p>
<hr>
<blockquote>
<p>ES5</p>
</blockquote>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function Emitter() {
var eventTarget = document.createDocumentFragment()
function delegate(method) {
this[method] = eventTarget[method].bind(eventTarget)
}
[
"addEventListener",
"dispatchEvent",
"removeEventListener"
].forEach(delegate, this)
}
// sample class to use it
function Example() {
Emitter.call(this)
}
// run it
var e = new Example()
e.addEventListener("something", function(event) {
console.log(event)
})
e.dispatchEvent(new Event("something"))</code></pre>
</div>
</div>
</p>
<p>Yeah!</p>
<hr>
<p>For those that need to support older versions of ecmascript, here you go</p>
<pre><code>// IE < 9 compatible
function Emitter() {
var eventTarget = document.createDocumentFragment();
function addEventListener(type, listener, useCapture, wantsUntrusted) {
return eventTarget.addEventListener(type, listener, useCapture, wantsUntrusted);
}
function dispatchEvent(event) {
return eventTarget.dispatchEvent(event);
}
function removeEventListener(type, listener, useCapture) {
return eventTarget.removeEventListener(type, listener, useCapture);
}
this.addEventListener = addEventListener;
this.dispatchEvent = dispatchEvent;
this.removeEventListener = removeEventListener;
}
</code></pre>
<p>The usage stays the same</p> |
11,410,017 | Git Submodule update over https | <p>I am sitting on a proxy which only allows http/https traffic only, I am able to clone a repository from Github, but I have to fetch/push using the https URL and username/password. </p>
<p>Now my issues is a repository with submodules, when I execute <code>git submodule update</code> it times out, and I can only assume this is because it's using an SSH connection which is blocked. (it doesn't even ask me for a password on private repos)</p> | 11,410,074 | 3 | 1 | null | 2012-07-10 09:07:01.297 UTC | 11 | 2021-12-01 16:13:26.583 UTC | null | null | null | null | 509,663 | null | 1 | 38 | git|proxy|git-submodules | 31,610 | <p>In your <code>.gitmodules</code> file in the root of your repo, and in the <code>.git/config</code> file, you should find a section for your submodule. You can edit the url there so it is accessed via https request rather ssh.</p>
<p>Of course it may already be an ssh url, in which case the problem may be something else, but this is the first place to check.</p> |
11,137,648 | How do I capture a "response end" event in node.js+express? | <p>I'd like to write an express middleware function that sets up a listener on the response's 'end' event, if one exists. The purpose is to do cleanup based on the http response code that the end handler decided to send, e.g. logging the response code and rollback/commit of a db transaction. i.e., I want this cleanup to be transparent to the end caller.</p>
<p>I'd like to do something like the following in express:</p>
<p>The route middleware</p>
<pre><code>function (req, res, next) {
res.on ('end', function () {
// log the response code and handle db
if (res.statusCode < 400) { db.commit() } else { db.rollback() }
});
next();
}
</code></pre>
<p>The route:</p>
<pre><code>app.post ("/something", function (req, res) {
db.doSomething (function () {
if (some problem) {
res.send (500);
} else {
res.send (200);
}
});
}
</code></pre>
<p>When I try this, the 'end' event handler never gets called. The same for <code>res.on('close')</code>, which I read about in another post. Do such events get fired?</p>
<p>The only other way I can think of doing this is wrapping <code>res.end</code> or <code>res.send</code> with my own version in a custom middleware. This is not ideal, because <code>res.end</code> and <code>res.send</code> don't take callbacks, so I can't just wrap them, call the original and then do my thing based on the response code that got set when they call me back (because they won't call me back).</p>
<p>Is there a simple way to do this?</p> | 11,140,274 | 3 | 4 | null | 2012-06-21 11:59:00.673 UTC | 4 | 2021-10-11 23:19:55.797 UTC | 2012-06-21 14:24:32.307 UTC | null | 559,023 | null | 559,023 | null | 1 | 40 | events|node.js|express|response | 33,105 | <p>Reading the <a href="http://expressjs.com/guide.html#res.send%28%29" rel="nofollow">documentation</a>, here is the signature of <code>res.send</code>:</p>
<pre><code>res.send(body|status[, headers|status[, status]])
</code></pre>
<p>Which means you can set your own status, like this: <code>res.send( 'some string', 200 );</code> or even just <code>res.send( 404 );</code>.</p>
<p>This method is the one you use to <em>send</em> the response.</p>
<p>Once it is sent to the client, you can't access it anymore, so there is no callback.</p>
<p><strong>This is the last thing your server does. Once it has processed the request, it sends the response.</strong></p>
<p>However, you can access it <em>before</em> you send it to the client. Which means you can:</p>
<pre><code>console.log( res );
res.send( datas );
</code></pre>
<p>If you want to rollback/commit, you do it when the database's callback is called, not when the response is gone.</p> |
10,921,430 | Fresh installation of sphinx-quickstart fails | <p>Trying to get it going with Sphinx for the first time, with a clean Sphinx 1.1.3 installation, and shinx-quickstart fails. Should there be any dependencies installed? I tried to <code>pip --force-reinstall sphinx</code> but the result is the same.</p>
<pre><code> myhost:doc anton$ sphinx-quickstart
Traceback (most recent call last):
File "/usr/local/bin/sphinx-quickstart", line 8, in <module>
load_entry_point('Sphinx==1.1.3', 'console_scripts', 'sphinx-quickstart')()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py", line 318, in load_entry_point
return get_distribution(dist).load_entry_point(group, name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py", line 2221, in load_entry_point
return ep.load()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py", line 1954, in load
entry = __import__(self.module_name, globals(),globals(), ['__name__'])
File "/Library/Python/2.7/site-packages/Sphinx-1.1.3-py2.7.egg/sphinx/quickstart.py", line 19, in <module>
from sphinx.util.osutil import make_filename
File "/Library/Python/2.7/site-packages/Sphinx-1.1.3-py2.7.egg/sphinx/util/__init__.py", line 25, in <module>
from docutils.utils import relative_path
File "/Library/Python/2.7/site-packages/docutils-0.9-py2.7.egg/docutils/utils/__init__.py", line 19, in <module>
from docutils.io import FileOutput
File "/Library/Python/2.7/site-packages/docutils-0.9-py2.7.egg/docutils/io.py", line 18, in <module>
from docutils.error_reporting import locale_encoding, ErrorString, ErrorOutput
File "/Library/Python/2.7/site-packages/docutils-0.9-py2.7.egg/docutils/error_reporting.py", line 47, in <module>
locale_encoding = locale.getlocale()[1] or locale.getdefaultlocale()[1]
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/locale.py", line 496, in getdefaultlocale
return _parse_localename(localename)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/locale.py", line 428, in _parse_localename
raise ValueError, 'unknown locale: %s' % localename
ValueError: unknown locale: UTF-8
</code></pre> | 10,926,115 | 1 | 2 | null | 2012-06-06 20:08:49.79 UTC | 8 | 2014-09-26 17:25:33.97 UTC | 2012-06-07 15:44:45.6 UTC | null | 407,651 | null | 431,270 | null | 1 | 45 | python-sphinx | 6,906 | <p>I was getting the same issue in Mac OS X Snow Leopard. It seems to be an issue with Terminal.app.</p>
<p>Please add the following to your $HOME/.bash_profile</p>
<pre><code>export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
</code></pre>
<p>Do</p>
<pre><code>source $HOME/.bash_profile
</code></pre>
<p>and try. This will solve the issue.</p> |
11,248,119 | Java equivalent of PHP's implode(',' , array_filter( array () )) | <p>I often use this piece of code in PHP</p>
<pre><code>$ordine['address'] = implode(', ', array_filter(array($cliente['cap'], $cliente['citta'], $cliente['provincia'])));
</code></pre>
<p>It clears empty strings and join them with a ",". If only one remains it doesn't add an extra unneeded comma. It doesn't add a comma at the end. If none remains it returns empty string.</p>
<p>Thus I can get one of the following results</p>
<pre><code>""
"Street abc 14"
"Street abc 14, 00168"
"Street abc 14, 00168, Rome"
</code></pre>
<p>What is the best Java implementation (less code) in Java <strong>without having to add external libraries</strong> (designing for Android)?</p> | 11,248,692 | 9 | 5 | null | 2012-06-28 15:38:57.177 UTC | 7 | 2021-01-06 21:22:21.257 UTC | 2020-06-20 15:53:16.623 UTC | null | 63,550 | null | 579,646 | null | 1 | 82 | java|php | 87,080 | <h3>Updated version using Java 8 (original at the end of post)</h3>
<p>If you don't need to filter any elements you can use</p>
<ul>
<li><p><a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.CharSequence...-" rel="noreferrer">String.join(CharSequence delimiter, <strong>CharSequence...</strong> elements)</a></p>
<ul>
<li><code>String.join(" > ", new String[]{"foo", "bar"});</code></li>
<li><code>String.join(" > ", "foo", "bar");</code><br />
<br/></li>
</ul>
</li>
<li><p>or <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.Iterable-" rel="noreferrer">String.join(CharSequence delimiter, <strong>Iterable<? extends CharSequence></strong> elements)</a></p>
<ul>
<li><code>String.join(" > ", Arrays.asList("foo", "bar"));</code></li>
</ul>
</li>
</ul>
<hr />
<p>Since Java 8 we can use <code>StringJoiner</code> (instead of originally used <code>StringBulder</code>) and simplify our code.<br />
Also to avoid recompiling <code>" *"</code> regex in each call of <code>matches(" *")</code> we can create separate Pattern which will hold its compiled version in some field and use it when needed.</p>
<pre><code>private static final Pattern SPACES_OR_EMPTY = Pattern.compile(" *");
public static String implode(String separator, String... data) {
StringJoiner sb = new StringJoiner(separator);
for (String token : data) {
if (!SPACES_OR_EMPTY.matcher(token).matches()) {
sb.add(token);
}
}
return sb.toString();
}
</code></pre>
<hr />
<p>With streams our code can look like.</p>
<pre><code>private static final Predicate<String> IS_NOT_SPACES_ONLY =
Pattern.compile("^\\s*$").asPredicate().negate();
public static String implode(String delimiter, String... data) {
return Arrays.stream(data)
.filter(IS_NOT_SPACES_ONLY)
.collect(Collectors.joining(delimiter));
}
</code></pre>
<p>If we use streams we can <code>filter</code> elements which <code>Predicate</code>. In this case we want predicate to accept strings which are not only spaces - in other words string must contain non-whitespace character.</p>
<p>We can create such Predicate from Pattern. Predicate created this way will accept any strings which will contain substring which could be matched by regex (so if regex will look for <code>"\\S"</code> predicate will accept strings like <code>"foo "</code>, <code>" foo bar "</code>, <code>"whatever"</code>, but will not accept <code>" "</code> nor <code>" "</code>).</p>
<p>So we can use</p>
<pre><code>Pattern.compile("\\S").asPredicate();
</code></pre>
<p>or possibly little more descriptive, negation of strings which are only spaces, or empty</p>
<pre><code>Pattern.compile("^\\s*$").asPredicate().negate();
</code></pre>
<p>Next when filter will remove all empty, or containing only spaces Strings we can <code>collect</code> rest of elements. Thanks to <code>Collectors.joining</code> we can decide which delimiter to use.</p>
<hr />
<h3>Original answer (before Java 8)</h3>
<pre><code>public static String implode(String separator, String... data) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < data.length - 1; i++) {
//data.length - 1 => to not add separator at the end
if (!data[i].matches(" *")) {//empty string are ""; " "; " "; and so on
sb.append(data[i]);
sb.append(separator);
}
}
sb.append(data[data.length - 1].trim());
return sb.toString();
}
</code></pre>
<p>You can use it like</p>
<pre><code>System.out.println(implode(", ", "ab", " ", "abs"));
</code></pre>
<p>or</p>
<pre><code>System.out.println(implode(", ", new String[] { "ab", " ", "abs" }));
</code></pre>
<p>Output <code>ab, abs</code></p> |
12,978,882 | What is the common sql for sysdate and getdate() | <p>I need to use sysdate in both Oracle and SQL Server, but SQL Server has a GETDATE() function instead.</p>
<p>But I don't want to create 2 separate queries</p>
<p>Is there any specific common syntax which gives same output to sysdate and getdate in SQL Server and oracle </p> | 12,979,168 | 2 | 4 | null | 2012-10-19 16:52:48.057 UTC | null | 2012-10-20 10:37:50.91 UTC | 2012-10-19 17:16:17.457 UTC | null | 1,691,232 | null | 1,136,172 | null | 1 | 9 | sql|sql-server|oracle11g | 76,851 | <p><code>CURRENT_TIMESTAMP</code> is valid syntax for both SQL Server and Oracle. Oracle will return the current date and time in the session time zone. SQL Server will return the current date and time of the Operating System</p> |
12,848,764 | What size should my images be for a mobile site | <p>We are designing a template for a mobile site and we got to the problem where we don't know what size a logo should be, or the background, etc.</p>
<p>We will use the Jquery mobile API and HTML5 / CSS3 which basically allows us to create the whole architecture of the site without worrying about the dimensions, but in terms of external assets like backgrounds and images we don't know what is the best size in order to be more compatible with most devices.</p> | 12,849,090 | 4 | 1 | null | 2012-10-11 21:27:21.903 UTC | 5 | 2017-01-27 19:12:47.913 UTC | null | null | null | null | 1,243,679 | null | 1 | 12 | html|css|mobile|jquery-mobile | 66,532 | <p>The iPhone 4S/5 has a high-resolution screen that's 640 pixels wide. Many Android smartphones top out at 720px wide, although some go up to 800px. Anything over that is probably considered a tablet.</p>
<p>The best thing you can do as far as wide compatibility, then, is a single CSS style:</p>
<pre><code>img { max-width: 100%; height: auto; }
</code></pre>
<p>This will ensure that no matter what resolution the screen is, your images will be no larger than the element containing it. (When building a responsive site with mobile users in mind, your element widths, margins and padding should all be computed as percentages whenever possible.) Obviously it also means that you're downloading more image data than many phones will need, but if you're dealing with two-color logos, it's not much of a difference. As always, keep your images as few and as small as possible.</p>
<p>In addition, if you're not dealing with photos, you should look at SVG images. Since they're vector-based, they resize perfectly at any resolution, and <a href="http://caniuse.com/#search=svg" rel="noreferrer">they're compatible with pretty much every browser except IE8 and Android 2.x</a>. </p> |
12,775,170 | How do I create a new Swing app in IntelliJ IDEA Community edition? | <p>I have created a new project using the Create New Project Wizard, by choosing "create project from scratch" but it's completely empty (no java classes at all, so I manually created a new swing form inside the empty project). </p>
<p>In many other IDEs I have used there is a way to click once, and get a new "new Gui project", and I usually expect it in the "File -> New Project" wizard or something, comparable.</p>
<p>There is a new project wizard in the IntelliJ IDEA IDE, but it only seems it can create a blank project, and then I can manually add a form to it. So I did that. But then, that lacks any of the usual Java code that you would expect it to have, to open up that form and show it as an application. </p>
<p>I am trying to understand the features and capabilities of IntelliJ IDEA, and it seems strong as a very fast and efficient editor and debugger and build system GUI wrapper around the ANT build system, but I was wondering if there are more "RAD" features that I have merely overlooked. I have done a bit of googling and reading the docs, but I haven't found much about using IntelliJ IDEA to build a GUI application in Java.</p>
<p>Where I'm currently stuck is when I tried to build and run my empty project with an empty form in it, and I get to some kind of "Run" target configuration screen, and I tried clicking the [+] icon, and adding "MyForm01" which is the empty swing form I created, and it says in a dialog box "MyForm01 is not acceptable". I know enough java to know that the basic "GUI app skeleton code" is not being auto-generated by the IDE. I could go and copy and paste something from the internet, but my interest here is in knowing whether the tool can automatically be used to build a GUI, with a workflow as simple as other RAD-style GUI builder tools, including NetBeans, which is the java tool I am most comfortable using, or Delphi, which is my main everyday tool, which is Pascal based, rather than Java.</p> | 12,775,408 | 4 | 3 | null | 2012-10-08 04:04:36.003 UTC | 9 | 2020-09-23 01:10:42.637 UTC | 2015-02-04 12:40:48.733 UTC | null | 3,701,228 | null | 84,704 | null | 1 | 24 | java|intellij-idea | 91,812 | <p>There is no such thing as GUI project in IDEA. You can add GUI forms there at any time you need, just by RightClick -> New -> GUI Form. You can create GUI app from it just by adding <code>main()</code> method into the form binding class. IDEA does the job for you if you hit Alt-Ins (or menu Code->Generate) when in the binding class editor. The only requirement for this is to place correct name for the form's root panel.</p>
<p>You also should check this manual to discover some other things: <a href="https://www.jetbrains.com/help/idea/designing-gui-major-steps.html" rel="nofollow noreferrer">https://www.jetbrains.com/help/idea/designing-gui-major-steps.html</a>. Anyway, the GUI builder is pretty intuitive.</p> |
12,802,722 | How to check if two dates not on the same calendar day | <p>How to check if two dates not on the same day. I came up with this solution but maybe there is a better way to do this:</p>
<pre><code> var actualDate = new Date();
var isNotToday = dateToCheck.getDay() !== actualDate.getDay() || dateToCheck < actualDate - 24 * 60 * 60 * 1000;
</code></pre> | 24,053,987 | 7 | 11 | null | 2012-10-09 14:50:21.817 UTC | 4 | 2017-01-13 04:52:36.767 UTC | null | null | null | null | 184,883 | null | 1 | 34 | javascript|date | 22,744 | <p>Another option is using <code>.toDateString()</code> function to parse both dates into strings. The function formats output to: "Wed Jul 28 1993." Then you can compare both date strings.</p>
<pre><code>actualDate.toDateString() === dateToCheck.toDateString()
// returns true if actualDate is same day as dateToCheck
</code></pre>
<p>Here's a Plunker:</p>
<p><a href="http://plnkr.co/edit/J5Dyn78TdDUzX82T0ypA">http://plnkr.co/edit/J5Dyn78TdDUzX82T0ypA</a></p>
<p>And more from MDN:</p>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString</a></p> |
12,842,760 | Change visual studio caret color | <p>I am trying the new Visual Studio 2012 dark theme. When moving the mouse of code I cannot see the cursor, since the code background is black and the mouse cursor is black.<br>
How to change the mouse cursor in code files to be white or any other color that is visible against a dark background?</p> | 13,822,396 | 7 | 4 | null | 2012-10-11 15:07:23.41 UTC | 6 | 2022-09-16 09:19:21.72 UTC | 2016-01-23 18:12:21.22 UTC | null | 3,800,096 | null | 351,025 | null | 1 | 44 | visual-studio-2012 | 30,097 | <p>In Windows 7 I resolved this by modifying my Windows system settings to use the Windows Black (system scheme). The caret I-Beam shape is surrounded by a white stroke that stands out over dark backgrounds and invisible over pure white backgrounds.</p>
<p>Go to Control Panel-->Appearance-->Ease of Access-->Make the mouse easier to use</p>
<p>and choose "Regular Black"</p>
<p>You would think that that the Inverted option would work, but the color remains black over the dark greys of the VS 2012 dark theme. The Regular Black does work well though.</p> |
12,810,638 | App crashed in iOS 6 when user changes Contacts access permissions | <p>I have an app that uses the Address Book. When running in iOS 6 it runs this code when the user does something that requires Address Book access.</p>
<pre><code>if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined)
{
ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);
ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error)
{
if (granted)
{
showContactChooser();
}
});
CFRelease(addressBookRef);
}
else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized)
{
showContactChooser();
}
else
{
showAccessDeniedAlert();
}
</code></pre>
<p>This works perfectly: I am able to read the contacts information and when the user denied access, the app reacts accordingly. </p>
<p>However, if the user:</p>
<ol>
<li>Allows Contacts access in the app,</li>
<li>Quits the app,</li>
<li>Goes to Settings->Privacy->Contacts and disables Contacts access for the app,</li>
<li>Runs the app,</li>
<li>While the app is running in background goes to settings and enables Contact access for the app,</li>
</ol>
<p>the app immediately crashes inside <code>main()</code> with no exception information or a meaningful stack trace. I tried turning on the "all exceptions" and <code>[NSException raise]</code> breakpoint, but that didn't give me any more information.</p>
<p>The crash can be reproduced even if the app doesn't run the above code during the launch.</p>
<p>What's happening here? Is there a callback that I should be subscribing to?</p> | 12,810,719 | 2 | 2 | null | 2012-10-10 01:17:03.597 UTC | 13 | 2015-05-19 16:03:19.66 UTC | null | null | null | null | 46,026 | null | 1 | 46 | ios|cocoa-touch|ios6|abaddressbook | 10,691 | <p>I've seen this in my own app. And I've seen others report this as well. I'm pretty sure this is deliberate behavior. The OS kills any background apps that react to changes in privacy permissions. Apple appears to have taken a sledgehammer approach to this. It's not a crash (though it may appear so when running in the debugger). Apps get terminated for various other reasons. Add this to the list of reasons. This gives us more reason to do a good job restoring app state upon a full restart of our apps.</p>
<p>Note that this behavior applies to all of the various privacy settings such as contacts, photos, microphone, calendar, and camera.</p> |
12,772,197 | What is the meaning of the "no index path for table cell being reused" message in iOS 6/7? | <p>Since starting to compile my app with iOS 6 (and since also iOS 7) I've started seeing this message. I know that the way that UITableViews go about managing cells is different in iOS 6 but I haven't needed to modify my code for it to keep working. But I'm concerned this message may point to some potential issue that I'm not yet seeing.
Can anyone shed any light?</p> | 18,769,328 | 14 | 0 | null | 2012-10-07 19:38:58.813 UTC | 15 | 2016-05-26 01:51:01.227 UTC | 2013-10-05 19:47:34.57 UTC | null | 1,368,854 | null | 1,368,854 | null | 1 | 58 | ios|ios6|uitableview|ios7 | 25,261 | <p>I started to get this error showing up in the log from iOS 7 beta 5 onwards, including in the iOS 7 GM/Release build, whilst never having had it happen in my app in iOS 6 or the earlier iOS 7 betas. After a lot of experimenting I found the cause:</p>
<p>I was using <code>UITableViewCell</code> objects for my section header views and returning them in <code>tableView:viewForHeaderInSection:</code>. This appears to be common practice, especially since iOS 5 when it became easy to design a section header view as a prototype table view cell in a StoryBoard with Interface Builder.</p>
<p>When I changed my app to use just regular <code>UIView</code> subclasses for my section header views, the errors went away and, more importantly, my table view stopped randomly deleting section headers!</p>
<p>It would appear that (since iOS 7 beta 5) <code>UITableView</code> is internally maintaining a mapping of all the <code>UITableViewCell</code> objects in its view hierarchy and their respective index paths. Since a section header (or a table view header of footer) doesn't have an index path, if you use a <code>UITableViewCell</code> object for these views, the table view will get confused when it finds a <code>UITableViewCell</code> for which it doesn't have an index path, resulting in the "no index path for table cell being reused" error and, if you're unlucky, display glitches in your table view:</p>
<p><strong>UPDATE</strong>: if you have access to the Apple Dev Forums, here's the thread about it (which I started): <a href="https://devforums.apple.com/message/882042#882042">https://devforums.apple.com/message/882042#882042</a></p>
<p>As suggested in that thread, if you don't want to re-factor much, you can create a <code>UIView</code> wrapper around your <code>UITableViewCell</code> and return that as the section header view. </p>
<pre><code>UIView *view = [[UIView alloc] initWithFrame:[cell frame]];
[view addSubview:cell];
return view;
</code></pre>
<p>Note however that this "wrapper" <code>UIView</code> approach will not play well with AutoLayout and device rotation, so I suggest that you use a <code>UIView</code> subclass for header and footer cells, not a <code>UITableViewCell</code> subclass as explained in the main part of the answer.</p> |
12,679,940 | Postgres No Primary Key Drawback | <p>Is there any drawback to not having a primary key for a table in Postgres? Since all data is stored unordered in the heap anyway, is the primary key just a way to enforce a unique key and an index at the same time? Or is there a fundamental feature that a primary key provides in a table as opposed to a table that does not have a primary key? </p> | 12,680,648 | 1 | 4 | null | 2012-10-01 19:42:53.693 UTC | 5 | 2019-05-22 08:59:34.167 UTC | null | null | null | null | 472,765 | null | 1 | 62 | postgresql | 36,295 | <p>Per the Postgres documentation (<a href="http://www.postgresql.org/docs/9.2/static/sql-createtable.html" rel="noreferrer">http://www.postgresql.org/docs/9.2/static/sql-createtable.html</a>):</p>
<blockquote>
<p>Technically, PRIMARY KEY is merely a combination of UNIQUE and NOT
NULL, but identifying a set of columns as primary key also provides
metadata about the design of the schema, as a primary key implies that
other tables can rely on this set of columns as a unique identifier
for rows.</p>
</blockquote>
<p>From my experience, I have created plenty of tables without them. But some replication solutions require there be a primary key, or at the single column identifier per row. </p> |
22,195,065 | How to send a JSON object using html form data | <p>So I've got this HTML form:</p>
<pre><code><html>
<head><title>test</title></head>
<body>
<form action="myurl" method="POST" name="myForm">
<p><label for="first_name">First Name:</label>
<input type="text" name="first_name" id="fname"></p>
<p><label for="last_name">Last Name:</label>
<input type="text" name="last_name" id="lname"></p>
<input value="Submit" type="submit" onclick="submitform()">
</form>
</body>
</html>
</code></pre>
<p>Which would be the easiest way to send this form's data as a JSON object to my server when a user clicks on submit?</p>
<p>UPDATE:
I've gone as far as this but it doesn't seem to work:</p>
<pre><code><script type="text/javascript">
function submitform(){
alert("Sending Json");
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action, true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
var j = {
"first_name":"binchen",
"last_name":"heris",
};
xhr.send(JSON.stringify(j));
</code></pre>
<p>What am I doing wrong?</p> | 22,195,193 | 9 | 10 | null | 2014-03-05 10:29:20.107 UTC | 66 | 2022-08-30 10:04:03.89 UTC | 2017-03-22 16:20:38.917 UTC | null | 3,885,376 | null | 178,728 | null | 1 | 175 | javascript|jquery|html|json|forms | 600,402 | <p>Get complete form data as array and json stringify it.</p>
<pre><code>var formData = JSON.stringify($("#myForm").serializeArray());
</code></pre>
<p>You can use it later in ajax. Or if you are not using ajax; put it in hidden textarea and pass to server. If this data is passed as json string via normal form data then you have to decode it. You'll then get all data in an array.</p>
<pre><code>$.ajax({
type: "POST",
url: "serverUrl",
data: formData,
success: function(){},
dataType: "json",
contentType : "application/json"
});
</code></pre> |
16,808,438 | The type or namespace name 'AspNet' does not exist in the namespace 'Microsoft' Error? | <p>I've downloaded a website and in VS express open it through file => open website. When I press <kbd>F5</kbd> to debug I get build errors:</p>
<blockquote>
<p>The type or namespace name 'AspNet' does not exist in the namespace 'Microsoft'</p>
</blockquote>
<p>I guess I'm missing a reference but how come it works on the server? References for these projects can be found in the bin directory right?</p>
<p>Under website => start options => build I've set the following: "Build web site" and target framework ".net framework 4" this is the same as the server.</p>
<p>I guess it's looking for a dll that contains Microsoft.aspNet which probably is in totallyUnrelatedName.dll in the folder scratchYourHeadAndLookSomeMore</p>
<p>Could someone help me out and give me a clue as to why Microsoft.aspNet would be missing from my computer?</p>
<p>I'm tempted to quit this job since all projects are web projects without any documentation that won't run locally but do need major changes. Client has no problem to implement changes on the live site but I do.</p> | 16,808,519 | 5 | 1 | null | 2013-05-29 08:00:09.113 UTC | 3 | 2021-04-12 04:04:32.787 UTC | 2020-08-03 03:37:17.763 UTC | null | 214,143 | null | 1,641,941 | null | 1 | 25 | asp.net|reference | 72,228 | <blockquote>
<p>I guess I'm missing a reference but how come it works on the server? References for these projects can be found in the bin directory right?</p>
</blockquote>
<p>Not if the used libraries are installed on the server. You might want to install them on your workstation too, or add the proper references (for example via NuGet) and do a bin-deploy.</p>
<p>On how to find out which libraries you're missing: find class names, not namespace names.</p> |
17,126,384 | g++ output: file not recognized: File format not recognized | <p>I am trying to build program with multiple files for the first time.
I have never had any problem with compliling program with main.cpp only.
With following commands, this is the result:</p>
<pre><code>$ g++ -c src/CNumber.cpp src/CNumber.h -o src/CNumber.o
$ g++ -c src/CExprPart.cpp src/CExprPart.h -o src/CExprPart.o
$ g++ -c src/CExpr.cpp src/CExpr.h -o src/CExpr.o
$ g++ -c src/main.cpp -o src/main.o
$ g++ src/CNumber.o src/CExprPart.o src/CExpr.o src/main.o -o execprogram
src/CNumber.o: file not recognized: File format not recognized
collect2: error: ld returned 1 exit status
</code></pre>
<p>What could cause such error and what should I do with it?
Using Linux Mint with gcc (Ubuntu/Linaro 4.7.2-2ubuntu1).
Thank you</p> | 17,126,626 | 3 | 2 | null | 2013-06-15 17:58:50.043 UTC | 4 | 2019-12-26 09:54:59.23 UTC | 2013-06-15 22:48:24.433 UTC | null | -1 | null | 2,489,350 | null | 1 | 32 | gcc|build|g++|makefile | 102,759 | <p>This is wrong:</p>
<pre><code> g++ -c src/CNumber.cpp src/CNumber.h -o src/CNumber.o
</code></pre>
<p>You shouldn't "compile" .h files. Doing so will create precompiled header files, which are not used to create an executable.
The above should simply be </p>
<pre><code> g++ -c src/CNumber.cpp -o src/CNumber.o
</code></pre>
<p>Similar for compiling the other .cpp files</p> |
16,664,090 | In Java, should I escape a single quotation mark (') in String (double quoted)? | <p>In Java, <code>\'</code> denotes a single quotation mark (single quote) character, and <code>\"</code> denotes a double quotation mark (double quote) character.</p>
<p>So, <code>String s = "I\'m a human.";</code> works well.</p>
<p>However, <code>String s = "I'm a human."</code> does not make any compile errors, either.</p>
<p>Likewise, <code>char c = '\"';</code> works, but <code>char c = '"';</code> also works.</p>
<p>In Java, which is better to use? In HTML or CSS, things like <code>style="font-family:'Arial Unicode MS';"</code> are more often (and for such tags, I think it's the only way to use quotation marks), but in Java, I usually saw people use escape characters like <code>"I\'m a human."</code></p> | 16,664,166 | 2 | 4 | null | 2013-05-21 07:08:17.787 UTC | 10 | 2021-08-06 13:22:28.987 UTC | 2015-12-22 00:02:51.717 UTC | user719662 | null | null | 869,330 | null | 1 | 33 | java|string|escaping|character | 121,698 | <p>You don't need to escape the <code>'</code> character in a String (wrapped in <code>"</code>), and you don't have to escape a <code>"</code> character in a char (wrapped in <code>'</code>).</p> |
16,947,559 | Can't remove a directory in Unix | <p>I've got a seemingly un-deletable directory in Unix that contains some hidden files with names that start with <code>.panfs</code>. I'm unable to delete it using either of these commands:</p>
<pre><code>rm -R <dir>
rm -Rf <dir>
</code></pre>
<p>Does anyone have any suggestions?</p> | 16,951,239 | 7 | 5 | null | 2013-06-05 18:48:07.063 UTC | 9 | 2021-10-20 10:19:09.073 UTC | 2017-12-23 11:41:20.627 UTC | null | 2,105,156 | null | 2,105,156 | null | 1 | 34 | linux|unix|directory|rm | 127,769 | <p>Try to delete it with <strong>root user</strong> or use <strong>sudo</strong>, if you are in trouble</p>
<p>Use <code>rm -rf dir</code> with root account and it will be deleted, since you should be facing a permissions issue.</p> |
17,120,476 | Click Event on UIImageView programmatically in ios | <p>I am displaying a image from code here is the code</p>
<pre><code>UIImageView *preArrowImage =[[UIImageView alloc]init ];
preArrowImage.image =[UIImage imageNamed:@"arrowprev.png"];
preArrowImage.frame = CGRectMake(20, 60, 10, 30);
[self.view addSubview:preArrowImage];
</code></pre>
<p>I want to handle the touch event on the preArrowImage programmatically. </p> | 17,120,537 | 8 | 2 | null | 2013-06-15 05:24:55.987 UTC | 23 | 2021-12-15 05:03:08.373 UTC | null | null | null | null | 1,085,352 | null | 1 | 103 | iphone|ios|uiimageview|uitouch|uitapgesturerecognizer | 95,086 | <p><strong>SWIFT 5</strong></p>
<pre><code>let preArrowImage : UIImageView // also give it frame
let singleTap = UITapGestureRecognizer(target: self, action: #selector(tapDetected))
preArrowImage.isUserInteractionEnabled = true
preArrowImage.addGestureRecognizer(singleTap)
//Action
func tapDetected() {
print("Imageview Clicked")
}
</code></pre>
<p><strong>Objective-c</strong></p>
<pre><code>UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDetected)];
singleTap.numberOfTapsRequired = 1;
[preArrowImage setUserInteractionEnabled:YES];
[preArrowImage addGestureRecognizer:singleTap];
-(void)tapDetected{
NSLog(@"single Tap on imageview");
}
</code></pre> |
17,049,473 | How to set custom header in Volley Request | <p>How can custom headers be set for a Volley request? At the moment, there is way to set body content for a POST request. I've a simple GET request, but I need to pass the custom headers alongwith. I don't see how JsonRequest class supports it. Is it possible at all?</p> | 17,050,421 | 13 | 1 | null | 2013-06-11 16:45:15.07 UTC | 41 | 2021-09-02 18:51:46.027 UTC | 2017-08-25 14:05:55.977 UTC | null | 3,885,376 | null | 911,359 | null | 1 | 111 | android|android-volley | 160,648 | <p>It looks like you override <code>public Map<String, String> getHeaders()</code>, <a href="https://github.com/google/volley/blob/18ed879dfa4671806f073dd1375cfede0a72d93c/core/src/main/java/com/android/volley/Request.java#L364-L372" rel="nofollow noreferrer">defined in <code>Request</code></a>, to return your desired HTTP headers.</p> |
16,794,695 | Connecting overloaded signals and slots in Qt 5 | <p>I'm having trouble getting to grips with the new signal/slot syntax (using pointer to member function) in Qt 5, as described in <a href="https://wiki.qt.io/New_Signal_Slot_Syntax" rel="noreferrer">New Signal Slot Syntax</a>. I tried changing this:</p>
<pre><code>QObject::connect(spinBox, SIGNAL(valueChanged(int)),
slider, SLOT(setValue(int));
</code></pre>
<p>to this:</p>
<pre><code>QObject::connect(spinBox, &QSpinBox::valueChanged,
slider, &QSlider::setValue);
</code></pre>
<p>but I get an error when I try to compile it:</p>
<blockquote>
<p>error: no matching function for call to <code>QObject::connect(QSpinBox*&,
<unresolved overloaded function type>, QSlider*&, void
(QAbstractSlider::*)(int))</code></p>
</blockquote>
<p>I've tried with clang and gcc on Linux, both with <code>-std=c++11</code>.</p>
<p>What am I doing wrong, and how can I fix it?</p> | 16,795,664 | 4 | 3 | null | 2013-05-28 14:30:46.977 UTC | 46 | 2019-10-01 02:30:51.76 UTC | 2016-05-18 15:20:33.167 UTC | null | 4,850,040 | null | 1,671,042 | null | 1 | 160 | c++|qt|qt5 | 69,928 | <p>The problem here is that there are <strong>two</strong> signals with that name: <code>QSpinBox::valueChanged(int)</code> and <code>QSpinBox::valueChanged(QString)</code>. From Qt 5.7, there are helper functions provided to select the desired overload, so you can write</p>
<pre class="lang-cpp prettyprint-override"><code>connect(spinbox, qOverload<int>(&QSpinBox::valueChanged),
slider, &QSlider::setValue);
</code></pre>
<p>For Qt 5.6 and earlier, you need to tell Qt which one you want to pick, by casting it to the right type:</p>
<pre class="lang-cpp prettyprint-override"><code>connect(spinbox, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged),
slider, &QSlider::setValue);
</code></pre>
<p>I know, it's <strong>ugly</strong>. But there's no way around this. Today's lesson is: <em>do not overload your signals and slots!</em></p>
<hr>
<p><strong>Addendum</strong>: what's really annoying about the cast is that </p>
<ol>
<li>one repeats the class name twice</li>
<li>one has to specify the return value even if it's usually <code>void</code> (for signals).</li>
</ol>
<p>So I've found myself sometimes using this C++11 snippet:</p>
<pre class="lang-cpp prettyprint-override"><code>template<typename... Args> struct SELECT {
template<typename C, typename R>
static constexpr auto OVERLOAD_OF( R (C::*pmf)(Args...) ) -> decltype(pmf) {
return pmf;
}
};
</code></pre>
<p>Usage:</p>
<pre class="lang-cpp prettyprint-override"><code>connect(spinbox, SELECT<int>::OVERLOAD_OF(&QSpinBox::valueChanged), ...)
</code></pre>
<p>I personally find it not really useful. I expect this problem to go away by itself when Creator (or your IDE) will automatically insert the right cast when autocompleting the operation of taking the PMF. But in the meanwhile...</p>
<p>Note: the PMF-based connect syntax <strong>does not require C++11</strong>!</p>
<hr>
<p><strong>Addendum 2</strong>: in Qt 5.7 helper functions were added to mitigate this, modelled after my workaround above. The main helper is <a href="https://doc.qt.io/qt-5/qtglobal.html#qOverload" rel="noreferrer"><code>qOverload</code></a> (you've also got <a href="https://doc.qt.io/qt-5/qtglobal.html#qConstOverload" rel="noreferrer"><code>qConstOverload</code></a> and <a href="https://doc.qt.io/qt-5/qtglobal.html#qNonConstOverload" rel="noreferrer"><code>qNonConstOverload</code></a>). </p>
<p>Usage example (from the docs):</p>
<pre class="lang-cpp prettyprint-override"><code>struct Foo {
void overloadedFunction();
void overloadedFunction(int, QString);
};
// requires C++14
qOverload<>(&Foo:overloadedFunction)
qOverload<int, QString>(&Foo:overloadedFunction)
// same, with C++11
QOverload<>::of(&Foo:overloadedFunction)
QOverload<int, QString>::of(&Foo:overloadedFunction)
</code></pre>
<hr>
<p><strong>Addendum 3</strong>: if you look at the documentation of any overloaded signal, now the solution to the overloading problem is clearly stated in the docs themselves. For instance, <a href="https://doc.qt.io/qt-5/qspinbox.html#valueChanged-1" rel="noreferrer">https://doc.qt.io/qt-5/qspinbox.html#valueChanged-1</a> says</p>
<blockquote>
<p>Note: Signal valueChanged is overloaded in this class. To connect to this signal by using the function pointer syntax, Qt provides a convenient helper for obtaining the function pointer as shown in this example:</p>
<pre class="lang-cpp prettyprint-override"><code> connect(spinBox, QOverload<const QString &>::of(&QSpinBox::valueChanged),
[=](const QString &text){ /* ... */ });
</code></pre>
</blockquote> |
10,115,806 | SELECT or PERFORM in a PL/pgSQL function | <p>I have this function in my database:</p>
<pre><code>CREATE OR REPLACE FUNCTION "insertarNuevoArticulo"(nombrearticulo character varying, descripcion text, idtipo integer, idfamilia bigint, artstock integer, minstock integer, maxstock integer, idmarca bigint, precio real, marcastock integer)
RETURNS boolean AS
$BODY$
DECLARE
articulo "Articulo"%ROWTYPE;
BEGIN
SELECT * INTO articulo FROM "Articulo" WHERE "Nombre" = $1 AND "idTipo"=$3 AND "idFamilia"=$4;
IF NOT FOUND THEN
INSERT INTO "Articulo" ("Nombre", "Descripcion", "idTipo", "idFamilia", "Stock", "MinStock", "MaxStock") Values ($1, $2, $3, $4, $5, $6, $7);
SELECT last_value
INTO articulo."idArticulo"
FROM "public"."Articulo_idArticulo_seq";
END IF;
SELECT * FROM "ArticuloMarca" AS am WHERE am."idArticulo" = articulo."idArticulo" and am."idMarca" = $8;
IF NOT FOUND THEN
Insert into "ArticuloMarca"("idArticulo", "idMarca", "PrecioReferencial", "Stock") Values (articulo."idArticulo", $8, $9, $10);
RETURN TRUE;
END IF;
RETURN FALSE;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION "insertarNuevoArticulo"(character varying, text, integer, bigint, integer, integer, integer, bigint, real, integer)
OWNER TO postgres;
</code></pre>
<p>But as soon as I try to use it, it says I need to use <code>PERFORM</code> if I want to discard the results! The problem here is that I don't want to! I want them in the <code>articulo</code> row I declared!</p>
<p>I'm using this statement: </p>
<pre><code>SELECT "insertarNuevoArticulo"('Acetaminofen', 'caro', '1' , '1', '8', '1', '10', '1', '150.7', '10');
</code></pre>
<p>And the error i get is 42601, a syntax error! How could it be if I'm using the IDE to create it? Any idea about the problem?</p> | 10,117,015 | 2 | 0 | null | 2012-04-12 00:21:11.277 UTC | 0 | 2020-08-20 23:21:27.163 UTC | 2018-04-01 01:06:39.047 UTC | null | 939,860 | null | 1,229,706 | null | 1 | 13 | postgresql|function|plpgsql|select-into | 41,476 | <p>In plpgsql code, <code>SELECT</code> without a target triggers an error. But you obviously do <em>not</em> want <code>SELECT INTO</code>, you just want to set the status of <code>FOUND</code>. You would use <a href="https://www.postgresql.org/docs/current/plpgsql-statements.html#PLPGSQL-STATEMENTS-SQL-NORESULT" rel="nofollow noreferrer"><strong><code>PERFORM</code></strong></a> for that.</p>
<ul>
<li><a href="https://stackoverflow.com/questions/37230750/select-raises-exception-in-pl-pgsql-function/37234043#37234043">SELECT raises exception in PL/pgSQL function</a></li>
</ul>
<p><strong>Better, yet</strong>, use <code>IF EXISTS ...</code>. Consider this rewrite of your function:</p>
<pre class="lang-sql prettyprint-override"><code>CREATE OR REPLACE FUNCTION "insertarNuevoArticulo"( nombrearticulo text, descripcion text, idtipo int, idfamilia bigint, artstock int, minstock int, maxstock int, idmarca bigint, precio real, marcastock int)
RETURNS boolean
LANGUAGE plpgsql AS
$func$
DECLARE
_id_articulo "Articulo"."idArticulo"%TYPE;
BEGIN
SELECT a."idArticulo" INTO _id_articulo
FROM "Articulo" a
WHERE a."Nombre" = $1 AND a."idTipo" = $3 AND a."idFamilia" = $4;
IF NOT FOUND THEN
INSERT INTO "Articulo"("Nombre", "Descripcion", "idTipo", "idFamilia", "Stock", "MinStock", "MaxStock")
VALUES ($1, $2, $3, $4, $5, $6, $7)
RETURNING "Articulo"."idArticulo" INTO _id_articulo;
END IF;
IF EXISTS (SELECT FROM "ArticuloMarca" a
WHERE a."idArticulo" = _id_articulo AND a."idMarca" = $8) THEN
RETURN false;
ELSE
INSERT INTO "ArticuloMarca"("idArticulo", "idMarca", "PrecioReferencial", "Stock")
VALUES (_id_articulo, $8, $9, $10);
RETURN true;
END IF;
END
$func$;
</code></pre>
<p>About <code>EXISTS</code>:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/11892233/pl-pgsql-checking-if-a-row-exists-select-into-boolean/11892796#11892796">PL/pgSQL checking if a row exists</a></li>
</ul>
<p>The <strong>other major point</strong>:</p>
<ul>
<li>Use the <a href="https://www.postgresql.org/docs/current/plpgsql-statements.html#PLPGSQL-STATEMENTS-SQL-ONEROW" rel="nofollow noreferrer"><code>RETURNING</code> clause</a> of the <code>INSERT</code> statement instead of an additional <code>SELECT</code>.</li>
</ul>
<h3>Postgres 9.5+</h3>
<p>In Postgres 9.5 or later use <code>INSERT ... ON CONFLICT DO NOTHING</code> (a.k.a. "UPSERT") instead.<br />
You would have <code>UNIQUE</code> constraints on <code>"Articulo"("Nombre", "idTipo", "idFamilia")</code> and <code>"ArticuloMarca"("idArticulo", "idMarca")</code> and then:</p>
<pre class="lang-sql prettyprint-override"><code>CREATE OR REPLACE FUNCTION insert_new_articulo( nombrearticulo text, descripcion text, idtipo int, idfamilia bigint, artstock int, minstock int, maxstock int, idmarca bigint, precio real, marcastock int)
RETURNS boolean
LANGUAGE plpgsql AS
$func$
DECLARE
_id_articulo "Articulo"."idArticulo"%TYPE;
BEGIN
LOOP
SELECT "idArticulo" INTO _id_articulo
FROM "Articulo"
WHERE "Nombre" = $1 AND "idTipo" = $3 AND "idFamilia" = $4;
EXIT WHEN FOUND;
INSERT INTO "Articulo"("Nombre", "Descripcion", "idTipo", "idFamilia", "Stock", "MinStock", "MaxStock")
VALUES ($1, $2, $3, $4, $5, $6, $7)
ON CONFLICT (tag) DO NOTHING
RETURNING "idArticulo" INTO _id_articulo;
EXIT WHEN FOUND;
END LOOP;
LOOP
INSERT INTO "ArticuloMarca"("idArticulo", "idMarca", "PrecioReferencial", "Stock")
VALUES (_id_articulo, $8, $9, $10)
ON CONFLICT ("idArticulo", "idMarca") DO NOTHING;
IF FOUND THEN
RETURN true;
END IF;
IF EXISTS (SELECT FROM "ArticuloMarca"
WHERE "idArticulo" = _id_articulo AND "idMarca" = $8) THEN
RETURN false;
END IF;
END LOOP;
END
$func$;
</code></pre>
<p>This is faster, simpler and more reliable. The added loops rule out any remaining race conditions with concurrent writes (while adding hardly any cost). Without concurrent writes, you can simplify. Detailed explanation:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/15939902/is-select-or-insert-in-a-function-prone-to-race-conditions/15950324#15950324">Is SELECT or INSERT in a function prone to race conditions?</a></li>
<li><a href="https://stackoverflow.com/questions/34708509/how-to-use-returning-with-on-conflict-in-postgresql/42217872#42217872">How to use RETURNING with ON CONFLICT in PostgreSQL?</a></li>
</ul>
<p>Aside: use legal, lower-case identifiers to avoid all the noisy <a href="https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS" rel="nofollow noreferrer">double-quotes</a>.</p> |
9,975,672 | c++ automatic factory registration of derived types | <p>Like many before me, I'm trying so get my derived types to automatically register with my factory. I read through many question and tried to focus on what I didn't find there.</p>
<p>I've got everything running nicely except the automatic registration.</p>
<p><strong>My Goals:</strong></p>
<ol>
<li>automatically register any derived class of my base class <strong>Base</strong>
<ol>
<li>only classes I mark as <em>registrable</em></li>
<li>not only direct sub-classes of <strong>Base</strong>
<ul>
<li><strong>ex:</strong> Base -> Device -> Camera -> <strong>Webcam</strong></li>
<li>this would make using the <a href="http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern" rel="noreferrer">CRTP</a> like described in <a href="https://stackoverflow.com/questions/6399804/automatic-static-invocation-of-derived-types">this question</a> dificult</li>
</ul></li>
</ol></li>
<li>minimal changes to the classes I want registered - <em>dummies proof</em></li>
<li>would prefer using a <strong>registrator class</strong> than macros
<ul>
<li>like in <a href="https://stackoverflow.com/questions/6399804/automatic-static-invocation-of-derived-types">this question</a>, but I'm not sure if this is dependent on <a href="http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern" rel="noreferrer">CRTP</a></li>
</ul></li>
</ol>
<p><strong>What I have:</strong></p>
<pre><code>template <class T>
class abstract_factory
{
public:
template < typename Tsub > static void register_class();
static T* create( const std::string& name );
private:
// allocator<T> is a helper class to create a pointer of correct type
static std::map<std::string, boost::shared_ptr<allocator<T> > > s_map;
};
</code></pre>
<ul>
<li>templated abstract factory, with <strong>std::string</strong> as <em>key type</em></li>
<li>abstract factory has all members and methods <strong>static</strong></li>
<li>class name is recovered automatically with <strong>typeid</strong> (no need for text name when registering)</li>
<li>registration by calling: <code>abstract_factory<Base>::register_class<MyDerived>();</code></li>
</ul>
<p><strong>What I tried (or would like to but don't know how to properly):</strong></p>
<ul>
<li><code>registrator<Derived> class</code>: templateded class that is instantiated statically in <code>Derived.cpp</code> and should call <code>abstract_factory::register_class<Derived>()</code> in it's constructor
<ul>
<li>never gets called or instantiated</li>
<li>if I make an instance of <code>Derived</code> in <code>main()</code> this works -> kinda defeats the purpose though </li>
</ul></li>
<li>declare a simple static variable in each <code>Derived.hpp</code> and set it with the static registration method in <code>Derived.cpp</code> -> again, never gets called.</li>
<li>make <code>abstract_factory</code> a true singleton instead of having everything static?</li>
</ul>
<p>Could use any advice, large or small, thanx.</p> | 9,976,054 | 2 | 0 | null | 2012-04-02 11:35:23.453 UTC | 10 | 2012-04-04 13:21:49.277 UTC | 2017-05-23 12:25:33.503 UTC | null | -1 | null | 613,391 | null | 1 | 17 | c++|templates|static-methods|factory-pattern | 17,319 | <p>I use a singleton with a member for registration, basically:</p>
<pre><code>template< typename KeyType, typename ProductCreatorType >
class Factory
{
typedef boost::unordered_map< KeyType, ProductCreatorType > CreatorMap;
...
};
</code></pre>
<p>Using Loki I then have something along these lines:</p>
<pre><code> typedef Loki::SingletonHolder< Factory< StringHash, boost::function< boost::shared_ptr< SomeBase >( const SomeSource& ) > >, Loki::CreateStatic > SomeFactory;
</code></pre>
<p>Registration is usually done using a macro such as: </p>
<pre><code>#define REGISTER_SOME_FACTORY( type ) static bool BOOST_PP_CAT( type, __regged ) = SomeFactory::Instance().RegisterCreator( BOOST_PP_STRINGIZE( type ), boost::bind( &boost::make_shared< type >, _1 ) );
</code></pre>
<p>This setup has a number of advantages:</p>
<ul>
<li>Works with for example boost::shared_ptr<>.</li>
<li>Does not require maintaining a huge file for all the registration needs.</li>
<li>Is very flexible with the creator, anything goes pretty much.</li>
<li>The macro covers the most common use case, while leaving the door open for alternatives.</li>
</ul>
<p>Invoking the macro in the .cpp file is then enough to get the type registered at start up during static initialization. This works dandy save for when the type registration is a part of a static library, in which case it won't be included in your binary. The only solutions which compiles the registration as a part of the library which I've seen work is to have one huge file that does the registration explicitly as a part of some sort of initialization routine. Instead what I do nowadays is to have a client folder with my lib which the user includes as a part of the binary build.</p>
<p>From your list of requirements I believe this satisfies everything save for using a registrator class.</p> |
10,105,666 | Clearing the terminal screen? | <p>I'm reading data from 9 different sensors for my robot and I need to display them all steadily, in the same window so I can compare the values and see if any of the readings is off.</p>
<p>The problem I'm having with both Serial.print and lcd.print is that the values are constantly moving and I can't really have a good look at them while moving the robot.</p>
<p>I was thinking to call something like Serial.clear() before displaying anything else and that would just keep things steady and in one place, changing only the values.</p>
<p>From what I found so far, Serial.print(17,BYTE) for instance is no longer supported (Calling the ESC key).</p>
<p>So...for those with a bit more Arduino experience...what is the proper way to do this?</p> | 15,559,322 | 14 | 0 | null | 2012-04-11 12:11:59.193 UTC | 6 | 2022-04-05 11:17:29.36 UTC | 2020-07-03 12:17:27.427 UTC | null | 8,422,953 | null | 872,893 | null | 1 | 20 | terminal|arduino|refresh|erase | 162,019 | <p>The Arduino serial monitor isn't a regular terminal so its not possible to clear the screen using standard terminal commands. I suggest using an actual terminal emulator, like <a href="http://www.putty.org/" rel="noreferrer">Putty</a>.</p>
<p>The command for clearing a terminal screen is ESC[2J</p>
<p>To accomplish in Arduino code:</p>
<pre><code> Serial.write(27); // ESC command
Serial.print("[2J"); // clear screen command
Serial.write(27);
Serial.print("[H"); // cursor to home command
</code></pre>
<p>Source:<br>
<a href="http://www.instructables.com/id/A-Wirelessly-Controlled-Arduino-Powered-Message-B/step6/Useful-Code-Explained-Clearing-a-Serial-Terminal/" rel="noreferrer">http://www.instructables.com/id/A-Wirelessly-Controlled-Arduino-Powered-Message-B/step6/Useful-Code-Explained-Clearing-a-Serial-Terminal/</a></p> |
9,891,407 | Getting the desugared part of a Scala for/comprehension expression? | <p>Does anyone know how to get the (Scala part only) desugared translation of a for/comprehension expression before it actually tries to compile in the REPL (or compiler)?</p>
<p>The only thing I've found so far is the compiler "-print" flag but that gives you the full Scala translation… </p> | 9,892,350 | 6 | 0 | null | 2012-03-27 14:19:26.4 UTC | 24 | 2017-05-25 17:32:53.57 UTC | 2012-03-27 15:14:48.953 UTC | null | 1,189,659 | null | 1,189,659 | null | 1 | 32 | scala|syntactic-sugar|for-comprehension | 10,882 | <p>It doesn't seem to exists any possibilities to desugar "for/comprehension" expressions directly within the REPL. But as an alternative one can use some Scala compiler options like "-print" or for simple expressions "Xprint:typer -e"</p>
<p>Example:</p>
<p>To get the desugard output from a file use the "-print" flag:</p>
<pre><code># scala -print file.scala
</code></pre>
<p>To desugar a simple one-liner expression, use the "-Xprint:typer -e" flag:</p>
<pre><code># scala -Xprint:typer -e "for (i <- 0 to 100) yield i"
</code></pre> |
9,659,265 | Check if Javascript script exists on page | <p>I have a bookmarklet that I've made and it loads a script from my server onto the users current page. However I have an if check in my script that if a condition is not met then no action is taken. However if the user then meets that condition then the code is run, but has caused there to be two sets of scripts inserted into their page. Can i prevent this?</p>
<pre><code> <a href="javascript: (function () {
var jsCode = document.createElement('script');
jsCode.setAttribute('src', 'http://xxx.co.uk/xxx/script.js');
document.body.appendChild(jsCode);
}());">Bookmarklet</a>
</code></pre> | 9,659,297 | 7 | 0 | null | 2012-03-11 21:56:33.427 UTC | 8 | 2022-04-07 07:04:47.487 UTC | null | null | null | null | 478,144 | null | 1 | 34 | javascript | 45,856 | <p>You can check whether your script is loaded like this:</p>
<pre><code>function isMyScriptLoaded(url) {
if (!url) url = "http://xxx.co.uk/xxx/script.js";
var scripts = document.getElementsByTagName('script');
for (var i = scripts.length; i--;) {
if (scripts[i].src == url) return true;
}
return false;
}
</code></pre>
<p>Alternatively, you could do something like this:</p>
<pre><code><a href="javascript:
if (!jsCode) {
var jsCode = document.createElement('script');
jsCode.setAttribute('src', 'http://xxx.co.uk/xxx/script.js');
document.body.appendChild(jsCode);
}
">Bookmarklet</a>
</code></pre>
<p>This "pollutes" the global namespace with the <code>jsCode</code> variable, but that might be a necessary evil. You could rename it to something that is unlikely to appear in the document where the bookmarklet is run.</p>
<hr>
<p>Please note that while the <code>javascript</code> URI scheme is okay for bookmarklets as in this case, it's not considered to be a good practice for normal use. </p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.