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
28,504,589
Creating an NSDateFormatter in Swift?
<p>I am new to swift and am very unfamiliar with Objective-C. Could someone help me convert this to Swift? I got this code from Ray Wenderlich's best iOS practices - <a href="http://www.raywenderlich.com/31166/25-ios-app-performance-tips-tricks" rel="noreferrer">http://www.raywenderlich.com/31166/25-ios-app-performance-tips-tricks</a></p> <p>Where would you put this code? Would it go in a class file full of global variables?</p> <pre><code>- (NSDateFormatter *)formatter { static NSDateFormatter *formatter; static dispatch_once_t onceToken; dispatch_once(&amp;onceToken, ^{ _formatter = [[NSDateFormatter alloc] init]; _formatter.dateFormat = @"EEE MMM dd HH:mm:ss Z yyyy"; // twitter date format }); return formatter; } </code></pre>
28,511,412
4
2
null
2015-02-13 16:49:06.117 UTC
9
2020-05-10 17:46:16.023 UTC
2017-06-20 17:32:55.097 UTC
null
74,118
null
4,162,864
null
1
24
objective-c|swift|date|nsdate|nsdateformatter
14,013
<ol> <li><p>If you're really looking for direct analog to the method in your question, you could do something like:</p> <pre><code>class MyObject { // define static variable private static let formatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy" return formatter }() // you could use it like so func someMethod(date: Date) -&gt; String { return MyObject.formatter.string(from: date) } } </code></pre> <p>The <code>static</code> properties, like globals, enjoy <code>dispatch_once</code> behavior for their default values. For more information, see the <code>dispatch_once</code> discussion at the end of the <a href="https://developer.apple.com/swift/blog/?id=7" rel="nofollow noreferrer">Files and Initialization</a> entry in Apple's Swift blog.</p></li> <li><p>Regarding best practices with date formatters, I would suggest:</p> <ul> <li><p>Yes, it is prudent to not unnecessarily create and destroy formatters that you're likely to need again. In WWDC 2012 video, <a href="https://developer.apple.com/videos/wwdc/2012/?id=235" rel="nofollow noreferrer">iOS App Performance: Responsiveness</a>, Apple explicitly encourages us to </p> <ul> <li><p>Cache one formatter per date format;</p></li> <li><p>Add observer for <code>NSLocale.currentLocaleDidChangeNotification</code> through the <code>NotificationCenter</code>, and clearing/resetting cached formatters if this occurs; and</p></li> <li><p>Note that resetting a format is as expensive as recreating, so avoid repeatedly changing a formatter's format string.<br />&nbsp;</p></li> </ul> <p>Bottom line, reuse date formatters wherever possible if you're using the same date format repeatedly.</p></li> <li><p>If using <code>DateFormatter</code> to parse date strings to be exchanged with a web service (or stored in a database), you should use <code>en_US_POSIX</code> locale to avoid problems with international users who might not be using Gregorian calendars. See <a href="https://developer.apple.com/library/mac/qa/qa1480/_index.html" rel="nofollow noreferrer">Apple Technical Q&amp;A #1480</a> or the “Working With Fixed Format Date Representations” discussion in the <a href="https://developer.apple.com/documentation/foundation/dateformatter" rel="nofollow noreferrer"><code>DateFormatter</code> documentation</a>. (Or in iOS 10 and macOS 10.12, use <a href="https://developer.apple.com/documentation/foundation/iso8601dateformatter" rel="nofollow noreferrer"><code>ISO8601DateFormatter</code></a>.)</p> <p>But when using <code>dateFormat</code> with <code>DateFormatter</code>, use the current locale for creating strings to be presented to the end user, but use <code>en_US_POSIX</code> local when creating/parsing strings to be used internally within the app or to be exchanged with a web service.</p></li> <li><p>If formatting date strings for the user interface, localize the strings by avoiding using string literals for <code>dateFormat</code> if possible. Use <code>dateStyle</code> and <code>timeStyle</code> where you can. And if you must use custom <code>dateFormat</code>, use templates to localize your strings. For example, rather than hard-coding <code>E, MMM d</code>, in Swift 3 and later, you would use <code>dateFormat(fromTemplate:options:locale:)</code>:</p> <pre><code>formatter.dateFormat = DateFormatter.dateFormat(fromTemplate: "EdMMM", options: 0, locale: Locale.current) </code></pre> <p>This will automatically show, for example, "Mon, Sep 5" for US users, but "Mon 5 Sep" for UK users. </p></li> <li><p>The <code>DateFormatter</code> is now thread safe on iOS 7 and later and 64-bit apps running on macOS 10.9 and later. </p></li> </ul></li> </ol> <p>For Swift 2 examples, see <a href="https://stackoverflow.com/revisions/28511412/9">previous revision of this answer</a>.</p>
36,285,253
Enable CORS for Web Api 2 and OWIN token authentication
<p>I have an ASP.NET MVC 5 webproject (localhost:81) that calls functions from my WebApi 2 project (localhost:82) using Knockoutjs, to make the communication between the two projects I enable CORS. Everything works so far until I tried to implement OWIN token authentication to the WebApi.</p> <p>To use the /token endpoint on the WebApi, I also need to enable CORS on the endpoint but after hours of trying and searching for solutions it is still now working and the api/token still results in:</p> <pre><code>XMLHttpRequest cannot load http://localhost:82/token. No 'Access-Control-Allow-Origin' header is present on the requested resource. </code></pre> <pre class="lang-cs prettyprint-override"><code>public void Configuration(IAppBuilder app) { app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); TokenConfig.ConfigureOAuth(app); ... } </code></pre> <p>TokenConfig</p> <pre class="lang-cs prettyprint-override"><code>public static void ConfigureOAuth(IAppBuilder app) { app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext&lt;AppUserManager&gt;(AppUserManager.Create); OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions() { AllowInsecureHttp = true, TokenEndpointPath = new PathString(&quot;/token&quot;), AccessTokenExpireTimeSpan = TimeSpan.FromDays(1), Provider = new SimpleAuthorizationServerProvider() }; app.UseOAuthAuthorizationServer(OAuthServerOptions); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); } </code></pre> <p>AuthorizationProvider</p> <pre class="lang-cs prettyprint-override"><code>public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add(&quot;Access-Control-Allow-Origin&quot;, new[] { &quot;*&quot; }); var appUserManager = context.OwinContext.GetUserManager&lt;AppUserManager&gt;(); IdentityUser user = await appUserManager.FindAsync(context.UserName, context.Password); if (user == null) { context.SetError(&quot;invalid_grant&quot;, &quot;The user name or password is incorrect.&quot;); return; } ... claims } </code></pre> <p>IdentityConfig</p> <pre class="lang-cs prettyprint-override"><code>public static AppUserManager Create(IdentityFactoryOptions&lt;AppUserManager&gt; options, IOwinContext context) { // Tried to enable it again without success. //context.Response.Headers.Add(&quot;Access-Control-Allow-Origin&quot;, new[] {&quot;*&quot;}); var manager = new AppUserManager(new UserStore&lt;AppUser&gt;(context.Get&lt;ApplicationDbContect&gt;())); ... var dataProtectionProvider = options.DataProtectionProvider; if (dataProtectionProvider != null) { manager.UserTokenProvider = new DataProtectorTokenProvider&lt;AppUser&gt;(dataProtectionProvider.Create(&quot;ASP.NET Identity&quot;)); } return manager; } </code></pre> <p>EDIT:</p> <p><strong>1. Important note is that opening the endpoint directly (localhost:82/token) works.</strong></p> <p><strong>2. Calling the Api (localhost:82/api/..) from the webproject also works, so the CORS is enabled for WebApi.</strong></p>
36,968,863
3
9
null
2016-03-29 13:09:22.34 UTC
16
2021-02-25 20:58:26.05 UTC
2021-02-25 20:58:26.05 UTC
null
1,075,980
null
4,836,952
null
1
33
asp.net-web-api|asp.net-mvc-5|cors|asp.net-web-api2|owin
31,374
<p>I know your issue was solved inside comments, but I believe is important to understand what was causing it and how to resolve this entire class of problems.</p> <p>Looking at your code I can see you are setting the <code>Access-Control-Allow-Origin</code> header more than once for the Token endpoint:</p> <pre><code>app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); </code></pre> <p>And inside <code>GrantResourceOwnerCredentials</code> method:</p> <pre><code>context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); </code></pre> <p>This, looking at the <a href="http://www.w3.org/TR/cors/" rel="noreferrer">CORS specifications</a>, is itself an issue because:</p> <blockquote> <p>If the response includes zero or more than one Access-Control-Allow-Origin header values, return fail and terminate this algorithm.</p> </blockquote> <p>In your scenario, the framework is setting this header two times, and understanding how CORS must be implemented, this will result in the header removed in certain circumstances (possibly client-related).</p> <p>This is also confirmed by the following question answer: <a href="https://stackoverflow.com/questions/13614316/duplicate-access-control-allow-origin-causing-cor-error">Duplicate Access-Control-Allow-Origin: * causing COR error?</a></p> <p>For this reason moving the call to <code>app.UseCors</code> after the call to <code>ConfigureOAuth</code> allows your CORS header to be set only once (because the owin pipeline is interrupted at the OAuth middleware, and never reaches the Microsoft CORS middleware for the <code>Token</code> endpoint) and makes your Ajax call working.</p> <p>For a better and global solution you may try to put again <code>app.UseCors</code> before the OAuth middleware call, and remove the second <code>Access-Control-Allow-Origin</code> insertion inside <code>GrantResourceOwnerCredentials</code>.</p>
36,608,780
og:image could not be downloaded because it exceeded the maximum allowed sized of 8Mb
<p>Building a website that requires sharing links with an image. Done this I don't know how often...but this time the Facebook Open Graph Debugger says:</p> <p>og:image {image url} could not be downloaded because it exceeded the maximum allowed sized of 8Mb</p> <p>But the image referenced is only 108KB? One other time it responded that my server might be too slow. But when I simply load up the image in a browser it's instantly there. Where should I be looking now?</p>
36,894,300
4
10
null
2016-04-13 20:18:23.373 UTC
8
2018-01-29 22:58:10.67 UTC
2016-08-06 01:32:05.143 UTC
null
212,378
null
5,036,871
null
1
49
facebook-opengraph
23,131
<p>This is a bug, and it's confirmed, after getting the warning, if you retry the debug, or click on "Scrape Again", the error message will be gone. This is an issue because if someone tries to share the post, the image will not show up since it didn't get scrapped, but subsequent shares will display the image.</p> <p>You may subscribe to the Bug report or add some extra comments.</p> <p><a href="https://developers.facebook.com/bugs/1626463061012181/" rel="noreferrer">https://developers.facebook.com/bugs/1626463061012181/</a></p> <p>And yeah, this started happening around April 17th, I hope this solves our issue.</p> <p><strong>EDIT:</strong></p> <p>Facebook Team replied with a workaround:</p> <blockquote> <p>It seems like the issue is with the misleading error message which we will be updating. In the meantime, since the crawler has to see an image at least once before it can be rendered, it means that the first person who shares a piece of content won't see a rendered image. This seems to be the actual issue here and the workaround is available here: <a href="https://developers.facebook.com/docs/sharing/best-practices#precaching" rel="noreferrer">https://developers.facebook.com/docs/sharing/best-practices#precaching</a> I will post here once we update the error message.</p> </blockquote> <p>Adding the <strong><code>og:image:width</code></strong> and <strong><code>og:image:height</code></strong> <em>Open Graph tags</em> seems to do the trick, I can swear I tried that before and didn't do much, but this time it seems to work just fine.</p>
7,055,652
Real-world example of exponential time complexity
<p>I'm looking for an intuitive, real-world example of a problem that takes (worst case) exponential time complexity to solve for a talk I am giving.</p> <p>Here are examples for other time complexities I have come up with (many of them taken from <a href="https://stackoverflow.com/questions/1592649/examples-of-algorithms-which-has-o1-on-log-n-and-olog-n-complexities">this SO question</a>):</p> <ul> <li>O(1) - determining if a number is odd or even</li> <li>O(log N) - finding a word in the dictionary (using binary search)</li> <li>O(N) - reading a book</li> <li>O(N log N) - sorting a deck of playing cards (using merge sort)</li> <li>O(N^2) - checking if you have everything on your shopping list in your trolley</li> <li>O(infinity) - tossing a coin until it lands on heads</li> </ul> <p>Any ideas?</p>
7,055,684
5
3
null
2011-08-14 07:45:54.84 UTC
21
2020-06-23 18:19:57.3 UTC
2017-05-23 12:02:56.8 UTC
null
-1
null
393,304
null
1
38
complexity-theory|exponential
35,918
<ul> <li>O(10^N): trying to break a password by testing every possible combination (assuming numerical password of length N)</li> </ul> <p><strike><strong>p.s.</strong> why is your last example is of complexity O(infinity) ? it's linear search O(N) .. there are less than 7 billion people in the world.</strike></p>
7,059,780
Find the element repeated more than n/2 times
<p>There is an array (of size N) with an element repeated more than N/2 number of time and the <strong>rest of the element in the array can also be repeated</strong> but only one element is repeated more than N/2 times. Find the number.</p> <p>I could think of few approaches:</p> <ul> <li>Naive, keep the count of each number in a hash map.</li> <li>Simplest, sort the array and the number at n/2+1 th index is the required number.</li> <li>Keep count of only consecutive duplicate values found. Check separately for the pattern where the values are stored alternatively.</li> </ul> <p>Unable to think of a better solution, there has to be. </p>
7,059,877
7
3
null
2011-08-14 21:16:56.903 UTC
26
2015-10-07 05:33:06.373 UTC
2011-12-15 20:57:31.477 UTC
null
501,557
null
854,075
null
1
31
arrays|algorithm
31,088
<p>There is a beautiful algorithm for solving this that works in two passes (total time O(N)) using only constant external space (O(1)). I have an implementation of this algorithm, along with comments including a correctness proof, <strong><a href="http://keithschwarz.com/interesting/code/?dir=majority-element" rel="noreferrer">available here</a></strong></p> <p>The intuition behind the algorithm is actually quite beautiful. Suppose that you were to have a roomful of people each holding one element of the array. Whenever two people find each other where neither is holding the same array element as the other, the two of them sit down. Eventually, at the very end, if anyone is left standing, there's a chance that they're in the majority, and you can just check that element. As long as one element occurs with frequency at least N/2, you can guarantee that this approach will always find the majority element.</p> <p>To actually implement the algorithm, you make a linear scan over the array and keep track of your current guess as to what the majority element is, along with the number of times that you've seen it so far. Initially, this guess is undefined and the number of repeats is zero. As you walk across the array, if the current element matches your guess, you increment the counter. If the current element doesn't match your guess, you decrement the counter. If the counter ever hits zero, then you reset it to the next element you encounter. You can think about this implementation as a concrete realization of the above "standing around in a room" algorithm. Whenever two people meet with different elements, they cancel out (dropping the counter). Whenever two people have the same element, then they don't interact with each other.</p> <p>For a full correctness proof, citation to the original paper (by Boyer and Moore of the more famous Boyer-Moore string matching algorithm), and an implementation in C++, check out the above link.</p>
7,070,011
Writing large number of records (bulk insert) to Access in .NET/C#
<p>What is the best way to perform bulk inserts into an MS Access database from .NET? Using ADO.NET, it is taking way over an hour to write out a large dataset.</p> <p><em>Note that my original post, before I "refactored" it, had both the question and answer in the question part. I took Igor Turman's suggestion and re-wrote it in two parts - the question above and followed by my answer.</em></p>
7,080,644
8
6
null
2011-08-15 19:55:31.633 UTC
27
2018-12-21 08:37:51.203 UTC
2011-08-16 15:22:21.067 UTC
null
1,955,013
null
1,955,013
null
1
55
c#|ms-access|dao|bulkinsert
54,254
<p>I found that using DAO in a specific manner is roughly 30 times faster than using ADO.NET. I am sharing the code and results in this answer. As background, in the below, the test is to write out 100 000 records of a table with 20 columns.</p> <p>A summary of the technique and times - from best to worse:</p> <ol> <li><strong>02.8 seconds:</strong> Use DAO, use <code>DAO.Field</code>'s to refer to the table columns </li> <li><strong>02.8 seconds:</strong> Write out to a text file, use Automation to import the text into Access</li> <li><strong>11.0 seconds:</strong> Use DAO, use the column index to refer to the table columns.</li> <li><strong>17.0 seconds:</strong> Use DAO, refer to the column by name</li> <li><strong>79.0 seconds:</strong> Use ADO.NET, generate INSERT statements for each row</li> <li><strong>86.0 seconds:</strong> Use ADO.NET, use DataTable to an DataAdapter for "batch" insert</li> </ol> <p>As background, occasionally I need to perform analysis of reasonably large amounts of data, and I find that Access is the best platform. The analysis involves many queries, and often a lot of VBA code.</p> <p>For various reasons, I wanted to use C# instead of VBA. The typical way is to use OleDB to connect to Access. I used an <code>OleDbDataReader</code> to grab millions of records, and it worked quite well. But when outputting results to a table, it took a long, long time. Over an hour.</p> <p>First, let's discuss the two typical ways to write records to Access from C#. Both ways involve OleDB and ADO.NET. The first is to generate INSERT statements one at time, and execute them, taking 79 seconds for the 100 000 records. The code is:</p> <pre><code>public static double TestADONET_Insert_TransferToAccess() { StringBuilder names = new StringBuilder(); for (int k = 0; k &lt; 20; k++) { string fieldName = "Field" + (k + 1).ToString(); if (k &gt; 0) { names.Append(","); } names.Append(fieldName); } DateTime start = DateTime.Now; using (OleDbConnection conn = new OleDbConnection(Properties.Settings.Default.AccessDB)) { conn.Open(); OleDbCommand cmd = new OleDbCommand(); cmd.Connection = conn; cmd.CommandText = "DELETE FROM TEMP"; int numRowsDeleted = cmd.ExecuteNonQuery(); Console.WriteLine("Deleted {0} rows from TEMP", numRowsDeleted); for (int i = 0; i &lt; 100000; i++) { StringBuilder insertSQL = new StringBuilder("INSERT INTO TEMP (") .Append(names) .Append(") VALUES ("); for (int k = 0; k &lt; 19; k++) { insertSQL.Append(i + k).Append(","); } insertSQL.Append(i + 19).Append(")"); cmd.CommandText = insertSQL.ToString(); cmd.ExecuteNonQuery(); } cmd.Dispose(); } double elapsedTimeInSeconds = DateTime.Now.Subtract(start).TotalSeconds; Console.WriteLine("Append took {0} seconds", elapsedTimeInSeconds); return elapsedTimeInSeconds; } </code></pre> <p>Note that I found no method in Access that allows a bulk insert.</p> <p>I had then thought that maybe using a data table with a data adapter would be prove useful. Especially since I thought that I could do batch inserts using the <code>UpdateBatchSize</code> property of a data adapter. However, apparently only SQL Server and Oracle support that, and Access does not. And it took the longest time of 86 seconds. The code I used was:</p> <pre><code>public static double TestADONET_DataTable_TransferToAccess() { StringBuilder names = new StringBuilder(); StringBuilder values = new StringBuilder(); DataTable dt = new DataTable("TEMP"); for (int k = 0; k &lt; 20; k++) { string fieldName = "Field" + (k + 1).ToString(); dt.Columns.Add(fieldName, typeof(int)); if (k &gt; 0) { names.Append(","); values.Append(","); } names.Append(fieldName); values.Append("@" + fieldName); } DateTime start = DateTime.Now; OleDbConnection conn = new OleDbConnection(Properties.Settings.Default.AccessDB); conn.Open(); OleDbCommand cmd = new OleDbCommand(); cmd.Connection = conn; cmd.CommandText = "DELETE FROM TEMP"; int numRowsDeleted = cmd.ExecuteNonQuery(); Console.WriteLine("Deleted {0} rows from TEMP", numRowsDeleted); OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM TEMP", conn); da.InsertCommand = new OleDbCommand("INSERT INTO TEMP (" + names.ToString() + ") VALUES (" + values.ToString() + ")"); for (int k = 0; k &lt; 20; k++) { string fieldName = "Field" + (k + 1).ToString(); da.InsertCommand.Parameters.Add("@" + fieldName, OleDbType.Integer, 4, fieldName); } da.InsertCommand.UpdatedRowSource = UpdateRowSource.None; da.InsertCommand.Connection = conn; //da.UpdateBatchSize = 0; for (int i = 0; i &lt; 100000; i++) { DataRow dr = dt.NewRow(); for (int k = 0; k &lt; 20; k++) { dr["Field" + (k + 1).ToString()] = i + k; } dt.Rows.Add(dr); } da.Update(dt); conn.Close(); double elapsedTimeInSeconds = DateTime.Now.Subtract(start).TotalSeconds; Console.WriteLine("Append took {0} seconds", elapsedTimeInSeconds); return elapsedTimeInSeconds; } </code></pre> <p>Then I tried non-standard ways. First, I wrote out to a text file, and then used Automation to import that in. This was fast - 2.8 seconds - and tied for first place. But I consider this fragile for a number of reasons: Outputing date fields is tricky. I had to format them specially (<code>someDate.ToString("yyyy-MM-dd HH:mm")</code>), and then set up a special "import specification" that codes in this format. The import specification also had to have the "quote" delimiter set right. In the example below, with only integer fields, there was no need for an import specification.</p> <p>Text files are also fragile for "internationalization" where there is a use of comma's for decimal separators, different date formats, possible the use of unicode.</p> <p>Notice that the first record contains the field names so that the column order isn't dependent on the table, and that we used Automation to do the actual import of the text file.</p> <pre><code>public static double TestTextTransferToAccess() { StringBuilder names = new StringBuilder(); for (int k = 0; k &lt; 20; k++) { string fieldName = "Field" + (k + 1).ToString(); if (k &gt; 0) { names.Append(","); } names.Append(fieldName); } DateTime start = DateTime.Now; StreamWriter sw = new StreamWriter(Properties.Settings.Default.TEMPPathLocation); sw.WriteLine(names); for (int i = 0; i &lt; 100000; i++) { for (int k = 0; k &lt; 19; k++) { sw.Write(i + k); sw.Write(","); } sw.WriteLine(i + 19); } sw.Close(); ACCESS.Application accApplication = new ACCESS.Application(); string databaseName = Properties.Settings.Default.AccessDB .Split(new char[] { ';' }).First(s =&gt; s.StartsWith("Data Source=")).Substring(12); accApplication.OpenCurrentDatabase(databaseName, false, ""); accApplication.DoCmd.RunSQL("DELETE FROM TEMP"); accApplication.DoCmd.TransferText(TransferType: ACCESS.AcTextTransferType.acImportDelim, TableName: "TEMP", FileName: Properties.Settings.Default.TEMPPathLocation, HasFieldNames: true); accApplication.CloseCurrentDatabase(); accApplication.Quit(); accApplication = null; double elapsedTimeInSeconds = DateTime.Now.Subtract(start).TotalSeconds; Console.WriteLine("Append took {0} seconds", elapsedTimeInSeconds); return elapsedTimeInSeconds; } </code></pre> <p>Finally, I tried DAO. Lots of sites out there give huge warnings about using DAO. However, it turns out that it is simply the best way to interact between Access and .NET, especially when you need to write out large number of records. Also, it gives access to all the properties of a table. I read somewhere that it's easiest to program transactions using DAO instead of ADO.NET. </p> <p>Notice that there are several lines of code that are commented. They will be explained soon.</p> <pre><code>public static double TestDAOTransferToAccess() { string databaseName = Properties.Settings.Default.AccessDB .Split(new char[] { ';' }).First(s =&gt; s.StartsWith("Data Source=")).Substring(12); DateTime start = DateTime.Now; DAO.DBEngine dbEngine = new DAO.DBEngine(); DAO.Database db = dbEngine.OpenDatabase(databaseName); db.Execute("DELETE FROM TEMP"); DAO.Recordset rs = db.OpenRecordset("TEMP"); DAO.Field[] myFields = new DAO.Field[20]; for (int k = 0; k &lt; 20; k++) myFields[k] = rs.Fields["Field" + (k + 1).ToString()]; //dbEngine.BeginTrans(); for (int i = 0; i &lt; 100000; i++) { rs.AddNew(); for (int k = 0; k &lt; 20; k++) { //rs.Fields[k].Value = i + k; myFields[k].Value = i + k; //rs.Fields["Field" + (k + 1).ToString()].Value = i + k; } rs.Update(); //if (0 == i % 5000) //{ //dbEngine.CommitTrans(); //dbEngine.BeginTrans(); //} } //dbEngine.CommitTrans(); rs.Close(); db.Close(); double elapsedTimeInSeconds = DateTime.Now.Subtract(start).TotalSeconds; Console.WriteLine("Append took {0} seconds", elapsedTimeInSeconds); return elapsedTimeInSeconds; } </code></pre> <p>In this code, we created DAO.Field variables for each column (<code>myFields[k]</code>) and then used them. It took 2.8 seconds. Alternatively, one could directly access those fields as found in the commented line <code>rs.Fields["Field" + (k + 1).ToString()].Value = i + k;</code> which increased the time to 17 seconds. Wrapping the code in a transaction (see the commented lines) dropped that to 14 seconds. Using an integer index <code>rs.Fields[k].Value = i + k;</code> droppped that to 11 seconds. Using the DAO.Field (<code>myFields[k]</code>) and a transaction actually took longer, increasing the time to 3.1 seconds.</p> <p>Lastly, for completeness, all of this code was in a simple static class, and the <code>using</code> statements are:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using ACCESS = Microsoft.Office.Interop.Access; // USED ONLY FOR THE TEXT FILE METHOD using DAO = Microsoft.Office.Interop.Access.Dao; // USED ONLY FOR THE DAO METHOD using System.Data; // USED ONLY FOR THE ADO.NET/DataTable METHOD using System.Data.OleDb; // USED FOR BOTH ADO.NET METHODS using System.IO; // USED ONLY FOR THE TEXT FILE METHOD </code></pre>
7,344,978
Verifying path equality with .Net
<p>What is the best way to compare two paths in .Net to figure out if they point to the same file or directory?</p> <ol> <li><p>How would one verify that these are the same:</p> <pre><code>c:\Some Dir\SOME FILE.XXX C:\\\SOME DIR\some file.xxx </code></pre></li> <li><p>Even better: is there a way to verify that these paths point to the same file on some network drive:</p> <pre><code>h:\Some File.xxx \\Some Host\Some Share\Some File.xxx </code></pre></li> </ol> <p><strong>UPDATE:</strong></p> <p>Kent Boogaart has answered my first question correctly; but I`m still curious to see if there is a solution to my second question about comparing paths of files and directories on a network drive.</p> <p><strong>UPDATE 2 (combined answers for my two questions):</strong></p> <p><strong>Question 1:</strong> local and/or network files and directories</p> <pre><code>c:\Some Dir\SOME FILE.XXX C:\\\SOME DIR\some file.xxx </code></pre> <p><strong>Answer:</strong> use <code>System.IO.Path.GetFullPath</code> as exemplified with:</p> <pre><code>var path1 = Path.GetFullPath(@"c:\Some Dir\SOME FILE.XXX"); var path2 = Path.GetFullPath(@"C:\\\SOME DIR\subdir\..\some file.xxx"); // outputs true Console.WriteLine("{0} == {1} ? {2}", path1, path2, string.Equals(path1, path2, StringComparison.OrdinalIgnoreCase)); </code></pre> <p><strong>Question 2:</strong> local and/or network files and directories</p> <p><strong>Answer:</strong> Use the GetPath method as posted on <a href="http://briancaos.wordpress.com/2009/03/05/get-local-path-from-unc-path/" rel="noreferrer">http://briancaos.wordpress.com/2009/03/05/get-local-path-from-unc-path/</a></p>
7,345,023
9
4
null
2011-09-08 08:07:48.147 UTC
4
2021-04-09 02:05:28.21 UTC
2011-09-12 10:43:17.843 UTC
user610650
null
user610650
null
null
1
46
c#|.net|path
24,393
<pre><code>var path1 = Path.GetFullPath(@"c:\Some Dir\SOME FILE.XXX"); var path2 = Path.GetFullPath(@"C:\\\SOME DIR\subdir\..\some file.xxx"); // outputs true Console.WriteLine("{0} == {1} ? {2}", path1, path2, string.Equals(path1, path2, StringComparison.OrdinalIgnoreCase)); </code></pre> <p>Ignoring case is only a good idea on Windows. You can use <code>FileInfo.FullName</code> in a similar fashion, but <code>Path</code> will work with both files and directories.</p> <p>Not sure about your second example.</p>
14,210,454
How to set two custom actionbar button in left and right in android?
<p>I am Using Sherlock library and i also implement with myself. My problem is that i added two items in menu, now i want 1 item in left of actionbar and second in right of actionbar. How to to it?</p>
14,211,619
2
2
null
2013-01-08 07:51:41.36 UTC
10
2018-05-28 21:04:02.343 UTC
null
null
null
null
1,531,657
null
1
15
android
35,357
<p>You can create such action bar, but it's little more complicated than inflating a menu. Menu created in <code>onCreateOptionsMenu()</code> method will be always aligned to right, placed in split action bar or hidden under the menu key. </p> <p>If you want your action bar to contain just two menu items - one on the left edge and the other on the right edge - you have to create custom view in the action bar.</p> <p>The custom view layout will be something like this:</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"&gt; &lt;ImageButton android:src="@drawable/ic_menu_item1" android:background="?attr/actionBarItemBackground" android:layout_width="?attr/actionBarSize" android:layout_height="match_parent" android:scaleType="centerInside" android:id="@+id/item1" android:layout_alignParentLeft="true" android:layout_alignParentTop="true"/&gt; &lt;ImageButton android:src="@drawable/ic_menu_item2" android:background="?attr/actionBarItemBackground" android:layout_width="?attr/actionBarSize" android:layout_height="match_parent" android:scaleType="centerInside" android:id="@+id/item2" android:layout_alignParentRight="true" android:layout_alignParentTop="true"/&gt; &lt;/RelativeLayout&gt; </code></pre> <p>Define in the theme that you want to use custom view. The theme should contain:</p> <pre class="lang-xml prettyprint-override"><code>&lt;style name="MyTheme" parent="@style/Theme.Sherlock"&gt; &lt;item name="actionBarStyle"&gt;@style/MyActionBarStyle&lt;/item&gt; &lt;item name="android:actionBarStyle"&gt;@style/MyActionBarStyle&lt;/item&gt; &lt;/style&gt; &lt;style name="MyActionBarStyle" parent="@style/Widget.Sherlock.ActionBar"&gt; &lt;item name="displayOptions"&gt;showCustom&lt;/item&gt; &lt;item name="android:displayOptions"&gt;showCustom&lt;/item&gt; &lt;/style&gt; </code></pre> <p>Set the custom view in the activity (or fragment):</p> <pre class="lang-java prettyprint-override"><code>@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActionBar ab = getSherlock().getActionBar(); LayoutInflater li = LayoutInflater.from(this); View customView = li.inflate(R.layout.my_custom_view, null); ab.setCustomView(customView); ImageButton ibItem1 = (ImageButton) customView.findViewById(R.id.item1); ibItem1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // ... } }); ImageButton ibItem2 = (ImageButton) customView.findViewById(R.id.item2); ibItem2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // ... } }); } </code></pre> <p>You have to add the click listeners for the menu items. You cannot use <code>onOptionsItemSelected()</code> in this case.</p>
14,075,465
Copy a file with a too long path to another directory in Python
<p>I am trying to copy files on Windows with Python 2.7, but sometimes this fails.</p> <pre><code>shutil.copyfile(copy_file, dest_file) </code></pre> <p>I get the following IOError:</p> <pre><code>[Errno 2] No such file or directory </code></pre> <p>But the file does exist! The problem is that the path of the file is too long. (> 255 characters)</p> <p>How do I copy these files? It isn't a problem to open them in other applications. </p> <p>To create a file with a too long path, create a file with an as long as possible file name and move the containing folder deeper down a tree structure.</p> <p>I've been trying some of these methods without success: <a href="http://timgolden.me.uk/python/win32_how_do_i/copy-a-file.html">http://timgolden.me.uk/python/win32_how_do_i/copy-a-file.html</a></p>
14,076,169
3
1
null
2012-12-28 20:35:59.057 UTC
9
2014-01-16 16:58:12.12 UTC
null
null
null
null
654,160
null
1
19
python|copy
20,205
<p>I wasn't sure about the 255 char limit so I stumbled on <a href="https://stackoverflow.com/questions/1857335/is-there-any-length-limits-of-file-path-in-ntfs#1857477">this post</a>. There I found a working answer: adding \\?\ before the path.</p> <pre><code>shutil.copyfile("\\\\?\\" + copy_file, dest_file) </code></pre> <p>edit: I've found that working with long paths causes issues on Windows. Another trick I use is to just shorten the paths:</p> <pre><code>import win32api path = win32api.GetShortPathName(path) </code></pre>
14,249,467
os.Mkdir and os.MkdirAll permissions
<p>I'm trying to create a log file at the start of my program.</p> <p>I need to check if a <code>/log</code> directory exists if it doesn't create the directory then move on to creating the log file.</p> <p>Well I tried to use <code>os.Mkdir</code> (as well as <code>os.MkdirAll</code>), but no matter what value I put into the second parameter I get a locked out folder with no permissions. What value should this be in order to get a read / write for user folder? I thought it would be <code>0x700</code> but it doesn't seem to work.</p> <p>Thanks!</p>
31,151,508
5
0
null
2013-01-10 01:33:50.06 UTC
37
2021-07-17 09:15:23.893 UTC
2021-07-17 09:15:23.893 UTC
user16442705
null
null
563,335
null
1
95
linux|go
80,809
<p>You can use octal notation directly:</p> <pre><code>os.Mkdir("dirname", 0700) </code></pre> <p><br> <strong>Permission Bits</strong></p> <pre><code>+-----+---+--------------------------+ | rwx | 7 | Read, write and execute | | rw- | 6 | Read, write | | r-x | 5 | Read, and execute | | r-- | 4 | Read, | | -wx | 3 | Write and execute | | -w- | 2 | Write | | --x | 1 | Execute | | --- | 0 | no permissions | +------------------------------------+ +------------+------+-------+ | Permission | Octal| Field | +------------+------+-------+ | rwx------ | 0700 | User | | ---rwx--- | 0070 | Group | | ------rwx | 0007 | Other | +------------+------+-------+ </code></pre> <p><a href="https://stackoverflow.com/a/35895436/395461">A Unix Permission Primer</a> <br> <br> <br> <strong>Common Permission Usages</strong></p> <p><strong>0755</strong> Commonly used on web servers. The owner can read, write, execute. Everyone else can read and execute but not modify the file.</p> <p><strong>0777</strong> Everyone can read write and execute. On a web server, it is not advisable to use ‘777’ permission for your files and folders, as it allows anyone to add malicious code to your server. </p> <p><strong>0644</strong> Only the owner can read and write. Everyone else can only read. No one can execute the file.</p> <p><strong>0655</strong> Only the owner can read and write, but not execute the file. Everyone else can read and execute, but cannot modify the file.</p> <p><a href="http://www.maketecheasier.com/file-permissions-what-does-chmod-777-means/" rel="noreferrer">www.maketecheasier.com/file-permissions-what-does-chmod-777-means/</a></p> <p><br> <strong>Directory Permissions on Linux</strong></p> <p>When applying permissions to directories on Linux, the permission bits have different meanings than on regular files. (<a href="https://unix.stackexchange.com/a/21252">source</a>)</p> <p><strong>Read bit</strong> The user can read the file names contained in the directory.<br> <strong>Write bit</strong> The user can {add,rename,delete} files names IF the execute bit is set too.<br> <strong>Execute bit</strong> The user can enter the directory and access the files inside.<br></p> <p><a href="https://unix.stackexchange.com/a/21252">https://unix.stackexchange.com/a/21252</a> <br> <br></p> <p><strong>Permissions Calculator</strong></p> <p><a href="http://permissions-calculator.org/" rel="noreferrer"><img src="https://i.stack.imgur.com/Qb9jq.png" alt="permissions calculator"></a></p> <p>A handy <a href="http://permissions-calculator.org/" rel="noreferrer">permissions calculator</a>.</p>
43,384,804
How to validate that at least one checkbox should be selected?
<p>I want to do validation for checkboxes here without form tag. <strong>At least one checkbox should be selected.</strong></p> <pre class="lang-xml prettyprint-override"><code>&lt;div *ngFor="let item of officeLIST"&gt; &lt;div *ngIf=" item.officeID == 1"&gt; &lt;input #off type="checkbox" id="off" name="off" value="1" [(ngModel)]="item.checked"&gt; &lt;label&gt;{{item.officename}}&lt;/label&gt; &lt;/div&gt; &lt;div *ngIf="item.officeID== 2"&gt; &lt;input #off type="checkbox" id="off" name="off" value="2" [(ngModel)]="item.checked"&gt; &lt;label&gt;{{item.officename}}&lt;/label&gt; &lt;/div&gt; &lt;div *ngIf="item.officeID== 3"&gt; &lt;input #off type="checkbox" id="off" name="off" value="3" [(ngModel)]="item.checked"&gt; &lt;label&gt;{{item.officename}}&lt;/label&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>for other field I will put required and do the error|touched|valid etc. but since checkbox is not single input, I cannot put required in every checkbox because all checkbox will be compulsory to checked. so how do I do the validation to alert user atleast one should be checked?</p>
43,386,577
7
2
null
2017-04-13 06:16:31.893 UTC
15
2021-10-21 17:37:56.77 UTC
2019-01-22 01:35:28.5 UTC
null
430,885
null
3,431,310
null
1
33
forms|angular|validation|typescript
61,760
<p>consider creating a <code>FormGroup</code> which contains your check-box group and bind the group's checked value to a hidden formcontrol with a required validator.</p> <p>Assume that you have three check boxes</p> <pre><code>items = [ {key: 'item1', text: 'value1'}, // checkbox1 (label: value1) {key: 'item2', text: 'value2'}, // checkbox2 (label: value2) {key: 'item3', text: 'value3'}, // checkbox3 (label: value3) ]; </code></pre> <p><strong>Step1: define <code>FormArray</code> for your check boxes</strong></p> <pre><code>let checkboxGroup = new FormArray(this.items.map(item =&gt; new FormGroup({ id: new FormControl(item.key), // id of checkbox(only use its value and won't show in html) text: new FormControl(item.text), // text of checkbox(show its value as checkbox's label) checkbox: new FormControl(false) // checkbox itself }))); </code></pre> <blockquote> <p>*easy to show via <em>ngFor</em></p> </blockquote> <p><strong>Step2: create a hidden required formControl to keep status of checkbox group</strong></p> <pre><code>let hiddenControl = new FormControl(this.mapItems(checkboxGroup.value), Validators.required); // update checkbox group's value to hidden formcontrol checkboxGroup.valueChanges.subscribe((v) =&gt; { hiddenControl.setValue(this.mapItems(v)); }); </code></pre> <blockquote> <p>we only care about hidden control's required validate status and won't show this hidden control in html.</p> </blockquote> <p><strong>Step3: create final form group contains below checkbox group and hidden formControl</strong></p> <pre><code>this.form = new FormGroup({ items: checkboxGroup, selectedItems: hiddenControl }); </code></pre> <p><strong>Html Template:</strong></p> <pre class="lang-xml prettyprint-override"><code>&lt;form [formGroup]="form"&gt; &lt;div [formArrayName]="'items'" [class.invalid]="!form.controls.selectedItems.valid"&gt; &lt;div *ngFor="let control of form.controls.items.controls; let i = index;" [formGroup]="control"&gt; &lt;input type="checkbox" formControlName="checkbox" id="{{ control.controls.id.value }}"&gt; &lt;label attr.for="{{ control.controls.id.value }}"&gt;{{ control.controls.text.value }}&lt;/label&gt; &lt;/div&gt; &lt;/div&gt; &lt;div [class.invalid]="!form.controls.selectedItems.valid" *ngIf="!form.controls.selectedItems.valid"&gt; checkbox group is required! &lt;/div&gt; &lt;hr&gt; &lt;pre&gt;{{form.controls.selectedItems.value | json}}&lt;/pre&gt; &lt;/form&gt; </code></pre> <p>refer this <a href="https://stackblitz.com/edit/angular-zrqy9i?file=src/app/app.component.ts" rel="nofollow noreferrer">demo</a>.</p>
9,353,414
Rounding Down to nearest whole number - am I cheating or is this more than adequate?
<p>Essentially, if the number generated is 2.3 then if I subtract .5 it will then be 1.8 but the rounding function will make it 2, which is what I want. Or if the answer is 2.99999 and I subtract .5, the answer is 2.49999 which should round down to 2 which is what I want. My question is if the answer is 2 even and I subtract .5, the answer is now 1.5, so will it still round up to 2. </p> <pre><code>temp1_1= Math.round(temp2_2/(360/temp_value)-.5); </code></pre> <p>this is my line of code for this.</p>
9,353,682
3
1
null
2012-02-19 21:28:35.963 UTC
3
2020-12-28 01:21:44.577 UTC
2020-12-28 01:21:44.577 UTC
null
1,783,163
null
1,108,852
null
1
15
java
70,233
<p>Even simpler and potential faster</p> <pre><code>double d = 2.99999999; long l = (long) d; // truncate to a whole number. </code></pre> <p>This will round towards 0. Math.floor() rounds towards negative infinity. Math.round(x - 0.5) also rounds towards negative infinity.</p>
9,226,323
Mocking a class vs. mocking its interface
<p>For a unit test, I need to mock several dependencies. One of the dependencies is a class which implements an interface:</p> <pre><code>public class DataAccessImpl implements DataAccess { ... } </code></pre> <p>I need to set up a mock object of this class which returns some specified values when provided with some specified parameters.</p> <p>Now, what I'm not sure of, is if it's better to mock the interface or the class, i.e.</p> <pre><code>DataAccess client = mock(DataAccess.class); </code></pre> <p>vs. </p> <pre><code>DataAccess client = mock(DataAccessImpl.class); </code></pre> <p>Does it make any difference in regard to testing? What would be the preferred approach?</p>
9,226,437
5
1
null
2012-02-10 10:30:56.723 UTC
11
2018-04-05 06:24:08.367 UTC
2014-05-26 11:22:05.053 UTC
null
145,287
null
1,178,669
null
1
53
java|unit-testing|junit|mocking
74,301
<p>It may not make much difference in your case but the preferred approach is to mock interface, as normally if you follow TDD (Test Driven Development) then you could write your unit tests even before you write your implementation classes. Thus even if you did not have concrete class <code>DataAccessImpl</code>, you could still write unit tests using your interface <code>DataAccess</code>.</p> <p>Moreover mocking frameworks have limitations in mocking classes, and some frameworks only mock interfaces by default.</p>
1,068,158
Put a button on top of a google map
<p>I would like to put a button on top of a Google Map next to the Map, Satelite and Hybrid buttons.</p> <p>I was wondering if its possible and how would be the best way to do it?</p> <p>So ideas I have are overlaying a image on top of the google map that is clickable but not sure if that will take all the events away from the google map.</p> <p>Do you have any ideas on how it could be done?</p>
1,068,388
5
0
null
2009-07-01 09:21:14.277 UTC
2
2017-07-12 15:18:03.683 UTC
2017-07-12 15:18:03.683 UTC
null
1,000,551
null
66,319
null
1
13
google-maps|button|overlay
49,977
<p>There is a pretty good description of how to do this <a href="http://code.google.com/apis/maps/documentation/controls.html#Custom_Controls" rel="nofollow noreferrer">here</a>.</p> <p>I am pretty sure you can style these guys to look like the standard buttons and you can definitely anchor it to the top right. When I get a chance I'll give it a try and update with my results.</p> <p>Update:</p> <p>I had a chance to try this out and it works ok:</p> <ul> <li><a href="http://www.cannonade.net/geo.php?test=geo10" rel="nofollow noreferrer">Map example with Google style buttons</a></li> <li><a href="http://www.cannonade.net/geo10.js" rel="nofollow noreferrer">Javascript Source</a></li> </ul> <p>Basically you end up doing very similar things implementing the buttons using GControl or just using absolute positioning of a DIV over the map (as <a href="https://stackoverflow.com/users/53487/chris-b">ChrisB</a> suggested). So I don't think there is a correct (or easier) approach, it's just a matter of personal preference. Good luck.</p>
639,886
Exporting from SQL Server to Excel with column headers?
<p>I have a query that has approximately 20 columns and I would like to export this to an Excel file with the column headers. </p> <p>I thought this would be easy to figure out but no luck! I searched the web and found one suggestion that did not end up working so I am stuck.</p>
640,619
5
2
null
2009-03-12 18:25:20.627 UTC
3
2022-07-21 17:15:25.937 UTC
2017-10-27 16:16:32.323 UTC
null
2,144,085
Mark K.
16,642
null
1
14
sql-server|excel|sql-server-2005|export
75,255
<p>I typically do this by simply click the upper left corner in the results grid, copy, and then paste into Excel. There is one catch, you need to go into options->query results-> SQL Server->results to grid (or text if you want to save to file for import into excel) and turn on include column headers when copying or saving the results. I find this works great.</p>
1,154,331
SQLAlchemy and django, is it production ready?
<p>Has anyone used <code>SQLAlchemy</code> in addition to <code>Django</code>'s ORM?</p> <p>I'd like to use Django's ORM for object manipulation and SQLalchemy for complex queries (like those that require left outer joins). </p> <p>Is it possible?</p> <p>Note: I'm aware about <code>django-sqlalchemy</code> but the project doesn't seem to be production ready. </p>
1,155,407
5
0
null
2009-07-20 15:44:44.8 UTC
12
2022-07-11 06:20:50.41 UTC
2013-09-05 20:09:57.45 UTC
null
1,628,832
null
80,869
null
1
24
python|database|django|sqlalchemy
12,706
<p>What I would do,</p> <ol> <li><p>Define the schema in Django orm, let it write the db via syncdb. You get the admin interface.</p></li> <li><p>In view1 you need a complex join</p></li> </ol> <pre> <code> def view1(request): import sqlalchemy data = sqlalchemy.complex_join_magic(...) ... payload = {'data': data, ...} return render_to_response('template', payload, ...) </code> </pre>
134,791
Why pool Stateless session beans?
<p>Stateless beans in Java do not keep their state between two calls from the client. So in a nutshell we might consider them as objects with business methods. Each method takes parameters and return results. When the method is invoked some local variables are being created in execution stack. When the method returns the locals are removed from the stack and if some temporary objects were allocated they are garbage collected anyway.</p> <p>From my perspective that doesn’t differ from calling method of the same single instance by separate threads. So why cannot a container use one instance of a bean instead of pooling a number of them?</p>
135,037
5
0
2008-09-25 17:43:30.05 UTC
2008-09-25 17:43:30.05 UTC
11
2018-03-30 13:23:20.697 UTC
null
null
null
null
3,980
null
1
28
java|ejb|pooling|stateless-session-bean
15,332
<p>Pooling does several things.</p> <p>One, by having one bean per instance, you're guaranteed to be threads safe (Servlets, for example, are not thread safe).</p> <p>Two, you reduce any potential startup time that a bean might have. While Session Beans are "stateless", they only need to be stateless with regards to the client. For example, in EJB, you can inject several server resources in to a Session Bean. That state is private to the bean, but there's no reason you can't keep it from invocation to invocation. So, by pooling beans you reduce these lookups to only happening when the bean is created.</p> <p>Three, you can use bean pool as a means to throttle traffic. If you only have 10 Beans in a pool, you're only going to get at most 10 requests working simultaneously, the rest will be queued up.</p>
157,603
Getting specific revision via http with VisualSVN Server
<p>I'm using VisualSVN Server to host an SVN repo, and for some automation work, I'd like to be able to get specific versions via the http[s] layer.</p> <p>I can get the HEAD version simply via an http[s] request to the server (httpd?) - but is there any ability to specify the revision, perhaps as a query-string? I can't seem to find it...</p> <p>I don't want to do a checkout unless I can help it, as there are a lot of files in the specific folder, and I don't want them all - just one or two.</p>
3,084,830
5
0
null
2008-10-01 13:29:00.29 UTC
12
2019-02-22 11:54:47.747 UTC
2012-07-19 12:48:33.887 UTC
null
761,095
Marc Gravell
23,354
null
1
33
svn|http|version-control|visualsvn|visualsvn-server
14,875
<p>Better late than never; <a href="https://entire/Path/To/Folder/file/?p=REV" rel="noreferrer">https://entire/Path/To/Folder/file/?p=REV</a></p> <p>?p=Rev specifies the revision</p>
30,914,964
How to update multiple tables with single query
<p>I have 2 tables that I need to update:</p> <p>Table A consists of: ID, personName, Date, status</p> <p>Table B consist of: PersonID, Date, status</p> <p>For every row in A there can be multiple rows in B with the same personID</p> <p>I need to "loop" over all results from A that the status=2 and update the date and status to 1.</p> <p>Also, for every row in A that status=2 I need to update all the rows in B that has the same personID (i.e, A.ID==B.PersonID) – I need to update date and status to 1 as well.</p> <p>So basically, if I was to do this programmatically (or algorithmically) its's something like that:</p> <pre><code>Foreach(var itemA in A) If (itemA.status = 2) itemA.status to 1 itemA.date = GetDate() foreach(var itemB in B) if(itemB.PersonID == itemA.ID &amp;&amp; itemB.status != 2 ) Change itemB.status to 1 Change itemB.date = GetDate() </code></pre> <p>i know how to update all the rows in B using the following sql statement:</p> <pre><code>UPDATE B SET status = 1, date = GETDATE() FROM B INNER JOIN A ON B.PersonID = A.ID </code></pre> <p>the problem is that i don't know how to also update table A since there can't be multiple tables in an update statement</p> <p>thanks for any help</p>
30,915,208
3
2
null
2015-06-18 12:08:36.817 UTC
2
2015-06-18 14:23:23.56 UTC
null
null
null
null
606,645
null
1
6
sql|sql-server
46,496
<p>Here is an example using the <code>output</code> clause:</p> <pre><code>declare @ids table (id int); update table1 set status = 1 output inserted.id into @ids where status = 2; update table2 set status = 1, date = getdate() where personid in (select id from @ids); </code></pre>
30,867,937
Redundant conformance error message Swift 2
<p>I updated my project to Swift 2, and received a bunch of <code>redundant conformance of XXX to protocol YYY</code>. This happens especially often (or always) when a class conforms to <code>CustomStringConvertible</code>. Also some place with <code>Equatable</code>.</p> <pre><code>class GraphFeatureNumbersetRange: GraphFeature, CustomStringConvertible { // &lt;--- get the error here ... } </code></pre> <p>I suspect that I don't need to explicitly conform to a protocol when I implement <code>var description: String { get }</code>, or whatever methods the protocol requires. Should I just follow fixit instructions and remove all these? Does Swift now automatically infer the conformance if a class implements all the protocol's methods?</p>
30,868,779
3
3
null
2015-06-16 12:43:49.027 UTC
2
2018-06-02 13:06:19.987 UTC
2015-06-16 13:40:59.407 UTC
null
1,187,415
null
1,572,953
null
1
52
xcode|swift
46,912
<p>You'll get that error message in Xcode 7 (Swift 2) if a subclass declares conformance to a protocol which is already inherited from a superclass. Example:</p> <pre><code>class MyClass : CustomStringConvertible { var description: String { return "MyClass" } } class Subclass : MyClass, CustomStringConvertible { override var description: String { return "Subclass" } } </code></pre> <p>The error log shows:</p> <pre> main.swift:10:27: error: redundant conformance of 'Subclass' to protocol 'CustomStringConvertible' class Subclass : MyClass, CustomStringConvertible { ^ main.swift:10:7: note: 'Subclass' inherits conformance to protocol 'CustomStringConvertible' from superclass here class Subclass : MyClass, CustomStringConvertible { ^ </pre> <p>Removing the protocol conformance from the subclass declaration solves the problem:</p> <pre><code>class Subclass : MyClass { override var description: String { return "Subclass" } } </code></pre> <p>But the superclass must declare the conformance explicitly, it is not automatically inferred from the existence of the <code>description</code> property.</p>
21,217,710
Factor Loadings using sklearn
<p>I want the correlations between individual variables and principal components in python. I am using PCA in sklearn. I don't understand how can I achieve the loading matrix after I have decomposed my data? My code is here.</p> <pre><code>iris = load_iris() data, y = iris.data, iris.target pca = PCA(n_components=2) transformed_data = pca.fit(data).transform(data) eigenValues = pca.explained_variance_ratio_ </code></pre> <p><a href="http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html">http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html</a> doesn't mention how this can be achieved.</p>
44,728,692
3
4
null
2014-01-19 14:03:00.593 UTC
12
2018-06-12 15:52:31.303 UTC
2014-01-20 07:10:38.997 UTC
null
1,286,398
null
1,286,398
null
1
29
python|scikit-learn|pca
32,692
<p>I think that @RickardSjogren is describing the eigenvectors, while @BigPanda is giving the loadings. There's a big difference: <a href="https://stats.stackexchange.com/questions/143905/loadings-vs-eigenvectors-in-pca-when-to-use-one-or-another">Loadings vs eigenvectors in PCA: when to use one or another?</a>.</p> <p>I created <a href="https://github.com/bsolomon1124/pyfinance/blob/cdc5b3b0c57feb93a1200745f05a75311c715a21/pyfinance/general.py#L555" rel="noreferrer">this PCA class</a> with a <code>loadings</code> method.</p> <p>Loadings, as given by <code>pca.components_ * np.sqrt(pca.explained_variance_)</code>, are more analogous to coefficients in a multiple linear regression. I don't use <code>.T</code> here because in the PCA class linked above, the components are already transposed. <code>numpy.linalg.svd</code> produces <code>u, s, and vt</code>, where <code>vt</code> is the Hermetian transpose, so you first need to back into <code>v</code> with <code>vt.T</code>.</p> <p>There is also one other important detail: the signs (positive/negative) on the components and loadings in <code>sklearn.PCA</code> may differ from packages such as R. More on that here:</p> <p><a href="https://stackoverflow.com/questions/44765682/in-sklearn-decomposition-pca-why-are-components-negative">In sklearn.decomposition.PCA, why are components_ negative?</a>.</p>
21,381,641
iOS, unrecognized selector sent to instance?
<p>I got a mainscreen with a imported custom actionBar. I created this actionBar in a separate .xib file, with a .m and .h file. </p> <p>I do some graphic setup in my actionBar.m's <code>viewDidLoad</code> like <code>backgroundColor</code> and some other stuff. </p> <p>I also got a button on this <code>actionBar</code> i linked the way i usually link buttons, with a <code>IBAction</code>.</p> <p>I load my actionBar into my mainscreen like this:</p> <pre><code>ActionBarWithLogoff *actionBar = [[ActionBarWithLogoff alloc] initWithNibName:@"ActionBarWithLogoff" bundle:nil]; [topBar addSubview:actionBar.view]; [actionBar release]; </code></pre> <p>My actionBar.h:</p> <pre><code>- (IBAction)ActionBarLogoff:(id)sender; </code></pre> <p>My actionBars.m's method:</p> <pre><code>-(void) ActionBarLogoff:(UIButton *)sender { NSLog(@"!!!!!!!!!!ActionBarLogoff"); } </code></pre> <p>This is were my error steels the picture, when i click the button i get the following error:</p> <blockquote> <p>2014-01-27 13:52:21.856 GB_Mobil_DK[2954:60b] -[__NSArrayM ActionBarLogoff:]: unrecognized selector sent to instance 0x1656d880 2014-01-27 13:52:21.858 GB_Mobil_DK[2954:60b] <strong>* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM ActionBarLogoff:]: unrecognized selector sent to instance 0x1656d880' *</strong> First throw call stack: (0x2f94be83 0x39ca86c7 0x2f94f7b7 0x2f94e0af 0x2f89cdc8 0x32104da3 0x32104d3f 0x32104d13 0x320f0743 0x3210475b 0x32104425 0x320ff451 0x320d4d79 0x320d3569 0x2f916f1f 0x2f9163e7 0x2f914bd7 0x2f87f471 0x2f87f253 0x345b92eb 0x32134845 0x97985 0x3a1a1ab7) libc++abi.dylib: terminating with uncaught exception of type NSException</p> </blockquote> <p>Anyone able to tell me why? and most importantly able to help me solve this problem^^?</p>
21,381,758
1
7
null
2014-01-27 13:02:54.857 UTC
null
2014-01-27 13:28:52.197 UTC
2014-01-27 13:28:52.197 UTC
null
1,497,737
null
2,408,952
null
1
6
ios|iphone|xib|ibaction
41,590
<p>You are releasing the <code>actionBar</code> instance and just retaining its <code>view</code>. If <code>actionBar</code> instance is responder to button action, then button click message is getting sent to deleted instance. You should retain the <code>actionBar</code> instance. One way to do this is making it an ivar or a <code>retain</code> property.</p> <p>Also looks like you are creating a <code>UIViewController</code> for a custom view. Instead you can create just a custom <code>UIView</code> with its XIB.</p> <p>EDIT</p> <p>Declare retain property,</p> <pre><code>@property (nonatomic, retain) ActionBarWithLogoff *actionBar; </code></pre> <p>OR</p> <p>Simply declare as ivar,</p> <pre><code>@interface YourViewController: UIViewController { ActionBarWithLogoff *actionBar; } </code></pre> <p>And in <code>dealloc</code> method,</p> <pre><code>-(void) dealloc { //... [actionBar release]; //... } </code></pre> <p>Hope that helps!</p>
18,215,899
Get type of generic parameter
<p>I wrote small function for better handling with types.</p> <pre><code>function evaluate(variable: any, type: string): any { switch (type) { case 'string': return String(variable); case 'number': return isNumber(variable) ? Number(variable) : -1; case 'boolean': { if (typeof variable === 'boolean') return variable; if (typeof variable === 'string') return (&lt;string&gt;variable).toLowerCase() === 'true'; if (typeof variable === 'number') return variable !== 0; return false; } default: return null; } } function isNumber(n: any): boolean { return !isNaN(parseFloat(n)) &amp;&amp; isFinite(n); } </code></pre> <p>I try same with generics, but don't know how to get type from generic parameter. It´s possible?</p>
18,216,538
2
3
null
2013-08-13 17:50:42.35 UTC
6
2020-07-06 06:15:12.543 UTC
null
null
null
null
2,438,165
null
1
21
generics|types|typescript
53,988
<p><code>typeof</code> is a JavaScript operator. It can be used at run time to get the types JavaScript knows about. Generics are a TypeScript concept that helps check the correctness of your code but doesn't exist in the compiled output. So the short answer is no, it's not possible.</p> <p>But you could do something like this:</p> <pre><code>class Holder&lt;T&gt; { value: T; constructor(value: T) { this.value = value; } typeof(): string { return typeof this.value; } } </code></pre> <p><a href="https://www.typescriptlang.org/play?#code/MYGwhgzhAEASD2IAmBTATgHgCoD5oG8AoaE6ANzBAFcUAuaLAbmNOHgDsIAXNK4L+GgAUFanQYBKAi1KkuACwCWEAHSia0ALzlKNZrIC+M6FwCeABxTwAZkIn1uaRewDm02bLQouVNOxMWVtYmSqrqKIwAkJHGRkaElOhcQuwoAO5wiKjCAESQSNY5EipmljZ2EoRAA" rel="nofollow noreferrer">Try it out</a>.</p> <p>This works because I'm operating on the value inside Holder, not on the Holder itself.</p>
17,838,221
JEE7: Do EJB and CDI beans support container-managed transactions?
<p>Java EE7 consists of a bunch of "bean" definitions:</p> <ul> <li>Managed Beans 1.0 (JSR-316 / JSR-250)</li> <li>Dependency Injection for Java 1.0 (JSR-330)</li> <li>CDI 1.1 (JSR-346)</li> <li>JSF Managed Beans 2.2 (JSR-344)</li> <li>EJB 3.2 (JSR-345)</li> </ul> <p>In order to get rid of the chaos in my mind, I studies several articles of "when to use which bean type". One of the pros for <strong>EJB</strong> seems to be that <strong>they alone support declarative container-managed transactions</strong> (the famous transaction annotations). I'm not sure, though, if this is correct. Can anyone approve this?</p> <p>Meanwhile, I came up with a simple demo application to check if this was actually true. I just defined a CDI bean (<strong><em>not</em></strong> an EJB - it has no class level annotations) as follows, based on <a href="https://stackoverflow.com/a/6259691/1399395">this</a> snippet:</p> <pre><code>public class CdiBean { @Resource TransactionSynchronizationRegistry tsr; @Transactional(Transactional.TxType.REQUIRED) public boolean isTransactional() { return tsr.getTransactionStatus() == Status.STATUS_ACTIVE; } } </code></pre> <p>Now, the outcome on GlassFish 4.0 is that this method actually returns true, which, according to my inquiries, is <strong><em>not working as expected</em></strong>. I did expect the container to ignore the @Transactional annotation on a CDI bean method, or to even throw an exception. I use a freshly-installed GlassFish 4 server, so there are no interferences.</p> <p>So my question is really:</p> <ul> <li>Which bean types do actually support container-managed transactions?</li> <li>Just for the sake of curiosity, how could I test it with a simple demo application if the code above is wrong?</li> </ul> <p>(BTW: Someone described a similar problem <a href="https://stackoverflow.com/questions/6908191/cdi-transactionattribute-for-bean">here</a>, but its solution does not apply to my case.</p>
17,842,796
2
1
null
2013-07-24 15:18:01.17 UTC
14
2016-02-25 21:10:16.783 UTC
2017-05-23 12:01:29.92 UTC
null
-1
null
1,399,395
null
1
20
java|jakarta-ee|ejb|cdi|jta
21,502
<p>Until Java EE 7 only EJB was transactional and the <code>@Transactional</code> annotation didn't exist.</p> <p>Since Java EE 7 and JTA 1.2 you can use transactional interceptor in CDI with <code>@Transactional</code> annotation.</p> <p>To answer your question about the best type of bean to use, the answer is CDI by default.</p> <p>CDI beans are lighter than EJB and support a lot of feature (including being an EJB) and is activated by default (when you add <code>beans.xml</code> file to your app). Since Java EE 6 <code>@Inject</code> supersede <code>@EJB</code>. Even if you use remote EJBs (feature not existing in CDI) the best practice suggest that you <code>@EJB</code> once to inject remote EJB and a CDI producer to expose it as a CDI bean</p> <pre><code>public class Resources { @EJB @Produces MyRemoteEJB ejb; } </code></pre> <p>The same is suggested for Java EE resources</p> <pre><code>public class Resources2 { @PersistenceContext @Produces EntityManager em; } </code></pre> <p>These producers will be used later</p> <pre><code>public class MyBean { @Inject MyRemoteEJB bean; @Inject EntityManager em; } </code></pre> <p>EJB continue to make sense for certain services they include like JMS or Asynchronous treatment, but you'll use them as CDI bean.</p>
2,006,763
What are the prerequisites to learning natural language processing?
<p>I am planning to learn natural language processing this year.</p> <p>But when I start reading introductory books on this topic, I found that I miss a lot of points relating mainly to mathematics.</p> <p>So I'm here searching for what I should learn before I can learn nlp, well, more smoothly?</p> <p>Thanks in advance.</p>
2,006,797
5
0
null
2010-01-05 14:54:15.77 UTC
24
2014-10-31 01:39:51.663 UTC
2010-01-05 14:58:24.783 UTC
null
164,901
null
225,262
null
1
25
nlp
16,187
<p>There are two main approaches to NLP right now - one is the language-based approach detailed by Jurafsky and Martin (<a href="https://rads.stackoverflow.com/amzn/click/com/0131873210" rel="noreferrer" rel="nofollow noreferrer">Speech and Language Processing</a>) and the other is a probability and statistics-based approach (<a href="https://rads.stackoverflow.com/amzn/click/com/0262133601" rel="noreferrer" rel="nofollow noreferrer">Foundations of Statistical Natural Language Processing</a>). </p> <p>Most people that I've talked to tend to prefer the latter as far as ease of ramping up and useful results. So I would recommend going over probability theory first and then tackling an NLP book (like the second one I linked to, which I am actually using on a project right now with pretty good results).</p> <p>While I agree with laura that formal language theory is highly useful, I actually think that currently if you just want to get into the actual NL parts of NLP, you can leave formal languages for later as there are enough tools that will do your lexical analysis / parsing / tokenizing / text transformations that you can use those rather than roll your own.</p> <p>Here is a book describing three such tools - I own it and recommend it as a good introduction to all three. <a href="https://rads.stackoverflow.com/amzn/click/com/0615204252" rel="noreferrer" rel="nofollow noreferrer">Building Search Applications: Lucene, LingPipe, and Gate</a></p> <p>Edit: in response to your question, I would say that the first step would be to get a thorough grounding in the basics of probability (the first 3-5 chapters of any undergrad prob/stats book should be fine), and then from there look up new topics as they come up in the NLP book. For instance, yesterday I had to learn about t-values or something (I'm bad with names) because they happened to be relevant to determining incidence of collocation.</p>
2,104,513
Minify HTML output from an ASP.Net MVC Application
<p>This is likely a duplicate of the below question but the only answer is a dead link:<br> <a href="https://stackoverflow.com/questions/255008/minify-html-output-of-asp-net-application">Minify Html output of ASP.NET Application</a></p> <p>When working with ASP.Net one of the more annoying aspects to me is the fact that Visual Studio puts spaces instead of tabs for white spacing which increases the size of the final HTML. I originally thought of simply changing Visual Studio settings to use tabs instead but then others on my team will still end up overlaying with spaces anyway.</p> <p>My question is two fold: first is there a way to on a per project setting to change if spaces or tabs are used (and is it even worthwhile if so) and second, is there a way to simply minify all of the views when generated?</p>
2,104,573
5
1
null
2010-01-20 20:01:44.593 UTC
11
2017-03-25 00:59:16.237 UTC
2017-05-23 12:02:48.59 UTC
null
-1
null
238,395
null
1
39
asp.net|asp.net-mvc|minify|asp.net-mvc-views
36,922
<p><a href="https://stackoverflow.com/questions/6992524/">Enabling GZIP</a> will have much more effect than minifying your HTML, anyway.</p> <p>Doing minification at runtime could hurt your servers (assuming you don't use caching). It may be a good idea to minfiy your Asp.Net markup during deployment. This way, you still have a non-minified version of code in your code repository, and a minified version on the server. Think of a deployment process where you invoke an HTML minifier (for instance, <a href="https://github.com/deanhume/html-minifier" rel="noreferrer">this tool by Dean Hume</a> looks promising) on all <code>.aspx</code> files.</p>
1,830,347
Quickest way to pass data to a popup window I created using window.open()?
<p>I have javascript code to open a popup window using the window.open() function. I'd like to pass data from the parent window to that popup window and I can't seem to find an elegant or simple solution anywhere on google or SO, but it seems like there should be support for this built into JS. What's the easiest way to pass data to the popup window?</p> <p>Thanks in advance for all your help!</p>
1,830,388
6
1
null
2009-12-02 02:43:09.383 UTC
8
2022-09-03 04:03:56.53 UTC
null
null
null
null
191,808
null
1
29
javascript
42,957
<p>Due to security restrictions it <em>is</em> super easy <em>only</em> if the parent window and the popup are from the same domain. If that is the case just use this:</p> <pre><code>// Store the return of the `open` command in a variable var newWindow = window.open('http://www.mydomain.com'); // Access it using its variable newWindow.my_special_setting = "Hello World"; </code></pre> <p>In the child (popup) window, you could access that variable like this:</p> <pre><code>window.my_special_setting </code></pre> <p>Was there something specific you wanted to do past that?</p>
1,466,000
Difference between modes a, a+, w, w+, and r+ in built-in open function?
<p>In the python built-in <a href="http://docs.python.org/library/functions.html#open" rel="noreferrer">open</a> function, what is the exact difference between the modes <code>w</code>, <code>a</code>, <code>w+</code>, <code>a+</code>, and <code>r+</code>?</p> <p>In particular, the documentation implies that all of these will allow writing to the file, and says that it opens the files for "appending", "writing", and "updating" specifically, but does not define what these terms mean.</p>
1,466,036
8
3
null
2009-09-23 13:27:36.45 UTC
418
2022-05-25 19:19:30.93 UTC
2020-05-20 05:47:17.2 UTC
null
6,862,601
null
63,051
null
1
784
python
595,827
<p>The opening modes are exactly the same as those for the C standard library function <strong><code>fopen()</code></strong>.</p> <p><a href="http://www.manpagez.com/man/3/fopen/" rel="noreferrer">The BSD <code>fopen</code> manpage</a> defines them as follows:</p> <pre class="lang-none prettyprint-override"><code> The argument mode points to a string beginning with one of the following sequences (Additional characters may follow these sequences.): ``r'' Open text file for reading. The stream is positioned at the beginning of the file. ``r+'' Open for reading and writing. The stream is positioned at the beginning of the file. ``w'' Truncate file to zero length or create text file for writing. The stream is positioned at the beginning of the file. ``w+'' Open for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file. ``a'' Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek(3) or similar. ``a+'' Open for reading and writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subse- quent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek(3) or similar. </code></pre>
1,371,351
Add files to an Xcode project from a script?
<p>Right now I'm using a few scripts to generate files that I'm including as resources in Xcode. The thing is I'm running the script, then deleting from the project, then adding back into the project. There must be a way to automate this last step, so that the script can generate the files and automatically add them into the xcode project for me.</p> <p>I'm using bash but any language examples would help.</p> <p>Thanks, Andrew</p>
1,371,595
8
1
null
2009-09-03 03:51:36.363 UTC
35
2021-03-19 10:00:09.483 UTC
2014-08-27 18:01:12.913 UTC
null
148,335
null
167,643
null
1
57
xcode|scripting|project
38,971
<p>This can be done by adding a new build phase to your application.</p> <ol> <li><p>In your Xcode project browser, find the target for your application, and expand it to show all of the build phases.</p></li> <li><p>Add a new <a href="http://developer.apple.com/mac/library/documentation/DeveloperTools/Conceptual/XcodeBuildSystem/200-Build_Phases/bs_build_phases.html#//apple_ref/doc/uid/TP40002690-SW1" rel="noreferrer">"run script" build phase</a> to your target. The easiest way is to right-click on the target and choose "Add/New Build Phase/New Run Script Build Phase"</p></li> <li><p>Adding the new build phase should bring up an inspector window. In this window, you can enter the entire shell script, or simply a command line to run the script.</p></li> <li><p>Here's the gold: At the bottom of the inspector window you can specify input files and output files. Specifying input files sets up dependencies automatically (the shell script will only be executed if some of the input files have been modified). Specifying output files automatically propagates the dependencies to those files. When your shell script is run, Xcode knows that it needs to deal with those files that the shell script has modified.</p></li> <li><p>Be sure to drag your new build phase up to the top of the list of phases as shown in the screenshot below. The order will be important if you need those resource files to be included in the bundle.</p></li> <li><p>Save, build, commit to the repository, ask for a raise, get some fresh air and have a nice day! :)</p></li> </ol>
2,190,625
What is the difference between framework and architecture?
<p>I would like to know the difference between framework and architecture.<br> for example: <code>dotnetnuke</code> is the framework and <code>mvc</code> is the architecture.</p> <p>so if we take both of this as a example, can anyone tell me difference between them?<br> Want to know which one is using when and where?<br> Which is good in terms of user requirement satisfaction?</p>
2,191,064
12
3
2010-02-03 08:37:22.643 UTC
2010-02-03 08:37:22.643 UTC
23
2018-12-02 01:08:30.733 UTC
2018-12-02 01:08:30.733 UTC
user3956566
null
null
200,349
null
1
34
.net|architecture|frameworks|dotnetnuke
35,952
<p>Let me illustrate the difference.</p> <p>Framework:</p> <p><img src="https://s3.amazonaws.com/finewoodworking.s3.tauntoncloud.com/app/uploads/2016/09/05213353/Woodworking_Tools.jpg" alt="Framework"></p> <p>Architecture:</p> <p><img src="https://i.imgur.com/kfZysaU.png" alt="Architecture"></p>
1,765,311
How to view files in binary from bash?
<p>I would like to view the contents of a file in the current directory, but in binary from the command line. How can I achieve this?</p>
20,305,782
13
0
null
2009-11-19 18:04:11.783 UTC
104
2021-05-10 23:34:30.243 UTC
2018-12-05 22:36:51.087 UTC
null
211,176
null
211,176
null
1
354
bash|shell|binary
514,488
<p><a href="https://linux.die.net/man/1/xxd" rel="noreferrer"><code>xxd</code></a> does both binary and hexadecimal.</p> <p>bin:</p> <pre><code>xxd -b file </code></pre> <p>hex:</p> <pre><code>xxd file </code></pre>
2,189,452
When to use margin vs padding in CSS
<p>When writing CSS, is there a particular rule or guideline that should be used in deciding when to use <code>margin</code> and when to use <code>padding</code>?</p>
9,183,818
16
1
null
2010-02-03 03:20:12.533 UTC
770
2022-09-12 15:03:15.967 UTC
2020-02-06 14:24:49.907 UTC
null
2,756,409
null
6,651
null
1
2,555
css|padding|margin
957,778
<p><strong>TL;DR:</strong> <em>By default I use margin everywhere, except when I have a border or background and want to increase the space inside that visible box.</em></p> <p>To me, the biggest difference between padding and margin is that vertical margins auto-collapse, and padding doesn't. </p> <p>Consider two elements one above the other each with padding of <code>1em</code>. This padding is considered to be part of the element and is always preserved. </p> <p>So you will end up with the content of the first element, followed by the padding of the first element, followed by the padding of the second, followed by the content of the second element. </p> <p>Thus the content of the two elements will end up being <code>2em</code> apart.</p> <p>Now replace that padding with 1em margin. Margins are considered to be outside of the element, and margins of adjacent items will overlap. </p> <p>So in this example, you will end up with the content of the first element followed by <code>1em</code> of combined margin followed by the content of the second element. So the content of the two elements is only <code>1em</code> apart. </p> <p>This can be really useful when you know that you want to say <code>1em</code> of spacing around an element, regardless of what element it is next to.</p> <p>The other two big differences are that padding is included in the click region and background color/image, but not the margin.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>div.box &gt; div { height: 50px; width: 50px; border: 1px solid black; text-align: center; } div.padding &gt; div { padding-top: 20px; } div.margin &gt; div { margin-top: 20px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;h3&gt;Default&lt;/h3&gt; &lt;div class="box"&gt; &lt;div&gt;A&lt;/div&gt; &lt;div&gt;B&lt;/div&gt; &lt;div&gt;C&lt;/div&gt; &lt;/div&gt; &lt;h3&gt;padding-top: 20px&lt;/h3&gt; &lt;div class="box padding"&gt; &lt;div&gt;A&lt;/div&gt; &lt;div&gt;B&lt;/div&gt; &lt;div&gt;C&lt;/div&gt; &lt;/div&gt; &lt;h3&gt;margin-top: 20px; &lt;/h3&gt; &lt;div class="box margin"&gt; &lt;div&gt;A&lt;/div&gt; &lt;div&gt;B&lt;/div&gt; &lt;div&gt;C&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
33,884,291
Pipes, dup2 and exec()
<p>I have to write a shell that can run pipes. For example commands like <code>ls -l | wc -l</code>". I have successfully parsed the command given by the user as below:</p> <blockquote> <p>"ls" = firstcmd</p> <p>"-l" = frsarg</p> <p>"wc" = scmd</p> <p>"-l" = secarg</p> </blockquote> <p>Now I have to use two forks since the commands are two and a pipe. The code block that I wrote to exec the command is the following:</p> <pre><code>pid_t pid; int fd[2]; pipe(fd); pid = fork(); if(pid==0) { dup2(fd[WRITE_END], STDOUT_FILENO); close(fd[READ_END]); execlp(firstcmd, firstcmd, frsarg, (char*) NULL); } else { pid=fork(); if(pid==0) { dup2(fd[READ_END], STDIN_FILENO); close(fd[WRITE_END]); execlp(scmd, scmd, secarg, (char*) NULL); } } </code></pre> <p>So when I run my shell and I enter the command <code>ls -l | wc -l</code> (for example) the result from the execs doesn't show up but the shell keeps running normally. </p> <p>The strange thing is that the result of the command shows only when I terminate my shell with "exit" or "^C".</p> <p>What is wrong with that output? Why doesn't it show up right after I enter the command?</p>
33,884,923
3
4
null
2015-11-24 02:16:56.247 UTC
9
2020-06-24 03:35:20.28 UTC
2017-05-19 15:05:56.873 UTC
null
15,168
null
2,964,459
null
1
12
c|linux|shell|exec|dup2
69,912
<p>You need to close all the pipe descriptors in both the parent process and the child process (after duplication in the child process). In your code the main issue is that, the <code>wc</code> process does not exit because there are still writers present (since the parent process has not closed the write end). Changes shown below. I have also added the <code>waitpid</code> in the parent process to wait for the <code>wc</code> process.</p> <pre><code>pid_t pid; int fd[2]; pipe(fd); pid = fork(); if(pid==0) { dup2(fd[WRITE_END], STDOUT_FILENO); close(fd[READ_END]); close(fd[WRITE_END]); execlp(firstcmd, firstcmd, frsarg, (char*) NULL); fprintf(stderr, "Failed to execute '%s'\n", firstcmd); exit(1); } else { pid=fork(); if(pid==0) { dup2(fd[READ_END], STDIN_FILENO); close(fd[WRITE_END]); close(fd[READ_END]); execlp(scmd, scmd, secarg,(char*) NULL); fprintf(stderr, "Failed to execute '%s'\n", scmd); exit(1); } else { int status; close(fd[READ_END]); close(fd[WRITE_END]); waitpid(pid, &amp;status, 0); } } </code></pre>
18,163,213
TypeError: abc.getAttribute is not a function
<p>For the following code:</p> <pre><code> &lt;span class="map-marker" data-lng="101.7113506794"&gt;&lt;/span&gt; &lt;span class="map-marker" data-lng="101.6311097146"&gt;&lt;/span&gt; var abc = $('.map-marker:first'); var xyz = abc.getAttribute("data-lat"); console.log(xyz); </code></pre> <p>I get the error message: <code>TypeError: abc.getAttribute is not a function</code>. What have I done wrong?</p>
18,163,229
7
2
null
2013-08-10 15:10:08.187 UTC
8
2019-09-17 09:02:11.69 UTC
2017-07-20 10:21:57.147 UTC
null
1,206,613
null
492,767
null
1
21
javascript|jquery
120,844
<p>Try this may be:</p> <pre><code>var abc = $(".map-marker:first")[0]; var xyz = abc.getAttribute("data-lat"); console.log(xyz); </code></pre> <p>Or this: </p> <pre><code>var abc = $(".map-marker:first"); var xyz = abc.data("lat"); console.log(xyz); </code></pre>
17,754,233
Crashlytics file not found
<p>Recently opened a project that I had compiled and submitted to Apple.</p> <p>I haven't touched it for a couple of months but I'm getting this odd compile error at:</p> <pre><code>#import &lt;Crashlytics/Crashlytics.h&gt; </code></pre> <p>The error reads:</p> <pre><code>'Crashlytics/Crashlytics.h' file not found </code></pre> <p>Clearly the framework can't be found but I'm puzzled as to why, when the project was working a few months ago, it's suddenly stopped. </p> <p>Any suggestions why?</p> <p>Xcode: 4.6.3 Mac OS X: 10.8.4</p>
18,506,633
13
5
null
2013-07-19 19:41:53.843 UTC
15
2022-05-24 03:51:23.08 UTC
2014-06-02 05:23:47.063 UTC
null
403,018
null
343,204
null
1
58
xcode|crashlytics
44,219
<p>Just add <code>$(SRCROOT)</code> to the <strong>Framework Search Paths</strong> in Project Build Settings (Search Paths).</p> <p>Crashlytics installation process drops its <code>Crashlytics.framework</code> to your project folder (or creates the symlink).</p> <p>If you moved Crashlytics.framework somewhere deeper in the project folder hierarchy - set 'recursive' to the right or just point directly to its parent folder in <code>Header Search Paths</code>:</p> <p><code>$(SRCROOT)/Path/to/the/folder/containing/Crashlytics.framework</code></p>
6,688,329
In Scala Akka futures, what is the difference between map and flatMap?
<p>in normal Scala map and flatMap are different in that flatMap will return a iterable of the data flattened out into a list. However in the Akka documentation, map and flatMap seem to do something different?</p> <p><a href="http://akka.io/docs/akka/1.1/scala/futures.html" rel="noreferrer">http://akka.io/docs/akka/1.1/scala/futures.html</a></p> <p>It says "Normally this works quite well as it means there is very little overhead to running a quick function. If there is a possibility of the function taking a non-trivial amount of time to process it might be better to have this done concurrently, and for that we use flatMap:"</p> <pre><code>val f1 = Future { "Hello" + "World" } val f2 = f1 flatMap {x =&gt; Future(x.length) } val result = f2.get() </code></pre> <p>Can someone please explain what is the difference between map and flatMap here in Akka futures?</p>
6,689,495
3
1
null
2011-07-14 04:00:07.293 UTC
16
2017-06-26 11:23:48.037 UTC
null
null
null
null
78,000
null
1
39
scala|akka
12,660
<p>In "normal" Scala (as you say), map and flatMap have nothing to do with Lists (check Option for example).</p> <p>Alexey gave you the correct answer. Now, if you want to know why we need both, it allows the nice <code>for</code> syntax when composing futures. Given something like:</p> <pre><code>val future3 = for( x &lt;- future1; y &lt;- future2 ) yield ( x + y ) </code></pre> <p>The compiler rewrites it as:</p> <pre><code>val future3 = future1.flatMap( x =&gt; future2.map( y =&gt; x+y ) ) </code></pre> <p>If you follow the method signature, you should see that the expression will return something of type <code>Future[A]</code>. </p> <p>Suppose now only map was used, the compiler could have done something like:</p> <pre><code>val future3 = future1.map( x =&gt; future2.map( y =&gt; x+y ) ) </code></pre> <p>However, the result whould have been of type <code>Future[Future[A]]</code>. That's why you need to flatten it. </p> <p>To learn about the concept behind, here is one the best introduction I've read:</p> <p><a href="http://www.codecommit.com/blog/ruby/monads-are-not-metaphors" rel="noreferrer">http://www.codecommit.com/blog/ruby/monads-are-not-metaphors</a></p>
6,814,620
Strange behavior using view-based NSOutline (Sourcelist)
<p>I have a (new in Lion) view-based NSOutlineView as Sidebar SourceList in my app using CoreData + NSTreeController + Bindings + NSOutlineView and an Object as NSOutlineViewDelegate.</p> <p>I use these delegate methods in the outlineview delegate:</p> <p><strong>- (BOOL)outlineView:(NSOutlineView *)outlineView isGroupItem:(id)item</strong> In my case a item is group when the (Core Data) parent relationship is nil.</p> <p><strong>- (NSView *)outlineView:(NSOutlineView *)outlineView viewForTableColumn:(NSTableColumn *)tableColumn item:(id)item</strong> To return the headercell view (group) or datacell view (icon + text).</p> <p>And I set the size style of the outline view (in Interface Builder in XCode) as "Sidebar System Default" so the cellview changes its size when the user change it in the system preferences.</p> <p>It works fine... but there are a few issues:</p> <p><img src="https://i.stack.imgur.com/poiWi.jpg" alt="enter image description here"></p> <ul> <li><p>The first cellview is a group cell (header cell) and when expand-collapse the textfield for this cellview moves up-down. Only happens with the first one.</p></li> <li><p>The textfield in the header cells changes it size (when changes the size in the system preferences) but I would like that the header cells size stay fixed like (Lion) Finder, Mail... does.</p></li> <li><p>The string value of the textfield in the header cells doesn´t appear uppercase.</p></li> <li><p>The images I use as icon in the image view of the data cells appears transparent (with a 0.5 alpha value or something like that).</p></li> </ul> <p>Any help? Thanks in advance</p> <p>SOLVED:</p> <ul> <li><p>For the movement when the first cellview expand/collapse use the method <strong>setFloatsGroupRows:NO</strong> with the outlineview (Thanks Anton!)</p></li> <li><p>If you want fixed size for the font of the groupcells (even if user change it in the system preferences) unbind in IB the header cell with its Table Cell View.</p></li> <li><p>Using a valueTransformer (that transform a string to uppercase) with the header cell the string will appear uppercase. Also you can do this with the nsoutlineview datasource method <strong>- outlineView:objectValueForTableColumn:byItem:</strong>...</p></li> <li><p>And finally the icon is semi-transparent because is not enabled. Uncheck "Conditionally Sets Enabled" in the Value or Value Path (depending the one you use) in the image cell bindings</p></li> </ul>
7,092,369
4
1
null
2011-07-25 10:17:27.62 UTC
16
2015-12-29 09:30:39.35 UTC
2011-08-18 07:20:49.4 UTC
null
449,424
null
449,424
null
1
18
cocoa|nsoutlineview
4,417
<p>Setting <strong>setFloatsGroupRows:NO</strong> for the outline view must solve the issue with first group item moving up-down when being expanded/collapsed.</p>
6,532,400
Linking files in g++
<p>Recently I have tried to compile a program in g++ (on Ubuntu). Usually i use Dev-C++ (on Windows) and it works fine there as long as I make a project and put all the necessary files in there. </p> <p>The error that occurs when compiling the program is:</p> <pre><code>$filename.cpp: undefined reference to '[Class]::[Class Member Function]' </code></pre> <p>The files used are as following:</p> <p><i>The source code (.cpp) file with the main function.</p> <p>The header file with the function prototypes.</p> <p>The .cpp file with the definitions for each function.</i></p> <p>Any help will be appreciated.</p>
6,532,492
4
2
null
2011-06-30 09:00:32.303 UTC
12
2019-05-04 07:54:15.997 UTC
null
null
null
null
784,079
null
1
24
c++|g++|compiler-errors|linker-errors
89,364
<p>You probably tried to either compile and link instead of just compiling source files or somehow forgot something.</p> <p>Variation one (everything in one line; recompiles everything all the time):</p> <pre><code>g++ -o myexecutable first.cpp second.cpp third.cpp [other dependencies, e.g. -Lboost, -LGL, -LSDL, etc.] </code></pre> <p>Variation two (step by step; if no <code>-o</code> is provided, gcc will reuse the input file name and just change the extension when not linking; this variation is best used for makefiles; allows you to skip unchanged parts):</p> <pre><code>g++ -c first.cpp g++ -c second.cpp g++ -c third.cpp g++ -o myexecutable first.o second.o third.o [other dependencies] </code></pre> <p>Variation three (some placeholders):</p> <p>Won't list it but the parameters mentioned above might as well take placeholders, e.g. <code>g++ -c *.cpp</code> will compile all cpp files in current directory to o(bject) files of the same name.</p> <p>Overall you shouldn't worry too much about it unless you really have to work without any IDE. If you're not that proficient with the command line syntax, stick to IDEs first.</p>
23,802,115
Is LIMIT clause in HIVE really random?
<p>The <a href="https://cwiki.apache.org/confluence/display/Hive/LanguageManual+Select" rel="noreferrer">documentation</a> of <code>HIVE</code> notes that <code>LIMIT</code> clause <code>returns rows chosen at random</code>. I have been running a <code>SELECT</code> table on a table with more than <code>800,000</code> records with <code>LIMIT 1</code>, but it always return me the same record. </p> <p>I'm using the <code>Shark</code> distribution, and I am wondering whether this has got anything to do with this not expected behavior? Any thoughts would be appreciated.</p> <p>Thanks, Visakh</p>
23,802,286
3
3
null
2014-05-22 08:55:44.15 UTC
4
2018-02-22 00:31:52.26 UTC
2014-05-22 11:37:48 UTC
null
354,577
null
295,338
null
1
15
sql|hive|hiveql|shark-sql
59,462
<p>Even though the documentation states it returns rows at random, it's not actually true. </p> <p>It returns "chosen rows at random" as it appears in the database without any where/order by clause. This means that it's not really random (or randomly chosen) as you would think, just that the order the rows are returned in can't be determined.</p> <p>As soon as you slap a <code>order by x DESC limit 5</code> on there, it returns the last 5 rows of whatever you're selecting from.</p> <p>To get rows returned at random, you would need to use something like: <code>order by rand() LIMIT 1</code></p> <p>However it can have a speed impact if your indexes aren't setup properly. Usually I do a min/max to get the ID's on the table, and then do a random number between them, then select those records (in your case, would be just 1 record), which tends to be faster than having the database do the work, especially on a large dataset</p>
15,714,342
Iterating through PostgreSQL records. How to reference data from next row?
<p>I'm new to PostgreSQL and writing functions here is tough as nails. So I'm hoping someone can help let me know how to do what I'm trying to do.</p> <p>I have a table of stock prices and dates. I want to calculate the percent change from the previous day for each entry. For the earliest day of data, there won't be a previous day, so that entry can simply be Nil. Can someone look over my function and help me with<br> a) how to reference data from the next row and<br> b) help me clean it up? </p> <p>I'm aware that the <code>WITH</code> statement is probably not supposed to be above the <code>IF</code> statement. However logically, this is how I've thought about it so far and thus how I've written it. If you could advise how that is supposed to look it would be much appreciated as well.</p> <pre><code>CREATE FUNCTION percentage_change_func(asset_histories) RETURNS numeric LANGUAGE sql IMMUTABLE AS $func$ DECLARE r asset_histories%rowtype BEGIN WITH twodaysdata AS (SELECT date,price,asset_symbol FROM asset_histories WHERE asset_symbol = $1.asset_symbol AND asset_histories.date &lt;= $1.date ORDER BY date DESC LIMIT 2), numberofrecords AS (SELECT count(*) FROM twodaysdata) IF numberofrecords = 2 THEN RETURN r.price / (r+1).price - 1 &lt;---How do I reference r + 1??/ ELSE RETURN NIL ENDIF END $func$ </code></pre> <p>PostgreSQL 9.2.</p>
15,716,499
2
0
null
2013-03-30 02:40:47.333 UTC
4
2013-03-30 08:29:23.437 UTC
2013-03-30 08:23:45.007 UTC
null
939,860
null
1,455,043
null
1
8
sql|postgresql|plpgsql|window-functions
43,494
<blockquote> <p>I want to calculate the percent change from the previous day for each entry.</p> </blockquote> <p>Generally you need to <strong>study the basics</strong>, before you start asking questions.<br> Read the excellent manual about <a href="http://www.postgresql.org/docs/current/interactive/sql-createfunction.html" rel="noreferrer"><strong><code>CREATE FUNCTION</code></strong></a>, <a href="http://www.postgresql.org/docs/current/interactive/plpgsql.html" rel="noreferrer"><strong>PL/pgSQL</strong></a> and <a href="http://www.postgresql.org/docs/current/interactive/xfunc-sql.html" rel="noreferrer"><strong>SQL functions</strong></a>.</p> <h3>Major points why the example is nonsense</h3> <ul> <li><p>First, you cannot hand in an <strong>identifier</strong> like you do. Identifiers cannot be parameterized in plain SQL. You'd need <a href="http://www.postgresql.org/docs/current/interactive/plpgsql-statements.html#PLPGSQL-STATEMENTS-EXECUTING-DYN" rel="noreferrer"><strong>dynamic SQL</strong></a> for that.<br> Of course, you don't actually need that, according to your requirements. There is only one table involved. It is nonsense to try and parameterize it.</p></li> <li><p>Don't use type names as identifiers. I use <code>_date</code> instead of <code>date</code> as parameter name and renamed your table column to <code>asset_date</code>. <code>ALTER</code> your table definition accordingly.</p></li> <li><p>A function fetching data from a table can never be <code>IMMUTABLE</code>. <a href="http://www.postgresql.org/docs/current/interactive/sql-createfunction.html" rel="noreferrer">Read the manual.</a></p></li> <li><p>You are mixing SQL syntax with plpgsql elements in nonsensical ways. <code>WITH</code> is part of a <code>SELECT</code> statement and cannot be mixed with plpgsql control structures like <code>LOOP</code> or <code>IF</code>.</p></li> </ul> <h3>Proper function</h3> <p>A proper function could look like this (one of many ways):</p> <pre><code>CREATE FUNCTION percentage_change_func(_asset_symbol text) RETURNS TABLE(asset_date date, price numeric, pct_change numeric) AS $func$ DECLARE last_price numeric; BEGIN FOR asset_date, price IN SELECT a.asset_date, a.price FROM asset_histories a WHERE a.asset_symbol = _asset_symbol ORDER BY a.asset_date -- traverse ascending LOOP pct_change := price / last_price; -- NULL if last_price is NULL RETURN NEXT; last_price := price; END LOOP; END $func$ LANGUAGE plpgsql STABLE </code></pre> <p>Performance shouldn't be so bad, but it's just pointless complication.</p> <h3>Proper solution: plain query</h3> <p>The simplest (and probably fastest) way would be with the window function <a href="http://www.postgresql.org/docs/current/interactive/functions-window.html" rel="noreferrer"><strong><code>lag()</code></strong></a>:</p> <pre><code>SELECT asset_date, price ,price / lag(price) OVER (ORDER BY asset_date) AS pct_change FROM asset_histories WHERE asset_symbol = _asset_symbol ORDER BY asset_date; </code></pre> <h3>Standard deviation</h3> <p>As per your later comment, you want to calculate statistical numbers like standard deviation.<br> There are dedicated <a href="http://www.postgresql.org/docs/current/interactive/functions-aggregate.html#FUNCTIONS-AGGREGATE-STATISTICS-TABLE" rel="noreferrer"><strong>aggregate functions for statistics</strong></a> in PostgreSQL.</p>
27,726,779
Declare Maven dependency as test runtime only
<p>What is the best way to declare a Maven dependency as only being used for the test runtime (but not test compilation) class path?</p> <p>Specifically, I want <code>slf4j-api</code> (a logging facade) as a typical, compile-scope dependency, but I want <code>slf4j-simple</code> (the barebones implementation suitable for unit tests) only on the test runtime class path (it's not needed for test compilation). I've been doing this:</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;org.slf4j&lt;/groupId&gt; &lt;artifactId&gt;slf4j-api&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.slf4j&lt;/groupId&gt; &lt;artifactId&gt;slf4j-simple&lt;/artifactId&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; </code></pre> <p>However, the downside of this is that <code>dependency:analyze</code> reports <code>slf4j-simple</code> as unused, presumably because it's not needed for compilation:</p> <pre><code>[WARNING] Unused declared dependencies found: [WARNING] org.slf4j:slf4j-simple:jar:1.7.7:test </code></pre> <p>I can't use a <code>runtime</code> dependency because I don't want that dependency transitively inherited (e.g. so downstream dependencies can use log4j, etc. instead). I tried <code>runtime</code> with <code>optional=true</code>, but that results in the same warning.</p> <p>(Note that I could also set <code>ignoreNonCompile</code> for the dependency plugin, but that seems like a very blunt instrument that would hide other potential problems.)</p>
27,729,783
4
4
null
2014-12-31 22:11:54.917 UTC
6
2021-06-17 06:16:04.48 UTC
null
null
null
null
123,336
null
1
33
java|maven|maven-3|maven-dependency-plugin
13,447
<p>There is no scope that does exactly what you want here; <code>test</code> is the best available option.</p> <p>A <code>test-runtime</code> scope has been requested before (<a href="https://mail-archives.apache.org/mod_mbox/maven-users/200811.mbox/%[email protected]%3E">Re: Need for a test-runtime scope?</a>) and the suggested workaround is exactly the <code>ignoreNonCompile</code> configuration you've already discovered.</p> <p><code>dependency:analyze</code> already has some limitations (<a href="http://maven.apache.org/shared/maven-dependency-analyzer/">"some cases are not detected (constants, annotations with source-only retention, links in javadoc)"</a>). You may have to accept that any <code>test</code>-scope dependencies that it warns against are false positives.</p> <p>(You <em>could</em> split the definition of your tests into a separate module, which would have no <code>slf4j</code> implementation dependencies, then run them in another module. I don't think that would be worth it.)</p>
5,459,708
Measuring the UITableView Scrolling Performance - iphone
<p>I am trying to measure the scrolling performance for my UITableView, between using subview and drawing the view myself. As we may know about scrolling performance, there are a couple of famous articles (<a href="http://blog.atebits.com/2008/12/fast-scrolling-in-tweetie-with-uitableview/" rel="noreferrer">Tweetie</a>, <a href="http://developer.apple.com/library/ios/#samplecode/TableViewSuite/Introduction/Intro.html" rel="noreferrer">TableViewSuite</a>, <a href="http://www.fieryrobot.com/blog/2008/10/01/glassy-scrolling-with-uitableview/" rel="noreferrer">Glassy</a> and <a href="http://www.fieryrobot.com/blog/2008/10/08/more-glassy-scrolling-with-uitableview/" rel="noreferrer">Glassy2</a> that help us with the technique and all will point to the same point: when we have lots of subviews, we should go with drawRect. </p> <p>The problem is that I do not know how to benchmark the performance in either case: using subview or drawing. And drawing is actually harder to do than subview, so it is hard to convince everybody to go with drawing directly. I am trying to write 2 small samples and using 2 techniques and benchmark the performance result. I am currently trying with this, but it generates the same results for both techniques:</p> <pre><code>NSDate *date = [NSDate date]; static NSString *CellIdentifier = @"CellIdentifier"; CustomDrawingTableViewCell *cell = (CustomDrawingTableViewCell *) [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[CustomDrawingTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } // Configure the cell... // Main Code is HERE NSDate *date2 = [NSDate date]; NSLog(@"%f", [date2 timeIntervalSinceDate:date]); return cell; </code></pre> <p>My Cell has around 4 images, 1 text</p>
5,459,796
2
1
null
2011-03-28 13:30:59.47 UTC
9
2012-10-10 15:10:09.283 UTC
2011-03-28 14:01:03.76 UTC
null
227,698
null
227,698
null
1
11
iphone|objective-c|performance|uitableview|scroll
3,949
<p>I'd suggest using Instruments rather than trying to run the test directly in your code. The Core Animation tool will track the actual number of frames per second (FPS) that your app’s displaying.</p>
5,578,535
Get Cell Value from Excel Sheet with Apache Poi
<p>How to get cell value with poi in java ?</p> <p>My code is look like this </p> <pre><code>String cellformula_total__percentage= "(1-E" + (rowIndex + 2) + "/" + "D" + (rowIndex + 2) + ")*100"; cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC); cell.setCellStyle(this.valueRightAlignStyleLightBlueBackground); cell.setCellFormula("abs(" + cellformula_total__percentage + ")"); </code></pre> <p>But if there is in this case how can i check that my cell value contain error value like #DIV/0! and how can i replace it with N/A</p>
5,578,666
2
0
null
2011-04-07 09:01:29.703 UTC
11
2011-09-20 15:26:17.28 UTC
2011-09-20 15:26:17.28 UTC
null
701,884
null
492,185
null
1
20
java|apache-poi
176,552
<p>You have to use the FormulaEvaluator, as shown <a href="http://poi.apache.org/spreadsheet/eval.html">here</a>. This will return a value that is either the value present in the cell or the result of the formula if the cell contains such a formula :</p> <pre><code>FileInputStream fis = new FileInputStream("/somepath/test.xls"); Workbook wb = new HSSFWorkbook(fis); //or new XSSFWorkbook("/somepath/test.xls") Sheet sheet = wb.getSheetAt(0); FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); // suppose your formula is in B3 CellReference cellReference = new CellReference("B3"); Row row = sheet.getRow(cellReference.getRow()); Cell cell = row.getCell(cellReference.getCol()); if (cell!=null) { switch (evaluator.evaluateFormulaCell(cell)) { case Cell.CELL_TYPE_BOOLEAN: System.out.println(cell.getBooleanCellValue()); break; case Cell.CELL_TYPE_NUMERIC: System.out.println(cell.getNumericCellValue()); break; case Cell.CELL_TYPE_STRING: System.out.println(cell.getStringCellValue()); break; case Cell.CELL_TYPE_BLANK: break; case Cell.CELL_TYPE_ERROR: System.out.println(cell.getErrorCellValue()); break; // CELL_TYPE_FORMULA will never occur case Cell.CELL_TYPE_FORMULA: break; } } </code></pre> <p>if you need the exact contant (ie the formla if the cell contains a formula), then this is shown <a href="http://poi.apache.org/spreadsheet/quick-guide.html#CellContents">here</a>.</p> <p><em><strong>Edit :</em></strong> Added a few example to help you.</p> <p>first you get the cell (just an example) </p> <pre><code>Row row = sheet.getRow(rowIndex+2); Cell cell = row.getCell(1); </code></pre> <p><strong>If you just want to set the value into the cell using the formula (without knowing the result) :</strong> </p> <pre><code> String formula ="ABS((1-E"+(rowIndex + 2)+"/D"+(rowIndex + 2)+")*100)"; cell.setCellFormula(formula); cell.setCellStyle(this.valueRightAlignStyleLightBlueBackground); </code></pre> <p><strong>if you want to change the message if there is an error in the cell, you have to change the formula to do so, something like</strong> </p> <pre><code>IF(ISERR(ABS((1-E3/D3)*100));"N/A"; ABS((1-E3/D3)*100)) </code></pre> <p>(this formula check if the evaluation return an error and then display the string "N/A", or the evaluation if this is not an error). </p> <p><strong>if you want to get the value corresponding to the formula, then you have to use the evaluator.</strong></p> <p>Hope this help,<br> Guillaume</p>
5,331,452
HTTP Accept Header meaning
<p>When a browser's Accept request header says something like the following:</p> <pre><code>Accept: application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5 </code></pre> <p>Does that mean that <code>application/xml</code>, <code>application/xhtml+xml</code>, and <code>text/html</code> all have a quality param of <code>0.9</code>?</p> <p>Or does it mean that <code>application/xml</code> and <code>application/xhtml+xml</code> have the default (<code>q=1</code>) and <code>text/html</code> has the <code>q=0.9</code> param?</p> <p>I'm assuming the former, but was hoping someone knew more definitively.</p>
5,331,486
2
0
null
2011-03-16 20:40:06.957 UTC
9
2015-08-18 01:15:02.143 UTC
2013-11-12 14:14:49.403 UTC
null
428,241
null
43,217
null
1
44
http|http-headers|mime-types|content-negotiation
46,512
<p>No, if the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1">quality parameter</a> is missing <code>q=1.0</code> is assumed:</p> <blockquote> <p>Each media-range MAY be followed by one or more accept-params, beginning with the "q" parameter for indicating a relative quality factor […] using the qvalue scale from 0 to 1 (section 3.9). The default value is q=1.</p> </blockquote> <p>So the given value is to be interpreted as: “<em>application/xml</em>, <em>application/xhtml+xml</em>, and <em>image/png</em> are the preferred media types, but if they don’t exist, then send the <em>text/html</em> entity (<code>text/html;q=0.9</code>), and if that doesn’t exist, then send the <em>text/plain</em> entity (<code>text/plain;q=0.8</code>), and if that doesn’t exist, send an entity with any other media type (<code>*/*;q=0.5</code>).”</p>
5,401,358
What's the difference between jaxws-ri and jaxws-rt?
<p>See the JAX-WS Maven repository from <em>java.net</em> - <a href="http://download.java.net/maven/2/com/sun/xml/ws/" rel="noreferrer">http://download.java.net/maven/2/com/sun/xml/ws/</a></p> <p>There are two similar folders - <strong>jaxws-rt</strong> and <strong>jaxws-ri</strong>. Currently, I'm using the <strong>jaxws-rt</strong> and it's working fine.</p> <p>Here are my questions:</p> <ol> <li>What's the difference between <strong><em>ri</em></strong> and <strong><em>rt</em></strong>?</li> <li>Does <strong><em>ri</em></strong> stand for <em>reference implementation</em> and <strong><em>rt</em></strong> stand for <em>runtime</em>?</li> </ol> <p>Please advice.<br> Thanks.</p>
15,149,814
2
0
null
2011-03-23 05:54:32.013 UTC
10
2019-04-06 14:18:10.803 UTC
2013-06-06 15:06:43.063 UTC
null
814,702
null
483,819
null
1
53
java|web-services|jax-ws
32,129
<p>As an answer to your <strong>second question</strong>: Yes, you are right.</p> <p>Below is the proof.</p> <hr> <p><strong>RI</strong> stands for <em>Reference Implementation</em>.</p> <p>Quote from the official <a href="http://jax-ws.java.net/" rel="noreferrer"><strong>JAX-WS project home page</strong></a> (an old site, see the UPDATE section below):</p> <blockquote> <p>Welcome to the JAX-WS <strong>Reference Implementation</strong> (<strong>RI</strong>) Project.</p> </blockquote> <p><br> Plus in the <a href="https://search.maven.org/artifact/com.sun.xml.ws/jaxws-ri/2.2.8-promoted-b146/pom" rel="noreferrer"><strong>POM file for the <em>jaxws-ri</em></strong></a> (version 2.2.8 at the time of writing) we can find the following: </p> <pre><code>&lt;name&gt;JAX-WS RI Standalone Zipped Bundle&lt;/name&gt; &lt;description&gt;Open source Reference Implementation of JSR-224: Java API for XML Web Services Distribution Bundle&lt;/description&gt; </code></pre> <hr> <p><strong>RT</strong> stands for <em>Runtime</em>.</p> <p>In the <a href="https://search.maven.org/artifact/com.sun.xml.ws/jaxws-rt/2.2.8-promoted-b146/pom" rel="noreferrer"><strong>POM file for the <em>jaxws-rt</em></strong></a> (version 2.2.8 at the time of writing) we can find the following: </p> <pre><code>&lt;name&gt;JAX-WS RI Runtime Bundle&lt;/name&gt; </code></pre> <p>(The word <em>Runtime</em> gives us a hint :-))</p> <hr> <h2>UPDATE (April 2019)</h2> <p>The were quite a few changes in the Java EE world recently. Java EE was moved to <em>Eclipse Enterprise for Java</em> (<strong>EE4J</strong>). Read <a href="https://www.eclipse.org/ee4j/faq.php" rel="noreferrer">EE4J FAQ</a> for more information.</p> <p>And JAX-WS project, which is now part of the EE4J, has also moved to another place:</p> <ul> <li>JAX-WS project's home page: <a href="https://javaee.github.io/metro-jax-ws/" rel="noreferrer">https://javaee.github.io/metro-jax-ws/</a></li> <li>JAX-WS project's code is hosted on GitHub: <a href="https://github.com/eclipse-ee4j/metro-jax-ws" rel="noreferrer">https://github.com/eclipse-ee4j/metro-jax-ws</a></li> </ul>
16,361,535
Webdriver findElements By xpath
<p>1)I am doing a tutorial to show how findElements By xpath works. I would like to know why it returns all the texts that following the <code>&lt;div&gt;</code> element with attribute <code>id=container</code>.</p> <p>code for xpath: <code>By.xpath("//div[@id='container']</code> </p> <p>2) how should I modify the code so it just return first or first few nodes that follow the parent note e.g. first node like 'Home', first few node like, Home, Manual Testing and Automation Testing.</p> <p>Thanks for your advise and help!</p> <p>Here is the code fragment for this tutorial:</p> <pre class="lang-java prettyprint-override"><code>import java.util.List; import org.junit.Test; import org.junit.Before; import org.junit.After; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class WD_findElements { @Test public void test_byxpath(){ WebDriver driver = new FirefoxDriver(); try{ driver.get("http://www.hexbytes.com"); List&lt;WebElement&gt; elements = driver.findElements(By.xpath("//div[@id='container']")); System.out.println("Test7 number of elements: " + elements.size()); for(WebElement ele : elements){ //ele.sendKeys("hexbyes"); System.out.println(ele.getText()); //System.out.println(ele.getAttribute("id")); //System.out.println(ele.getTagName()); } } finally { driver.close(); } }//end of test_byxpath public void xpathDemo2() { WebDriver driver = new FirefoxDriver(); try{ driver.get("http://www.hexbytes.com"); WebElement webelement = driver.findElement(By.id("container")); //matching single element with attribute value=container System.out.println("The id value is: " + webelement.getAttribute("id")); System.out.println("The tag name is: " + webelement.getTagName()); } finally { driver.close(); } }//end of xpathDemo2 public void xpathDemo3() { WebDriver driver = new FirefoxDriver(); try{ driver.get("http://www.hexbytes.com"); //find first child node of div element with attribute=container List&lt;WebElement&gt; elements = driver.findElements(By.xpath("//div[@id='container']/*[1]")); System.out.println("Test1 number of elements: " + elements.size()); for(WebElement ele : elements){ System.out.println(ele.getTagName()); System.out.println(ele.getAttribute("id")); System.out.println(""); System.out.println(""); } } finally { driver.close(); } }//end of xpathDemo3 } </code></pre>
16,362,800
3
0
null
2013-05-03 14:39:52.007 UTC
4
2015-09-16 13:15:07.54 UTC
2015-09-16 13:15:07.54 UTC
null
487,494
null
2,061,466
null
1
7
java|selenium|xpath|selenium-webdriver|webdriver
102,057
<p>Your questions:</p> <p><strong>Q 1.) I would like to know why it returns all the texts that following the div?</strong><br> It should not and I think in will not. It returns all div with 'id' attribute value equal 'containter' (and all children of this). But you are printing the results with <code>ele.getText()</code> Where getText will return all text content of all children of your result. </p> <p><em>Get the visible (i.e. not hidden by CSS) innerText of this element, including sub-elements, without any leading or trailing whitespace.<br> Returns:<br> The innerText of this element.</em></p> <p><strong>Q 2.) how should I modify the code so it just return first or first few nodes that follow the parent note</strong><br> This is not really clear what you are looking for. Example:</p> <pre><code>&lt;p1&gt; &lt;div/&gt; &lt;/p1 &lt;p2/&gt; </code></pre> <p>The following to parent of the div is p2. This would be:</p> <pre><code> //div[@id='container'][1]/parent::*/following-sibling::* </code></pre> <p>or shorter</p> <pre><code> //div[@id='container'][1]/../following-sibling::* </code></pre> <p>If you are only looking for the first one extent the expression with an "predicate" (e.g <code>[1]</code> - for the first one. or <code>[position() &amp;lt; 4]</code>for the first three) </p> <p>If your are looking for the first child of the first div:</p> <pre><code>//div[@id='container'][1]/*[1] </code></pre> <p>If there is only one div with id an you are looking for the first child:</p> <pre><code> //div[@id='container']/*[1] </code></pre> <p>and so on.</p>
16,493,280
Close Bootstrap Modal
<p>I have a bootstrap modal dialog box that I want to show initially, then when the user clicks on the page, it disappears. I have the following:</p> <pre><code>$(function () { $('#modal').modal(toggle) }); &lt;div class="modal" id='modal'&gt; &lt;div class="modal-header"&gt; &lt;button type="button" class="close" data-dismiss="modal" aria-hidden="true"&gt;×&lt;/button&gt; &lt;h3 id="myModalLabel"&gt;Error:&lt;/h3&gt; &lt;/div&gt; &lt;div class="modal-body"&gt; &lt;p&gt;Please correct the following errors:&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>The modal is displayed initially, but it does not close when clicked outside of the modal. Also, the content area is not greyed out.. How can I get the modal to display initially, then close after the user clicks outside the area? And how can I get the background to be grayed out as in the demo?</p>
16,493,402
30
2
null
2013-05-11 02:49:23.84 UTC
58
2022-07-08 17:29:40.5 UTC
2016-03-03 07:08:15.983 UTC
null
2,202,702
null
903,143
null
1
521
jquery|twitter-bootstrap|modal-dialog
1,465,297
<p>Put <code>modal('toggle')</code> instead of <code>modal(toggle)</code></p> <pre><code>$(function () { $('#modal').modal('toggle'); }); </code></pre>
319,594
Calculate a color fade
<p>Given two colors and <em>n</em> steps, how can one calculate n colors including the two given colors that create a fade effect? </p> <p>If possible pseudo-code is preferred but this will probably be implemented in Java.</p> <p>Thanks!</p>
319,604
7
0
null
2008-11-26 02:38:59.577 UTC
11
2015-07-13 05:38:56.26 UTC
null
null
null
Trentula
868
null
1
12
colors|fade
17,344
<p>Divide each colour into its RGB components and then calculate the individual steps required.</p> <pre><code>oldRed = 120; newRed = 200; steps = 10; redStepAmount = (newRed - oldRed) / steps; currentRed = oldRed; for (i = 0; i &lt; steps; i++) { currentRed += redStepAmount; } </code></pre> <p>Obviously extend that for green and blue.</p>
448,126
lambda functions in bash
<p>Is there a way to implement/use lambda functions in bash? I'm thinking of something like:</p> <pre><code>$ someCommand | xargs -L1 (lambda function) </code></pre>
448,166
7
0
null
2009-01-15 19:30:37.257 UTC
8
2020-10-11 22:04:40.74 UTC
2009-07-09 01:08:19.263 UTC
null
68,587
Daniel
38,967
null
1
30
bash|lambda
16,630
<p>I don't know of a way to do this, however you may be able to accomplish what you're trying to do using:</p> <pre><code>somecommand | while read -r; do echo "Something with $REPLY"; done </code></pre> <p>This will also be faster, as you won't be creating a new process for each line of text.</p> <p><strong>[EDIT 2009-07-09]</strong> I've made two changes:</p> <ol> <li>Incorporated litb's suggestion of using <code>-r</code> to disable backslash processing -- this means that backslashes in the input will be passed through unchanged.</li> <li>Instead of supplying a variable name (such as <code>X</code>) as a parameter to <code>read</code>, we let <code>read</code> assign to its default variable, <code>REPLY</code>. This has the pleasant side-effect of preserving leading and trailing spaces, which are stripped otherwise (even though internal spaces are preserved).</li> </ol> <p>From my observations, together these changes preserve everything except literal NUL (ASCII 0) characters on each input line.</p> <p><strong>[EDIT 26/7/2016]</strong></p> <p>According to commenter Evi1M4chine, setting <code>$IFS</code> to the empty string before running <code>read X</code> (e.g., with the command <code>IFS='' read X</code>) should also preserve spaces at the beginning and end when storing the result into <code>$X</code>, meaning you aren't forced to use <code>$REPLY</code>.</p>
1,089,504
OO Software Design Principles
<p>I am a huge fan of software design principles such as <strong>SOLID</strong> and <strong>DRY</strong>. What other principles exist for OO software design? </p> <p>Note. I’m not looking for answers like "comment your code" but instead looking for OO design principles like the ones discussed by <a href="http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod" rel="nofollow noreferrer">Uncle Bob</a>.</p>
1,089,551
8
7
2009-08-05 00:22:38.737 UTC
2009-07-06 22:29:10.173 UTC
14
2017-07-29 13:39:37.313 UTC
2009-07-06 22:35:55.713 UTC
null
101,361
null
113,535
null
1
4
oop|principles|design-principles
3,273
<p>A fairly comprehensive list from Wikipedia:</p> <p><a href="http://en.wikipedia.org/wiki/List_of_software_development_philosophies" rel="noreferrer">http://en.wikipedia.org/wiki/List_of_software_development_philosophies</a></p> <ul> <li>Agile software development</li> <li>Agile Unified Process (AUP) </li> <li>Behavior Driven Development (BDD) </li> <li>Big Design Up Front (BDUF) </li> <li>Brooks's law </li> <li>Cathedral and the Bazaar </li> <li>Code and fix </li> <li>Constructionist design methodology (CDM) </li> <li>Cowboy coding </li> <li>Crystal Clear </li> <li>Design-driven development (D3) </li> <li>Don't repeat yourself (DRY) or Once and Only Once (OAOO), Single Point of Truth (SPoT) </li> <li>Dynamic Systems Development Method (DSDM) </li> <li>Extreme Programming (XP) </li> <li>Feature Driven Development </li> <li>Hollywood Principle </li> <li>Iterative and incremental development </li> <li>Joint application design, aka JAD or "Joint Application Development" </li> <li>Kaizen </li> <li>Kanban </li> <li>KISS principle (Keep It Simple, Stupid) </li> <li>Lean software development </li> <li>Microsoft Solutions Framework (MSF) </li> <li>Model-driven architecture (MDA) </li> <li>Open source </li> <li>Open Unified Process </li> <li>Quick-and-dirty </li> <li>Rational Unified Process (RUP) </li> <li>Scrum </li> <li>Smart (agile development) </li> <li>Separation of concerns (SoC) </li> <li>Service-oriented modeling </li> <li>Software Craftsmanship </li> <li>Software System Safety </li> <li>Spiral model </li> <li>Test-driven development (TDD) </li> <li>Unified Process (UP) </li> <li>V-Model </li> <li>Waterfall model </li> <li>Wheel and spoke model </li> <li>Worse is better (New Jersey style, as contrasted with the MIT approach) </li> <li>Xtreme </li> <li>You Ain't Gonna Need It (YAGNI) </li> <li>Zero One Infinity </li> </ul>
667,147
Hacking and exploiting - How do you deal with any security holes you find?
<p>Today online security is a very important factor. Many businesses are completely based online, and there is tons of sensitive data available to check out only by using your web browser. </p> <p>Seeking knowledge to secure my own applications I've found that I'm often testing others applications for exploits and security holes, maybe just for curiosity. As my knowledge on this field has expanded by testing on own applications, reading zero day exploits and by reading the book <a href="http://eu.wiley.com/WileyCDA/WileyTitle/productCd-0470170778.html" rel="nofollow noreferrer">The Web Application Hacker's Handbook: Discovering and Exploiting Security Flaws</a>, I've come to realize that a majority of online web applications are really exposed to a lot of security holes. </p> <p>So what do you do? I'm in no interest of destroying or ruining anything, but my biggest "break through" on hacking I decided to alert the administrators of the page. My inquiry was promptly ignored, and the security hole has yet not been fixed. Why wouldn't they wanna fix it? How long will it be before someone with bad intentions break inn and choose to destroy everything?</p> <p>I wonder why there's not more focus on this these days, and I would think there would be plenty of business opportunities in actually offering to test web applications for security flaws. Is it just me who have a too big curiosity or is there anyone else out there who experience the same? It is punishable by law in Norway to actually try break into a web page, even if you just check the source code and find the "hidden password" there, use it for login, you're already breaking the law.</p>
673,377
8
3
null
2009-03-20 17:28:17.617 UTC
20
2014-08-17 21:04:44.747 UTC
2014-08-17 21:04:44.747 UTC
Wouter van Nifterick
2,246,344
ChrisAD
39,268
null
1
26
security|exploit
3,846
<p>"Ive found that Im often testing others applications for exploits and security holes, maybe just for curiosity". </p> <p>In the UK, we have the "Computer Misuse Act". Now if these applications you're proverbially "looking at" are say Internet based and the ISP's concerned can be bothered to investigate (for purely political motivations) then you're opening yourself up getting fingered. Even doing the slightest "testing" unlesss you are the BBC is sufficient to get you convicted here.</p> <p>Even Penetration Test houses require Sign Off from companies who wish to undertake formal work to provide security assurance on their systems. </p> <p>To set expectations on the difficulty in reporting vulnerabilties, I have had this with actual employers where some pretty serious stuff has been raised and people have sat on it for months from the likes of brand damage to even completely shutting down operations to support an annual £100m E-Com environment. </p>
295,628
SecureRandom: init once or every time it is needed?
<p>Our team is using a SecureRandom to generate a list of key pairs (the SecureRandom is passed to a KeyPairGenerator). We cannot agree on which of the following two options to use:</p> <ol> <li><p>Create a new instance every time we need to generate a key pair</p></li> <li><p>Initialize a static instance and use it for all key pairs</p></li> </ol> <p>Which approach is generally better and <em>why</em>?</p> <p>ADDED: My gut feeling is that the second option is more secure. But my only argument is a theoretical attack based on the assumption that the pseudorandomness is derived from the current timestamp: someone may see the creation time of the key pair, guess timestamps in the surrounding time interval, compute the possible pseudorandom sequences, and obtain the key material.</p> <p>ADDED: My assumption about determinism based on a timestamp was wrong. That's the difference between Random and SecureRandom. So, it looks like the answer is: in terms of security it doesn't really matter.</p>
295,652
8
0
null
2008-11-17 14:03:32.49 UTC
9
2021-10-15 17:06:46.333 UTC
2008-11-18 08:25:16.37 UTC
null
23,109
null
23,109
null
1
32
java|security|random|cryptography
14,935
<p>Unlike the <code>java.util.Random</code> class, the <code>java.security.SecureRandom</code> class must produce non-deterministic output on each call.</p> <p>What that means is, in case of <code>java.util.Random</code>, if you were to recreate an instance with the same seed each time you needed a new random number, you would essentially get the <em>same</em> result every time. However, <code>SecureRandom</code> is guaranteed to NOT do that - so, creating a single instance or creating a new one each time does <em>not</em> affect the randomness of the random bytes it generates.</p> <p>So, from just normal good coding practices view point, why create too many instances when one will do?</p>
434,641
How do I set permissions (attributes) on a file in a ZIP file using Python's zipfile module?
<p>When I extract files from a ZIP file created with the Python <a href="http://docs.python.org/library/zipfile.html" rel="noreferrer"><code>zipfile</code></a> module, all the files are not writable, read only etc.</p> <p>The file is being created and extracted under Linux and Python 2.5.2.</p> <p>As best I can tell, I need to set the <code>ZipInfo.external_attr</code> property for each file, but this doesn't seem to be documented anywhere I could find, can anyone enlighten me?</p>
434,689
8
0
null
2009-01-12 06:51:27.26 UTC
6
2022-05-01 12:31:45.827 UTC
2022-05-01 12:31:45.827 UTC
null
1,839,439
Tom
3,715
null
1
46
python|attributes|zip|file-permissions|python-zipfile
31,130
<p>This seems to work (thanks Evan, putting it here so the line is in context):</p> <pre><code>buffer = "path/filename.zip" # zip filename to write (or file-like object) name = "folder/data.txt" # name of file inside zip bytes = "blah blah blah" # contents of file inside zip zip = zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) info = zipfile.ZipInfo(name) info.external_attr = 0777 &lt;&lt; 16L # give full access to included file zip.writestr(info, bytes) zip.close() </code></pre> <p>I'd still like to see something that documents this... An additional resource I found was a note on the Zip file format: <a href="http://www.pkware.com/documents/casestudies/APPNOTE.TXT" rel="noreferrer">http://www.pkware.com/documents/casestudies/APPNOTE.TXT</a></p>
48,320
Best Ruby on Rails social networking framework
<p>I'm planning on creating a social networking + MP3 lecture downloading / browsing / commenting / discovery website using Ruby on Rails. Partially for fun and also as a means to learn some Ruby on Rails. I'm looking for a social networking framework that I can use as a basis for my site. I don't want to re-invent the wheel. </p> <p>Searching the web I found three such frameworks. Which of these three would you recommend using and why?</p> <p><a href="http://portal.insoshi.com/" rel="nofollow noreferrer">http://portal.insoshi.com/</a></p> <p><a href="http://www.communityengine.org/" rel="nofollow noreferrer">http://www.communityengine.org/</a></p> <p><a href="http://lovdbyless.com/" rel="nofollow noreferrer">http://lovdbyless.com/</a></p>
161,963
9
3
null
2008-09-07 11:06:48.497 UTC
36
2022-05-30 15:35:15.223 UTC
2022-05-30 15:35:15.223 UTC
null
3,689,450
Candidasa
5,010
null
1
27
ruby-on-rails|ruby|social-media
38,487
<p>It depends what your priorities are.</p> <p>If you really want to learn RoR, <strong>do it all from scratch</strong>. Seriously. Roll your own. It's the best way to learn, far better than hacking through someone else's code. If you do that, sometimes you'll be learning Rails, but sometimes you'll just be learning that specific social network framework. And <strong>you won't know which is which...</strong></p> <p>The type of site you're suggesting sounds perfect for a Rails project. If you get stuck, <strong>then</strong> go browse the repositories of these frameworks. Who cares if you're reinventing the wheel? It's your site, your vision, your rules.</p> <p>If you just want a site up and running, then I would pick Insoshi or LovdbyLess simply because they're out of the box apps so you'll have to do less to do get running. I suggest trying to install them both, and introducing yourself in the Google Groups. That'll give you a good indication of wether you're going to get along.</p>
925,221
Can I hook into UISearchBar's Clear Button?
<p>I've got a UISearchBar in my interface and I want to customise the behaviour of the the small clear button that appears in the search bar after some text has been entered (it's a small grey circle with a cross in it, appears on the right side of the search field).</p> <p>Basically, I want it to not only clear the text of the search bar (which is the default implementation) but to also clear some other stuff from my interface, but calling one of my own methods.</p> <p>I can't find anything in the docs for the UISearchBar class or the UISearchBarDelegate protocol - it doesn't look like you can directly get access to this behaviour.</p> <p>The one thing I did note was that the docs explained that the delegate method:</p> <pre><code>- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText; </code></pre> <p>is called after the clear button is tapped.</p> <p>I initially wrote some code in that method that checked the search bar's text property, and if it was empty, then it had been cleared and to do all my other stuff.</p> <p>Two problems which this though:</p> <p>Firstly, for some reason I cannot fathom, even though I tell the search bar to resignFirstResponder at the end of my method, something, somewhere is setting it back to becomeFirstResponder. Really annoying...</p> <p>Secondly, if the user doesn't use the clear button, and simply deletes the text in the bar using the delete button on the keyboard, this method is fired off and their search results go away. Not good.</p> <p>Any advice or pointers in the right direction would be great!</p> <p>Thanks!</p>
3,852,512
9
2
null
2009-05-29 09:48:19.463 UTC
4
2015-11-25 12:15:40.23 UTC
2009-05-29 09:55:21.617 UTC
null
76,559
null
76,559
null
1
37
iphone|objective-c|uikit|uisearchbar
51,275
<p>The answer which was accepted is incorrect. This can be done, I just figured it out and posted it in another question:</p> <p><a href="https://stackoverflow.com/questions/1092246/uisearchbar-clearbutton-forces-the-keyboard-to-appear/3852509#3852509">UISearchbar clearButton forces the keyboard to appear</a></p> <p>Best</p>
321,118
What is the short cut in eclipse to terminate debugging/running?
<p>What is the shortcut in eclipse to terminate debugging/running? Looking under Preferences -> Keys says <kbd>Ctrl</kbd> + <kbd>F2</kbd> but it doesn't work.</p>
321,150
9
0
null
2008-11-26 15:34:05.847 UTC
6
2018-04-26 17:44:33.617 UTC
2011-09-08 19:09:11.467 UTC
Vijay Dev
321,366
cretzel
18,722
null
1
48
eclipse|keyboard-shortcuts
72,007
<p>As said <a href="http://dev.eclipse.org/newslists/news.eclipse.newcomer/msg21758.html" rel="noreferrer">here</a>, you can add/enable the Debug command group to any perspective using<br> <code>Window / Customize Perspective &gt; Commands</code>.<br> (Select the 'Debug' group)</p> <p>Then open the Debug view in the Java perspective (as a Fast view perhaps) and you should get your Terminate keybinding.</p> <p>I suppose it was not working because you tried it in a non-debug session.</p>
893,295
What are some of the most useful yet little known features in the PowerShell language
<p>A while back I was reading about multi-variable assignments in PowerShell. This lets you do things like this</p> <pre><code>64 &gt; $a,$b,$c,$d = "A four word string".split() 65 &gt; $a A 66 &gt; $b four </code></pre> <p>Or you can swap variables in a single statement</p> <pre><code>$a,$b = $b,$a </code></pre> <p>What little known nuggets of PowerShell have you come across that you think may not be as well known as they should be?</p>
893,321
11
2
2010-03-20 09:53:18.51 UTC
2009-05-21 14:45:23.863 UTC
29
2019-08-10 16:56:01.713 UTC
null
null
null
null
45,571
null
1
26
powershell
3,151
<p>The <code>$$</code> command. I often have to do repeated operations on the same file path. For instance check out a file and then open it up in VIM. The <code>$$</code> feature makes this trivial</p> <pre><code>PS&gt; tf edit some\really\long\file\path.cpp PS&gt; gvim $$ </code></pre> <p>It's short and simple but it saves a lot of time.</p>
910,873
How can I determine if a file is binary or text in c#?
<p>I need to determine in 80% if a file is binary or text, is there any way to do it even quick and dirty/ugly in c#?</p>
910,927
11
3
null
2009-05-26 14:05:20.297 UTC
21
2015-05-20 18:24:14.39 UTC
2012-05-01 11:55:13.523 UTC
null
50,776
null
30,729
null
1
60
c#|text|file-io|binary
52,192
<p>I would probably look for an abundance of control characters which would typically be present in a binary file but rarely in an text file. Binary files tend to use 0 enough that just testing for many 0 bytes would probably be sufficient to catch most files. If you care about localization you'd need to test multi-byte patterns as well.</p> <p>As stated though, you can always be unlucky and get a binary file that looks like text or vice versa. </p>
144,261
Memory leak detection tools
<p>Does Apple's Xcode development environment provide any tools for memory leak detection?</p> <p>I am especially interested in tools that apply to the iPhone SDK. Currently my favourite platform for hobby programming projects</p> <p>Documentations/tutorials for said tools would be very helpful.</p>
144,866
11
0
null
2008-09-27 19:17:08.443 UTC
15
2016-04-24 08:09:42.543 UTC
2015-12-19 13:46:54.023 UTC
null
1,659,677
SytS
22,502
null
1
64
iphone|xcode|memory-management|memory-leaks
80,337
<p>There is one specifically called <code>Leaks</code> and like a previous poster said, the easiest way to run it is straight from Xcode: </p> <blockquote> <blockquote> <p>run -> Start with Performance Tool -> Leaks</p> </blockquote> </blockquote> <p>It seems very good at detecting memory leaks, and was easy for a Non-C Head like me to figure out.</p>
446,358
Storing a large number of images
<p>I'm thinking about developing my own PHP based gallery for storing lots of pictures, maybe in the tens of thousands.</p> <p>At the database I'll point to the url of the image, but here's the problem: I know is impractical to have all of them sitting at the same directory in the server as it would slow access to a crawl, so, how would you store all of them? Some kind of tree based on the name of the jpeg/png?</p> <p>What rules to partition the images would you recommend me?</p> <p>(It will focused for using in cheapo dot coms, so no mangling with the server is possible)</p>
446,401
12
0
null
2009-01-15 10:57:43.097 UTC
33
2011-12-27 17:50:14.36 UTC
2009-03-24 12:22:50.143 UTC
Pete Kirkham
1,527
Saiyine
38,238
null
1
52
image|tree|filesystems
14,630
<p>We had a similar problem in the past. And found a nice solution:</p> <ul> <li>Give each image an unique guid.</li> <li>Create a database record for each image containing the name, location, guid and possible location of sub images (thumbnails, reducedsize, etc.).</li> <li>Use the first (one or two) characters of the guid to determine the toplevel folder.</li> <li>If the folders have too much files, split again. Update the references and you are ready to go.</li> <li>If the number of files and the accesses are too high, you can spread folders over different file servers.</li> </ul> <p>We have experienced that using the guids, you get a more or less uniform division. And it worked like a charm.</p> <p>Links which might help to generate a unique ID:</p> <ul> <li><a href="http://en.wikipedia.org/wiki/Universally_Unique_Identifier" rel="noreferrer">http://en.wikipedia.org/wiki/Universally_Unique_Identifier</a></li> <li><a href="http://en.wikipedia.org/wiki/Sha1" rel="noreferrer">http://en.wikipedia.org/wiki/Sha1</a></li> </ul>
459,238
When and how do you use server side JavaScript?
<p>Occasionally I search for some JavaScript help and I come upon the term "Server-side JavaScript". When would you use JavaScript server-side? And how? </p> <p>My experiences of JavaScript have been in the browser. Is there a compiled version of JS?</p>
459,379
12
6
null
2009-01-19 21:33:42.957 UTC
24
2018-06-28 20:32:30.9 UTC
2009-01-20 00:07:56.25 UTC
Peter Hilton
2,670
John Nolan
1,116
null
1
81
javascript|server-side
79,350
<p>There's the project <a href="https://phobos.java.net/" rel="noreferrer">Phobos</a>, which is a server side JavaScript framework.</p> <p>Back In The Day, the Netscape web server offered server-side java script as well.</p> <p>In both of these cases, JavaScript is used just like you'd use any language on the server. Typically to handle HTTP requests and generate content.</p> <p><a href="http://www.mozilla.org/rhino/" rel="noreferrer">Rhino</a>, which is Mozilla's JavaScript system for Java, compiles JavaScript in to Java byte codes, which the JVM can choose to JIT. Other systems use other means for executing java script, even to the point that some are JIT compiling their java script internal codes.</p> <p>I foresee that there will be more and more JavaScript on the server. When you're writing "thick" applications in JavaScript on the client, then you may as well be able to write your logic in JavaScript on the server in order to not have to make the cognitive leaps from one language to another. The environments will be different, but much of your code and knowledge will be shareable.</p> <p>Finally, JavaScript is probably the singular language that has the most money pointing at it right now in terms of implementations. From Apple, Mozilla, Google, and even Microsoft as well as the efforts to make it an even more advanced language (i.e. basically a Scheme with Algol syntax sans macros).</p> <p>Most of those implementation are buried in the browser, but that's not to say that there's no value on the server side as well.</p> <p>The tooling is the biggest place where JavaScript is lacking, especially on the server side, but if you consider something like Phobos, where you can debug your server side JavaScript in the IDE, that's a great advancement.</p> <p>Personally, I'm tossing JavaScript around in my applications like white paint. It offers cheap extensibility for very little cost and is a great enabler.</p>
310,634
What is the "right" way to iterate through an array in Ruby?
<p>PHP, for all its warts, is pretty good on this count. There's no difference between an array and a hash (maybe I'm naive, but this seems obviously right to me), and to iterate through either you just do</p> <pre><code>foreach (array/hash as $key =&gt; $value) </code></pre> <p>In Ruby there are a bunch of ways to do this sort of thing:</p> <pre><code>array.length.times do |i| end array.each array.each_index for i in array </code></pre> <p>Hashes make more sense, since I just always use</p> <pre><code>hash.each do |key, value| </code></pre> <p>Why can't I do this for arrays? If I want to remember just one method, I guess I can use <code>each_index</code> (since it makes both the index and value available), but it's annoying to have to do <code>array[index]</code> instead of just <code>value</code>.</p> <hr> <p>Oh right, I forgot about <code>array.each_with_index</code>. However, this one sucks because it goes <code>|value, key|</code> and <code>hash.each</code> goes <code>|key, value|</code>! Is this not insane?</p>
310,638
12
2
null
2008-11-22 00:38:19.963 UTC
99
2022-02-25 21:42:12.147 UTC
2011-08-28 03:30:16.19 UTC
null
38,765
Horace Loeb
25,068
null
1
391
ruby|arrays|loops
614,616
<p>This will iterate through all the elements:</p> <pre class="lang-rb prettyprint-override"><code>array = [1, 2, 3, 4, 5, 6] array.each { |x| puts x } # Output: 1 2 3 4 5 6 </code></pre> <p>This will iterate through all the elements giving you the value and the index:</p> <pre class="lang-rb prettyprint-override"><code>array = [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;] array.each_with_index {|val, index| puts &quot;#{val} =&gt; #{index}&quot; } # Output: A =&gt; 0 B =&gt; 1 C =&gt; 2 </code></pre> <p>I'm not quite sure from your question which one you are looking for.</p>
1,058,736
How to create a NSString from a format string like @"xxx=%@, yyy=%@" and a NSArray of objects?
<p>Is there any way to create a new NSString from a format string like @"xxx=%@, yyy=%@" and a NSArray of objects?</p> <p>In the NSSTring class there are many methods like:</p> <pre><code>- (id)initWithFormat:(NSString *)format arguments:(va_list)argList - (id)initWithFormat:(NSString *)format locale:(id)locale arguments:(va_list)argList + (id)stringWithFormat:(NSString *)format, ... </code></pre> <p>but non of them takes a NSArray as an argument, and I cannot find a way to create a va_list from a NSArray...</p>
1,061,750
13
1
null
2009-06-29 14:46:09.507 UTC
16
2017-07-15 10:04:39.883 UTC
2009-06-29 17:42:20.51 UTC
null
120,292
null
19,331
null
1
32
objective-c|cocoa|nsstring|nsarray|string-formatting
49,934
<p>It is actually not hard to create a va_list from an NSArray. See Matt Gallagher's <a href="http://cocoawithlove.com/2009/05/variable-argument-lists-in-cocoa.html" rel="nofollow noreferrer">excellent article</a> on the subject.</p> <p>Here is an NSString category to do what you want:</p> <pre><code>@interface NSString (NSArrayFormatExtension) + (id)stringWithFormat:(NSString *)format array:(NSArray*) arguments; @end @implementation NSString (NSArrayFormatExtension) + (id)stringWithFormat:(NSString *)format array:(NSArray*) arguments { char *argList = (char *)malloc(sizeof(NSString *) * arguments.count); [arguments getObjects:(id *)argList]; NSString* result = [[[NSString alloc] initWithFormat:format arguments:argList] autorelease]; free(argList); return result; } @end </code></pre> <p>Then:</p> <pre><code>NSString* s = [NSString stringWithFormat:@"xxx=%@, yyy=%@" array:@[@"XXX", @"YYY"]]; NSLog( @"%@", s ); </code></pre> <p>Unfortunately, for 64-bit, the va_list format has changed, so the above code no longer works. And probably should not be used anyway given it depends on the format that is clearly subject to change. Given there is no really robust way to create a va_list, a better solution is to simply limit the number of arguments to a reasonable maximum (say 10) and then call stringWithFormat with the first 10 arguments, something like this:</p> <pre><code>+ (id)stringWithFormat:(NSString *)format array:(NSArray*) arguments { if ( arguments.count &gt; 10 ) { @throw [NSException exceptionWithName:NSRangeException reason:@"Maximum of 10 arguments allowed" userInfo:@{@"collection": arguments}]; } NSArray* a = [arguments arrayByAddingObjectsFromArray:@[@"X",@"X",@"X",@"X",@"X",@"X",@"X",@"X",@"X",@"X"]]; return [NSString stringWithFormat:format, a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9] ]; } </code></pre>
348,040
iPhone and OpenCV
<p>I know that <a href="http://opencv.willowgarage.com/wiki/Mac_OS_X_OpenCV_Port" rel="noreferrer">OpenCV was ported to Mac OS X</a>, however I did not find any info about a port to the iPhone.</p> <p>I am not a Mac developer, so that I do not know whether a Mac OS X port is enough for the iPhone.</p> <p>Does anyone know better than me? </p>
12,662,359
13
0
null
2008-12-07 20:38:55.4 UTC
78
2019-05-23 06:28:45.07 UTC
2019-05-23 06:28:45.07 UTC
Chris Hanson
2,272,431
Pascal T.
19,816
null
1
97
ios|iphone|opencv
71,564
<p>OpenCV now (since <strong>2012</strong>) has an <strong>official port</strong> for the iPhone (iOS).</p> <p>You can find <a href="http://opencv.org" rel="nofollow noreferrer">all of OpenCV's releases here.</a></p> <p>And find install instructions here: </p> <p><a href="https://docs.opencv.org/3.4.3/d5/da3/tutorial_ios_install.html" rel="nofollow noreferrer">Tutorials &amp; introduction for the new version 3.x</a></p>
338,206
Why can't I use switch statement on a String?
<p>Is this functionality going to be put into a later Java version?</p> <p>Can someone explain why I can't do this, as in, the technical way Java's <code>switch</code> statement works?</p>
338,230
14
3
null
2008-12-03 18:23:57.127 UTC
195
2022-09-22 02:19:10.857 UTC
2018-07-09 21:52:21.683 UTC
Nalandial
8,583,692
Nalandial
14,007
null
1
1,042
java|string|switch-statement
768,431
<p>Switch statements with <code>String</code> cases have been implemented in <a href="http://openjdk.java.net/projects/jdk7/features/" rel="nofollow noreferrer">Java SE 7</a>, at least 16 years <a href="https://bugs.java.com/bugdatabase/view_bug.do?bug_id=1223179" rel="nofollow noreferrer">after they were first requested.</a> A clear reason for the delay was not provided, but it likely had to do with performance.</p> <h2>Implementation in JDK 7</h2> <p>The feature has now been implemented in <code>javac</code> <a href="http://blogs.oracle.com/darcy/entry/project_coin_string_switch_anatomy" rel="nofollow noreferrer">with a &quot;de-sugaring&quot; process;</a> a clean, high-level syntax using <code>String</code> constants in <code>case</code> declarations is expanded at compile-time into more complex code following a pattern. The resulting code uses JVM instructions that have always existed.</p> <p>A <code>switch</code> with <code>String</code> cases is translated into two switches during compilation. The first maps each string to a unique integer—its position in the original switch. This is done by first switching on the hash code of the label. The corresponding case is an <code>if</code> statement that tests string equality; if there are collisions on the hash, the test is a cascading <code>if-else-if</code>. The second switch mirrors that in the original source code, but substitutes the case labels with their corresponding positions. This two-step process makes it easy to preserve the flow control of the original switch.</p> <h2>Switches in the JVM</h2> <p>For more technical depth on <code>switch</code>, you can refer to the JVM Specification, where the <a href="http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-3.html#jvms-3.10" rel="nofollow noreferrer">compilation of switch statements</a> is described. In a nutshell, there are two different JVM instructions that can be used for a switch, depending on the sparsity of the constants used by the cases. Both depend on using integer constants for each case to execute efficiently.</p> <p>If the constants are dense, they are used as an index (after subtracting the lowest value) into a table of instruction pointers—the <code>tableswitch</code> instruction.</p> <p>If the constants are sparse, a binary search for the correct case is performed—the <code>lookupswitch</code> instruction.</p> <p>In de-sugaring a <code>switch</code> on <code>String</code> objects, both instructions are likely to be used. The <code>lookupswitch</code> is suitable for the first switch on hash codes to find the original position of the case. The resulting ordinal is a natural fit for a <code>tableswitch</code>.</p> <p>Both instructions require the integer constants assigned to each case to be sorted at compile time. At runtime, while the <code>O(1)</code> performance of <code>tableswitch</code> generally appears better than the <code>O(log(n))</code> performance of <code>lookupswitch</code>, it requires some analysis to determine whether the table is dense enough to justify the space–time tradeoff. Bill Venners wrote <a href="http://www.artima.com/underthehood/flowP.html" rel="nofollow noreferrer">a great article</a> that covers this in more detail, along with an under-the-hood look at other Java flow control instructions.</p> <h2>Before JDK 7</h2> <p>Prior to JDK 7, <code>enum</code> could approximate a <code>String</code>-based switch. This uses <a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.9.3" rel="nofollow noreferrer">the static <code>valueOf</code></a> method generated by the compiler on every <code>enum</code> type. For example:</p> <pre><code>Pill p = Pill.valueOf(str); switch(p) { case RED: pop(); break; case BLUE: push(); break; } </code></pre>
1,102,692
How to alpha blend RGBA unsigned byte color fast?
<p>I am using c++ , I want to do alpha blend using the following code.</p> <pre><code>#define CLAMPTOBYTE(color) \ if ((color) &amp; (~255)) { \ color = (BYTE)((-(color)) &gt;&gt; 31); \ } else { \ color = (BYTE)(color); \ } #define GET_BYTE(accessPixel, x, y, scanline, bpp) \ ((BYTE*)((accessPixel) + (y) * (scanline) + (x) * (bpp))) for (int y = top ; y &lt; bottom; ++y) { BYTE* resultByte = GET_BYTE(resultBits, left, y, stride, bytepp); BYTE* srcByte = GET_BYTE(srcBits, left, y, stride, bytepp); BYTE* srcByteTop = GET_BYTE(srcBitsTop, left, y, stride, bytepp); BYTE* maskCurrent = GET_GREY(maskSrc, left, y, width); int alpha = 0; int red = 0; int green = 0; int blue = 0; for (int x = left; x &lt; right; ++x) { alpha = *maskCurrent; red = (srcByteTop[R] * alpha + srcByte[R] * (255 - alpha)) / 255; green = (srcByteTop[G] * alpha + srcByte[G] * (255 - alpha)) / 255; blue = (srcByteTop[B] * alpha + srcByte[B] * (255 - alpha)) / 255; CLAMPTOBYTE(red); CLAMPTOBYTE(green); CLAMPTOBYTE(blue); resultByte[R] = red; resultByte[G] = green; resultByte[B] = blue; srcByte += bytepp; srcByteTop += bytepp; resultByte += bytepp; ++maskCurrent; } } </code></pre> <p>however I find it is still slow, it takes about 40 - 60 ms when compose two 600 * 600 image. Is there any method to improve the speed to less then 16ms?</p> <p>Can any body help me to speed this code? Many thanks!</p>
1,102,810
17
3
null
2009-07-09 09:04:36.64 UTC
23
2021-12-08 09:16:52.01 UTC
2016-12-12 02:35:04.663 UTC
null
432,509
null
25,749
null
1
23
c++|performance
30,781
<p><a href="http://www2.units.it/~csia/calcolointensivo/tartaglia/intel/cce/intref_cls.pdf" rel="noreferrer">Use SSE</a> - start around page 131. </p> <p>The basic workflow</p> <ol> <li><p>Load 4 pixels from src (16 1 byte numbers) RGBA RGBA RGBA RGBA (streaming load)</p></li> <li><p>Load 4 more which you want to blend with srcbytetop RGBx RGBx RGBx RGBx </p></li> <li><p>Do some swizzling so that the A term in 1 fills every slot I.e </p> <p>xxxA xxxB xxxC xxxD -> AAAA BBBB CCCC DDDD </p> <p>In my solution below I opted instead to re-use your existing "maskcurrent" array but having alpha integrated into the "A" field of 1 will require less loads from memory and thus be faster. Swizzling in this case would probably be: And with mask to select A, B, C, D. Shift right 8, Or with origional, shift right 16, or again.</p></li> <li><p>Add the above to a vector that is all -255 in every slot </p></li> <li><p>Multiply 1 * 4 (source with 255-alpha) and 2 * 3 (result with alpha). </p> <p>You should be able to use the "multiply and discard bottom 8 bits" SSE2 instruction for this.</p></li> <li><p>add those two (4 and 5) together </p></li> <li><p>Store those somewhere else (if possible) or on top of your destination (if you must)</p></li> </ol> <p>Here is a starting point for you:</p> <pre><code> //Define your image with __declspec(align(16)) i.e char __declspec(align(16)) image[640*480] // so the first byte is aligned correctly for SIMD. // Stride must be a multiple of 16. for (int y = top ; y &lt; bottom; ++y) { BYTE* resultByte = GET_BYTE(resultBits, left, y, stride, bytepp); BYTE* srcByte = GET_BYTE(srcBits, left, y, stride, bytepp); BYTE* srcByteTop = GET_BYTE(srcBitsTop, left, y, stride, bytepp); BYTE* maskCurrent = GET_GREY(maskSrc, left, y, width); for (int x = left; x &lt; right; x += 4) { //If you can't align, use _mm_loadu_si128() // Step 1 __mm128i src = _mm_load_si128(reinterpret_cast&lt;__mm128i*&gt;(srcByte)) // Step 2 __mm128i srcTop = _mm_load_si128(reinterpret_cast&lt;__mm128i*&gt;(srcByteTop)) // Step 3 // Fill the 4 positions for the first pixel with maskCurrent[0], etc // Could do better with shifts and so on, but this is clear __mm128i mask = _mm_set_epi8(maskCurrent[0],maskCurrent[0],maskCurrent[0],maskCurrent[0], maskCurrent[1],maskCurrent[1],maskCurrent[1],maskCurrent[1], maskCurrent[2],maskCurrent[2],maskCurrent[2],maskCurrent[2], maskCurrent[3],maskCurrent[3],maskCurrent[3],maskCurrent[3], ) // step 4 __mm128i maskInv = _mm_subs_epu8(_mm_set1_epu8(255), mask) //Todo : Multiply, with saturate - find correct instructions for 4..6 //note you can use Multiply and add _mm_madd_epi16 alpha = *maskCurrent; red = (srcByteTop[R] * alpha + srcByte[R] * (255 - alpha)) / 255; green = (srcByteTop[G] * alpha + srcByte[G] * (255 - alpha)) / 255; blue = (srcByteTop[B] * alpha + srcByte[B] * (255 - alpha)) / 255; CLAMPTOBYTE(red); CLAMPTOBYTE(green); CLAMPTOBYTE(blue); resultByte[R] = red; resultByte[G] = green; resultByte[B] = blue; //---- // Step 7 - store result. //Store aligned if output is aligned on 16 byte boundrary _mm_store_si128(reinterpret_cast&lt;__mm128i*&gt;(resultByte), result) //Slow version if you can't guarantee alignment //_mm_storeu_si128(reinterpret_cast&lt;__mm128i*&gt;(resultByte), result) //Move pointers forward 4 places srcByte += bytepp * 4; srcByteTop += bytepp * 4; resultByte += bytepp * 4; maskCurrent += 4; } } </code></pre> <p>To find out which AMD processors will run this code (currently it is using SSE2 instructions) see <a href="http://en.wikipedia.org/wiki/List_of_AMD_Turion_microprocessors" rel="noreferrer">Wikipedia's List of AMD Turion microprocessors</a>. You could also look at other lists of processors on Wikipedia but my research shows that AMD cpus from around 4 years ago all support at least SSE2.</p> <p>You should expect a good SSE2 implimentation to run around 8-16 times faster than your current code. That is because we eliminate branches in the loop, process 4 pixels (or 12 channels) at once and improve cache performance by using streaming instructions. As an alternative to SSE, you could probably make your existing code run much faster by eliminating the if checks you are using for saturation. Beyond that I would need to run a profiler on your workload.</p> <p>Of course, the best solution is to use hardware support (i.e code your problem up in DirectX) and have it done on the video card.</p>
157,429
What are the benefits of using Perforce instead of Subversion?
<p>My team has been using SVN for a few years. We now have the option of switching to Perforce.</p> <p>What would be the benefits (and pitfalls) of making such a switch?</p>
157,482
17
0
null
2008-10-01 12:52:46.46 UTC
24
2016-05-11 13:26:31.41 UTC
2008-10-01 13:03:34.173 UTC
jfm3
11,138
Ferruccio
4,086
null
1
66
svn|perforce
42,729
<ul> <li>P4 keeps track of your working copy on the server. This means that <ol> <li>Large working copies are processed much faster. I used to have a large SVN project and a simple update took 15 minutes because it had to create a tree of the local working copy (thousands of folders). File access is slow. P4 stores the information about the working copy in the database, so any operations were always near-instantaneous.</li> <li>If you mess around with your files and do not tell the server, you are in trouble! You cannot just delete a file - you have to delete a file with the P4 client so the server knows. Note that if you locally delete a file, it will not be downloaded again on successive updates because the server thinks you already have it! When lots of this happened and I ended up wildly out of sync, I usually had to resort to cleaning out my local copy and downloading it again, which could be time-consuming. You <em>must</em> be careful about this.</li> </ol></li> <li>The Explorer shell extension client (think TortoiseSVN) sucks and is completely unusable.</li> <li>There are two GUI client applications which offer the best functionality: P4Win and P4V, of which P4V is newer and more easy to use but not as feature-rich.</li> <li>There are Visual Studio and Eclipse plug-ins, which work relatively well, although they do not have many advanced features.</li> <li>Generally speaking, P4 offers much less features than SVN and is sometimes downright confusing.</li> <li>Working copy definitions were nice and flexible. I believe P4 is superior to SVN here: you can define masks for working copy folders and create all sorts of bizarre trees, so you download only what you want to exactly where you want, without having to manually futz with multiple checkouts. This came in very handy when I had gigabytes of stuff on the server and only wanted a specific subset of it. I used SVN in a similar situation with much more hassle.</li> <li>Branching under P4 is... odd. Branchsets and different kinds of branches and confusing UI. I do not remember much details about this, unfortunately.</li> </ul> <p>Other than that, it's pretty standard.</p> <p>I recommend you keep SVN unless you deal with huge codebases or hate the .svn folders littering up your filesystem. SVN+TortoiseSVN is far more confortable for most situations.</p>
798,545
What is the Java ?: operator called and what does it do?
<p>I have been working with Java a couple of years, but up until recently I haven't run across this construct:</p> <pre><code>int count = isHere ? getHereCount(index) : getAwayCount(index); </code></pre> <p>This is probably a very simple question, but can someone explain it? How do I read it? I am pretty sure I know how it works.</p> <ul> <li>if <code>isHere</code> is true, <code>getHereCount()</code> is called, </li> <li>if <code>isHere</code> is false <code>getAwayCount()</code> is called.</li> </ul> <p>Correct? What is this construct called?</p>
798,556
17
4
null
2009-04-28 15:28:50.42 UTC
52
2022-03-22 07:01:39.943 UTC
2016-05-27 09:44:54.467 UTC
null
1,752,988
null
33,863
null
1
188
java|syntax|ternary-operator|conditional-operator
261,170
<p>Yes, it is a shorthand form of</p> <pre><code>int count; if (isHere) count = getHereCount(index); else count = getAwayCount(index); </code></pre> <p>It's called the <strong>conditional operator</strong>. Many people (erroneously) call it <em>the ternary operator</em>, because it's the only ternary (three-argument) operator in Java, C, C++, and probably many other languages. But theoretically there <em>could</em> be another ternary operator, whereas there can only be one <em>conditional operator</em>.</p> <p>The official name is given in the <a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.25" rel="noreferrer">Java Language Specification</a>:</p> <blockquote> <h3>§15.25 Conditional Operator ? :</h3> <p>The conditional operator <code>? :</code> uses the boolean value of one expression to decide which of two other expressions should be evaluated.</p> </blockquote> <p>Note that both branches must lead to methods with return values:</p> <blockquote> <p><strong>It is a compile-time error for either the second or the third operand expression to be an invocation of a void method.</strong></p> <p><sup><em>In fact, by the grammar of expression statements (<a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.8" rel="noreferrer">§14.8</a>), it is not permitted for a conditional expression to appear in any context where an invocation of a void method could appear.</em></sup></p> </blockquote> <p>So, if <code>doSomething()</code> and <code>doSomethingElse()</code> are void methods, you cannot compress this:</p> <pre><code>if (someBool) doSomething(); else doSomethingElse(); </code></pre> <p>into this:</p> <pre><code>someBool ? doSomething() : doSomethingElse(); </code></pre> <p>Simple words:</p> <pre><code>booleanCondition ? executeThisPartIfBooleanConditionIsTrue : executeThisPartIfBooleanConditionIsFalse </code></pre>
74,148
How to convert numbers between hexadecimal and decimal
<p>How do you convert between hexadecimal numbers and decimal numbers in C#?</p>
74,223
20
0
null
2008-09-16 16:18:59.327 UTC
48
2022-02-22 22:44:53.993 UTC
2018-12-10 09:52:57.623 UTC
null
1,671,066
Andy McCluggage
3,362
null
1
168
c#|hex|type-conversion|decimal
414,072
<p>To convert from decimal to hex do...</p> <pre><code>string hexValue = decValue.ToString("X"); </code></pre> <p>To convert from hex to decimal do either...</p> <pre><code>int decValue = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber); </code></pre> <p>or </p> <pre><code>int decValue = Convert.ToInt32(hexValue, 16); </code></pre>
869,033
How do I copy an object in Java?
<p>Consider the code below:</p> <pre><code>DummyBean dum = new DummyBean(); dum.setDummy("foo"); System.out.println(dum.getDummy()); // prints 'foo' DummyBean dumtwo = dum; System.out.println(dumtwo.getDummy()); // prints 'foo' dum.setDummy("bar"); System.out.println(dumtwo.getDummy()); // prints 'bar' but it should print 'foo' </code></pre> <p>So, I want to copy the <code>dum</code> to <code>dumtwo</code> and change <code>dum</code> without affecting the <code>dumtwo</code>. But the code above is not doing that. When I change something in <code>dum</code>, the same change is happening in <code>dumtwo</code> also.</p> <p>I guess, when I say <code>dumtwo = dum</code>, Java copies the <strong>reference only</strong>. So, is there any way to create a fresh copy of <code>dum</code> and assign it to <code>dumtwo</code>?</p>
869,078
23
0
null
2009-05-15 14:30:26.943 UTC
305
2021-12-08 11:57:38.64 UTC
2017-12-23 19:15:19.35 UTC
null
5,345,646
null
42,372
null
1
896
java|object|copy|clone
1,401,924
<p>Create a copy constructor:</p> <pre><code>class DummyBean { private String dummy; public DummyBean(DummyBean another) { this.dummy = another.dummy; // you can access } } </code></pre> <p>Every object has also a clone method which can be used to copy the object, but don't use it. It's way too easy to create a class and do improper clone method. If you are going to do that, read at least what Joshua Bloch has to say about it in <em><a href="http://books.google.com/books?id=ka2VUBqHiWkC&amp;pg=PA55&amp;lpg=PA55&amp;dq=effective+java+clone&amp;source=bl&amp;ots=yXGhLnv4O4&amp;sig=zvEip5tp5KGgwqO1sCWgtGyJ1Ns&amp;hl=en&amp;ei=CYANSqygK8jktgfM-JGcCA&amp;sa=X&amp;oi=book_result&amp;ct=result&amp;resnum=3#PPA54,M1" rel="noreferrer">Effective Java</a></em>.</p>
181,530
Styling multi-line conditions in 'if' statements?
<p>Sometimes I break long conditions in <code>if</code>s onto several lines. The most obvious way to do this is:</p> <pre><code> if (cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4'): do_something </code></pre> <p>Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.</p> <p>For the moment I'm using:</p> <pre><code> if ( cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4'): do_something </code></pre> <p>But this isn't very pretty. :-)</p> <p>Can you recommend an alternative way?</p>
181,557
30
5
null
2008-10-08 06:19:07.67 UTC
157
2019-10-25 17:28:13.22 UTC
2017-05-30 17:35:39.673 UTC
DzinX
355,230
eliben
8,206
null
1
825
python|coding-style|if-statement
1,490,075
<p>You don't need to use 4 spaces on your second conditional line. Maybe use:</p> <pre><code>if (cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4'): do_something </code></pre> <p>Also, don't forget the whitespace is more flexible than you might think:</p> <pre><code>if ( cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4' ): do_something if (cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4'): do_something </code></pre> <p>Both of those are fairly ugly though.</p> <p>Maybe lose the brackets (the <a href="https://www.python.org/dev/peps/pep-0008/#multiline-if-statements" rel="noreferrer">Style Guide</a> discourages this though)?</p> <pre><code>if cond1 == 'val1' and cond2 == 'val2' and \ cond3 == 'val3' and cond4 == 'val4': do_something </code></pre> <p>This at least gives you some differentiation.</p> <p>Or even:</p> <pre><code>if cond1 == 'val1' and cond2 == 'val2' and \ cond3 == 'val3' and \ cond4 == 'val4': do_something </code></pre> <p>I think I prefer:</p> <pre><code>if cond1 == 'val1' and \ cond2 == 'val2' and \ cond3 == 'val3' and \ cond4 == 'val4': do_something </code></pre> <p>Here's the <a href="https://www.python.org/dev/peps/pep-0008/#multiline-if-statements" rel="noreferrer">Style Guide</a>, which (since 2010) recommends using brackets.</p>
6,492,033
Return value for performSelector:
<p>What will the return value for performSelector: if I pass a selector that returns a primitive type (on object), such as 'week' on NSDateComponents (which will return an int)?</p>
10,973,879
5
0
null
2011-06-27 11:18:09.223 UTC
12
2017-03-29 02:37:23.94 UTC
null
null
null
null
74,415
null
1
41
objective-c|cocoa-touch|cocoa|performselector
20,516
<p>An example of using NSInvocation to return a float:</p> <pre><code>SEL selector = NSSelectorFromString(@"someSelector"); if ([someInstance respondsToSelector:selector]) { NSInvocation *invocation = [NSInvocation invocationWithMethodSignature: [[someInstance class] instanceMethodSignatureForSelector:selector]]; [invocation setSelector:selector]; [invocation setTarget:someInstance]; [invocation invoke]; float returnValue; [invocation getReturnValue:&amp;returnValue]; NSLog(@"Returned %f", returnValue); } </code></pre>
6,550,795
Uncaught TypeError: Cannot read property 'value' of undefined
<p>I have some JavaScript code that gives this error</p> <pre class="lang-none prettyprint-override"><code>Uncaught TypeError: Cannot read property 'value' of undefined </code></pre> <p>Code</p> <pre><code>var i1 = document.getElementById('i1'); var i2 = document.getElementById('i2'); var __i = {'user' : document.getElementsByName("username")[0], 'pass' : document.getElementsByName("password")[0] }; if( __i.user.value.length &gt;= 1 ) { i1.value = ''; } else { i1.value = 'Acc'; } if( __i.pass.value.length &gt;= 1 ) { i2.value = ''; } else { i2.value = 'Pwd'; } </code></pre> <p>What does this error mean?</p>
6,550,881
7
0
null
2011-07-01 16:43:31.837 UTC
15
2020-04-07 19:59:30.07 UTC
2020-04-07 19:59:30.07 UTC
null
12,820,864
null
572,737
null
1
55
javascript|typeerror
670,951
<p>Seems like one of your values, with a property key of 'value' is undefined. Test that <code>i1</code>, <code>i2</code>and <code>__i</code> are defined before executing the if statements:</p> <pre><code>var i1 = document.getElementById('i1'); var i2 = document.getElementById('i2'); var __i = {'user' : document.getElementsByName("username")[0], 'pass' : document.getElementsByName("password")[0] }; if(i1 &amp;&amp; i2 &amp;&amp; __i.user &amp;&amp; __i.pass) { if( __i.user.value.length &gt;= 1 ) { i1.value = ''; } else { i1.value = 'Acc'; } if( __i.pass.value.length &gt;= 1 ) { i2.value = ''; } else { i2.value = 'Pwd'; } } </code></pre>
38,129,284
Is GCM (now FCM) free for any limit?
<p>I would like to know if Firebase Cloud Messaging is free or not for unlimited users?</p>
38,316,883
4
2
null
2016-06-30 16:59:45.723 UTC
10
2021-04-20 18:14:28.16 UTC
2018-12-18 14:21:50.35 UTC
null
1,079,901
null
5,097,682
null
1
64
android|firebase|google-cloud-platform|google-cloud-messaging|firebase-cloud-messaging
52,206
<p>In addition to the <a href="https://stackoverflow.com/a/38136653/1079901">answer</a> from <a href="https://stackoverflow.com/users/4625829/al">AL</a>.<br /> From the <a href="https://firebase.google.com/pricing/" rel="noreferrer">Pricing page Faqs</a>:</p> <blockquote> <p><strong>Which products are paid? Which are free?</strong></p> <p>Firebase's paid infrastructure products are the Realtime Database, Firebase Storage, Hosting, and Test Lab. We offer a free tier for all of these products except Test Lab.</p> <p>Firebase also has many free products: Analytics, App Indexing, Authentication, Dynamic Links, Cloud Messaging, Notifications, Invites, Crash Reporting, &amp;, Remote Config. You can use an unlimited amount of these in all plans, including our free Spark Plan.</p> </blockquote> <p>So, it's free. The limit is not mentioned anywhere in the docs, however there's a limit on the Firebase realtime database, as mentioned in the FAQs:</p> <blockquote> <p>Firebase imposes hard limits on the number of connections to your app's database at the same time. These limits are in place to protect both Firebase and our users from abuse.</p> <p>The free plan limit is 100, and cannot be raised. The Flame and Blaze Plans have an initial limit of 10,000 simultaneous database connections. This is to prevent abuse and can be raised by contacting Firebase support with 24 hours notice.</p> <p>This limit isn't the same as the total number of users of your app, because your users don't all connect at once. We encourage you to monitor your peak simultaneous database connections and upgrade if needed.</p> <p>We're working hard to remove the initial 10,000 simultaneous connection cap on the Flame and Blaze plans.</p> </blockquote> <p>So if you are using the Firebase Database to save your User's data and want to send a lot of Push Notifications to your user's devices using the FCM registration token stored in the Firebase Database, you might hit the limit in the free Spark plan, however it's really tough to hit the 10k limit.</p>
15,720,545
Use stat_summary to annotate plot with number of observations
<p>How can I use <code>stat_summary</code> to label a plot with <code>n = x</code> where is <code>x</code> a variable? Here's an example of the desired output:</p> <p><img src="https://i.stack.imgur.com/EX1ab.png" alt="enter image description here"></p> <p>I can make that above plot with this rather inefficient code: </p> <pre><code>nlabels &lt;- sapply(1:length(unique(mtcars$cyl)), function(i) as.vector(t(as.data.frame(table(mtcars$cyl))[,2][[i]]))) ggplot(mtcars, aes(factor(cyl), mpg, label=rownames(mtcars))) + geom_boxplot(fill = "grey80", colour = "#3366FF") + geom_text(aes(x = 1, y = median(mtcars$mpg[mtcars$cyl==sort(unique(mtcars$cyl))[1]]), label = paste0("n = ",nlabels[[1]]) )) + geom_text(aes(x = 2, y = median(mtcars$mpg[mtcars$cyl==sort(unique(mtcars$cyl))[2]]), label = paste0("n = ",nlabels[[2]]) )) + geom_text(aes(x = 3, y = median(mtcars$mpg[mtcars$cyl==sort(unique(mtcars$cyl))[3]]), label = paste0("n = ",nlabels[[3]]) )) </code></pre> <p>This is a follow up to this question: <a href="https://stackoverflow.com/q/15660829/1036500">How to add a number of observations per group and use group mean in ggplot2 boxplot?</a> where I can use <code>stat_summary</code> to calculate and display the number of observations, but I haven't been able to find a way to include <code>n =</code> in the <code>stat_summary</code> output. Seems like <code>stat_summary</code> might be the most efficient way to do this kind of labelling, but other methods are welcome.</p>
15,720,769
2
0
null
2013-03-30 16:00:48.067 UTC
8
2018-03-20 03:14:48.183 UTC
2017-05-23 11:55:07.73 UTC
null
-1
null
1,036,500
null
1
17
r|graph|plot|ggplot2
23,634
<p>You can make your own function to use inside the <code>stat_summary()</code>. Here <code>n_fun</code> calculate place of y value as <code>median()</code> and then add <code>label=</code> that consist of <code>n=</code> and number of observations. It is important to use <code>data.frame()</code> instead of <code>c()</code> because <code>paste0()</code> will produce character but <code>y</code> value is numeric, but <code>c()</code> would make both character. Then in <code>stat_summary()</code> use this function and <code>geom="text"</code>. This will ensure that for each x value position and label is made only from this level's data.</p> <pre><code>n_fun &lt;- function(x){ return(data.frame(y = median(x), label = paste0("n = ",length(x)))) } ggplot(mtcars, aes(factor(cyl), mpg, label=rownames(mtcars))) + geom_boxplot(fill = "grey80", colour = "#3366FF") + stat_summary(fun.data = n_fun, geom = "text") </code></pre> <p><img src="https://i.stack.imgur.com/uEAtU.png" alt="enter image description here"></p>
15,818,364
VS 2012 launching app based on wrong path
<p>I have a app which is under source control (TFS 2012 also) on c:\Dev\MyApp\Main.</p> <p>Because im developing a new feature I decided to open a branch on c:\Dev\MyApp\BranchNewFeature.</p> <p>I developed and when I decided that it was time to test it was like i hadn't done any changes at all. I hit F5 and i see the baseline version of the app... Looking into it I noticed a very curious fact: When i check IIS Express the "launch path" for the applications is the old one (c:\Dev\MyApp\Main).</p> <p>Can anyone help me make IIS Express point to the new path? (C:\Dev\MyApp\BranchNewFeature)</p>
16,619,659
7
7
null
2013-04-04 17:58:47.93 UTC
9
2016-10-14 13:15:40.09 UTC
2013-05-18 00:49:17.723 UTC
null
2,069
null
505,990
null
1
21
iis|version-control|visual-studio-2012|iis-express
13,197
<p>I ran into the same issue. To fix it, I used <a href="https://stackoverflow.com/users/1443490/cheesemacfly">cheesemacfly</a>'s suggestion, to update <code>C:\Users\%USERNAME%\Documents\IISExpress\config\applicationhost.config</code> to point to the new directory.</p> <p>The obvious downside with this solution is that you need to do this repeatedly if you plan on switching between your new branches often. Seems like a bug in VS2012...</p>
35,789,520
How do I put object to amazon s3 using presigned url?
<p>I am trying to use signed url to upload images to s3 bucket. Following is my bucket policy: </p> <pre><code>{ "Version": "2012-10-17", "Statement": [ { "Sid": "", "Effect": "Allow", "Principal": { "AWS": [ "arn:aws:iam::12345678:user/myuser", "arn:aws:iam::12345678:root" ] }, "Action": [ "s3:List*", "s3:Put*", "s3:Get*" ], "Resource": [ "arn:aws:s3:::myBucket", "arn:aws:s3:::myBucket/*" ] } ] } </code></pre> <p>I am generating the signed url from the server as follows:</p> <pre><code>var aws = require('aws-sdk'); aws.config = { accessKeyId: myAccessKeyId, secretAccessKey: mySecretAccessKey }; var s3 = new aws.s3(); s3.getSignedUrl('putObject', { Bucket: 'myBucket', Expires: 60*60, key: 'myKey' }, function (err, url) { console.log(url); }); </code></pre> <p>I get the url. But when I try to put an object I get the following error: </p> <pre><code>&lt;Error&gt; &lt;Code&gt;AccessDenied&lt;/Code&gt; &lt;Message&gt;Access Denied&lt;/Message&gt; &lt;RequestId&gt;FXXXXXXXXX&lt;/RequestId&gt; &lt;HostId&gt;fXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&lt;/HostId&gt; &lt;/Error&gt; </code></pre> <p><strong>Update 1</strong></p> <p>Here is myuser's policy:</p> <pre><code>{ "Version": "2012-10-17", "Statement": [ { "Sid": "", "Effect": "Allow", "Principal": { "AWS": [ "arn:aws:iam::2xxxxxxxxxxx:user/myuser", "arn:aws:iam::2xxxxxxxxxxx:root" ] }, "Action": [ "s3:*" ], "Resource": [ "arn:aws:s3:::myBucket", "arn:aws:s3:::myBucket/*" ] } ] } </code></pre> <p><strong>Update 2</strong> I can upload only when following option is set. I dont understand whats the use of bucket policy if only the manual selection of permission work. </p> <p><a href="https://i.stack.imgur.com/zJ0iI.png" rel="noreferrer"><img src="https://i.stack.imgur.com/zJ0iI.png" alt="Permission for everyone"></a></p> <p><strong>Update 3</strong> </p> <p>The following code works. Now the only problem is the signed url</p> <pre><code> #!/bin/bash file="$1" bucket="mybucket" resource="/${bucket}/${file}" contentType="image/png" dateValue=`date -R` stringToSign="PUT\n\n${contentType}\n${dateValue}\n${resource}" s3Key="AKxxxxxxxxxxxxxxxxx" s3Secret="/Wuxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" signature=`echo -en ${stringToSign} | openssl sha1 -hmac ${s3Secret} -binary | base64` curl -X PUT -T "${file}" \ -H "Host: ${bucket}.s3.amazonaws.com" \ -H "Date: ${dateValue}" \ -H "Content-Type: ${contentType}" \ -H "Authorization: AWS ${s3Key}:${signature}" \ https://${bucket}.s3.amazonaws.com/${file} </code></pre>
35,923,104
5
7
null
2016-03-04 06:35:52.243 UTC
9
2021-03-04 06:22:57.127 UTC
2016-03-09 18:37:13.633 UTC
null
3,698,232
null
3,698,232
null
1
28
javascript|node.js|amazon-web-services|amazon-s3|pre-signed-url
28,999
<p>I managed to succesfully upload a file by using your code. </p> <p>Here are the steps I followed:</p> <ol> <li><p>Created a new bucket and a new IAM user</p></li> <li><p>Set IAM user's policy as below:</p> <pre><code>{ "Version": "2012-10-17", "Statement": [ { "Sid": "Stmt1418647210000", "Effect": "Allow", "Action": [ "s3:Put*" ], "Resource": [ "arn:aws:s3:::myBucket/*" ] } ] } </code></pre></li> <li><p>Did NOT create a bucket policy</p></li> <li><p>Used your code to generate the pre-signed URL:</p> <pre><code>var aws = require('aws-sdk'); aws.config = { accessKeyId: myAccessKeyId, secretAccessKey: mySecretAccessKey }; var s3 = new aws.s3(); s3.getSignedUrl('putObject', { Bucket: 'myBucket', Expires: 60*60, Key: 'myKey' }, function (err, url) { console.log(url); }); </code></pre></li> <li><p>Copied the URL on the screen and used curl to test the upload as below:</p> <pre><code>curl.exe -k -X PUT -T "someFile" "https://myBucket.s3.amazonaws.com/myKey?AWSAccessKeyId=ACCESS_KEY_ID&amp;Expires=1457632663&amp;Signature=Dhgp40j84yfjBS5v5qSNE4Q6l6U%3D" </code></pre></li> </ol> <p>In my case it generally took 5-10 seconds for the policy changes to take effect so if it fails the first time make sure to keep sending it for a while.</p> <p>Hope this helps.</p>
10,743,622
ConcurrentHashMap: avoid extra object creation with "putIfAbsent"?
<p>I am aggregating multiple values for keys in a multi-threaded environment. The keys are not known in advance. I thought I would do something like this:</p> <pre><code>class Aggregator { protected ConcurrentHashMap&lt;String, List&lt;String&gt;&gt; entries = new ConcurrentHashMap&lt;String, List&lt;String&gt;&gt;(); public Aggregator() {} public void record(String key, String value) { List&lt;String&gt; newList = Collections.synchronizedList(new ArrayList&lt;String&gt;()); List&lt;String&gt; existingList = entries.putIfAbsent(key, newList); List&lt;String&gt; values = existingList == null ? newList : existingList; values.add(value); } } </code></pre> <p>The problem I see is that every time this method runs, I need to create a new instance of an <code>ArrayList</code>, which I then throw away (in most cases). This seems like unjustified abuse of the garbage collector. Is there a better, thread-safe way of initializing this kind of a structure without having to <code>synchronize</code> the <code>record</code> method? I am somewhat surprised by the decision to have the <code>putIfAbsent</code> method not return the newly-created element, and by the lack of a way to defer instantiation unless it is called for (so to speak).</p>
10,743,710
7
3
null
2012-05-24 18:54:25.49 UTC
21
2017-08-11 09:55:26.997 UTC
2015-04-02 14:04:55.297 UTC
user166390
146,197
null
389,051
null
1
42
java|synchronization|thread-safety|concurrenthashmap
18,953
<p>Java 8 introduced an API to cater for this exact problem, making a 1-line solution:</p> <pre><code>public void record(String key, String value) { entries.computeIfAbsent(key, k -&gt; Collections.synchronizedList(new ArrayList&lt;String&gt;())).add(value); } </code></pre> <p>For Java 7:</p> <pre><code>public void record(String key, String value) { List&lt;String&gt; values = entries.get(key); if (values == null) { entries.putIfAbsent(key, Collections.synchronizedList(new ArrayList&lt;String&gt;())); // At this point, there will definitely be a list for the key. // We don't know or care which thread's new object is in there, so: values = entries.get(key); } values.add(value); } </code></pre> <p>This is the standard code pattern when populating a <code>ConcurrentHashMap</code>.</p> <p>The special method <a href="http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ConcurrentMap.html#putIfAbsent%28K,%20V%29" rel="noreferrer"><code>putIfAbsent(K, V))</code></a> will either put your value object in, or if another thread got before you, then it will ignore your value object. Either way, after the call to <code>putIfAbsent(K, V))</code>, <code>get(key)</code> is guaranteed to be consistent between threads and therefore the above code is threadsafe.</p> <p>The only wasted overhead is if some other thread adds a new entry at the same time for the same key: You <em>may</em> end up throwing away the newly created value, but that only happens if there is not already an entry <em>and</em> there's a race that your thread loses, which would typically be rare.</p>
10,817,721
Wipe data/Factory reset through ADB
<p>Basically this is my problem/</p> <p>I have 200+ phones running stock Android that need to be wiped (in the Wipe Data/Factory Reset way) and then a new ROM installed with some additional apks.</p> <p>Currently I've got everything automated except the Wipe Data part. Everything else can be done through a .bat with a set of commands quite happily but I cannot for the life of me work out how to either imitate or force the recovery mode to wipe the data.</p> <p>Things I've currently tried:</p> <ul> <li>Wiping the data myself using rm -r * on the folders it's supposed to do (data,cache,sd-ext etc.). This does wipe but then the ROM doesn't work properly and gets stuck in a bootloop.</li> <li>Trying to use "adb input keyevent" to mimic the key presses. I have no idea what they are mapped to because they are in a UNIX shell basically and even then there is no "input" because the OS hasn't been loaded anyway.</li> <li>Trying to find the file/script on the system that actually runs the wipe/reset and then running that manually. This might be the simplest way as it's already been written for me somewhere but I just cannot see where it is hidden, even in something like CWM.</li> </ul> <p>If anyone has got any method whereby I could do this factory reset through a .bat or through the adb shell I would greatly appreciate it. Been trying to solve this for about 2 days now with little progress.</p>
10,829,600
1
5
null
2012-05-30 13:52:53.803 UTC
20
2014-03-20 15:57:10.22 UTC
null
null
null
null
1,267,231
null
1
60
android|adb|reset|recovery
324,689
<p>After a lot of digging around I finally ended up downloading the source code of the recovery section of Android. Turns out you can actually send commands to the recovery.</p> <pre><code> * The arguments which may be supplied in the recovery.command file: * --send_intent=anystring - write the text out to recovery.intent * --update_package=path - verify install an OTA package file * --wipe_data - erase user data (and cache), then reboot * --wipe_cache - wipe cache (but not user data), then reboot * --set_encrypted_filesystem=on|off - enables / diasables encrypted fs </code></pre> <p>Those are the commands you can use according to the one I found but that might be different for modded files. So using adb you can do this:</p> <pre><code>adb shell recovery --wipe_data </code></pre> <p>Using --wipe_data seemed to do what I was looking for which was handy although I have not fully tested this as of yet.</p> <p>EDIT:</p> <p>For anyone still using this topic, these commands may change based on which recovery you are using. If you are using Clockword recovery, these commands should still work. You can find other commands in /cache/recovery/command</p> <p>For more information please see here: <a href="https://github.com/CyanogenMod/android_bootable_recovery/blob/cm-10.2/recovery.c" rel="noreferrer">https://github.com/CyanogenMod/android_bootable_recovery/blob/cm-10.2/recovery.c</a></p>
31,748,575
How to access the Component on a Angular2 Directive?
<p>I'm doing some tests with Angular 2 and I have a directive (layout-item) that can be applied to all my components.</p> <p>Inside that directive I want to be able to read some metadata defined on the component but for that I need to access the component's reference.</p> <p>I have tried the following approach but I was unable to get what I need. Does any one has a suggestion?</p> <pre><code>@Component({...}) @View({...}) @MyAnnotation({...}) export class MyComponentA {...} // Somewhere in a template &lt;myComponentA layout-item="my config 1"&gt;&lt;/myComponentA&gt; &lt;myComponentB layout-item="my config 2"&gt;&lt;/myComponentA&gt; // ---------------------- @ng.Directive({ selector: "[layout-item]", properties: [ "strOptions: layout-item" ], host: { } }) export class LayoutItem { // What works constructor(@Optional() @Ancestor({self: true}) private component: MyComponent1) { // with the constructor defined like this, component is defined with myComponent1 instance. Reflector.getMetadata("MyAnnotation", component.constructor); // &gt; metadata is here! } // What I needed constructor(@Optional() @Ancestor({self: true}) private component: any) { // This will crash the app. If instead of any I specify some other type, the app will not crash but component will be null. // This directive can be applied to any component, so specifying a type is not a solution. } } </code></pre>
31,796,289
6
3
null
2015-07-31 14:25:47.933 UTC
13
2021-06-13 11:16:37.123 UTC
2018-08-13 04:26:17.713 UTC
user6749601
null
null
1,613,980
null
1
16
typescript|angular
26,524
<p><strong>UPDATE</strong>:</p> <p>Since Beta 16 there is no official way to get the same behavior. There is an unofficial workaround here: <a href="https://github.com/angular/angular/issues/8277#issuecomment-216206046" rel="nofollow">https://github.com/angular/angular/issues/8277#issuecomment-216206046</a></p> <hr> <p>Thanks @Eric Martinez, your pointers were crucial in getting me in the right direction!</p> <p>So, taking Eric's approach, I have managed to do the following:</p> <p><strong>HTML</strong></p> <pre><code>&lt;my-component layout-item="my first component config"&gt;&lt;/my-component&gt; &lt;my-second-component layout-item="my second component config"&gt;&lt;/my-second-component&gt; &lt;my-third-component layout-item="my third component config"&gt;&lt;/my-third-component&gt; </code></pre> <p>Three different components, all of the share the same <code>layout-item</code> attribute.</p> <p><strong>Directive</strong></p> <pre><code>@Directive({ selector : '[layout-item]' }) export class MyDirective { constructor(private _element: ElementRef, private _viewManager: AppViewManager) { let hostComponent = this._viewManager.getComponent(this._element); // on hostComponent we have our component! (my-component, my-second-component, my-third-component, ... and so on! } } </code></pre>
33,575,109
MySQL - Entity : The value for column 'IsPrimaryKey' in table 'TableDetails' is DBNull
<p>I am using <strong>Visual Studio 2013</strong> with <strong>Entity Framework 5</strong> and M<strong>ySQL Server 5.7.9</strong>.</p> <p>When trying to create a Model from the database (<em>or 'Update Model From Database'</em>) the following message appears:</p> <blockquote> <p>'System.Data.StrongTypingException: The value for column 'IsPrimaryKey' in table 'TableDetails' is DBNull . ---> System.InvalidCastException: Specified cast is not valid.</p> </blockquote> <p>I know that this question has been asked before, but i haven't find any solution. Also i don't have the option of downgrading to MySQL 5.6.</p> <p>The problem occurs even for a simple table.</p> <p>The sample table</p> <pre><code>CREATE TABLE new_table ( id int(11) NOT NULL AUTO_INCREMENT, name varchar(45) NOT NULL, PRIMARY KEY (id) ) ENGINE = InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; </code></pre> <p>If the table consists only from the Primary Key then the model is being created as it should.</p> <p><strong>EDIT:</strong> If i make both the fields PRIMARY Keys the model is being created without any errors.</p> <p>Does anyone have any idea about this?</p> <p>Kind Regards.</p> <p>The full error stack:</p> <blockquote> <p>Unable to generate the model because of the following exception: 'System.Data.StrongTypingException: The value for column 'IsPrimaryKey' in table 'TableDetails' is DBNull. ---> System.InvalidCastException: Specified cast is not valid. at Microsoft.Data.Entity.Design.VersioningFacade.ReverseEngineerDb.SchemaDiscovery.TableDetailsRow.get_IsPrimaryKey() --- End of inner exception stack trace --- at Microsoft.Data.Entity.Design.VersioningFacade.ReverseEngineerDb.SchemaDiscovery.TableDetailsRow.get_IsPrimaryKey() at Microsoft.Data.Entity.Design.VersioningFacade.ReverseEngineerDb.StoreModelBuilder.CreateProperties(IList<code>1 columns, IList</code>1 errors, List<code>1&amp; keyColumns, List</code>1&amp; excludedColumns, List<code>1&amp; invalidKeyTypeColumns) at Microsoft.Data.Entity.Design.VersioningFacade.ReverseEngineerDb.StoreModelBuilder.CreateEntityType(IList</code>1 columns, Boolean&amp; needsDefiningQuery) at Microsoft.Data.Entity.Design.VersioningFacade.ReverseEngineerDb.StoreModelBuilder.CreateEntitySets(IEnumerable<code>1 tableDetailsRows, EntityRegister entityRegister, IList</code>1 entitySetsForReadOnlyEntityTypes, DbObjectType objectType) at Microsoft.Data.Entity.Design.VersioningFacade.ReverseEngineerDb.StoreModelBuilder.CreateEntitySets(IEnumerable<code>1 tableDetailsRowsForTables, IEnumerable</code>1 tableDetailsRowsForViews, EntityRegister entityRegister) at Microsoft.Data.Entity.Design.VersioningFacade.ReverseEngineerDb.StoreModelBuilder.Build(StoreSchemaDetails storeSchemaDetails) at Microsoft.Data.Entity.Design.VisualStudio.ModelWizard.Engine.ModelGenerator.CreateStoreModel() at Microsoft.Data.Entity.Design.VisualStudio.ModelWizard.Engine.ModelGenerator.GenerateModel(List<code>1 errors) at Microsoft.Data.Entity.Design.VisualStudio.ModelWizard.Engine.ModelBuilderEngine.GenerateModels(String storeModelNamespace, List</code>1 errors) at Microsoft.Data.Entity.Design.VisualStudio.ModelWizard.Engine.ModelBuilderEngine.GenerateModel(EdmxHelper edmxHelper)'. Loading metadata from the database took 00:00:00.5856317.</p> </blockquote>
35,422,569
11
5
null
2015-11-06 20:21:19.617 UTC
40
2017-12-26 08:29:15.457 UTC
2015-11-06 21:26:54.11 UTC
null
1,669,037
null
1,669,037
null
1
53
c#|mysql|entity-framework
60,099
<p>Entity Framework (version 6.1.3) and MySQL Server (>= 5.7.6)</p> <p>One way to resolve the issue is,</p> <pre><code>1. Open Services (services.msc) and restart MySQL57 service. 2. Execute the following commands in MySQL. use &lt;&lt;database name&gt;&gt;; set global optimizer_switch='derived_merge=OFF'; 3. Update the .edmx. </code></pre> <p>It's a late reply. But hope it will help somebody.</p> <p>Thanks.</p>
13,729,788
Very large single page application design problems
<p>I am currently writing whats going to be a very, very large single page web/javascript application.</p> <p>Technologies I am using are ASP.NET MVC4, jquery, knockout.js and amplify.js.</p> <p>The problem I am having is that most if not all of the single page application examples are for smaller applications where having all of the script templates (be it jquery, handlbars, etc...) are all in the same file along with the rest of the html code. This is fine for smaller apps but the application I am building is an entire maintenance logistics application with many, many, many screens.</p> <p>The approach I took so far is I have an outer shell (my main index.cshtml file) and I am using jquery's load() method to load or rather inject the particular file I need when a user makes a certain selection.</p> <p>example:</p> <pre><code>function handleLoginClick(){ App.mainContentContainer.delegate('#btnLogin', 'click', function() { App.loadModule('Home/ProductionControlMenu', App.MainMenuView.render()); }); } </code></pre> <p>here's the code for the App.loadModule function:</p> <pre><code>App.loadModule = function(path, callback){ App.mainContentContainer.load(App.siteRoot + path, callback); }; </code></pre> <p>All was going well until I needed to actually start interacting with the various form elements on the newly loaded screen. jquery can't seem to get a handle on them directly. I can't use .live() or .delegate() because they aren't events, they are textboxes and buttons and sometimes I need to change their css classes.</p> <p>They only way I found is to get a handle on an element from the outer shell (something that wasn't loaded via .load() ) and use jquery's .find() method like so:</p> <pre><code> App.mainContentContainer.find('#btnLogin').addClass('disabled'); </code></pre> <p>clearly I don't want to have to do something like this everytime I need to interact with or even retrieve values from a form element.</p> <p>Does anybody have any ideas as to how I can create a maintainable very large single page application with potentially hundreds of .html files without having to have all that html code located in a single file and still get around this .load() issue I am having?</p> <p>Any thoughts would be greatly appreciated. :-)</p> <p>V/R</p> <p>Chris</p> <p><strong>UPDATE</strong></p> <p>I thought I'd post an update and as to how things went and what worked. After much research I decided to go with Google's AngularJS Javascript framework. It simplified the ordeal exponentially and I would definitely, definitely advise all who are looking into making a large SPA to give it a look.</p> <p>Links: </p> <p>Main Site <a href="http://angularjs.org/">http://angularjs.org/</a></p> <p>Awesome free short videos on Angular: <a href="http://www.egghead.io/">http://www.egghead.io/</a></p>
13,730,376
8
2
null
2012-12-05 18:18:01.157 UTC
10
2017-05-24 22:01:20.937 UTC
2013-06-25 15:40:06.657 UTC
null
825,559
null
825,559
null
1
9
javascript|jquery|asp.net-mvc-4|angularjs|singlepage
16,208
<p>This is actually a very complicated question as it really gets down to the design of your architecture.</p> <p>For large-scale single-page applications, it's best to use some sort of front-end MV* style framework such as <a href="http://backbonejs.org" rel="noreferrer">backbone.js</a>, which ties in to jQuery quite usefully. You should also think about using some sort of dependency management framework such as <a href="http://requirejs.org/" rel="noreferrer">require.js</a> in order to load your scripts and dependencies asynchronously, and even better -- use the AMD pattern in your application design to make your architecture modular and easier to manage.</p> <p>As far as how this relates to your MVC4 project, you have some options:</p> <ol> <li>Do you want to use MVC as a "service layer" of sorts, that simply returns JSON objects, allowing your front-end to do the markup/template creation (think <a href="http://handlebarsjs.com/" rel="noreferrer">handlebars.js</a>), or</li> <li>Do you want your MVC project to return partial views (HTML) as a response, where you leverage the Razor templating system and simply use the front end to display what comes back from the server? </li> </ol> <p>Either way, you will have to devise a way to handle front-end events and navigation (backbone provides both of these things when coupled with jQuery). Even more complicated is the pattern you choose to notify one view of another view's activities (there are many ways to do this) -- a publish/subscribe pattern for example.</p> <p>I hope I have helped a bit, I know I'm not fully answering the question, but the answer could get really long!</p>
13,787,258
PyCrypto install error on Windows
<p>I am trying to install <a href="http://pypi.python.org/pypi/pycrypto/2.6" rel="noreferrer">PyCrypto 2.6</a> Library on my computer. But I keep getting the following error</p> <pre><code>D:\Software\Python\package\pycrypto-2.6&gt;python setup.py build running build running build_py running build_ext warning: GMP or MPIR library not found; Not building Crypto.PublicKey._fastmath. building 'Crypto.Random.OSRNG.winrandom' extension error: Unable to find vcvarsall.bat </code></pre> <p>My System has Windows 8 Pro 64-bit, Visual Studio Enterprise 2012 and Python 3.3</p> <p>To fix the error I tried to set the Environment Variable <code>VS90COMNTOOLS=%VS110COMNTOOLS%</code> as advised by <a href="https://stackoverflow.com/a/10558328/777593">fmuecke in the post error: Unable to find vcvarsall.bat</a> but it didn't work for me.</p> <p>Can any one please advise me how to fix this error.</p> <p>FYI, I don't to install VC2008 etc..</p>
13,787,598
9
3
null
2012-12-09 12:09:12.137 UTC
3
2021-11-03 15:10:17.027 UTC
2017-05-23 11:54:55.323 UTC
null
-1
null
777,593
null
1
16
python|python-3.x|distutils|pycrypto
43,931
<p>I managed to install PyCrypto 2.6 by using the <a href="http://www.voidspace.org.uk/downloads/pycrypto26/pycrypto-2.6.win-amd64-py3.3.exe" rel="noreferrer">prebuilt binary for Python3.3</a> from <a href="http://www.voidspace.org.uk/python/modules.shtml#pycrypto" rel="noreferrer">The Voidspace Python Modules</a>.</p> <p>It doesn't actually fix the <code>error: Unable to find vcvarsall.bat</code> for other package which don't have a prebuilt binaries available.</p> <p>However it eliminates the need to build PyCrypto package, allowing me to install PyCrypto on my system without getting the error.</p>
13,556,885
How to change the executable output directory for Win32 builds, in CMake?
<p>My problem is as such : I'm developing a small parser using Visual Studio 2010. I use CMake as a build configuration tool.</p> <p>But I find the default executable building behaviour, inconvenient. What I want is, have my final program be located in :</p> <pre><code>E:/parsec/bin/&lt;exe-name&gt;.&lt;build-type&gt;.exe </code></pre> <p>rather than</p> <pre><code>E:/parsec/bin/&lt;build-type&gt;/&lt;exe-name&gt;.exe </code></pre> <p>How would you do that using CMake ?</p>
13,562,211
2
0
null
2012-11-25 23:51:38.09 UTC
8
2012-11-26 09:47:04.657 UTC
null
null
null
null
683,913
null
1
18
c++|visual-studio|cmake
35,023
<p>There are several options:</p> <ol> <li>Copy the executable after building</li> <li>Customizing the output-directory for your executable(s)</li> </ol> <h2>Copy the executable after building</h2> <p>After a succesful build you can copy the executable (see Beginners answer), but perhaps it is nicer to use an install target: </p> <p>Use the <a href="http://www.cmake.org/cmake/help/v2.8.10/cmake.html#command:install" rel="noreferrer">install</a> command to specify targets (executables, libraries, headers, etc.) which will be copied to the <a href="http://www.cmake.org/cmake/help/v2.8.10/cmake.html#variable:CMAKE_INSTALL_PREFIX" rel="noreferrer">CMAKE_INSTALL_PREFIX</a> directory. You can specify the CMAKE_INSTALL_PREFIX on the commandline of cmake (or in the cmake GUI).</p> <h2>Customizing the output-directory for your executable(s)</h2> <p><strong>Warning:</strong> It is not advised to set absolute paths directly in your cmakelists.txt.</p> <p>Use <a href="http://www.cmake.org/cmake/help/v2.8.10/cmake.html#command:set_target_properties" rel="noreferrer">set_target_properties</a> to customize the <a href="http://www.cmake.org/cmake/help/v2.8.10/cmake.html#prop_tgt:RUNTIME_OUTPUT_DIRECTORY" rel="noreferrer">RUNTIME_OUTPUT_DIRECTORY</a> </p> <pre><code>set_target_properties( yourexe PROPERTIES RUNTIME_OUTPUT_DIRECTORY E:/parsec/bin/ ) </code></pre> <p>As an alternative, modifying the <a href="http://www.cmake.org/cmake/help/v2.8.10/cmake.html#variable:CMAKE_RUNTIME_OUTPUT_DIRECTORY" rel="noreferrer">CMAKE_RUNTIME_OUTPUT_DIRECTORY</a> allows you to specify this for <strong>all</strong> targets in the cmake project. Take care that you modify the <a href="http://www.cmake.org/cmake/help/v2.8.10/cmake.html#variable:CMAKE_LIBRARY_OUTPUT_DIRECTORY" rel="noreferrer">CMAKE_LIBRARY_OUTPUT_DIRECTORY</a> as well when you build dlls.</p> <pre><code>set( CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin ) set( CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib ) </code></pre> <p><strong>Additional info</strong>: Take a look at these questions: </p> <ul> <li><p><a href="https://stackoverflow.com/questions/7747857/in-cmake-how-do-i-work-around-the-debug-and-release-directories-visual-studio-2">In CMake, how do I work around the Debug and Release directories Visual Studio 2010 tries to add?</a></p></li> <li><p><a href="https://stackoverflow.com/questions/6561754/cmake-changing-name-of-visual-studio-and-xcode-exectuables-depending-on-config">CMake : Changing name of Visual Studio and Xcode exectuables depending on configuration in a project generated by CMake</a></p></li> <li><p><a href="https://stackoverflow.com/questions/8848268/how-to-not-add-release-or-debug-to-output-path">How to not add Release or Debug to output path?</a></p></li> </ul>
13,487,625
Overlaying two graphs using ggplot2 in R
<p>I have two graphs and I am trying to overlay one on top of the other:</p> <p>An example of the data frame "ge" looks like this. In actuality there are 10 Genes with 200 samples each, so there are 2000 rows and 3 columns:</p> <pre><code>Exp Gene Sample 903.0 1 1 1060.0 1 2 786.0 1 3 736.0 1 4 649.0 2 1 657.0 2 2 733.5 2 3 774.0 2 4 </code></pre> <p>An example of the data frame "avg" looks like this. This is an average of the data points for each gene across all samples. In actuality this graph has 10 genes, so the matrix is 4col X 10 rows:</p> <pre><code>mean Gene sd se 684.2034 1 102.7142 7.191435 723.2892 2 100.6102 7.044122 </code></pre> <p>The first graph graphs a line of the average expression for each gene along with the standard deviation for each data point.</p> <pre><code>avggraph &lt;- ggplot(avg, aes(x=Gene, y=mean)) + geom_point() +geom_line() + geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd), width=.1) </code></pre> <p>The second graph graphs the gene expression in the form a line for each sample across all the genes.</p> <pre><code>linegraphs &lt;- ggplot(ge, aes(x=Gene, y=Expression, group=Samples, colour="#000099")) + geom_line() + scale_x_discrete(limits=flevels.tge) </code></pre> <p>I would like to superimpose <strong>avggraph</strong> on top of <strong>linegraphs</strong>. Is there a way to do this? I've tried avggraph + linegraphs but I'm getting an error. I think this is because the graphs are generated by two different data frames.</p> <p>I should also point out that the axes of both graphs are the same. Both graphs have the genes on the X-axis and the gene expression on the Y-axis.</p> <p>Any help would be greatly appreciated!</p>
13,488,046
2
0
null
2012-11-21 06:32:13.957 UTC
8
2018-07-02 18:45:56.063 UTC
2012-11-21 07:03:42.82 UTC
null
1,342,339
null
1,342,339
null
1
27
r|graph|ggplot2
98,717
<p>One way is to add the <code>geom_line</code> command for the second plot to the first plot. You need to tell <code>ggplot</code> that this geom is based on a different data set:</p> <pre><code>ggplot(avg, aes(x=Gene, y=mean)) + geom_point() + geom_line() + geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd), width=.1) + geom_line(data = ge, aes(x=Gene, y=Exp, group=Sample, colour="#000099"), show_guide = FALSE) </code></pre> <p>The last <code>geom_line</code> command is for creating the lines based on the raw data. <img src="https://i.stack.imgur.com/qZykU.png" alt="enter image description here"></p>
13,525,140
How to solve the "TypeError: array.splice is not a function" when 'var array = {}'?
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/208105/how-to-remove-a-property-from-a-javascript-object">How to remove a property from a javascript object</a><br> <a href="https://stackoverflow.com/questions/368280/javascript-hashmap-equivalent">JavaScript Hashmap Equivalent</a> </p> </blockquote> <p>I am using jQuery and I am handling a variable this way:</p> <pre><code>var array = {}; array[an_object] = something array[another_object] = something_else array[...] = ... </code></pre> <p>When I try to run the <a href="http://www.w3schools.com/jsref/jsref_splice.asp" rel="noreferrer"><code>splice</code></a> method on the <code>array</code> I get a <code>TypeError: array.splice is not a function</code>. <em>My intent is to remove the <code>an_object</code> "key" and all its content from the <code>array</code> variable.</em></p> <p>How can I make that? </p> <hr> <p><em>Note</em>: When I run the <code>console.log(array[an_object])</code> (the same is valid for <code>another_object</code> and all other objects) I get:</p> <pre><code>[Object { label="str1", value=1 }, Object { label="str2", value=2 }, { label="strN", value=N }] </code></pre>
13,525,373
5
9
null
2012-11-23 08:09:11.717 UTC
3
2015-08-03 10:55:42.853 UTC
2017-05-23 12:26:23.81 UTC
null
-1
null
920,796
null
1
40
javascript|jquery|arrays
107,645
<p>First of all, name your variables what they are. The name <code>array</code> you're using, is misleading if you use it to create a object.</p> <pre><code>var myObject = {}; myObject[an_object] = "xyz"; myObject[another_object] = "abc"; </code></pre> <p>Now, you can delete the entry in the object with the <code>delete</code> statement:</p> <pre><code>delete myObject[an_object]; // Returns true / false if the deletion is a success / failure console.log(myObject[an_object]) // Returns undefined </code></pre> <hr> <p>Now, that said, this will not work like you'd expect. <code>myObject[an_object]</code> will contain "abc"<br> Don't use objects as keys. Use strings, instead.<br> This is because of the fact that any parameter entered in the <code>[]</code> will be converted to string. So actually, you're entering <code>myObject["[object Object]"]</code></p>
13,648,515
Why doesn't $.each() iterate through every item?
<p>I have the following markup containing 10 <code>pre</code> elements with the class <code>indent</code>:</p> <pre><code>​&lt;pre class="indent"&gt;&lt;/pre&gt; &lt;pre class="indent"&gt;&lt;/pre&gt; &lt;pre class="indent"&gt;&lt;/pre&gt; &lt;pre class="indent"&gt;&lt;/pre&gt; &lt;pre class="indent"&gt;&lt;/pre&gt; &lt;pre class="indent"&gt;&lt;/pre&gt; &lt;pre class="indent"&gt;&lt;/pre&gt; &lt;pre class="indent"&gt;&lt;/pre&gt; &lt;pre class="indent"&gt;&lt;/pre&gt; &lt;pre class="indent"&gt;&lt;/pre&gt;​ </code></pre> <p>I'm using the following jQuery <code>.each()</code> function to iterate through each element:</p> <pre><code>​$(function(){ $.each(".indent", function(index){ alert(index); }); });​ </code></pre> <p>I would expect to see 10 alerts, however I only see 7</p> <p><a href="http://jsfiddle.net/6nzw9/" rel="noreferrer"><strong>-- See Fiddle --</strong></a></p> <hr> <p>However, this works as expected with <code>$(".indent").each()</code>:</p> <pre><code>$(function(){ $(".indent").each(function(index){ alert(index); }); });​ </code></pre> <p><a href="http://jsfiddle.net/6nzw9/" rel="noreferrer"><strong>-- See Fiddle --</strong></a></p> <hr> <p>Looking at the <code>$.each()</code> documentation, I understand theres a difference:</p> <blockquote> <p>The $.each() function is not the same as $(selector).each(), which is used to iterate, exclusively, over a jQuery object.</p> </blockquote> <p>But I don't understand why in this instance, it doesn't iterate through all elements.</p> <p>Why is this happening?</p>
13,648,529
3
4
null
2012-11-30 15:50:29.41 UTC
5
2013-09-09 11:51:48.793 UTC
2012-12-03 12:08:55.63 UTC
null
263,525
null
370,103
null
1
54
javascript|iteration|jquery
3,225
<pre><code>$.each(".indent", function(index){ </code></pre> <p>doesn't iterate over the elements of <code>$('.indent')</code> but over the <code>".indent"</code> string whose length is 7 chars.</p> <p>See <a href="http://api.jquery.com/jQuery.each/" rel="noreferrer">reference</a></p> <hr> <p><strong>A more detailed explanation based on <a href="http://code.jquery.com/jquery-latest.js" rel="noreferrer">jQuery source code</a> :</strong></p> <p>jQuery first checks if the first parameter, <code>obj</code> (here your string), has a <code>length</code> :</p> <pre><code>var ... length = obj.length, isObj = length === undefined || jQuery.isFunction( obj ); </code></pre> <p>Your string having a <code>length</code> (and not being a function), <code>isObj</code> is <code>false</code>.</p> <p>In this case, the following code is executed :</p> <pre><code>for ( ; i &lt; length; ) { if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) { break; } } </code></pre> <p>So, given the function <code>f</code>, the following code</p> <pre><code>$.each(".indent", f); </code></pre> <p>is equivalent to</p> <pre><code>for (var i=0; i&lt;".indent".length; i++) { var letter = ".indent"[i]; f.call(letter, i, letter); } </code></pre> <p>(you can log the letters using <code>var f = function(i,v){console.log(v)};</code> or be reminded one of the subtleties of <code>call</code> using <code>var f = function(){console.log(this)};</code>)</p>
13,372,179
Creating a folder when I run file_put_contents()
<p>I have uploaded a lot of images from the website, and need to organize files in a better way. Therefore, I decide to create a folder by months.</p> <pre><code>$month = date('Yd') file_put_contents("upload/promotions/".$month."/".$image, $contents_data); </code></pre> <p>after I tried this one, I get error result.</p> <blockquote> <p>Message: file_put_contents(upload/promotions/201211/ang232.png): failed to open stream: No such file or directory</p> </blockquote> <p>If I tried to put only file in exist folder, it worked. However, it failed to create a new folder. </p> <p>Is there a way to solve this problem?</p>
13,372,192
6
0
null
2012-11-14 02:28:31.53 UTC
13
2022-02-08 15:23:52.043 UTC
2014-12-01 16:37:47.283 UTC
null
2,264,626
null
1,454,031
null
1
78
php
72,864
<p><a href="http://us1.php.net/file_put_contents" rel="noreferrer"><code>file_put_contents()</code></a> does not create the directory structure. Only the file.</p> <p>You will need to add logic to your script to test if the <em>month</em> directory exists. If not, use <a href="http://us1.php.net/mkdir" rel="noreferrer"><code>mkdir()</code></a> first.</p> <pre><code>if (!is_dir('upload/promotions/' . $month)) { // dir doesn't exist, make it mkdir('upload/promotions/' . $month); } file_put_contents('upload/promotions/' . $month . '/' . $image, $contents_data); </code></pre> <p><strong>Update:</strong> <code>mkdir()</code> accepts a third parameter of <code>$recursive</code> which will create <em>any</em> missing directory structure. Might be useful if you need to create multiple directories.</p> <p>Example with recursive and directory permissions set to 777:</p> <pre><code>mkdir('upload/promotions/' . $month, 0777, true); </code></pre>
24,245,230
'http-server' is not recognized as an internal or external command
<p>After installing angular-seed project, i did the following steps:</p> <p>Cloned the repository : </p> <blockquote> <p>git clone <a href="https://github.com/angular/angular-seed.git">https://github.com/angular/angular-seed.git</a> </p> <p>cd angular-seed</p> </blockquote> <p>Then I ran npm install</p> <p>at the end of the install i get:</p> <blockquote> <blockquote> <p>[email protected] prestart C:\Users\user\Documents\GitHub\comilion\angular-seed npm install</p> <p>[email protected] postinstall C:\Users\user\Documents\GitHub\myproject\angular-seed bower install</p> <p>[email protected] start C:\Users\user\Documents\GitHub\myproject\angular-seed http-server -a localhost -p 2324</p> </blockquote> <p>'http-server' is not recognized as an internal or external command, operable program or batch file.</p> <p>npm ERR! [email protected] start: <code>http-server -a localhost -p 2324</code> npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the [email protected] start script. npm ERR! This is most likely a problem with the angular-seed package, npm ERR! not with npm itself. npm ERR! Tell the author that this fails on your system: npm ERR!<br> http-server -a localhost -p 2324 npm ERR! You can get their info via: npm ERR! npm owner ls angular-seed npm ERR! There is likely additional logging output above. npm ERR! System Windows_NT 6.1.7601 npm ERR! command "C:\Program Files\nodejs\\node.exe" "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js" "start" npm ERR! cwd C:\Users\user\Documents\GitHub\myproject\angular-seed npm ERR! node -v v0.10.22 npm ERR! npm -v 1.3.14 npm ERR! code ELIFECYCLE npm ERR! npm ERR! Additional logging details can be found in: npm ERR!<br> C:\Users\user\Documents\GitHub\myproject\angular-seed\npm-debug.log</p> </blockquote> <p>please let me know if you have any suggestions how to solve this issue.</p>
24,257,994
7
2
null
2014-06-16 13:44:34.807 UTC
6
2021-06-29 04:35:41.8 UTC
null
null
null
null
345,944
null
1
20
node.js|angularjs|npm|angular-seed
55,515
<p>@BenFortune found the answer it was</p> <p>http-server needs to be installed globally with <code>npm install -g http-server</code></p>
23,950,450
Slow scroll speed down
<p>Ok, so I can't find anything about this. </p> <p>I know it is horrible to change the scroll speed of a site, but I need to do this for a site which is more a game than a site. </p> <p>Can someone tell me how to slow down de scrollspeed? Jquery or css?</p> <p>EDIT: I want to change the scrollspeed whem people scroll with the mouse wheel. </p>
23,950,885
4
3
null
2014-05-30 08:45:38.22 UTC
2
2019-12-02 09:31:59.06 UTC
2014-05-30 08:52:29.637 UTC
null
1,737,979
null
1,737,979
null
1
14
jquery|html|css|scroll
57,361
<p><a href="https://nicescroll.areaaperta.com" rel="nofollow noreferrer"><strong>NiceScroll</strong></a> Plugin</p> <p><strong>jQuery</strong></p> <pre><code>$(document).ready(function() { $("html").niceScroll(); } ); </code></pre>
3,391,585
How does an .apk files get signed
<p>This is not a question about how to sign an .apk file. I want to know what does signing actually means and how it is implemented.</p> <p>Inside the .apk file there is META-INF folder and inside that there are two files.</p> <p>First one is CERT.SF contains SHA1 hashes for various components and looks like this:</p> <pre><code>Name: res/layout/main.xml SHA1-Digest: Cox/T8fN1X9Hv4VqjH9YKqc/MsM= Name: AndroidManifest.xml SHA1-Digest: wZ418H9Aix1LNch3ci7c+cHyuZc= Name: resources.arsc SHA1-Digest: P+uoRrpFyVW6P3Wf+4vuR2ZSuXY= Name: classes.dex SHA1-Digest: cN3zXtGii9zuTOkBqDTLymeMZQI= </code></pre> <p>There is also a file called CERT.RSA. I assume it is the public key to verify the signature.</p> <p>My question is, where is the signature for the whole .apk file is stored? And what is actually signed? It could be either</p> <ul> <li>.apk file used as a single binary object and this is signed</li> <li>or CERT.SF is signed which contains individual hashes for different components</li> </ul> <p>It would be also much better if you can point me to the documentation of the detailed signing and verification process.</p>
3,391,855
2
0
null
2010-08-02 20:43:41.73 UTC
10
2012-02-21 20:48:17.287 UTC
null
null
null
null
33,885
null
1
22
android|code-signing
13,484
<p>This actually has nothing to do with Android. APK files are signed using <code>jarsigner</code>. <a href="http://www.manpagez.com/man/1/jarsigner/" rel="nofollow noreferrer">Here is a link to the manpage</a>.</p>
45,416,000
Why is the sum of an int and a float an int?
<p>Consider the following code:</p> <pre><code>float d = 3.14f; int i = 1; auto sum = d + i; </code></pre> <p>According to <a href="http://en.cppreference.com/w/c/language/conversion" rel="noreferrer">cppreference.com</a>, <code>i</code> should be converted to <code>float</code> when it is added to <code>d</code>. However, when I actually run the code, I find that <code>sum</code> is 4. Why does this happen?</p> <p>Interestingly, when I explicitly put my compiler into C11 mode, I found that <code>sum</code> was 4.14. What rules does the C11 standard change that affect the outcome?</p> <p>What would happen if I compiled the same code using a C++ compiler?</p>
45,416,095
3
8
null
2017-07-31 12:30:06.557 UTC
10
2017-08-10 12:25:57.617 UTC
2017-08-10 12:25:57.617 UTC
null
366,904
null
5,193,248
null
1
46
c++|c|type-conversion
21,052
<p>In C (and C++), <code>3.14f + 1</code> is a <code>float</code> type due to <em>type promotion</em> of <code>int</code> to <code>float</code>.</p> <p><strong>But</strong> in C, up to and including C90, and such a standard may well possibly be your C compiler default, this is assigned to an <code>int</code> type, yielding 4, since <code>int</code> is the default type for a variable with automatic storage duration. From C99 onwards, compilation will fail as implicit int was withdrawn, although compilers might still permit it, with a warning.</p> <p>(In C++11 and later, <code>auto</code> instructs the compiler to deduce the type. <code>sum</code> will be a <code>float</code> with value <code>3.14f + 1</code>. Compiling as C++98 or C++03 may still work, but generate a warning about C++11 extensions. <a href="https://gcc.godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAKxAEZSBnVAV2OUxAHIB6bgajQBbAA54ANpmJ9UwgnlQA7BiACkABgCCvPgFoAHsj5EBqEeMx8Ahgz4BhAHQCEqVAwuL3AMz591W/j66DAToKgDMACLIAJxqPjrBoZEx0fGJ4VG0tH7apoR8%2BcZCohJWNrYqAEwAQlXVjk4ubtIKXj45AWkhGch1ddEAHEHdyX01amHDSVFj1VlTPbO0ACwLozV1tABefn54CgQFBySeYqiWBAD6lsxEAG6WxBB3qHjoAJS7AOy1moHoLAARqV0L5InwwvYVuFfhpAvtDngwRE%2BNkwrDAjdjAxmIJkXxQXUCjC/IFiJgCKwFHwGHgtphUJ4IDjBJ90T5tKtBJhLEojgRSHwhtzeTYAcxgZhvhFdpoEfyTmcLpdMHphOSGLTFM9Xh9vhifOLJQT8ZDoejST55UiMqiSX8fOTKcRqbT6YyIISagU2dUOfwuTy%2BQjBcKg2KgRJpX5OO9SGIuABWTikBRcNQp1BcCobb1MVjsXyVMK0FMEdOxuMAaxAibU8a4yxTac4GdIWc4KeU9fLrdjpDgsBgiBQphKknIlGK5mIKDEvOAyzU9c84gIkmUEEu27UlDjgIrpCE3IOAHkFGIAJ6H/Dk5ByO6YZR98gHTAJl9UACOzEk184kKVFCKYSAowAEEg9DqpgdynoCVCYPelDbpcu7MnSWwSLQda0AAbGoiZfAMuFZMslDMAoWCrq06CUBIwCYJR8CJqQ9acKW7ycXGoHgZBpDQbB8GIeWW47pQVAAIq/sQl5hJUtBqF8XyJtEYS4csynLsslTqQMtCUPgDDCPO/79m6mGYNhah4QRREkSs5GUZg1GYLRED0YxtGQCxbEcVx8aMbxdD%2BTIciKM%2B%2BiGAkIyZLQgS6AA6pYYhiLop5hF2LBsBwtDcUmzaHh2ejETo6kCPOYF8Ms9hqDVfAQLghAkEWJaCrYY4zi1uVlhWnGkAgPJYLOEB5ZwTakIIICVF89i4WEcmJsRagDAMXzRF8uGpoVXBdiAPa9QOw4QEgLAEMItyThA04SLO9CuU1t2jcmW0vh2VQlnwADuhAIHwxW4aVqzIBVwBVTVNU9X2fUDZYQ17g2Y0ppNKz2OtuEDGo2kDNpaiVMuXwvW2Ha7ftUOHfAx2jmYN2XddkhzguS4rmuG7IWJI2kAeL7HoxBDnleN54HeD5PoeCLvoe37Sf%2BgHAQFYEQXQ/HkoJCFIaJqGUOZWE4fhhHEaRjlUfsrl0ZgDFMZACmsaQ7GVn1PGK1BKtwWrIkoWhknS3JClKSpakaXWmM6csekGXgRkmTtcba5Zuu2QbDkQBRxs0WbFteRA1u%2Bfb3GBU7IWyPIShcNF0y9Lm1QTPFOhJSlaUZYwWXsMFCPPS2RNcP9gPlQuYO1XEDX4EQUjvfQdgdTdLWVO8kMZn1NZ1gj42TWEtUG2o0RbypAyJomoeE5mO2MHtpC9vP5OwCdtznQKFBXZP9OVKQ90j63H7t9tnDvZUX0/X9JUyrAz7tVAec9KzLyRlNXC9hEyVBWmEL4KwvhqFwtNTaHcj6dhPqTee1Zaz1g/I3TB7Zj7nwgR%2BSoBVXpkN6nGR8xAtRpmWEAA" rel="noreferrer">This is what clang does, for example</a>. This re-defining of <code>auto</code> in C++11 represents another material divergence between C and C++.)</p>
9,057,387
Process all arguments except the first one (in a bash script)
<p>I have a simple script where the first argument is reserved for the filename, and all other optional arguments should be passed to other parts of the script.</p> <p>Using Google I found <a href="http://wiki.bash-hackers.org/scripting/posparams#mass_usage">this wiki</a>, but it provided a literal example:</p> <pre><code>echo "${@: -1}" </code></pre> <p>I can't get anything else to work, like:</p> <pre><code>echo "${@:2}" </code></pre> <p>or</p> <pre><code>echo "${@:2,1}" </code></pre> <p>I get "Bad substitution" from the terminal.</p> <p>What is the problem, and how can I process all but the first argument passed to a bash script?</p>
9,057,392
5
2
null
2012-01-29 22:31:22.757 UTC
140
2020-06-29 04:35:59.09 UTC
2016-08-23 23:19:16.77 UTC
null
875,915
null
992,005
null
1
588
bash|shell
243,170
<p>Use this:</p> <pre><code>echo "${@:2}" </code></pre> <hr> <p>The following syntax:</p> <pre><code>echo "${*:2}" </code></pre> <p>would work as well, but is not recommended, because as <a href="https://stackoverflow.com/questions/9057387/process-all-arguments-except-the-first-one#comment11369452_9057392">@Gordon</a> already explained, that using <code>*</code>, it runs all of the arguments together as a single argument with spaces, while <code>@</code> preserves the breaks between them (even if some of the arguments themselves contain spaces). It doesn't make the difference with <code>echo</code>, but it matters for many other commands.</p>
16,542,118
Phonegap - navigator.app.backHistory() not working on HTML back button
<p>In my app i am using phonegap 2.6.For back button, I am using the following function</p> <pre><code>document.addEventListener("backbutton", onBackKeyDown, false); function onBackKeyDown() { alert("hello"); navigator.app.backHistory(); } document.addEventListener('deviceready', onDeviceReady, true); </code></pre> <p>The above function <strong>works fine when I click on the device's hardware back button</strong>. But when I click on the back button it is not working.</p> <p>I have designed my back button as below:</p> <pre><code>&lt;a class="ui-link" href="#" rel="external" onclick="onBackKeyDown()"&gt; &lt;img src="images/icon-back.png" alt="Phone" border="0"&gt; &lt;/a&gt; </code></pre> <p>But this button is working fine for this <code>navigator.app.exitApp();</code> (application exit).</p> <pre><code>//Working Fine function onBackKeyDown() { navigator.app.exitApp(); } //Not Working function onBackKeyDown() { navigator.app.backHistory(); } </code></pre> <p>but not working for <code>navigator.app.backHistory();</code>.</p>
16,589,826
5
1
null
2013-05-14 11:34:59.74 UTC
8
2022-02-16 16:41:23.13 UTC
2013-05-14 12:13:25.013 UTC
null
1,127,669
null
1,254,796
null
1
17
android|ios|cordova|back-button|back-button-control
28,580
<p>I have tried 3 separate things when I faced the same situation:</p> <ul> <li><p><code>window.history.back()</code></p></li> <li><p><code>navigator.app.backHistory();</code></p></li> <li><p><code>History.go(-1);</code></p></li> </ul> <p>Individually, none of these solve the problem. I put all 3 things together and much to my surprise it worked. I really don't know what is behind it.</p> <p>Then I decreased to two functions and removed:</p> <ul> <li><code>window.history.back()</code></li> </ul> <p>Now I am using this function and it is working fine.</p> <pre><code>//Works Fine function onBackKeyDown() { history.go(-1); navigator.app.backHistory(); } </code></pre>
16,368,937
getDimension()/getDimensionPixelSize() - mutliplier issue
<p>So I have android 2.3.5 device which is NORMAL/HDPI. I have a dimens.xml in my project:</p> <pre><code>... &lt;dimen name="gameresult_congrats_label_msg_textSize"&gt;20sp&lt;/dimen&gt; ... </code></pre> <p>this file is absolutely identical in values-normal/values-hdpi and so on folders. In my first activity app shows me that value using:</p> <pre><code>Toast.makeText(this, "textSize is "+getResources().getDimensionPixelSize(R.dimen.gameresult_congrats_label_msg_textSize), Toast.LENGTH_SHORT).show(); </code></pre> <p>and it displays 30. I Tried also:</p> <pre><code>Toast.makeText(this, "textSize is "+getResources().getDimension(R.dimen.gameresult_congrats_label_msg_textSize), Toast.LENGTH_SHORT).show(); </code></pre> <p>but result is the same. But only when I tried this:</p> <pre><code>Toast.makeText(this, "textSize is "+getResources().getString(R.dimen.gameresult_congrats_label_msg_textSize), Toast.LENGTH_SHORT).show(); </code></pre> <p>I got my "20sp" finally! But why is that? <a href="http://developer.android.com/reference/android/content/res/Resources.html#getDimension%28int%29">Official docs says that those methods</a> returns</p> <blockquote> <p>Resource dimension value multiplied by the appropriate metric.</p> </blockquote> <p>I checked this by changing my value to 25 and I got 38 which means aos uses 1.5 multiplier. But why? It already gets value from appropriate folder which means it gets a ready to use value! From where aos gets that 1.5x multiplier? I know it depends on DisplayMetrics. But how it calculates 1.5x?<br> <strong>UPDATE</strong><br> I understand about multiplier but, you see, the real problem here is about double scaling. And thats why I did asked this question.<br> So if I have some layout.xml (in res\layout folder) with TexView defined like:</p> <pre><code>&lt;TextView android:id="@+id/congratsLabel" ... android:textSize="@dimen/gameresult_congrats_label_msg_textSize" /&gt; </code></pre> <p>Everything looks ok. I mean textview is like Im expecting. <br> Now lets do the same in code:</p> <pre><code>TextView congratsLabel = fineViewById(R.id.congratsLabel); textSize = getResources().getDimension(R.dimen.gameresult_congrats_label_msg_textSize) congratsLabel.setTextSize(textSize) </code></pre> <p>and here is the issue!!! getResources().getDimension() returns a <strong>SCALED</strong> value and thats ok. But the resulting size of my textView will be 1.5 greater than I expecting cuz setTextSize works with SP and here comes the second scale! And thats why AOS makes resulting text size scaled to 45 (originally defined as 20sp). </p>
16,369,021
5
1
null
2013-05-03 23:23:16.81 UTC
5
2021-09-17 07:34:33.98 UTC
2014-04-09 14:21:30.83 UTC
null
1,811,719
null
1,811,719
null
1
21
android|textview|dimensions
48,274
<p>Per the <a href="http://developer.android.com/training/multiscreen/screendensities.html">Supporting Different Screen Densities training</a>, hdpi is 1.5x normal (mdpi) sizes. As <code>getDimensionPixelSize</code> takes this difference into account when converting into pixels, the returned value will be 1.5x your value in <code>sp</code>.</p> <p>Note that <code>sp</code> is also dependent on the user's preferred text size and can therefore change to be even larger than 1.5x your expected value.</p>
16,446,619
How to ignore enum fields in Jackson JSON-to-Object mapping?
<p>I have a JSON Object something like:</p> <pre><code>{"name":"John", "grade":"A"} </code></pre> <p>or</p> <pre><code>{"name":"Mike", "grade":"B"} </code></pre> <p>or</p> <pre><code>{"name":"Simon", "grade":"C"} </code></pre> <p>etc</p> <p>I am trying to map the above JSON to:</p> <pre><code>@JsonIgnoreProperties(ignoreUnknown = true) public class Employee{ @JsonIgnoreProperties(ignoreUnknown = true) public enum Grade{ A, B, C } Grade grade; String name; public Grade getGrade() { return grade; } public void setGrade(Grade grade) { this.grade = grade; } public String getName() { return name; } public void setName(String name) { this.name = name; } } </code></pre> <p>the above mapping works fine but in the future there will be more "Grade" types let say D,E etc which breaks the existing mapping and throws the following exception</p> <pre><code>05-08 09:56:28.130: W/System.err(21309): org.codehaus.jackson.map.JsonMappingException: Can not construct instance of Employee from String value 'D': value not one of declared Enum instance names </code></pre> <p>Is there a way to ignore unknown fields with in enum types?</p> <p>Thanks</p>
16,447,052
5
3
null
2013-05-08 17:20:48.533 UTC
9
2020-10-30 15:22:12.037 UTC
2013-05-08 18:57:21.917 UTC
null
1,522,067
null
1,522,067
null
1
26
java|jackson
31,398
<p>I think you should define external <a href="http://jackson.codehaus.org/1.1.2/javadoc/org/codehaus/jackson/map/JsonDeserializer.html" rel="noreferrer">deserializer</a> for <code>Grade</code> enum.</p> <p>I added additional field to enum - UNKNOWN:</p> <pre><code>enum Grade { A, B, C, UNKNOWN; public static Grade fromString(String value) { for (Grade grade : values()) { if (grade.name().equalsIgnoreCase(value)) { return grade; } } return UNKNOWN; } } class Employee { @JsonDeserialize(using = GradeDeserializer.class) private Grade grade; private String name; public Grade getGrade() { return grade; } public void setGrade(Grade grade) { this.grade = grade; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Employee [grade=" + grade + ", name=" + name + "]"; } } </code></pre> <p>Now, parser could look like that:</p> <pre><code>class GradeDeserializer extends JsonDeserializer&lt;Grade&gt; { @Override public Grade deserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException { return Grade.fromString(parser.getValueAsString()); } } </code></pre> <p>Example usage:</p> <pre><code>public class JacksonProgram { public static void main(String[] args) throws Exception { ObjectMapper objectMapper = new ObjectMapper(); JsonFactory jsonFactory = new JsonFactory(); JsonParser parser = jsonFactory .createJsonParser("{\"name\":\"John\", \"grade\":\"D\"}"); Employee employee = objectMapper.readValue(parser, Employee.class); System.out.println(employee); } } </code></pre> <p>Output:</p> <pre><code>Employee [grade=UNKNOWN, name=John] </code></pre> <p>If you don't want to add additional field, you would return <code>null</code> for example.</p>
16,047,829
Proxy cannot be cast to CLASS
<p>I'm using Spring for wiring dependencies specifically for DAO classes that use Hibernate, but I'm getting an exception that has me puzzled:</p> <p><strong>$Proxy58 cannot be cast to UserDao</strong></p> <p>My DAO is configured as follows:</p> <pre><code>&lt;bean id="userDao" class="com.domain.app.dao.UserDao"&gt; &lt;property name="sessionFactory" ref="sessionFactory" /&gt; &lt;/bean&gt; </code></pre> <p>And I have an interface, abstract base class and a final implementation as follows.</p> <p>Interface:</p> <pre><code>public interface Dao { public void save(Object object); public Object load(long id); public void delete(Object object); public void setSessionFactory(SessionFactory sessionFactory); } </code></pre> <p>Abstract Base Class:</p> <pre><code>public abstract class BaseDao implements Dao { private SessionFactory sessionFactory; @Transactional @Override public void save(Object object) { PersistentEntity obj = (PersistentEntity) object; currentSession().saveOrUpdate(obj); } @Transactional @Override public abstract Object load(long id); @Transactional @Override public void delete(Object object) { // TODO: this method! } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public Session currentSession() { return sessionFactory.getCurrentSession(); } } </code></pre> <p>Implementation:</p> <pre><code>public class UserDao extends BaseDao implements Dao { @Transactional(readOnly=true) @Override public Object load(long id) { Object user = currentSession().get(User.class, id); return user; } } </code></pre> <p>The following throws the exception mentioned above:</p> <p><em>UserDao dao = (UserDao) context.getBean("userDao");</em></p> <p>This, however, does not throw an exception:</p> <p><em>Dao dao = (Dao) context.getBean("userDao");</em></p> <p>If anyone can offer any assistance or guidance as to why this exception is happening, I would be very appreciative.</p>
16,047,976
2
1
null
2013-04-16 21:56:10.42 UTC
8
2018-02-01 14:25:13.863 UTC
2013-04-18 21:25:03.32 UTC
null
1,150,982
null
1,150,982
null
1
27
spring|hibernate|casting
32,018
<p>Spring uses <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Proxy.html" rel="noreferrer">JDK dynamic proxies</a> by default (<code>$Proxy58</code> is one of them), that can only proxy interfaces. This means that the dynamically created type <code>$Proxy58</code> will implement one or more of the interfaces implemented by the wrapped/target class (<code>UserDao</code>), but it won't be an actual subclass of it. That's basically why you can cast the <code>userDao</code> bean to the <code>Dao</code> <em>interface</em>, but not to the <code>UserDao</code> <em>class</em>.</p> <p>You can use <code>&lt;tx:annotation-driven proxy-target-class="true"/&gt;</code> to instruct Spring to use CGLIB proxies that are actual subclasses of the proxied class, but I think it's better practice to program against interfaces. If you need to access some methods from the proxied class which are not declared in one of it's interfaces, you should ask yourself first, why this is the case?<br> (Also, in your code above there are no new methods introduced in <code>UserDao</code>, so there is no point in casting the bean to this concrete implementation type anyway.)</p> <p>See more about different proxying mechanisms in the official <a href="http://static.springsource.org/spring/docs/current/spring-framework-reference/html/aop.html#aop-proxying" rel="noreferrer">Spring reference</a>.</p>
16,239,819
Performance of Firebase with large data sets
<p>I'm testing firebase for a project that may have a reasonably large numbers of keys, potentially millions.</p> <p>I've tested loading a few 10k of records using node, and the load performance appears good. However the "FORGE" Web UI becomes unusably slow and renders every single record if I expand my root node.</p> <p>Is Firebase not designed for this volume of data, or am I doing something wrong?</p>
16,240,601
1
1
null
2013-04-26 15:15:23.137 UTC
41
2014-12-19 15:43:15.01 UTC
2014-12-19 15:43:15.01 UTC
null
52,522
null
1,421,831
null
1
29
firebase
26,696
<p>It's simply the limitations of the Forge UI. It's still fairly rudimentary.</p> <p>The real-time functions in Firebase are not only suited for, but designed for large data sets. The fact that records stream in real-time is perfect for this.</p> <p>Performance is, as with any large data app, only as good as your implementation. So here are a few gotchas to keep in mind with large data sets.</p> <p><strong>DENORMALIZE, DENORMALIZE, DENORMALIZE</strong></p> <p>If a data set will be iterated, and its records can be counted in thousands, store it in its own path. </p> <p>This is bad for iterating large data sets:</p> <pre><code>/users/uid /users/uid/profile /users/uid/chat_messages /users/uid/groups /users/uid/audit_record </code></pre> <p>This is good for iterating large data sets:</p> <pre><code>/user_profiles/uid /user_chat_messages/uid /user_groups/uid /user_audit_records/uid </code></pre> <p><strong>Avoid 'value' on large data sets</strong></p> <p>Use the <code>child_added</code> since <code>value</code> must load the entire record set to the client.</p> <p><strong>Watch for hidden <code>value</code> operations on children</strong></p> <p>When you call <code>child_added</code>, you are essentially calling <code>value</code> on every child record. So if those children contain large lists, they are going to have to load all that data to return. Thus, the DENORMALIZE section above.</p>
21,724,337
Signing and Verifying on iOS using RSA
<p>How to sign and verify some data on iOS with an RSA key (preferably using the system own <code>libcommonCrypto</code>)?</p>
21,826,729
2
6
null
2014-02-12 09:53:50.44 UTC
16
2021-01-09 09:45:38.793 UTC
null
null
null
null
1,037,200
null
1
20
ios|rsa|pkcs#7|commoncrypto
14,219
<p>Since there hasn't been nearly any knowledge about signing and verifying found on StackOverflow and the Apple docs, I had to manually browse around in the iOS header files and found <code>SecKeyRawSign</code> and <code>SecKeyRawVerify</code>. The following lines of code seem to work.</p> <hr> <p><strong>Signing NSData (using SHA256 with RSA):</strong></p> <pre><code>NSData* PKCSSignBytesSHA256withRSA(NSData* plainData, SecKeyRef privateKey) { size_t signedHashBytesSize = SecKeyGetBlockSize(privateKey); uint8_t* signedHashBytes = malloc(signedHashBytesSize); memset(signedHashBytes, 0x0, signedHashBytesSize); size_t hashBytesSize = CC_SHA256_DIGEST_LENGTH; uint8_t* hashBytes = malloc(hashBytesSize); if (!CC_SHA256([plainData bytes], (CC_LONG)[plainData length], hashBytes)) { return nil; } SecKeyRawSign(privateKey, kSecPaddingPKCS1SHA256, hashBytes, hashBytesSize, signedHashBytes, &amp;signedHashBytesSize); NSData* signedHash = [NSData dataWithBytes:signedHashBytes length:(NSUInteger)signedHashBytesSize]; if (hashBytes) free(hashBytes); if (signedHashBytes) free(signedHashBytes); return signedHash; } </code></pre> <hr> <p><strong>Verification (using SHA256 with RSA):</strong></p> <pre><code>BOOL PKCSVerifyBytesSHA256withRSA(NSData* plainData, NSData* signature, SecKeyRef publicKey) { size_t signedHashBytesSize = SecKeyGetBlockSize(publicKey); const void* signedHashBytes = [signature bytes]; size_t hashBytesSize = CC_SHA256_DIGEST_LENGTH; uint8_t* hashBytes = malloc(hashBytesSize); if (!CC_SHA256([plainData bytes], (CC_LONG)[plainData length], hashBytes)) { return nil; } OSStatus status = SecKeyRawVerify(publicKey, kSecPaddingPKCS1SHA256, hashBytes, hashBytesSize, signedHashBytes, signedHashBytesSize); return status == errSecSuccess; } </code></pre> <hr> <p><strong>Alternatives (OpenSSL):</strong></p> <p>There is a very good alternative available which utilizes OpenSSL directly instead of libCommonCrypto. <a href="https://github.com/hohl/MIHCrypto" rel="noreferrer">MIHCrypto</a> is a well-designed Objective-C wrapper library for OpenSSL which makes working with cryptography very easy. See the example below.</p> <p>Generating a key is that simple:</p> <pre><code>MIHAESKeyFactory *factory = [[MIHAESKeyFactory alloc] init]; id&lt;MIHSymmetricKey&gt; aesKey = [factory generateKey]; </code></pre> <p>Or loading a key from file:</p> <pre><code>NSData *privateKeyData = [[NSFileManager defaultManager] contentsAtPath:"mykey.pem"]; MIHRSAPrivateKey *privateKey = [[MIHRSAPrivateKey alloc] initWithData:privateKeyData]; </code></pre> <p>Now sign something:</p> <pre><code>NSError *signingError = nil; NSData *message = // load something to sign from somewhere NSData *signature = [privateKey signWithSHA256:message error:&amp;signingError] </code></pre> <p>For more examples browse the <a href="https://github.com/hohl/MIHCrypto" rel="noreferrer">MIHCrypto</a> page.</p>
17,358,159
Why use CJSON encode when we have json_encode
<p>I am building an API for a website using Yii. I know that there is a utility class called CJson and has a function called encode.</p> <p>As far as I know there are additional parameters that can be customized in the native json_encode function like the JSON_NUMERIC_CHECK which is really useful. It creates</p> <pre><code>{ "id": 17 } </code></pre> <p>instead of Yii's CJSON encode which makes the '17' a string.</p> <pre><code>{ "id": "17" } </code></pre> <p>So my question is whether there is any reason I should use CJSON encode instead of the built in PHP function json_encode ?</p>
17,358,224
4
1
null
2013-06-28 06:00:05.94 UTC
2
2016-02-02 09:12:37.62 UTC
null
null
null
null
923,109
null
1
30
php|json|yii
7,421
<p>Only thing I can think minimum php version support. </p> <p>Yii support php 5.1 as minimum version See <a href="http://www.yiiframework.com/doc/guide/1.1/en/quickstart.installation">Yii Installation Page</a> . While json_encode/json_decode introduced in php 5.2. So It can be a reason for Yii having a library for CJson. </p>