input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Rails Active Record find(:all, :order => ) issue <p>I seem to be unable to use the ActiveRecord::Base.find option :order for more than one column at a time. </p>
<p>For example, I have a "Show" model with date and attending columns.</p>
<p>If I run the following code:</p>
<pre><code>@shows = Show.find(:all, :order => "date")
</code></pre>
<p>I get the following results:</p>
<pre><code>[#<Show id: 7, date: "2009-04-18", attending: 2>,
#<Show id: 1, date: "2009-04-18", attending: 78>,
#<Show id: 2, date: "2009-04-19", attending: 91>,
#<Show id: 3, date: "2009-04-20", attending: 16>,
#<Show id: 4, date: "2009-04-21", attending: 136>]
</code></pre>
<p>If I run the following code: </p>
<pre><code>@shows = Show.find(:all, :order => "attending DESC")
[#<Show id: 4, date: "2009-04-21", attending: 136>,
#<Show id: 2, date: "2009-04-19", attending: 91>,
#<Show id: 1, date: "2009-04-18", attending: 78>,
#<Show id: 3, date: "2009-04-20", attending: 16>,
#<Show id: 7, date: "2009-04-18", attending: 2>]
</code></pre>
<p>But, if I run:</p>
<pre><code>@shows = Show.find(:all, :order => "date, attending DESC")
</code></pre>
<p>OR </p>
<pre><code>@shows = Show.find(:all, :order => "date, attending ASC")
</code></pre>
<p>OR </p>
<pre><code>@shows = Show.find(:all, :order => "date ASC, attending DESC")
</code></pre>
<p>I get the same results as only sorting by date:</p>
<pre><code> [#<Show id: 7, date: "2009-04-18", attending: 2>,
#<Show id: 1, date: "2009-04-18", attending: 78>,
#<Show id: 2, date: "2009-04-19", attending: 91>,
#<Show id: 3, date: "2009-04-20", attending: 16>,
#<Show id: 4, date: "2009-04-21", attending: 136>]
</code></pre>
<p>Where as, I want to get these results:</p>
<pre><code>[#<Show id: 1, date: "2009-04-18", attending: 78>,
#<Show id: 7, date: "2009-04-18", attending: 2>,
#<Show id: 2, date: "2009-04-19", attending: 91>,
#<Show id: 3, date: "2009-04-20", attending: 16>,
#<Show id: 4, date: "2009-04-21", attending: 136>]
</code></pre>
<p>This is the query being generated from the logs:</p>
<pre><code>[4;35;1mUser Load (0.6ms)[0m [0mSELECT * FROM "users" WHERE ("users"."id" = 1) LIMIT 1[0m
[4;36;1mShow Load (3.0ms)[0m [0;1mSELECT * FROM "shows" ORDER BY date ASC, attending DESC[0m
[4;35;1mUser Load (0.6ms)[0m [0mSELECT * FROM "users" WHERE ("users"."id" = 1) [0m
</code></pre>
<p>Finally, here is my model:</p>
<pre><code> create_table "shows", :force => true do |t|
t.string "headliner"
t.string "openers"
t.string "venue"
t.date "date"
t.text "description"
t.datetime "created_at"
t.datetime "updated_at"
t.decimal "price"
t.time "showtime"
t.integer "attending", :default => 0
t.string "time"
end
</code></pre>
<p>What am I missing? What am I doing wrong?</p>
<p><strong>UPDATE: Thanks for all your help, but it seems that all of you were stumped as much as I was. What solved the problem was actually switching databases. I switched from the default sqlite3 to mysql.</strong> </p>
| <p><strong>Could be two things. First,</strong></p>
<p>This code is deprecated:</p>
<pre><code>Model.find(:all, :order => ...)
</code></pre>
<p>should be:</p>
<pre><code>Model.order(...).all
</code></pre>
<p>Find is no longer supported with the :all, :order, and many other options.</p>
<p><strong>Second,</strong> you might have had a default_scope that was enforcing some ordering before you called <code>find</code> on <code>Show</code>.</p>
<p>Hours of digging around on the internet led me to a few useful articles that explain the issue:</p>
<ul>
<li><a href="http://m.onkey.org/active-record-query-interface">http://m.onkey.org/active-record-query-interface</a></li>
<li><a href="http://www.simonecarletti.com/blog/2010/07/the-way-to-rails-3/">http://www.simonecarletti.com/blog/2010/07/the-way-to-rails-3/</a></li>
</ul>
|
Encoding PHP Tags for Security? <p><a href="http://docs.kohanaphp.com/helpers/security#encode%5Fphp%5Ftags" rel="nofollow">Kohana</a> and <a href="http://codeigniter.com/user%5Fguide/helpers/security%5Fhelper.html" rel="nofollow">Codeigniter</a> both have <code>encode_php_tags()</code>. I understand XSS cleaning (for Javascript), but when and why would you use <code>encode_php_tags()</code>? What is the security threat?</p>
| <p>A smart fellow on the #kohana forum suggested that it is there because Expression Engine uses eval() for templates. If someone were to embed PHP in a string it is possible it would be eval()'d and executed. Since Kohana does not use eval() for templates it is possible that it is just left over from Codeigniter days.</p>
|
Clone isn't cloning select values <p>I didn't expect it but the following test fails on the cloned value check:</p>
<pre><code>test("clone should retain values of select", function() {
var select = $("<select>").append($("<option>")
.val("1"))
.append($("<option>")
.val("2"));
$(select).val("2");
equals($(select).find("option:selected").val(), "2", "expect 2");
var clone = $(select).clone();
equals($(clone).find("option:selected").val(), "2", "expect 2");
});
</code></pre>
<p>Is this right?</p>
| <p>After further research I found this ticket in the JQuery bug tracker system which explains the bug and provides a work around. Apparently, it is too expensive to clone the select values so they won't fix it. </p>
<p><a href="http://dev.jquery.com/ticket/1294">http://dev.jquery.com/ticket/1294</a></p>
<p>My use of the clone method was in a generic method where anything might be cloned so I'm not sure when or if there will be a select to set the value on. So I added the following:</p>
<pre><code>var selects = $(cloneSourceId).find("select");
$(selects).each(function(i) {
var select = this;
$(clone).find("select").eq(i).val($(select).val());
});
</code></pre>
|
Background image positioning problem <p>I have this as my CSS styling. My <code>#pg_wrap</code> is not centering with the background image when the browser window is resized. The screen shot I have is when you reduce the browser window less than 1344px than the <code>#pg_wrap</code> width (the width doesn't have to be that, was just a test number).</p>
<p>The screen shot was taken with Firefox, which does it. Chrome does not do this. How do I get the background image to stay put?</p>
<p><a href="http://img9.imageshack.us/my.php?image=sschrome.png&via=yfrog" rel="nofollow">Chrome</a></p>
<p><a href="http://img9.imageshack.us/my.php?image=94209626.png&via=yfrog" rel="nofollow">Firefox</a></p>
<pre><code>body
{
text-align: center;
background-image: url('p_bg_75.jpg');
background-repeat: repeat-y;
background-color: black;
background-attachment:fixed
margin: 0px;
padding: 0px;
}
#pg_wrap
{
margin-left: auto;
margin-right: auto;
width: 1344px;
height: 1000px;
border: 1px solid white;
text-align: center;
}
</code></pre>
| <p>The difference is because the browsers handle incorrect css in different ways.</p>
<p>Change</p>
<pre><code>background-attachment:fixed
</code></pre>
<p>to</p>
<pre><code>background-attachment:fixed;
</code></pre>
|
A strange Problem about gdi+ bitmap! <p>I am using the following code to get a Bitmap point, </p>
<p>(width = 800, height = 600);</p>
<pre><code>Bitmap* m_BitmapCanvasCore = new Bitmap(width, height, PixelFormat32bppARGB);
</code></pre>
<p>but the m_BitmapCanvasCore always is NULL...
Is there any thing wrong about gdi+? Or any namespace polution I need to avoid?
Why?</p>
| <p>Did you call <a href="http://msdn.microsoft.com/en-us/library/ms534077(VS.85).aspx" rel="nofollow">GdiplusStartup</a> before creating the Bitmap?</p>
|
Which initializer(s) to override for UITableViewController subclass <p>I have a <code>UITableViewController</code> subclass that's instantiated, depending on where it's used, in a NIB or via code. In both cases I want to do customization in the initializer method. Does that mean I need to implement both <code>initWithNibName:bundle:</code> <em>and</em> <code>initWithCoder:</code>, and would each method call its respective super initializer?</p>
<p>While I don't need this right now, what if I also want to be able to instantiate the view controller with <code>initWithStyle:</code>? Would I then need 3 different init methods that replicate the same behavior?</p>
<p>It seems like this violates the whole designated initializer convention, as there would essentially be 3 separate initializers that don't end up calling a common init method. Or is there a way to create a common designated initializer while supporting the 3 different instantiate routes?</p>
| <p>My confusion was based on the mistaken belief that each class should have a single designated initializer. This is not true, and in the case of <code>UITableViewController</code> there are 3 designated initializers (as far as I can tell):</p>
<ol>
<li><code>initWithStyle:</code> declared locally</li>
<li><code>initWithNibName:bundle:</code> inherited from <code>UIViewController</code></li>
<li><code>initWithCoder:</code> from adopting <code>NSCoding</code> protocol</li>
</ol>
<p>You need to override 1 <strong><em>or more</em></strong> of these in your subclass depending on how your subclass gets instantiated. In my case I had to implement #2 and #3 since the class can be loaded from a NIB, or instantiated via code with reference to a NIB. (I imagine it's rare that you'll use both <code>initWithStyle:</code> and <code>initWithNibName:bundle:</code> for a single class.)</p>
<p>I found Apple's <em><a href="http://developer.apple.com/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/FrameworkImpl.html">Coding Guidelines for Cocoa</a></em> helpful.</p>
|
Input still existing when removed <p>i append a text input into form by using javascript, after i removed it by removeNode, it disappear, document.forms["form"].length = 0, but i can still get it's obj by using document.forms["form"]["inputname"] (not return null)</p>
<p>why?</p>
| <p>I think you are having trouble with firefox. In IE your code seems to work without any problem.</p>
<p>For removeNode to work in both IE and FF you can write like this</p>
<p>var objectToRemove = document.getElementByID ( "your object to remove" ); </p>
<p>var parentNode = objectToRemove .parentNode; </p>
<p>parentNode.removeChild ( objectToRemove );</p>
<p>Hope this helps</p>
|
What's a good guide to WPF Panels & layout in general? <p>Is there a good, concise guide to the various behaviors of the controls that inherit from System.Windows.Controls.Panel? Or just a WPF layout guide in general?</p>
<p>In particular, I'm interested in how the panels handle child objects that have width or height set to "Auto" and Horizontal or Vertical Alignment set to "Stretch". Some layouts cause the objects to fill the size of their container, others just cause them to size based on their own content. </p>
| <p>See <a href="http://msdn.microsoft.com/en-us/library/ms754152.aspx">http://msdn.microsoft.com/en-us/library/ms754152.aspx</a> for a start... it sounds like you may be particularly interested in the table in the "User Interface Panels" section.</p>
|
How do I get the current hour using Cocoa? <p>How do I get the current hour in Cocoa using Objective-C?</p>
| <p>To start off, you should read <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/DatesAndTimes/DatesAndTimes.html#//apple%5Fref/doc/uid/10000039">Dates and Times Programming Topics for Cocoa</a>. That will give you a good understanding of using the various date/time/calendar objects that are provided in Cocoa for high-level conversions of dates.</p>
<p>This code snip, however, will answer your specific problem:</p>
<pre><code>- (NSInteger)currentHour
{
// In practice, these calls can be combined
NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSHourCalendarUnit fromDate:now];
return [components hour];
}
</code></pre>
|
How to prevent vim from creating (and leaving) temporary files? <p>Why does vim create <code><filename>~</code> files? Is there a way to disable that? </p>
<p>If it's for backup (or something), I use git for that.</p>
<p>Also, these <code>.<filename.with.path.hints>.swp</code> files too.</p>
<p>How do I tell vim not to create those, or at the least to cleanup after itself?</p>
<p><strong>EDIT</strong></p>
<p>wops, duplicate:</p>
<blockquote>
<p><a href="http://stackoverflow.com/questions/607435/why-does-vim-save-files-with-a-extension">Why does Vim save files with a ~ extension?</a></p>
</blockquote>
<p>I adopted <a href="http://stackoverflow.com/questions/607435/why-does-vim-save-files-with-a-extension/607474#607474">rogeriopvl's answer</a> from there.</p>
<p>verbatim copy:</p>
<pre><code>set nobackup #no backup files
set nowritebackup #only in case you don't want a backup file while editing
set noswapfile #no swap files
</code></pre>
| <p>I'd strongly recommend to keep working with swap files (in case Vim crashes).</p>
<p>You can set the directory where the swap files are stored, so they don't clutter your normal directories:</p>
<pre><code>set swapfile
set dir=~/tmp
</code></pre>
<p>See also</p>
<pre><code>:help swap-file
</code></pre>
|
Issue with streaming AVI files <p>I am writing a video streaming server application. I have an AVI file and I have put it on IIS 7 for streaming. I found that client cannot jump to an arbitrary location of the media, if the media is not buffered already. I think some meta-data is missing during recording?</p>
<p>After searching, I think, Windows Media Player could not jump to any arbitrary location before buffered locally, since Index block of AVI (needed for seeking) is stored at the end of file.</p>
<p>Here is an example, if my recorded avi video is 10 mins, and now I am playing to the 4th mins, and the local buffered streaming media is buffered to the 5th mins, I cannot jump to any time after the 5th mins, like the 7th mins in Windows Media Player.</p>
<p>I did not face the same issue with other formats like asf/wmv. So I think it is an AVI issue rather than server or any other environmental issue.</p>
<p>My questions are,</p>
<ol>
<li>What is the actual reason for not being able to jump to arbitrary location for AVI file, before it is buffered?</li>
<li>Any solutions or workarounds? Can I use other smarter players instead, which can handle this issue or can I add some code fix at the server side?</li>
</ol>
| <p>As you already discovered yourself, index is written at the end of avi containers. That's why avi format is not good for streaming. </p>
<p>You should convert your video to some other format which has the indexing information at the beginning. For example, flv, wmv, ogg/theora, etc.</p>
|
A way to add pictures to Excel sheet programmtically but not from file <p>I work on a product that loads a file into the Excel worksheet. The file contains data that is converted to a picture (using some WebService) and then displayed on the worksheet.</p>
<p>Lately, I was thinking of avoiding the file IO in this load operation. If the import file contains 1000 records then the load method has to create and delete 1000 temp files which are imported into Excel using Shapes.AddPicture() command.</p>
<p>Is there a way to add a picture on Excel sheet using some in-memory method and avoid the File IO?</p>
| <p>Yes, you can put your picture in the clipboard and paste it.</p>
<p>This, however, has a disadvantage of wiping off user's stuff from the clipboard which is not a good thing to do.</p>
|
Exceptions over remote methods <p>What are the best practices for exceptions over remote methods?</p>
<p>I'm sure that you need to handle all exceptions at the level of a remote method implementation, because you need to log it on the server side. But what should you do afterwards?</p>
<p>Should you wrap the exception in a RemoteException (java) and throw it to the client? This would mean that the client would have to import all exceptions that could be thrown. Would it be better to throw a new custom exception with fewer details? Because the client won't need to know all the details of what went wrong. What should you log on the client? I've even heard of using return codes(for efficiency maybe?) to tell the caller about what happened.</p>
<p>The important thing to keep in mind, is that the client <strong>must</strong> be informed of what went wrong. A generic answer of "Something failed" or no notification at all is unacceptable. And what about runtime (unchecked) exceptions?</p>
| <p>It seems like you want to be able to differentiate if the failure was due to a system failure (e.g. a service or machine is down) or a business logic failure (e.g. the user does not exist).</p>
<p>I'd recommend wrapping all system exceptions from the RMI call with your own custom exception. You can still maintain the information in the exception by passing it to your custom exception as the cause (this is possible in Java, not sure about other languages). That way client only need to know how to handle the one exception in the cause of system failure. Whether this custom exception is checked or runtime is up for debate (probably depends on your project standards). I would definitely log this type of failure.</p>
<p>Business type failures can be represented as either a separate exception or some type of default (or null) response object. I would attempt to recover (i.e. take some alternative action) from this type of failure and log only if the recovery fails.</p>
|
Transaction timeout expired while using Linq2Sql DataContext.SubmitChanges() <p>please help me resolve this problem:</p>
<p>There is an ambient MSMQ transaction. I'm trying to use new transaction for logging, but get next error while attempt to submit changes - "Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding." Here is code:</p>
<pre><code>public static void SaveTransaction(InfoToLog info)
{
using (TransactionScope scope =
new TransactionScope(TransactionScopeOption.RequiresNew))
{
using (TransactionLogDataContext transactionDC =
new TransactionLogDataContext())
{
transactionDC.MyInfo.InsertOnSubmit(info);
transactionDC.SubmitChanges();
}
scope.Complete();
}
}
</code></pre>
<p>Please help me.
Thx.</p>
| <p>You could consider increasing the timeout or eliminating it all together.</p>
<p>Something like:</p>
<pre><code>using(TransactionLogDataContext transactionDC = new TransactionLogDataContext())
{
transactionDC.CommandTimeout = 0; // No timeout.
}
</code></pre>
<p>Be careful</p>
|
Google geomap with jquery fails in IE <p>I faced with problem that geomap by google fails with JQuery together in Internet explorer.</p>
<p>Otherwise in Firefox it looks like this:</p>
<p><img src="http://clip2net.com/clip/m0/1239617014-clip-11kb.jpg" alt="1239617014-clip-11kb"/></p>
<p>Here comes js references </p>
<pre><code><script type="text/javascript" src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABCDEFG">
</script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script src="/js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="/js/ui.core.js" type="text/javascript"></script>
<script src="/js/ui.accordion.js" type="text/javascript"></script>
</code></pre>
<p><img src="http://clip2net.com/clip/m0/1239620705-clip-21kb.png" alt="1239620705-clip-21kb"/></p>
<p>Please anybody help with this...</p>
<p>Thanks in advise.</p>
| <p>It's hard to debug javascript in IE, but it's even harder to debug without the actual url, or when using minified javascript. You might want to switch to the full non-minified version of jquery temporarily, so that you can find the line where the error occurs and see what's going on.</p>
<p>Also, in firefox you can try using firebug to see if it throws any errors. Even though the map is working in firefox, it may be silently recovering from an error that IE can't recover from.</p>
|
Page Refresh Causes Duplicate POST in ASP.NET Applications <p>i have an application in which i am adding a new record and the record is added two times if i am pressing refresh button.</p>
<p>I am clearing the cache but i am having the same problem.
what to do?</p>
| <p>Once you have handled a post back to a page, best practice is to then redirect so that you can't have the data posted a second time using the "refresh" button. This is common to all web develoment, not just ASP.NET.</p>
|
making joomla search page search engine friendly <p>I want to add some seo features to a joomla search component, such as meta and integrated title page. What should i hack in the file ?
Thanks
joomla verion 1.0.15</p>
| <p>I'd suggest hacking directly at the Joomla! search module. this should <code>modules/mod_search.php</code> file and go from there to add your functionality. I'm not too familiar with the topics of SEO optimization.</p>
|
Exchange data between programs written in various languages <p>I'm writing a small browser game and as I'm not a good designer, I wanted to start with the technical part first and add the user interface later, so I wanted to have the first version include bot support, so everyone could write their own bot and have it play the game.
This way, I don't have to care about making graphics for the user interface and can concentrate on the game's core while having a steady flow of test data and many testers.</p>
<p>However, I can't decide betweens the various ways of exchanging data between the server (C++) and the clients (any language, but the first reference implementations will be in C++ and Python).<br />
For the transport I thought of offering HTTP and TCP (some simple homebrew protocol), as most languages have beginner friendly implementations of those protocols.</p>
<p>For encoding the data I considered something arbitrarily defined by me (something primitive like CSV), JSON and XML, but I'd like some comments regarding ease of use in C++, easy implementations on various languages and understandability by humans.</p>
<p>What should I do?</p>
| <p>If you're going to be making a browser based game, then the people that will be playing it will be making use of http requests and visiting certain URLs. It makes sense to me to keep your API for the bots similiar to this, rather than duplicating work for yourself. So why not expose your game's functionality through webservices?</p>
<p>As far as possible, I would try to keep the protocol/API as standard as possible. Having to learn your homebrew version is an extra hurdle people have to get over before they can interact with your game. </p>
<p>As for languages, is there a reason you're picking C++ for a browser based game? There are lots of web frameworks out there, but few use C++.</p>
|
ASP.NET MVC Default Parameters <p>I have created a new route like the following:</p>
<pre><code> routes.MapRoute(
"BlogYMD",
"blog/date/{year}/{month}/{day}",
new { controller = "Blog", action = "Date", year = "2009", month="01", day="01" });
</code></pre>
<p>The view simply returns a concatenation of year, month and day. This works fine for URL's like:</p>
<p><a href="http://localhost/blog/date/2009/01/01" rel="nofollow">http://localhost/blog/date/2009/01/01</a></p>
<p>However if I enter this URL:</p>
<p><a href="http://localhost/blog/date/2009" rel="nofollow">http://localhost/blog/date/2009</a></p>
<p>I would expect the default values for month and day to be passed to the date method. However they aren't, all the parameters on the method come through as null.</p>
<p>Am I missing something obvious?</p>
| <p>You don't show the rest of your routes, but I suspect you have another route above this one in your global.asax.CS (for example, the default route) which matches the second URL.</p>
|
how to have a Hover details box in flex 3 similar to ones present in google geomap visualization examples <p>i want to know if there is a already available hover details component similar to the one shown in <a href="http://code.google.com/apis/visualization/documentation/gallery/geomap.html" rel="nofollow">google geomap visualizations examples</a> which shows city name and its details, or any other similar component that can be used a hover details box. </p>
| <p>You could conceivably do this with the Flex framework's own ToolTip class. All standard Flex components (derived from UIComponent) have a toolTip property that's used to create tooltips. The standard tooltip style is black text on a yellow-ish background, but this is easily changed using CSS. For some more elaborate styling, you could use the htmlText property on the TextField within the ToolTip class.</p>
<p>Here are some examples: <a href="http://livedocs.adobe.com/flex/3/html/help.html?content=tooltips_3.html" rel="nofollow">http://livedocs.adobe.com/flex/3/html/help.html?content=tooltips_3.html</a></p>
|
How to automate tests for reports in SSRS <p>My current project uses SSRS as the reporting engine. I have the report executing a text command with about 10 variables passed to it. I have been looking for a solution on how to unit test (acceptance or integration, whatever, just some automation) to an SSRS report project.</p>
<p>I thought about using this method:</p>
<ol>
<li>Move the SQL text command to a stored procedure </li>
<li>Create a Reports.Tests project</li>
<li>Create a project_tests database and point the connection string to this database</li>
<li>Set up my unit test <Setup> with the data I would return in the test</li>
<li>Create a test with the parameters passed and test the result set</li>
</ol>
<p>I wanted to be sure that I wasn't missing something obvious.</p>
<p>How do other programmers test their reports automatically? Any suggestions on how to improve this method?</p>
<p>EDIT: I should clarify that I would like to only test the result set and not formatting of the report.</p>
| <p>Do acceptance/smoke tests with <strong><a href="http://watin.sourceforge.net/" rel="nofollow">watin</a></strong> or <strong><a href="http://seleniumhq.org/projects/remote-control/" rel="nofollow">selenium rc</a></strong> with your favorite unit testing framework.</p>
|
PHP/MySQL: Convert from YYYY-MM-DD to DD Month, YYYY? <p>I have in a MySQL table a DATE column that represents the date in this format: YYYY-MM-DD.</p>
<p>I wanto to retrieve the date from the database using PHP but display it like this: DD Month, YYYY.</p>
<p>From '2009-04-13' to '13 April, 2009' for example.</p>
<p>Witch is the best way to do it?? ( I know how to get the date from the DB. I only need to know how to convert it)</p>
<p>I also need to display the month names in Spanish. There is a way to do it without translating each month using strplc or something like that??</p>
<p>I'm new to programming, please be detailed.</p>
<p>Thanks!!!</p>
| <p>Refer to <a href="http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function%5Fdate-format">DATE_FORMAT()</a> function in MySQL. I guess that's the best way for you to do it.</p>
<p>Also, you can make this:</p>
<ul>
<li>Fetch your date from DB</li>
<li>Use <a href="http://www.php.net/strtotime">strtotime</a> in PHP, to convert to unix time</li>
<li>Then format the time using <a href="http://www.php.net/date">date</a>.</li>
</ul>
<p>By using date() you'll be able to get months names in Spanish when you set your locale in PHP with <a href="http://us2.php.net/manual/en/function.setlocale.php">setlocale</a>.</p>
|
How can I disable the security warning when viewing XML in IE? <p>When I view XML files in Internet Explorer, it does syntax highlighting and provides clickable expand/collapse controls. But for every file I open, I get a yellow
warning bar that takes three clicks to dismiss. These are local files, so the security warning shouldn't be necessary. Can it be disabled?</p>
<p><img src="http://carrieandtim.com/drop/iexmlwarning.png" alt="IE yellow security warning bar for viewing local xml file" /></p>
| <p>The previous suggestions on this page didn't work for me. I found the answer on <a href="http://www.leonmeijer.nl/archive/2008/04/27/106.aspx">this page</a></p>
<p>To summarise, go into Internet Options > Advanced then down to the Security section, and tick the box for "Allow active content to run in files on My Computer*"</p>
<p>The * means the setting only takes effect after Internet Explorer is restarted.</p>
|
CEdit numeric validation event C++ MFC <p><br />
I have a CEdit text box which is a part of a property pane and only allows numeric values (positive integers). The box works fine when people enter non-numeric values, but when they delete the value in the box a dialog pops up saying:
"Please enter a positive integer."</p>
<p>Here is the situation:<br />
1. I have a number (say 20) in the box.<br />
2. I delete the number.<br />
3. I get the error dialog.<br />
Could anybody tell me how I can intercept this event and put a default value in there?</p>
<p>Here is what my property pane looks like:</p>
<pre><code>
const int DEFAULT_VALUE = 20;
class MyPropertyPane:public CPropertyPane
{
//....
private:
CEdit m_NumericBox;
int m_value;
//....
public:
afx_msg void OnEnChangeNumericBox();
//....
}
void MyPropertyPane::MyPropertyPane()
{
// Set a default value
m_value = DEFAULT_VALUE;
}
//....
void MyPropertyPane::DoDataExchange(CDataExchange* pDX)
{
DDX_Control(pDX, IDC_NUMERIC_BOX, m_NumericBox);
// this sets the displayed value to 20
DDX_Text(pDX, IDC_NUMERIC_BOX, m_value);
}
//....
void MyPropertyPane::OnEnChangeNumericBox()
{
// Somebody deleted the value in the box and I got an event
// saying that the value is changed.
// I try to get the value from the box by updating my data
UpdateData(TRUE);
// m_value is still 20 although the value is
// deleted inside the text box.
}
</code></pre>
| <p>The message you are receiving is coming from the data validation routines, not the data exchange routines. There is probably a call like this in DoDataExchange():</p>
<pre><code>void MyPropertyPane::DoDataExchange(CDataExchange* pDX)
{
DDX_Control(pDX, IDC_NUMERIC_BOX, m_NumericBox);
DDX_Text(pDX, IDC_NUMERIC_BOX, m_value);
DDV_MinMaxInt(pDX, m_value, 1, 20); // if the value in m_value is outside the range 1-20, MFC will pop up an error dialog
}
</code></pre>
<p>You can fix this problem by removing the built-in MFC data validation and adding your own:</p>
<pre><code>void MyPropertyPane::DoDataExchange(CDataExchange* pDX)
{
DDX_Control(pDX, IDC_NUMERIC_BOX, m_NumericBox);
DDX_Text(pDX, IDC_NUMERIC_BOX, m_value);
if( m_value < 1 || m_value > 20 )
{
m_value = DefaultValue;
}
}
</code></pre>
|
Nhibernate error: NO row with given identifier found error <p>I know that this question is repeated one.
But no one could answer briefly enough to answer corrctly.
I am getting Nhibernate error " No row with given identiifer found error" when im trying to use the guid to give me the record from the table.
I am using Nhibernate load function to load the record with the unique identifier(GUID) but if the record is not there it is giving exception.
Am I missing some property in hbm.xml file?</p>
| <p>From the <a href="http://www.hibernate.org/hib%5Fdocs/nhibernate/1.2/reference/en/html%5Fsingle/#manipulatingdata-loading" rel="nofollow">documentation</a>, </p>
<blockquote>
<p>Note that Load() will throw an unrecoverable exception if there is no matching database row.</p>
</blockquote>
<p>If you want to query for a particular record and not have an exception, use an actual query or the <code>Get()</code> method.</p>
<p>Also from the documentation:</p>
<blockquote>
<p>If you are not certain that a matching row exists, you should use the Get() method, which hits the database immediately and returns null if there is no matching row.</p>
</blockquote>
<p>So use <code>Get()</code> and check the result for null.</p>
|
Help me find the best of WPF <p>I would like to find what people got the most out of using WPF, in particular:</p>
<ul>
<li>The best and stunning UI examples out there </li>
<li>Dark corners that no other UI can implement with ease and style (say MFC or GTK)</li>
<li>Professional examples with code </li>
</ul>
<p>Suggestions?</p>
<p>Probably the best book on the subject is <a href="http://manning.com/feldman2/" rel="nofollow">WPF in Action with Visual Studio 2008</a></p>
| <p>Here's some of my favorites:</p>
<ul>
<li><p><a href="http://www.vertigo.com/familyshow.aspx" rel="nofollow">Family.Show</a> - An genealogy application (with code)
<img src="http://blogcasts.de/dwalzen/blog/FamilyShow.png" alt="Family.Show" /></p></li>
<li><p><a href="http://www.photosuru.com/" rel="nofollow">PhotoSuru</a> - A photo browser (with code)
<img src="http://www.photosuru.com/default%5Ffiles/image002.jpg" alt="PhotoSuru" /></p></li>
<li><p><a href="http://72.32.149.120/index.html" rel="nofollow">Eikos Partners Products</a> - Just screenshots, but looks really nice
<img src="http://72.32.149.120/screens/EP9.jpg" alt="EP Trading" /></p></li>
</ul>
|
How to insert single quotes on a databound asp:hyperlink field in asp.net? <p>I am trying to bind an ASP.NET hyperlink to the "Handle" column of my dataset like this:</p>
<pre><code><ItemTemplate>
<asp:HyperLink ID="idTracking" runat="server" NavigateUrl='<%# "javascript:SendPath(" + Eval( "Handle", "{0}") + ")" %>' Text="Test" />
</ItemTemplate>
</code></pre>
<p>I would like the NavigateUrl to read: </p>
<pre><code>javascript:SendPath('123abc')
</code></pre>
<p>However, I cannot introduce the single quotes. How do I do this?</p>
| <p>As far as I know the text property of the hyperlink control automatically encodes, I've always has to simply do it as a standard html anchor tag.</p>
<p>So something like this.</p>
<pre><code><a href='<%# "javascript:SendPath(" + Eval( "Handle", "{0}") + ")" %>'>Your Link</a>
</code></pre>
|
How can I separate Visual State Managment from Custom Control template? <p>How can I separate Visual State Management from a Custom Control template?</p>
<p>I have one Custom Control, but with several different faces placed in templates.
All templates must have same state-based visualisation.
Is there any way to set my VSM once only? Otherwise I need to copy the VSM code in each template.</p>
| <p>Re-templating often leads to duplicate code, especially for VSM code. There isn't an easy way to abstract out that code today, unfortunately.</p>
|
Turning off auto-complete for text fields in Firefox <p>Am supposed to be learning French at the moment, but rather than learning any vocab, I've been mucking around with a rails app that tests vocab - so it displays a word, and I have to type its translation.</p>
<p>Unfortunately, Firefox remembers everything I've already type there, so which diminishes its usefulness somewhat.</p>
<p>Is it possible, through the options for form_for or otherwise, to turn this normally useful behaviour off?</p>
| <p>So it turns out it's pretty simple. Rather than</p>
<pre><code><%= f.text_field :fieldname %>
</code></pre>
<p>put</p>
<pre><code><%= f.text_field :fieldname, :autocomplete => :off %>
</code></pre>
|
How to change Entity type in JPA? <p>In my specific case, I am making use of a discriminator column strategy. This means that my JPA implementation (Hibernate) creates a <em>users</em> table with a special <em>DTYPE</em> column. This column contains the class name of the entity. For example, my <em>users</em> table can have subclasses of <strong>TrialUser</strong> and <strong>PayingUser</strong>. These class names would be in the <em>DTYPE</em> column so that when the EntityManager loads the entity from the database, it knows which type of class to instantiate. </p>
<p>I've tried two ways of converting Entity types and both feel like dirty hacks:</p>
<ol>
<li>Use a native query to manually do an UPDATE on the column, changing its value. This works for entities whose property constraints are similar.</li>
<li>Create a new entity of the target type, do a <em>BeanUtils.copyProperties()</em> call to move over the properties, save the new entity, then call a named query which manually replaces the new Id with the old Id so that all the foreign key constraints are maintained.</li>
</ol>
<p>The problem with #1 is that when you manually change this column, JPA doesn't know how to refresh/reattach this Entity to the Persistance Context. It expects a <strong>TrialUser</strong> with Id 1234, not a <strong>PayingUser</strong> with Id 1234. It fails out. Here I could probably do an EntityManager.clear() and detach all Entities/clear the Per. Context, but since this is a Service bean, it would wipe pending changes for all users of the system.</p>
<p>The problem with #2 is that when you delete the <strong>TrialUser</strong> all of the properties you have set to Cascade=ALL will be deleted as well. This is bad because you're only trying to swap in a different User, not delete all the extended object graph.</p>
<p><strong><em>Update 1</em></strong>: The problems of #2 have made it all but unusable for me, so I've given up on trying to get it to work. The more elegant of the hacks is definitely #1, and I have made some progress in this respect. The key is to first get a reference to the underlying Hibernate Session (if you're using Hibernate as your JPA implementation) and call the Session.evict(user) method to remove only that single object from your persistance context. Unfortunitely there is no pure JPA support for this. Here is some sample code:</p>
<pre><code> // Make sure we save any pending changes
user = saveUser(user);
// Remove the User instance from the persistence context
final Session session = (Session) entityManager.getDelegate();
session.evict(user);
// Update the DTYPE
final String sqlString = "update user set user.DTYPE = '" + targetClass.getSimpleName() + "' where user.id = :id";
final Query query = entityManager.createNativeQuery(sqlString);
query.setParameter("id", user.getId());
query.executeUpdate();
entityManager.flush(); // *** PROBLEM HERE ***
// Load the User with its new type
return getUserById(userId);
</code></pre>
<p>Notice the manual <strong>flush()</strong> which throws this exception:</p>
<pre><code>org.hibernate.PersistentObjectException: detached entity passed to persist: com.myapp.domain.Membership
at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:102)
at org.hibernate.impl.SessionImpl.firePersistOnFlush(SessionImpl.java:671)
at org.hibernate.impl.SessionImpl.persistOnFlush(SessionImpl.java:663)
at org.hibernate.engine.CascadingAction$9.cascade(CascadingAction.java:346)
at org.hibernate.engine.Cascade.cascadeToOne(Cascade.java:291)
at org.hibernate.engine.Cascade.cascadeAssociation(Cascade.java:239)
at org.hibernate.engine.Cascade.cascadeProperty(Cascade.java:192)
at org.hibernate.engine.Cascade.cascadeCollectionElements(Cascade.java:319)
at org.hibernate.engine.Cascade.cascadeCollection(Cascade.java:265)
at org.hibernate.engine.Cascade.cascadeAssociation(Cascade.java:242)
at org.hibernate.engine.Cascade.cascadeProperty(Cascade.java:192)
at org.hibernate.engine.Cascade.cascade(Cascade.java:153)
at org.hibernate.event.def.AbstractFlushingEventListener.cascadeOnFlush(AbstractFlushingEventListener.java:154)
at org.hibernate.event.def.AbstractFlushingEventListener.prepareEntityFlushes(AbstractFlushingEventListener.java:145)
at org.hibernate.event.def.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:88)
at org.hibernate.event.def.DefaultAutoFlushEventListener.onAutoFlush(DefaultAutoFlushEventListener.java:58)
at org.hibernate.impl.SessionImpl.autoFlushIfRequired(SessionImpl.java:996)
at org.hibernate.impl.SessionImpl.executeNativeUpdate(SessionImpl.java:1185)
at org.hibernate.impl.SQLQueryImpl.executeUpdate(SQLQueryImpl.java:357)
at org.hibernate.ejb.QueryImpl.executeUpdate(QueryImpl.java:51)
at com.myapp.repository.user.JpaUserRepository.convertUserType(JpaUserRepository.java:107)
</code></pre>
<p>You can see that the <strong>Membership</strong> entity, of which <strong>User</strong> has a OneToMany Set, is causing some problems. I don't know enough about what's going on behind the scenes to crack this nut.</p>
<p><strong><em>Update 2</em></strong>: The only thing that works so far is to change DTYPE as shown in the above code, then call <strong>entityManager.clear()</strong></p>
<p>I don't completely understand the ramifications of clearing the entire persistence context, and I would have liked to get <strong>Session.evict()</strong> working on the particular Entity being updated instead.</p>
| <p>Do you really need to represent the subscription level in the User type? Why don't you add a Subscription type in your system?</p>
<p>The relation would then be expressed as: a User has one Subscription. It could also be modeled as a one-to-many relationship if you wish to keep an history of subscriptions.</p>
<p>Then when you want to change the Subscription level of a User, instead of instantiating a new User you would create a new Subscription and assign it to a user.</p>
<pre><code>// When you user signs up
User.setSubscription(new FreeSubscription());
// When he upgrades to a paying account
User.setSubscription(new PayingSubscription());
</code></pre>
<p>Is a TrialUser really that different from a PayingUser? Probably not. You would be better served with aggregation instead of inheritance.</p>
<p>The Subscription data can be stored in a separate table (mapped as an Entity) or it can be stored inside the Users table (mapped as a Component).</p>
|
TripleDES: Specified key is a known weak key for 'TripleDES' and cannot be used <p>I'm using the .NET 3.0 class <code>System.Security.Cryptography.MACTripleDES</code> class to generate a MAC value. Unfortunately, I am working with a hardware device that uses "<code>1111111111111111</code>" (as hex) as a single-length DES key. The <code>System.Security.Cryptography</code> library does some sanity checking on the key and returns a Exception if you try to use a cryptographically weak key.</p>
<p>For example:</p>
<pre><code>byte[] key = new byte[24];
for (int i = 0; i < key.Length; i++)
key[i] = 0x11;
byte[] data = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
byte[] computedMac = null;
using (MACTripleDES mac = new MACTripleDES(key))
{
computedMac = mac.ComputeHash(data);
}
</code></pre>
<p>throws an exception</p>
<pre><code>System.Security.Cryptography.CryptographicException : Specified key is a known weak key for 'TripleDES' and cannot be used.
</code></pre>
<p>I know this is not a secure key. In production, the device will be flashed with a new, secure key. In the mean time, is there any way to inhibit this Exception from being thrown? Perhaps an <code>app.config</code> or registry setting?</p>
<p>Edit: The key would actually be 101010... due to the algorithm forcing odd parity. I'm not sure if this is universal to the DES algorithm or just a requirement in the payment processing work I do.</p>
<p>Edit 2: Daniel's answer below has some very good information about hacking .NET. Unfortunately, I wasn't able to solve my problem using this technique, but there is still some interesting reading there.</p>
| <p>I wouldn't really recommend it, but you should be able to modify the IL-code that checks for weak keys using <a href="http://sebastien.lebreton.free.fr/reflexil/" rel="nofollow">Reflector</a> and the Add-in <a href="http://www.red-gate.com/products/reflector/" rel="nofollow">ReflexIL</a></p>
<p>edit:</p>
<p>Sorry, it took a while for me to load all of it up in my Virtual Machine (running Ubuntu) and didn't want to mess with Mono.</p>
<ul>
<li>Install the ReflexIL Add-in: View -> Add-ins -> Add</li>
<li>Open ReflexIL: Tools -> ReflexIL v0.9</li>
<li>Find the IsWeakKey() function. (You can use Search: F3)</li>
<li>Two functions will come up, doubleclick the one found in System.Security.Cryptography.TripleDES</li>
<li>ReflexIL should have come up too. In the Instructions tab, scroll all the way down to line 29 (offset 63).</li>
<li>Change ldc.i4.1 to ldc.i4.0, this means the function will always return false.</li>
</ul>
<p>In your assemblies pane (left one), you can now scroll up and click on "Common Language Runtime Library", the ReflexIL pane will give you an option to save it.</p>
<p>Important notes:</p>
<ul>
<li>BACK UP your original assembly first! (mscorlib.dll)</li>
<li>mscorlib.dll is a signed assembly and you will need the .NET SDK (sn.exe tool) for ReflexIL to make it skip verification. I just checked this myself, you should already have this with Visual C# installed. Just click "Register it for verification skipping (on this computer)" when asked to.</li>
<li>I don't think I have to tell you to only use this on your development machine :)</li>
</ul>
<p>Good luck! If you need additional instructions, please feel free to use the commentbox.</p>
<p>edit2:</p>
<p>I'm confused!</p>
<p><a href="http://i44.tinypic.com/2r6fwbo.png" rel="nofollow"><img src="http://i44.tinypic.com/2r6fwbo_th.png"></a></p>
<p>I completely removed the IsWeakKey check from the set_Key function in the mscorlib assembly. I am absolutely certain that I modified the correct function, and that I did it correctly. Reflector's disassembler does no longer show the check. The funny thing is however, that Visual C# still throws the same exception.</p>
<p>This leads me to believe that mscorlib must somehow still be cached somewhere. However, renaming mscorlib.dll to mscorlib.dll_ leads MSVC# to crash, so it must still be dependent on the original dll.</p>
<p>This is quite interesting stuff, but I think I've reached the point where I have no clue what is going on, it just doesn't make any sense! See attached image. :(</p>
<p>edit3:</p>
<p>I notice in Olly, that unlike assemblies such as mscoree, mscorsec and mscorwks; mscorlib.dll isn't actually located in:
c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\</p>
<p>But instead, in what appears to be a non-existent location:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\6d667f19d687361886990f3ca0f49816\mscorlib.ni.dll</p>
<p>I think I am missing something here :) Will investigate this some more.</p>
<p>edit4:</p>
<p>Even after having patched out EVERYTHING in IsWeakKey, and played around with both removing and generating new native images (x.<b>ni</b>.dll) of mscorlib.dll using "ngen.exe", I am getting the same exception. I must be noted that even after uninstalling the native mscorlib images, it is still using mscorlib.ni.dll... Meh.</p>
<p>I give up. I hope someone will be able to answer what the hell is going on because I sure don't know. :)</p>
|
Lucene SpanQuery - what is it good for? <p>Can someone explain or provide a link to an explanation of what a SpanQuery is, and what are typical use cases for it?</p>
<p>The <a href="http://lucene.apache.org/java/2%5F4%5F1/api/org/apache/lucene/search/spans/SpanQuery.html">javadoc</a> is very laconic, and keeps mentioning the concept of "Span", which I'm not quite sure I get.</p>
<p>Also, I'm interested in the <a href="http://lucene.apache.org/java/2%5F4%5F1/api/contrib-highlighter/org/apache/lucene/search/highlight/SpanScorer.html"><code>SpanScorer</code></a> in the highlighter, and what it does exactly.</p>
| <p>Spans provide a <a href="https://lucene.apache.org/core/4_10_0/core/org/apache/lucene/search/spans/package-summary.html#package_description" rel="nofollow">proximity search</a> feature to Lucene. They are used to find multiple terms near each other, without requiring the terms to appear in a specified order. You can specify the terms that you want to find, and how close they must be. You can combine these span queries with each other or with other types of Lucene queries.</p>
|
Sandcastle Help File Builder and VS 2008 <p>how to add a sandcastle help file builder project (.shfbproj) to a visual studio 2008 solution?</p>
| <p>Yes, there is a way to create Sandcastle docs inside Visual Studio: <a href="http://www.codeplex.com/DocProject" rel="nofollow">DocProject</a></p>
<p>To quote the project web site:</p>
<blockquote>
<p>DocProject drives the Sandcastle help
generation tools using the power of
Visual Studio 2005/2008 and MSBuild.
Choose from various project templates
that build compiled help version 1.x
or 2.x for all project references.
DocProject facilitates the
administration and development of
project documentation with Sandcastle,
allowing you to use the integrated
tools of Visual Studio to customize
Sandcastle's output.</p>
</blockquote>
<p>Marc</p>
|
Converting Ruby to C# <p>Need to convert the following code from Ruby to C#. However I'm kind of puzzled by the use of the yield keyword and the general syntax of Ruby. Can anyone that knows a little bit Ruby please help out and convert the code </p>
<pre><code>class < < Cache
STALE_REFRESH = 1
STALE_CREATED = 2
# Caches data received from a block
#
# The difference between this method and usual Cache.get
# is following: this method caches data and allows user
# to re-generate data when it is expired w/o running
# data generation code more than once so dog-pile effect
# won't bring our servers down
#
def smart_get(key, ttl = nil, generation_time = 30.seconds)
# Fallback to default caching approach if no ttl given
return get(key) { yield } unless ttl
# Create window for data refresh
real_ttl = ttl + generation_time * 2
stale_key = "#{key}.stale"
# Try to get data from memcache
value = get(key)
stale = get(stale_key)
# If stale key has expired, it is time to re-generate our data
unless stale
put(stale_key, STALE_REFRESH, generation_time) # lock
value = nil # force data re-generation
end
# If no data retrieved or data re-generation forced, re-generate data and reset stale key
unless value
value = yield
put(key, value, real_ttl)
put(stale_key, STALE_CREATED, ttl) # unlock
end
return value
end
</code></pre>
<p>end</p>
| <p>I don't know C# at all, so anything I say about C# should be taken with a grain of salt. However, I will try to explain what goes on in that piece of Ruby code.</p>
<pre><code>class << Cache
</code></pre>
<p>Ruby has something called <em>singleton methods</em>. These have nothing to do with the Singleton Software Design Pattern, they are just methods that are defined for one and only one object. So, you can have two instances of the same class, and add methods to one of those two objects.</p>
<p>There are two different syntaxes for singleton methods. One is to just prefix the name of the method with the object, so <code>def foo.bar(baz)</code> would define a method <code>bar</code> only for object <code>foo</code>. The other method is called <em>opening up the singleton class</em> and it looks syntactically similar to defining a class, because that's also what happens semantically: singleton methods actually live in an invisible class that gets inserted between the object and its actual class in the class hierarchy.</p>
<p>This syntax looks like this: <code>class << foo</code>. This opens up the singleton class of object <code>foo</code> and every method defined inside of that class body becomes a singleton method of object <code>foo</code>.</p>
<p>Why is this used here? Well, Ruby is a pure object-oriented language, which means that <em>everything</em>, including classes is an object. Now, if methods can be added to individual objects, and classes are objects, this means that methods can be added to individual classes. In other words, Ruby has no need for the artificial distinction between regular methods and static methods (which are a fraud, anyway: they aren't really methods, just glorified procedures). What is a static method in C#, is just a regular method on a class object's singleton class.</p>
<p>All of this is just a longwinded way of explaining that everything defined between <code>class << Cache</code> and its corresponding <code>end</code> becomes <code>static</code>.</p>
<pre><code> STALE_REFRESH = 1
STALE_CREATED = 2
</code></pre>
<p>In Ruby, every variable that starts with a capital letter, is actually a constant. However, in this case we won't translate these as <code>static const</code> fields, but rather an <code>enum</code>, because that's how they are used.</p>
<pre><code> # Caches data received from a block
#
# The difference between this method and usual Cache.get
# is following: this method caches data and allows user
# to re-generate data when it is expired w/o running
# data generation code more than once so dog-pile effect
# won't bring our servers down
#
def smart_get(key, ttl = nil, generation_time = 30.seconds)
</code></pre>
<p>This method has three parameters (four actually, we will see exactly <em>why</em> later), two of them are optional (<code>ttl</code> and <code>generation_time</code>). Both of them have a default value, however, in the case of <code>ttl</code> the default value isn't really used, it serves more as a marker to find out whether the argument was passed in or not.</p>
<p><code>30.seconds</code> is an extension that the <code>ActiveSupport</code> library adds to the <code>Integer</code> class. It doesn't actually do anything, it just returns <code>self</code>. It is used in this case just to make the method definition more readable. (There are other methods which do something more useful, e.g. <code>Integer#minutes</code>, which returns <code>self * 60</code> and <code>Integer#hours</code> and so on.) We will use this as an indication, that the type of the parameter should not be <code>int</code> but rather <code>System.TimeSpan</code>.</p>
<pre><code> # Fallback to default caching approach if no ttl given
return get(key) { yield } unless ttl
</code></pre>
<p>This contains several complex Ruby constructs. Let's start with the easiest one: trailing conditional modifiers. If a conditional body contains only one expression, then the conditional can be appended to the end of the expression. So, instead of saying <code>if a > b then foo end</code> you can also say <code>foo if a > b</code>. So, the above is equivalent to <code>unless ttl then return get(key) { yield } end</code>.</p>
<p>The next one is also easy: <code>unless</code> is just syntactic sugar for <code>if not</code>. So, we are now at <code>if not ttl then return get(key) { yield } end</code></p>
<p>Third is Ruby's truth system. In Ruby, truth is pretty simple. Actually, falseness is pretty simple, and truth falls out naturally: the special keyword <code>false</code> is false, and the special keyword <code>nil</code> is false, everything else is true. So, in this case the conditional will <em>only</em> be true, if <code>ttl</code> is either <code>false</code> or <code>nil</code>. <code>false</code> isn't a terrible sensible value for a timespan, so the only interesting one is <code>nil</code>. The snippet would have been more clearly written like this: <code>if ttl.nil? then return get(key) { yield } end</code>. Since the default value for the <code>ttl</code> parameter is <code>nil</code>, this conditional is true, if no argument was passed in for <code>ttl</code>. So, the conditional is used to figure out with how many arguments the method was called, which means that we are not going to translate it as a conditional but rather as a method overload.</p>
<p>Now, on to the <code>yield</code>. In Ruby, every method can accept an implicit code block as an argument. That's why I wrote above that the method actually takes <em>four</em> arguments, not three. A code block is just an anonymous piece of code that can be passed around, stored in a variable, and invoked later on. Ruby inherits blocks from Smalltalk, but the concept dates all the way back to 1958, to Lisp's lambda expressions. At the mention of anonymous code blocks, but at the very least now, at the mention of lambda expressions, you should know how to represent this implicit fourth method parameter: a delegate type, more specifically, a <code>Func</code>.</p>
<p>So, what's <code>yield</code> do? It transfers control to the block. It's basically just a very convenient way of invoking a block, without having to explicitly store it in a variable and then calling it.</p>
<pre><code> # Create window for data refresh
real_ttl = ttl + generation_time * 2
stale_key = "#{key}.stale"
</code></pre>
<p>This <code>#{foo}</code> syntax is called <em>string interpolation</em>. It means "replace the token inside the string with whatever the result of evaluating the expression between the braces". It's just a very concise version of <code>String.Format()</code>, which is exactly what we are going to translate it to.</p>
<pre><code> # Try to get data from memcache
value = get(key)
stale = get(stale_key)
# If stale key has expired, it is time to re-generate our data
unless stale
put(stale_key, STALE_REFRESH, generation_time) # lock
value = nil # force data re-generation
end
# If no data retrieved or data re-generation forced, re-generate data and reset stale key
unless value
value = yield
put(key, value, real_ttl)
put(stale_key, STALE_CREATED, ttl) # unlock
end
return value
end
end
</code></pre>
<p>This is my feeble attempt at translating the Ruby version to C#:</p>
<pre><code>public class Cache<Tkey, Tvalue> {
static const enum Stale { Refresh, Created };
/* Caches data received from a delegate
*
* The difference between this method and usual Cache.get
* is following: this method caches data and allows user
* to re-generate data when it is expired w/o running
* data generation code more than once so dog-pile effect
* won't bring our servers down
*/
public static Tvalue SmartGet(Tkey key, TimeSpan ttl, TimeSpan generationTime, Func<Tvalue> strategy)
{
// Create window for data refresh
var realTtl = ttl + generationTime * 2;
var staleKey = String.Format("{0}stale", key);
// Try to get data from memcache
var value = Get(key);
var stale = Get(staleKey);
// If stale key has expired, it is time to re-generate our data
if (stale is null)
{
Put(staleKey, Stale.Refresh, generationTime); // lock
value = null; // force data re-generation
}
// If no data retrieved or data re-generation forced, re-generate data and reset stale key
if (value is null)
{
value = strategy();
Put(key, value, realTtl);
Put(staleKey, Stale.Created, ttl) // unlock
}
return value;
}
// Fallback to default caching approach if no ttl given
public static Tvalue SmartGet(Tkey key, Func<Tvalue> strategy)
{
return Get(key, strategy);
}
// Simulate default argument for generationTime
// C# 4.0 has default arguments, so this wouldn't be needed.
public static Tvalue SmartGet(Tkey key, TimeSpan ttl, Func<Tvalue> strategy)
{
return SmartGet(key, ttl, new TimeSpan(0, 0, 30), strategy);
}
// Convenience overloads to allow calling it the same way as
// in Ruby, by just passing in the timespans as integers in
// seconds.
public static Tvalue SmartGet(Tkey key, int ttl, int generationTime, Func<Tvalue> strategy)
{
return SmartGet(key, new TimeSpan(0, 0, ttl), new TimeSpan(0, 0, generationTime), strategy);
}
public static Tvalue SmartGet(Tkey key, int ttl, Func<Tvalue> strategy)
{
return SmartGet(key, new TimeSpan(0, 0, ttl), strategy);
}
}
</code></pre>
<p>Please note that I do not know C#, I do not know .NET, I have not tested this, I don't even know if it is syntactically valid. Hope it helps anyway.</p>
|
iPhone SDK: How can I determine the last active tab in a TabBarController? <p>One of the tab bar controller tabs in my iPhone app changes what it displays based on where the user arrived from (which other tabs). For example, if the tabs are A, B, C and D, the C tab will display a picture if the user was previously on tab A, but text if the user was previously on tab B. </p>
<p>I'm not sure how to implement this without subclassing the TabBarController (which Apple documentation discourages). TabBarController has a property for currently active controller, and a list of all controllers in the tab bar, but no way to see the 'tab bar controller traversion tree/stack', so to speak. Any thoughts?</p>
| <p>Instead of subclass <code>UITabBarController</code> you can set a delegate and keep track of the last selected view controller via </p>
<pre><code>- (void)tabBarController:(UITabBarController *)tabBarController
didSelectViewController:(UIViewController *)viewController;
</code></pre>
|
Converting a C++ .exe project to a dll <p>Microsoft provides the source code of vshadow to manipulate VSS (Volume Shadow Service [shadow copy]), and I've modified it a bit but I want to make it into a dll so I can use it in my C# projects. I don't know exactly how to go about doing that, the source code is fairly simple, and it shouldn't be too hard, but I don't really know where to get started. How should I go about converting it to a usable dll instead of compiling to a executable?</p>
<p><b>Update</b>: Someone has already done this: <a href="http://www.alphaleonis.com/2008/08/alphavss-bringing-windows-shadow-copy-service-vss-to-net/" rel="nofollow">http://www.alphaleonis.com/2008/08/alphavss-bringing-windows-shadow-copy-service-vss-to-net/</a></p>
| <p>You will need to change your project settings in Visual Studio to create a DLL. In addition you will need to define dll entry points.</p>
<p><strike>However, the VSS is a set of COM API's, so you can call them directly from C# with pinvoke, instead of using this wrapper C++ executable. </strike></p>
<p>Since the SDK only contains libs, not DLL's you'll have to create a dll project to use it.</p>
<p>This is a <a href="http://geeklit.blogspot.com/2006/08/calling-c-lib-from-c.html" rel="nofollow">good blog-how-to</a>.</p>
<p>You'll need to download the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=0b4f56e4-0ccc-4626-826a-ed2c4c95c871&DisplayLang=en#QuickInfoContainer" rel="nofollow">VSS SDK</a> (if you haven't already).</p>
<p><a href="http://msdn.microsoft.com/en-us/magazine/cc164123.aspx" rel="nofollow">Decent article on pinvoke.</a></p>
<p>Hope this helps.</p>
|
Does it make sense to integrate scripting languages to C# apps? <p>I have been thinking about integrating Ruby into my app, but some of my friends at work told me that C# is already very high level. But to me it seems like it has more baggage for doing very quick things.</p>
<p>What do you guys think?</p>
<p>Also if I do integrate, then does it make sense to limit it so that you can do just about anything using the existing functionality of the app, but not extend it?</p>
<p>Reason for this is, scritping languages aren't known for performance, and if you say give people to write Filters like Blur, Contrast, etc, then those would be way slower than they should be and degrade the experience of the client of the scripter, right?</p>
| <p>I've integrated (lua) scripting into applications, and I've also used c# itself as a "scripting language", by compiling dynamic assemblies on-the-fly from code provided by the user. I've also implemented "plug-in" systems using user-provided assemblies that conform to specific interfaces or base classes.</p>
<p>There are lots of things to consider, from security, to performance, to end-user confusion to consider. I don't think that you could make a blanket statement like "scripting languages don't belong in applications", or even "scripting languages belong in applications". Any given specific case needs careful consideration of all the options and the consequences of those options before running off and doing something that you might regret later.</p>
|
Linq to SQL - Update a calculated field (like "subtotal") on parent object when child objects change <p>I have a L2S SalesOrder entity with a child set of LineItems. Using winforms, on my Sales Order form I have a datagridview bound to the LineItems and it works like a dream. If the user changes a LineItem quantity (for instance), my LineItem partial class handles the OnQuantityChanged and recalculates the LineItem SubTotal field and the grid is automagically updated. I'm ecstatic with how clean and neat it is.</p>
<p>Now I would like to have a calculated field on my SalesOrder object called "Total" that is the total of all the LineItems' SubTotal fields (plus a few other things like tax and shipping, but don't worry about that for now). What is the best/cleanest way for the SalesOrder's Total field to be automagically updated whenever a LineItem is changed? If someone could just point me in the right direction on this I would be most appreciative. </p>
<p>Don't know if it makes a difference but I'm using <a href="http://www.west-wind.com/WebLog/posts/246690.aspx" rel="nofollow">Rick Strahl's Linq To SQL business framework</a> (and it is fantastic, BTW!).</p>
<p>Thanks!</p>
| <p>You might want to check out <a href="http://www.codeplex.com/bindablelinq" rel="nofollow">Bindable LINQ</a>:</p>
<blockquote>
<p>Bindable LINQ is a set of extensions
to LINQ that add data binding and
change propagation capabilities to
standard LINQ queries.</p>
</blockquote>
|
SharePoint deployment failure using VS2008 on the comannd line <p>I am trying to implement a nightly build environment for our SharePoint solution that includes VS 2008 and VS 2008 extensions for Windows SharePoint Services 3.0 (version 1.2).
When I deploy via the VS 2008 GUI it works fine.
When I use the command line:</p>
<pre><code>c:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe SharePoint.sln /Deploy Release
</code></pre>
<p>I get the following error:</p>
<pre><code>------ Deploy started: Project: SharePoint.Site, Configuration: Release Any CPU ------
------ Generate solution file and setup batch file ------
Creating solution ...
System.NotImplementedException
Error: The method or operation is not implemented.
</code></pre>
<p>Others seem to be having <a href="http://social.msdn.microsoft.com/Forums/en-US/sharepointdevelopment/thread/5241b654-49b1-407f-aa6d-f4a739cc9b3b" rel="nofollow">similar issues</a>.</p>
| <p>VSeWSS 1.2 doesn't support command line builds. I would either try the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=FB9D4B85-DA2A-432E-91FB-D505199C49F6&displaylang=en" rel="nofollow">CTP for VSeWSS 1.3</a> or a community tool like <a href="http://stsdev.codeplex.com/" rel="nofollow">STSDev</a> or <a href="http://wspbuilder.codeplex.com/" rel="nofollow">WSPBuilder</a>.</p>
|
How can you change an age-mismatched PDB to match properly? <p>Our nightly build process was broken for a long time, such that it generated PDB files that were a few hours different in age than the corresponding image files. I have since fixed the problem.</p>
<p>However, I would like to start using a symbol server, but cannot due to having to use these age-mismatched pdb files. I work around this issue by using the .symopt +0x40 method in windbg. That means I have to organize all my pdb files by hand, and after years upon years of releases, that adds up.</p>
<p>I am looking for a way to modify the mechanism that windbg uses to mark a pdb's age, and force it to match my image file. The utility <a href="http://www.debuginfo.com/tools/chkmatch.html">ChkMatch</a> does something similar, but for pdb signatures. The developer states on the page "ChkMatch is capable of making an executable and PDB file match if they have different signatures but the same age (see this article for more information about PDB signature and age). If the age differs, the tool cannot make the files match."</p>
<p>I took a look inside a hexeditor, and even found what looked like the bits corresponding to the age, but it must pull some more tricks internally, cause I couldn't get it to work.</p>
<p>Any ideas?</p>
<p><strong>EDIT</strong>:
I don't know if this helps, but in my particular case the age difference was caused by unnecessarily relinking dll's, which would recreate the PDB files as well. However, our build process was storing the original dlls (before the relink), and the pdb after the relink. I thought about somehow recreating such a situation by hand. Meaning, forcing a relink on a DLL, but saving off the pdb in both cases. Then I could do a binary compare of the two files to see how they changed. Perhaps run some sort of patching software that does this automatically? By seeing what exactly changed in my control case, perhaps I could do the same to the DLLs and PDBs saved in my companies build process? </p>
<p><strong>EDIT</strong>:
I FIGURED IT OUT!!!! Thanks to one of the comments on the first answer, I checked out a link to the pdfs of the book "Undocumented Windows 2000 Secrets: A Programmers Cookbook". And the author goes into great detail about the pdb file format. As I said before, I had already loaded the pdb into a hex editor and flipped some bits around appearing that I made the age/signature match, but it didn't work. Well, after using the utility from the W2k secrets book to "explode" the pdb into the included streams, I found out that they hide another reference to the age in stream 3!!!!!!! Once I flipped that one as well, it matched up in windbg. THIS IS HUGE!!!! Thank you so much....symbol server HERE I COME!</p>
| <p>the windbg will not modify pdb's age - it only looks it up to match that of executable - the compiler does when it (re)generates executable and debug files.
<p>now, based on the debuginfo.com article, it is not too difficult to arrive at the proper debug directory (of type codeview), match it against PDB7 signature and make modifications to either age or GUID inside an executable. why is that not an option?
<p>i guess, you want to update pdb instead? i'm afraid, pdb is a proprietary format. there're multiple read-only APIs (dbghelp.dll and dia sdk), but as far as modifications go, you need to guess the details to be able to modify.</p>
|
How can I improve this Rails code? <p>I'm writing a little browser game as a project to learn RoR with and I'm quite new to it.</p>
<p>This is a little method that's called regularly by a cronjob.</p>
<p>I'm guessing there should be some way of adding elements to the potions array and then doing a bulk save at the end, I'm also not liking hitting the db each time in the loop to get the number of items for the market again.</p>
<pre><code>def self.restock_energy_potions
market = find_or_create_market
potions = EnergyPotion.find_all_by_user_id(market.id)
while (potions.size < 5)
potion = EnergyPotion.new(:user_id => market.id)
potion.save
potions = EnergyPotion.find_all_by_user_id(market.id)
end
end
</code></pre>
| <p>I'm not sure I'm understanding your question. Are you looking for something like this?</p>
<pre><code>def self.restock_energy_potions
market = find_or_create_market
potions = EnergyPotion.find_all_by_user_id(market.id)
(potions.size...5).each {EnergyPotion.new(:user_id => market.id).save }
end
end
</code></pre>
<p>Note the triple dots in the range; you don't want to create a potion if there are already 5.</p>
<p>Also, if your potions were linked (e.g. by <code>has_many</code>) you could create them through the <code>market.potions</code> property (I'm guessing here, about the relationship between users and markets--details depend on how your models are set up) and save them all at once. I don't think the data base savings would be significant though.</p>
|
Working with jQuery Slider - positions <p>I have been working with the slider and am using the following code:</p>
<pre><code> $(function(){
$('#slider').slider({
animate: true,
step: 1,
min: 0,
max: 10,
orientation: 'vertical',
start: function(event, ui){
$('#current_value').empty();
$('#current_value').fadeIn().append('Value is ' + ui.value);
},
change: function(event, ui){
alert();
//$('#current_value').empty();
}
});
});
</code></pre>
<p>I am trying to get it for at the top it is a value of 10 and the bottom is a value of 1 and step 1. Does that look correct?</p>
<p>The other problem I am having is when you move from one position to another, I want it to show the position it stopped on (the current). </p>
<p>So if it is at 4 and you click 7, when you stop append to the DIV I tried changed and stop, but it isnt behaving that way. It is taking the wrong position value.</p>
<p><strong>Link</strong>: <a href="http://www.ryancoughlin.com/demos/interactive-slider/index.html" rel="nofollow">http://www.ryancoughlin.com/demos/interactive-slider/index.html</a>
if you use the keyboard and go to the bottom my goal is to have it step from 1 to 10 in 1 increments </p>
<p>Any thoughts?</p>
| <p>replace your CHANGE event with SLIDE ... i've asked <a href="http://stackoverflow.com/questions/621147/jquery-ui-slider-cant-slide-to-0">similar question</a> a while ago.</p>
<p>you might want to add STOP event as well ... move your logic from START to SLIDE and STOP</p>
|
Hide mouse cursor after an idle time <p>I want to hide my mouse cursor after an idle time and it will be showed up when I move the mouse. I tried to use a timer but it didn't work well. Can anybody help me? Please!</p>
| <p>If you are using WinForms and will only deploy on Windows machines then it's quite easy to use <a href="http://msdn.microsoft.com/en-us/library/ms646302.aspx"><code>user32 GetLastInputInfo</code></a> to handle both mouse and keyboard idling.</p>
<pre><code>public static class User32Interop
{
public static TimeSpan GetLastInput()
{
var plii = new LASTINPUTINFO();
plii.cbSize = (uint)Marshal.SizeOf(plii);
if (GetLastInputInfo(ref plii))
return TimeSpan.FromMilliseconds(Environment.TickCount - plii.dwTime);
else
throw new Win32Exception(Marshal.GetLastWin32Error());
}
[DllImport("user32.dll", SetLastError = true)]
static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
struct LASTINPUTINFO
{
public uint cbSize;
public uint dwTime;
}
}
</code></pre>
<p>And then in your <code>Form</code></p>
<pre><code>public partial class MyForm : Form
{
Timer activityTimer = new Timer();
TimeSpan activityThreshold = TimeSpan.FromMinutes(2);
bool cursorHidden = false;
public Form1()
{
InitializeComponent();
activityTimer.Tick += activityWorker_Tick;
activityTimer.Interval = 100;
activityTimer.Enabled = true;
}
void activityWorker_Tick(object sender, EventArgs e)
{
bool shouldHide = User32Interop.GetLastInput() > activityThreshold;
if (cursorHidden != shouldHide)
{
if (shouldHide)
Cursor.Hide();
else
Cursor.Show();
cursorHidden = shouldHide;
}
}
}
</code></pre>
|
Best way to reload web assemblies without IISReset <p>What's the best way to reload assemblies after you do a publish to a website and or gac some assemblies.</p>
<p>An easy trick I've learned is to touch the web.config and it reloads the app domain. </p>
<p>What are the best practices related to this?</p>
<p>Is it possible to update a Server Activated Serviced Component without an IISRESET that is referenced by a webpage? </p>
<p>Thanks</p>
| <p>you can run </p>
<blockquote>
<p>iisapp.vbs /a "App Pool Name" /r</p>
</blockquote>
<p>This will restart the app pool and leave the rest of the app pools untouched. No IIS Services are stopped or started.</p>
|
convert sql to linq <pre><code>select m.messageID,m.[addeddate],m.message,count(*) as Comments
from intranet.dbo.Blog_Messages AS m inner join
intranet.dbo.Blog_Comments AS c on c.messageid = m.messageid
group by m.messageID,m.[addeddate],m.message
</code></pre>
<p>need help converting this to linq to sql</p>
| <pre><code>from m in context.Blog_Messages
select new
{
MessageId = m.MessageID,
AddedDate = m.AddedDate,
Message = m.Message,
Comments = m.Blog_Comments.Count()
}
</code></pre>
<p>It isn't a direct conversion, but I think that is what you are after.</p>
|
Using JQuery hover with HTML image map <p>I have a complicated background image with a lot of small regions that need rollover illustration highlights, along with additional text display and associated links for each one. The final illustration stacks several static images with transparency using z-index, and the highlight rollover illustrations need to display in one of the in-between âsandwichâ layers to achieve the desired effect.</p>
<p>After some unsuccessful fiddling with blocks, I decided this might be done with an old-school image map. I made a schematic test map with four geometric shape outlines and âfilledâ them using with png rollovers. The idea is to associate the image map with the bottom background layer, initialize all the rollovers with css {visibility: hidden} and use Jqueryâs hover method to make them visible as well as reveal associated text in a separate div. The separate text function is why Iâm not trying to this with the :hover pseudoclass instead of jQuery hover. Because I was using the image map, I made all the rollover pngs (which have transparent backgrounds) sized to the full container for exact placement so everything lines up precisely.</p>
<p>What I got works... not really! The image map is correctly mapped to activate only the geometric areas. But the href from each rollover area works only intermittently, and using Jquery hover with css visibility is messed up. Desired behavior is that rolling into the area simply would make the shape solid. What actually happens is any motion inside the shape makes rapid toggling between visible and hidden; when the cursor stops within the shape, it might be visible or it might not. Any ideas appreciated!</p></p>
<p>sample hover setup (Iâll ultimately use arrays for real rollovers, associated links and text):</p>
<pre><code>$('#triangle').hover(
function() {
$('#ID_triangle').css({'visibility' : 'visible'});
},
function() {
$('#ID_triangle').css({'visibility' : 'hidden'});
}
)
</code></pre>
<p>image map:</p>
<pre><code><div id="container">
<img src="images/testMap_w.png" width="800" height="220" alt="TestMap W" usemap="#testMap">
<map name="testMap">
<area shape="polygon" coords="20,20,106,20,106,106,20,106" href="http://www.stackoverflow.com" id="box" />
<area shape="polygon" coords="216,50,339,50,277,156" href="http://www.google.com" id="triangle" />
<area shape="polygon" coords="460,0,574,0,460,220" href="http://www.cnn.com" id="bordertriangle" />
<area shape="polygon" coords="704,65,769,115,744,196,665,196,640,115" href="http://slashdot.org" id="pentagon" />
</map>
<img src="images/testMap_box.png" width="800" height="220" alt="TestMap Box" id="ID_box">
<img src="images/testMap_triangle.png" width="800" height="220" alt="TestMap Triangle" id="ID_triangle">
<img src="images/testMap_border_triangle.png" width="800" height="220" alt="TestMap Border Triangle" id="ID_bordertriangle">
<img src="images/testMap_pentagon.png" width="800" height="220" alt="TestMap Pentagon" id="ID_pentagon">
</div>
</code></pre>
| <p>You should check out this plugin:</p>
<p><a href="https://github.com/kemayo/maphilight">https://github.com/kemayo/maphilight</a></p>
<p>and the demo:</p>
<p><a href="http://davidlynch.org/js/maphilight/docs/demo_usa.html">http://davidlynch.org/js/maphilight/docs/demo_usa.html</a></p>
<p>if anything, you might be able to borrow some code from it to fix yours.</p>
|
How to determine UIWebView height based on content, within a variable height UITableView? <p>I am trying to create a <code>UITableView</code> with variable height rows as explained in the answer to <a href="http://stackoverflow.com/questions/272584/is-there-a-better-way-to-determine-the-right-size-for-a-uitableviewcell">this question</a></p>
<p>My problem is each cell contains a <code>UIWebView</code> with different (statically loaded) content I can't figure out how to calculate the proper height based on the content. Is there a way to do this? I've tried things like this:</p>
<pre><code> (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
WebViewCell *cell = (WebViewCell*)[self tableView:tableView cellForRowAtIndexPath:indexPath];
[cell setNeedsLayout];
[cell layoutIfNeeded];
return cell.bounds.size.height;
}
</code></pre>
<p>The cells themselves are loaded from a nib, which is simply a <code>UITableViewCell</code> containing a <code>UIWebView</code>. (It would also be fine if the cells just adjusted themselves to the largest of the html content, though variable height would be nicer).</p>
| <p>This code is probably too slow for table view use, but does the trick. It doesn't look like there's any alternative, as UIWebView offers no direct access to the DOM.</p>
<p>In a view controller's <code>viewDidLoad</code> I load some HTML in a webview and when the load is finished run some javascript to return the element height.</p>
<pre><code>- (void)viewDidLoad
{
[super viewDidLoad];
webview.delegate = self;
[webview loadHTMLString:@"<div id='foo' style='background: red'>The quick brown fox jumped over the lazy dog.</div>" baseURL:nil];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSString *output = [webview stringByEvaluatingJavaScriptFromString:@"document.getElementById(\"foo\").offsetHeight;"];
NSLog(@"height: %@", output);
}
</code></pre>
|
What is a good SQL Server 2008 solution for handling massive writes so that they don't slow down reads for users of the database? <p>We have large SQL Server 2008 databases. Very often we'll have to run massive data imports into the databases that take a couple hours. During that time everyone else's read and small write speeds slow down a ton. </p>
<p>I'm looking for a solution where maybe we setup one database server that is used for bulk writing and then two other database servers that are setup to be read and maybe have small writes made to them. The goal is to maintain fast small reads and writes while the bulk changes are running.</p>
<p>Does anyone have an idea of a good way to accomplish this using SQL Server 2008?</p>
| <p>Paul. There's two parts to your question.</p>
<p><strong>First, why are writes slow?</strong></p>
<p>When you say you have large databases, you may want to clarify that with some numbers. The Microsoft teams have demonstrated multi-terabyte loads in less than an hour, but of course they're using high-end gear and specialized data warehousing techniques. I've been involved with data warehousing teams that regularly loaded so much data overnight that the transaction log drives had to be over a terabyte just to handle the quick bursts, but not a terabyte per hour.</p>
<p>To find out why writes are slow, you'll want to compare your load methods to data warehousing techniques. For example, have you tried using staging tables? Table partitioning? Data and log files on different arrays? If you're not sure where to start, check out my Perfmon tutorial to measure your system looking for bottlenecks:</p>
<p><a href="http://www.brentozar.com/archive/2006/12/dba-101-using-perfmon-for-sql-performance-tuning/">http://www.brentozar.com/archive/2006/12/dba-101-using-perfmon-for-sql-performance-tuning/</a></p>
<p><strong>Second, how do you scale out?</strong></p>
<p>You asked how to set up multiple database servers so that one handles the bulk load while others handle reads and some writes. I would heavily, heavily caution against taking the multiple-servers-for-writes approach because it gets a lot more complicated quickly, but using multiple servers for reads is not uncommon. </p>
<p>The easiest way to do it is with log shipping: every X minutes, the primary server takes a transaction log backup and then that log backup is applied to the read-only reporting server. There's some catches with this - the data is a little behind, and the restore process has to kick all connections out of the database to apply the restore. This can be a perfectly acceptable solution for things like data warehouses, where the end users want to keep running their own reports while the new day's data loads. You can simply not do transaction log restores while the data warehouse is loading, and the users can maintain connections the whole time.</p>
<p>To help find out what solution is right for you, consider adding the following to your question:</p>
<ul>
<li>The size of your database (GB/TB in size, # of millions of rows in the largest table that's having the writes)</li>
<li>The size of your server & storage (a box with 10 drives has different solutions available than a box hooked up to a SAN)</li>
<li>The method of loading data (is it single-record inserts, are you using bulk load, are you using table partitioning, etc)</li>
</ul>
|
c# sizeof decimal? <p>Unclear on the sizeof for decimal types. Does the size in bytes vary by precision as in sql server? Is the precision variable for the c# type 'decimal'?</p>
<p>I don't want to turn on unsafe code to just call sizeof on a decimal type. How would you approach this?</p>
| <blockquote>
<p>The decimal keyword indicates a 128-bit data type.</p>
</blockquote>
<p>Source: <a href="http://msdn.microsoft.com/en-us/library/364x0z75%28loband%29.aspx">MSDN</a></p>
|
matrix text style in action script <p>I am working in AS3, and I was wondering if anyone knew how to create a matrix effect (the moving green text lines in the movie) in action script. I have found a few examples online, but none of them seem to work.</p>
<p>Thanks.</p>
| <p>There is a great effect with source code:</p>
<p><a href="http://www.bherholz.com/experiments/matrix/" rel="nofollow">http://www.bherholz.com/experiments/matrix/</a></p>
|
Does setting the max memory of a Java program affect the GC? <p>Does adding -Xmx argument when running a Java program cause the garbage collector to act differently or occur less often?</p>
| <p>Yes, most Java garbage collectors only run as needed, as opposed to running on a schedule whether needed or not. So, in general, more memory causes less frequent, longer garbage collections.</p>
<p>The generational garbage collectors have <a href="http://java.sun.com/docs/hotspot/gc5.0/gc%5Ftuning%5F5.html#1.1.Sizing%20the%20Generations%7Coutline" rel="nofollow">settings to control the allocation of memory between the young and tenured generations.</a> By setting these to use a smaller proportion of total memory for the young generation, the absolute size of the young generation can be kept the same as the total heap size is increased. Then, you won't see much of a change in garbage collection frequency or duration—but you will have more room for long-lived objects for applications like caching.</p>
|
How does For loop work in VB.NET? <p>I though that I know this one... I had no clue.</p>
<p>This simple For loop:</p>
<pre><code>Dim i As Integer
Dim n As Integer = 10
Dim s As Integer = 1
For i = 0 To n Step s
Console.WriteLine(i)
Next
</code></pre>
<p>compiles into this (I put it through Refelctor, so it's easier to read). I couldn't even get what it does with all these bit-shifts:</p>
<pre><code>Dim n As Integer = 10
Dim VB$t_i4$L1 As Integer = 1
Dim VB$t_i4$L0 As Integer = n
Dim i As Integer = 0
Do While (((VB$t_i4$L1 >> &H1F) Xor i) <= ((VB$t_i4$L1 >> &H1F) Xor VB$t_i4$L0))
Console.WriteLine(i)
i = (i + VB$t_i4$L1)
Loop
</code></pre>
<p>Why For loop is mutilated like this?</p>
| <p>Probably because it's the "generic way" to cover all cases. Remember that for/step/next can go in any direction with any sign on the increment.</p>
<p>You used parameters on both the increment and the end-bound. The compiler has no way to know if you are going to count up or down, and if th end-bound is higher or lower than the start bound.</p>
<p>My guess is this is a way to get code that will work whatever you put in n and s (just a guess, I'm too tired to try and see if that is the case).</p>
<p>Also it makes copies of the parameters to prevent outside interference (like changing s or n during the enumeration).</p>
<p>=== UPDATE ===</p>
<p>I doubt anybody is still watching that question but I came back to this nugget just for the sake of completeness, and because I had some time.
What VB is doing is a bit sneaky. The bit shift of S basically creates an integer based on the sign of S (it copies the MSB of s, ending up with &hFFFFFFFF is S is negative and &h00000000 if S is positive).</p>
<p>XOR of an integer value with -1 is equivalent to (-value-1). XOR with 0 is obviously a NOP.
So if s is negative, it reverses both values (the -1 cancel each other) to compare them, effectively reversing the order of comparison without the need or a conditional, and thus no jump in the program flow.
If s is positive it just compares them.</p>
<p>so, for s<0 you end up with</p>
<pre><code>while (-i-1)<=(-n-1)
==> while -i <= -n
==> while i>=n
</code></pre>
<p>for s>0 you end up with</p>
<pre><code>while i <= n
</code></pre>
<p>Takes me back to my 68k ASM days where such tricks where the everyday stuff (such as XOR.l D0,D0 because XORing a register with itself was faster than loading zero in it...) :p</p>
|
ASPX That Returns An Image - Output Cache-able? <p>Greetings!</p>
<p>I've created an APSX web form that returns a remote image based on some supplied parameters. It can be used like this:</p>
<pre><code><img src="/ImageGetter.aspx?param1=abc&param2=123" />
</code></pre>
<p>ImageGetter.aspx's markup and code look similar to this:</p>
<pre><code><%@ OutputCache Duration="100000" VaryByParam="*" Location="ServerAndClient" %>
<%@ Page Language="C#" AutoEventWireup="false" EnableSessionState="False" CodeBehind="ImageGetter.aspx.cs" Inherits="ACME.Helpers.ImageGetter" %>
</code></pre>
<p>This code is called in ImageGetter.aspx's Page_Load method:</p>
<pre><code>byte[] data = null;
Dictionary<string, string> file_locations = GetImageLocations(param1, param2);
try
{
data = new WebClient().DownloadData(file_locations["main"]);
}
catch (WebException wex)
{
try
{
data = new WebClient().DownloadData(file_locations["backup"]);
}
catch (Exception e)
{
throw;
}
}
Response.ContentType = "image/jpeg";
Response.OutputStream.Write(data, 0, data.Length);
Response.End();
</code></pre>
<p>From my testing, it doesn't appear to be caching. Is this possible to do with Output Caching or should I resort to writing my own cache to store the byte arrays depending on query string paramters?</p>
| <p>Try dropping the Response.End() as this will terminate the thread prematurely and prevent output caching from taking place.</p>
<p>See: <a href="http://bytes.com/groups/net-asp/323363-cache-varybyparam-doesnt-work">http://bytes.com/groups/net-asp/323363-cache-varybyparam-doesnt-work</a></p>
<p>You <i>may</i> wish to consider using an ASHX handler and using your own caching method.</p>
|
Gem Loading Error, installed from Github <p><strong>Update</strong>: This gem DOES install with sudo rake gems:install. The problem is with loading. For instance, when I run script/console, it throws:</p>
<pre><code>no such file to load -- outoftime-noaa ...
</code></pre>
<p>Even though sudo rake gems:install just installed it. I'm not sure if this matter, probably does, but it throws this error twice.</p>
<p>-=-=-</p>
<p>I'm looking to provide users with up to date weather information in my Rails application. </p>
<p>I'm looking for something similar to outoftime's NOAA gem (<a href="http://github.com/outoftime/noaa/tree/master" rel="nofollow">http://github.com/outoftime/noaa/tree/master</a>). </p>
<p>The reason I ask is I'm having a hell of a time getting the gem to work. If anyone here has a revelation as to what's going on, I'd appreciate the help.</p>
<p>I've added this to my environment config:</p>
<pre><code>config.gem "outoftime-noaa", :source => "http://gems.github.com"
</code></pre>
<p>I've run </p>
<pre><code>sudo rake gems:install
</code></pre>
<p>I get this error</p>
<pre><code>no such file to load -- outoftime-noaa
</code></pre>
<p>I have the other two required gems already installed on my system. I'm using one of them (geokit) in my app.</p>
<p>I'm using Rails 2.3.2, Ruby 1.8.6 and Rubygems 1.3.1.</p>
| <p>Try </p>
<pre><code>config.gem "outoftime-noaa", :lib => "noaa", :source => "http://gems.github.com"
</code></pre>
<p>Most github gems need the lib specified. </p>
|
Installing Exuberant Ctags on Windows (Vista and XP) <p>I want to use Exuberant Ctags on Vista (and probably the XP laptop) at work; no choice about the OS. I'm use GVim instead of the Flex Builder recommended by my co-worker, because the FB is buggy and doesn't do what GVim does, anyway. I got the zip file <a href="http://prdownloads.sourceforge.net/ctags/ec57w32.zip">here</a>. The Ctags install file says, among other things:</p>
<pre>
mk_bc3.mak For MSDOS using Borland C/C++ 3.x
mk_bc5.mak For Win32 using Borland C++ 5.5
mk_djg.mak For MSDOS using DJGPP Gnu GCC (better to follow Unix install)
mk_ming.mak For Win32 using Mingw32
mk_mvc.mak For Win32 using Microsoft Visual C++
</pre>
<p>I don't really understand what all that means (I have some grasp of each idea individually, but not put together like this), but I chose the last option as sounding Most Likely to Succeed. I opened the command prompt as Administrator, cd'd to the unzipped ec57w32 folder, and typed mk_mvc.mak.</p>
<p>Visual Studio welcomed me to the conversion wizard, offered to make a backup before proceeding to which I assented, and conversion failed. The conversion log says, Cannot load the project due to a corrupt project file. Same thing happened when I downloaded again, unzipped again, and did not make backup files; and also when I tried each of the other mk commands. There weren't any other choices along the way.</p>
<p>What else can I try?</p>
| <p>The exuberant ctags binary is pre-built and available for download at <a href="http://ctags.sourceforge.net/">http://ctags.sourceforge.net/</a></p>
<ol>
<li>Unzip the file contents to somewhere like C:\Program Files\ctags</li>
<li>Then add the ctags.exe path to your PATH environment variable.
<ol>
<li>In XP, right click on My Computer and select Properties.</li>
<li>Move to the Advanced tab and click the Environment Variables button.</li>
<li>Click the System variables select box, find and highlight the Path variable.</li>
<li>Click the Edit button.</li>
<li>Append to the Variable Value ";C:\Program Files\ctags" (without the quotes).</li>
</ol></li>
</ol>
<p>Now in the command shell you should be able to use the command ctags to generate your tags. To create the tags file:</p>
<pre><code>ctags -R "C:\Documents and Settings\My User\My Documents\My Code"
</code></pre>
<p>Since you are using vim, you probably want the taglist plugin (which I would link to if I had enough reputation). You do not need to create the tags file to use this plugin.</p>
|
How do you escape a file system path for the iPhone? <p>Is there a system library for escaping a file system path for iPhone development? I have to read and write files where the file name is based on 3rd party values so I want to make sure the paths I'm actually writing to are nice and safe.</p>
<p>I would have thought there was an NS library that would do this for me, since this is the "simple" type of function every developer probably shouldn't be rewriting, but I can't find it if there is one.</p>
<p>Thanks!</p>
<p>Edit: Thanks for the reply, stringByStandardizingPath: looks good for getting a real file path for a string, but what I'm looking for would do something similar to the following:</p>
<pre><code>in: @"~/Foo/Bar"
out: @"__Foo_Bar" or @"FooBar" etc.
</code></pre>
<p>Basically it would strip any unsafe characters out of a file path component.</p>
<p>After continued research it looks like almost any unicode character besides '/' is allowed in a file path. However, file paths are usually fragile and can be manipulated by an escape sequence, etc. so I'm hoping the big brains at Apple have an API to strip a file path component of unsafe values.</p>
| <p>You can try NSString's <code>- (NSString *)stringByStandardizingPath</code></p>
|
semantic markup for Python's difflib.HtmlDiff <p>It appears Python's <code>difflib.HtmlDiff</code>, rather than using <code>INS</code> and <code>DEL</code>, uses <code>SPAN</code> elements with custom classes:</p>
<pre><code>python -c 'import difflib; txt1 = "lorem ipsum\ndolor sit amet".splitlines(); txt2 = "lorem foo isum\ndolor amet".splitlines(); d = difflib.HtmlDiff(); print d.make_table(txt1, txt2)'
</code></pre>
<p>Before I go about fixing this myself, has anyone looked into this already?
Is there perhaps a valid reason for not using POSH?
(Google wasn't a big help here... )</p>
| <p><a href="http://www.aaronsw.com/2002/diff/" rel="nofollow">This script</a> by Aaron Swartz uses difflib to output <code>ins</code>/<code>del</code>.</p>
|
How to disable subsampling with .NET / GDI+? <p>I am trying to save a JPEG image using the Bitmap class. I noticed that sharp edges were always blury regardless of the quality level that I specify. I figured out that it is due to subsampling of one or more of the channels. How do I disable subsampling when saving the image?</p>
<p>I am currently using this code:</p>
<pre><code>EncoderParameters parameters = new EncoderParameters(1);
parameters.Param[0] = new EncoderParameter(Encoder.Quality, 85L);
ImageCodecInfo codec = GetEncoderInfo("image/jpeg");
image.Save(path, codec, parameters);
</code></pre>
<h3>NOTE</h3>
<p>I know that JPEG is lossy, but that's not the issue here. If I use ImageMagick and save the image with the default options, I get similar results. However, if I specify 1:1:1 subsampling, the blurring disappears.</p>
<p>I do not want to use PNG because I need better compression. If I save the image as BMP and then convert it manually to JPEG, I get excellent results, without blurring. Therefore, the format is not the issue here.</p>
| <p>JPEG is an image format which uses <a href="http://en.wikipedia.org/wiki/Lossy%5Fcompression" rel="nofollow">lossy compression</a>. It will cause degredation of your image, no matter what quality setting you choose. </p>
<p>Try using a better format for this, such as .PNG. Since .PNG files use a lossless compression algorithm, you will not get the artifacts you are seeing.</p>
<p><hr /></p>
<p>The problem (after reading your edits) is probably due to the fact that GDI+ uses 4:1:1 subsampling for JPG files in it's default Encoder.</p>
<p>I believe you could either install another encoder (not sure how to do this). Otherwise, I'd recommend using something like MagickNet to handle saving your JPG files. (It's a .net wrapper for ImageMagick - there are a couple of them out there.)</p>
<p><hr /></p>
<p>Edit 2: After further looking into this, it looks like you may be able to have some effect on this by tweaking the Encoder <a href="http://msdn.microsoft.com/en-us/library/system.drawing.imaging.encoder.luminancetable.aspx" rel="nofollow">Luminance Table</a> and <a href="http://msdn.microsoft.com/en-us/library/system.drawing.imaging.encoder.chrominancetable.aspx" rel="nofollow">Chrominance Table</a>.</p>
|
How can you make a recursive symlink for folders/files in Ubuntu? <p><strong>My folder Structure</strong></p>
<pre><code>/UNIX
/Find
/Grep
/Find-Grep
</code></pre>
<p>I made a symlink to the UNIX folders unsuccessfully by</p>
<pre><code>ln -s /I/Unix path/Dropbox/myFriend
</code></pre>
<p>I removed a .todo -file at /Dropbox/myFriend/Unix/Find/.todo.
I noticed that that my .todo file at /I/Unix/Find was also removed.</p>
<p><strong>How can you make a symlink</strong> such that my friend can see my files but he cannot remove my them in my computer? </p>
<p>[edit]</p>
<p>The first problem is solved: we can create a recursive symlink.</p>
<p>However, we have not found a method not to allow my friend to delete my files in my computer too, when we use Symlinks in Dropbox.</p>
| <p>I was going to suggest remounting the directory bind,ro</p>
<pre><code>mount -o bind,ro /I/Unix /Dropbox/myFriend
</code></pre>
<p>but it seems that functionality isn't in the kernel yet. Might be in yours, but not in my ubuntu box. So, alternately (instead of changing the permissions on all of your files) you could export the directory to nfs as read-only.</p>
|
In explicit LINQ-to-SQL (C#) does order matter? <p>I know Linq-to-SQL is dead, but anyway, I think this is really basic, I'm just confused about what magic Linq-to-SQL does and doesn't do with regards to the SQL it generates.</p>
<p>If I have built up an Expression tree as "myPredicate", and have something like this:</p>
<pre><code>(from request in DataContext.RequestsTable
select request).Where(myPredicate)
.OrderByDescending(item => item.changeDate)
.Take(10)
</code></pre>
<p>is it going to work like the following SQL:</p>
<pre><code>SELECT TOP 10 * FROM RequestsTable
WHERE (<<myPredicate equivalent>>)
ORDER BY ChangeDate DESC
</code></pre>
<p>It just seems weird to me because the ".Where()" comes after the "select" in my example code. Does the relative positioning of the "select" and "where()" and "orderby()" affect things?</p>
<p>Alternatively, could I do it all in sql-esque syntax? For example, is there some way to use my WHERE predicate in the alternative syntax, something like this?</p>
<pre><code>(from request in DataContext.RequestsTable
where [somehow inject myPredicate]
order by changeDate descending
select request).Take(10)
</code></pre>
| <p>You've got the same query there, LINQ to SQL won't evaluate and generate the T-SQL until after you've done something to execute the query (such as a .ToList() for example. The ordering doesn't matter. </p>
<p>In fact, you can even add OrderBy and Where clauses after the assignment of the initial query.</p>
<p>e.g </p>
<pre><code>var query = (from x in context.RequestsTable
select x);
query = query.AsQueryable().Where(<>);
return query.ToList(); //executes
</code></pre>
<p>is the same as:</p>
<pre><code>return (from x in context.RequestsTable
where <>
select x).ToList(); //executes
</code></pre>
<p>is the same as:</p>
<pre><code>return (from x in context.RequestsTable
selext x).Where(<>).ToList();
</code></pre>
<p>I'm not sure LINQ to SQL is "dead" however I have heard that it might be being rolled into the ADO Entity Framework. LINQ to SQL's generated T-SQL is far superior to the Entity Framework's!</p>
|
Reasons why PHP mail might not be working <p>I'm using the PHP <code>mail()</code> function to send email from a contact form. The function returns <code>true</code> so should be fine. But I'm not receiving the email.</p>
<p>I've seen posts that say you should always use the <em>From</em> and <em>Reply-To</em> headers in PHP mail to make sure it's delivered. I've tried various configs but nothing is working yet.</p>
<p>Is there any other way to debug the <code>mail()</code> function?</p>
| <p>If you are on windows you will need to install an SMTP server.</p>
<p>If you are on linux you will need to enable sendmail and ensure the user account PHP is installed on has access to the sendmail binary.</p>
<p>Ask your host if your account has sufficient permissions to access the binary.</p>
<p>Posting your code here might also help in case it is an error in there you overlooked.</p>
|
What's the fastest way to select a large amount of checkboxes and de/select them? <p>Since I use jQuery 1.3+ all except one timed test is using that. The other is plain javascript I found from back in 2000. I stopped going that route as it was taking around 150 seconds to run the test. I've read quite a few jQuery optimization web pages that relate to selecting a single element. A '#id' is the best case for using that, but now I have the issue of <strong>checking all checkboxes in one column in a rather large table that has multiple checkbox columns</strong>.</p>
<p>What I have done is setup a page the creates 20,000 table rows with two check box columns. The goal is to check the second column see how long that took, and then uncheck them and see how long that took. Obviously we want the lowest time. I'm only using IE6 and 7 and in my case all of my users will be doing the same.</p>
<p>20,000 rows you say? That's what I said too, but this is going to production (out of my hands) and it's too late to change now. I'm just trying to throw a hail mary with 1 second left on the clock. Besides, I've learned that input.chkbox isn't the fastest selector (for IE7)! :)</p>
<p>The question is, is there a better way to do this jQuery or otherwise? I'd love it to be running in less than half a second on my machine.</p>
<p>So you don't have to retype all the crap I've already done here's the test stuff I came up with:</p>
<p><strong>Updated Morning 4/14 to include further time trials:</strong></p>
<pre><code><form id="form1" runat="server">
<div>
<a href="#" id="one">input[id^='chkbox'][type='checkbox']</a><br />
<a href="#" id="two">#myTable tr[id^='row'] input[id^='chkbox'][type='checkbox']</a><br />
<a href="#" id="three">#myTable tr.myRow input[id^='chkbox'][type='checkbox']</a><br />
<a href="#" id="four">tr.myRow input[id^='chkbox'][type='checkbox']</a><br />
<a href="#" id="five">input[id^='chkbox']</a><br />
<a href="#" id="six">.chkbox</a><br />
<a href="#" id="seven">input.chkbox</a><br />
<a href="#" id="eight">#myTable input.chkbox</a><br />
<a href="#" id="nine">"input.chkbox", "tr"</a><br />
<a href="#" id="nine1">"input.chkbox", "tr.myRow"</a><br />
<a href="#" id="nine2">"input.chkbox", "#form1"</a><br />
<a href="#" id="nine3">"input.chkbox", "#myTable"</a><br />
<a href="#" id="ten">input[name=chkbox]</a><br />
<a href="#" id="ten1">"input[name=chkbox]", "tr.myRow"</a><br />
<a href="#" id="ten2">"input[name=chkbox]", "#form1"</a><br />
<a href="#" id="ten3">"input[name=chkbox]", "#myTable"</a><br />
<a href="#" id="ten4">"input[name=chkbox]", $("#form1")</a><br />
<a href="#" id="ten5">"input[name=chkbox]", $("#myTable")</a><br />
<a href="#" id="eleven">input[name='chkbox']:checkbox</a><br />
<a href="#" id="twelve">:checkbox</a><br />
<a href="#" id="twelve1">input:checkbox</a><br />
<a href="#" id="thirteen">input[type=checkbox]</a><br />
<div>
<input type="text" id="goBox" /> <button id="go">Go!</button>
<div id="goBoxTook"></div>
</div>
<table id="myTable">
<tr id="headerRow"><th>Row #</th><th>Checkboxes o' fun!</th><th>Don't check these!</th></tr>
<% for(int i = 0; i < 20000;i++) { %>
<tr id="row<%= i %>" class="myRow">
<td><%= i %> Row</td>
<td>
<input type="checkbox" id="chkbox<%= i %>" name="chkbox" class="chkbox" />
</td>
<td>
<input type="checkbox" id="otherBox<%= i %>" name="otherBox" class="otherBox" />
</td>
</tr>
<% } %>
</table>
</div>
<script type="text/javascript" src="<%= ResolveUrl("~/") %>Javascript/jquery.1.3.1.min.js"></script>
<script type="text/javascript">
$(function() {
function run(selectorText, el) {
var start = new Date();
$(selectorText).attr("checked", true);
var end = new Date();
var timeElapsed = end-start;
$(el).after("<br />Checking Took " + timeElapsed + "ms");
start = new Date();
$(selectorText).attr("checked", false);
end = new Date();
timeElapsed = end-start;
$(el).after("<br />Unchecking Took " + timeElapsed + "ms");
}
function runWithContext(selectorText, context, el) {
var start = new Date();
$(selectorText, context).attr("checked", true);
var end = new Date();
var timeElapsed = end-start;
$(el).after("<br />Checking Took " + timeElapsed + "ms");
start = new Date();
$(selectorText, context).attr("checked", false);
end = new Date();
timeElapsed = end-start;
$(el).after("<br />Unchecking Took " + timeElapsed + "ms");
}
$("#one").click(function() {
run("input[id^='chkbox'][type='checkbox']", this);
});
$("#two").click(function() {
run("#myTable tr[id^='row'] input[id^='chkbox'][type='checkbox']", this);
});
$("#three").click(function() {
run("#myTable tr.myRow input[id^='chkbox'][type='checkbox']", this);
});
$("#four").click(function() {
run("tr.myRow input[id^='chkbox'][type='checkbox']", this);
});
$("#five").click(function() {
run("input[id^='chkbox']", this);
});
$("#six").click(function() {
run(".chkbox", this);
});
$("#seven").click(function() {
run("input.chkbox", this);
});
$("#eight").click(function() {
run("#myTable input.chkbox", this);
});
$("#nine").click(function() {
runWithContext("input.chkbox", "tr", this);
});
$("#nine1").click(function() {
runWithContext("input.chkbox", "tr.myRow", this);
});
$("#nine2").click(function() {
runWithContext("input.chkbox", "#form1", this);
});
$("#nine3").click(function() {
runWithContext("input.chkbox", "#myTable", this);
});
$("#ten").click(function() {
run("input[name=chkbox]", this);
});
$("#ten1").click(function() {
runWithContext("input[name=chkbox]", "tr.myRow", this);
});
$("#ten2").click(function() {
runWithContext("input[name=chkbox]", "#form1", this);
});
$("#ten3").click(function() {
runWithContext("input[name=chkbox]", "#myTable", this);
});
$("#ten4").click(function() {
runWithContext("input[name=chkbox]", $("#form1"), this);
});
$("#ten5").click(function() {
runWithContext("input[name=chkbox]", $("#myTable"), this);
});
$("#eleven").click(function() {
run("input[name='chkbox']:checkbox", this);
});
$("#twelve").click(function() {
run(":checkbox", this);
});
$("#twelve1").click(function() {
run("input:checkbox", this);
});
$("#thirteen").click(function() {
run("input[type=checkbox]", this);
});
$('#go').click(function() {
run($('#goBox').val(), this);
});
});
</script>
</form>
</code></pre>
| <p><strong>input[name=chkbox]</strong> is coming in as the fastest jQuery selector on my machine under IE7.</p>
<pre><code>Unchecking Took 2453ms
Checking Took 2438ms
Unchecking Took 2438ms
Checking Took 2437ms
Unchecking Took 2453ms
Checking Took 2438ms
</code></pre>
<p><strong>input.chkbox</strong> and...</p>
<pre><code>Unchecking Took 2813ms
Checking Took 2797ms
Unchecking Took 2797ms
Checking Took 2797ms
Unchecking Took 2813ms
Checking Took 2797ms
</code></pre>
<p><strong>input:checkbox.chkbox</strong> seem tied</p>
<pre><code>Unchecking Took 2797ms
Checking Took 2797ms
Unchecking Took 2813ms
Checking Took 2781ms
</code></pre>
<p><strong>.chkbox</strong> almost takes twice as long as the input.chkbox</p>
<pre><code>Unchecking Took 4031ms
Checking Took 4062ms
Unchecking Took 4031ms
Checking Took 4062ms
</code></pre>
<p>The javascript for loop is by far the worst coming in at:</p>
<pre><code>Checking Took 149797ms
</code></pre>
<p>150 seconds! It locks the browser too. This just makes me really impressed with jQuery. I honestly didn't expect it to be that slow. Probably because I'm passing across each individual element which it's then having to find...</p>
<p>This was pretty interesting to me as well:</p>
<p><strong>input[id^='chkbox']</strong></p>
<pre><code>Unchecking Took 3031ms
Checking Took 3016ms
</code></pre>
<p>took <strong>less</strong> time than:</p>
<p><strong>input[id^='chkbox'][type='checkbox']</strong></p>
<pre><code>Unchecking Took 3375ms
Checking Took 3344ms
</code></pre>
<p>I thought since I posted more filters it'd be faster. Nope!</p>
<p>Specifying even more paths to the checkbox makes it way slower:</p>
<p><strong>#myTable tr[id^='row'] input[id^='chkbox'][type='checkbox']</strong></p>
<pre><code>Checking Took 10422ms
</code></pre>
<p>It didn't even run the second uncheck as it asked me if I wanted to continue running scripts on my computer. Crazy! :P</p>
<p><strong>Update Morning 4/14:</strong></p>
<p>Someone brought up setting the context: I actually did a few of those and much to my suprise and against what a lot of people have said on the web <strong>on IE7 these were slower</strong>! Here are the times I got with a few different context's specified paired with the quicker selector's above:</p>
<p><strong>"input.chkbox", "tr"</strong></p>
<pre><code>Checking Took 8546ms
</code></pre>
<p><strong>"input.chkbox", "tr.myRow"</strong></p>
<pre><code>Checking Took 8875ms
</code></pre>
<p><strong>"input.chkbox", "#form1"</strong></p>
<pre><code>Unchecking Took 3032ms
Checking Took 3000ms
</code></pre>
<p><strong>"input.chkbox", "#myTable"</strong></p>
<pre><code>Unchecking Took 2906ms
Checking Took 2875ms
</code></pre>
<p>Current winner (still): <strong>input[name=chkbox]</strong></p>
<pre><code>Unchecking Took 2469ms
Checking Took 2453ms
</code></pre>
<p><strong>"input[name=chkbox]", "tr.myRow"</strong></p>
<pre><code>Checking Took 9547ms
</code></pre>
<p><strong>"input[name=chkbox]", "#form1"</strong></p>
<pre><code>Unchecking Took 3140ms
Checking Took 3141ms
</code></pre>
<p><strong>"input[name=chkbox]", "#myTable"</strong></p>
<pre><code>Unchecking Took 2985ms
Checking Took 2969ms
</code></pre>
<p><strong>Update 2 Morning 4/14</strong></p>
<p>Thought I might have had a better one after I noticed a syntax difference from <a href="http://beardscratchers.com/journal/jquery-its-all-about-context" rel="nofollow">http://beardscratchers.com/journal/jquery-its-all-about-context</a>. It seems that these are NOT the same as <strong>they are giving slightly better times, but still doesn't beat the non-contexted selector</strong> - darn.</p>
<p><strong>"input[name=chkbox]", $("#form1")</strong></p>
<pre><code>Unchecking Took 3078ms
Checking Took 3000ms
Unchecking Took 3078ms
Checking Took 3016ms
</code></pre>
<p><strong>"input[name=chkbox]", $("#myTable")</strong></p>
<pre><code>Unchecking Took 2938ms
Checking Took 2906ms
Unchecking Took 2938ms
Checking Took 2921ms
</code></pre>
<p><strong>Update 3 Morning 4/14</strong></p>
<p>Russ wanted me to try these out, they de/select ALL the boxes but again it was interesting:</p>
<p><strong>:checkbox</strong></p>
<pre><code>Unchecking Took 8328ms
Checking Took 6250ms
</code></pre>
<p><strong>input:checkbox</strong></p>
<pre><code>Unchecking Took 5016ms
Checking Took 5000ms
</code></pre>
<p>-> Fastest?!?! <strong>input[type=checkbox]</strong></p>
<pre><code>Unchecking Took 4969ms
Checking Took 4938ms
</code></pre>
<p>The fact that the third up there is the fastest is quite interesting as that goes against what I would have thought. Why wouldn't (for IE7 at least) the :checkbox just use the type=checkbox to achieve a faster time? These are really close scores but the checking took 62ms less time. Also, why are the first two different at all? Is there a different element besides an input that can take have a checkbox?</p>
|
Does Scaleform now support AS3? <p>Does Scaleform now support AS3?</p>
| <p>Supposedly they're working on AS3 now and will have it available by the end of the year. They also claim to be optimizing the rendering engine to fully support Flash 9/10 effects in hardware, which will be super cool.</p>
<p>Their new CLIK Flash UI components were made by the same guy that made Adobe's Flash 9 components, Grant Skinner. Basically it cuts down a huge amount of time/risk by providing a drag and drop ActionScript based UI widget set specially for game developers... it's pretty neat and probably very useful, esp since it's free with the kit.
https://www.scaleform.com/products/clik </p>
<p>I'm starting to dig into their new AMP memory/performance reporting tool and Flash Video support. Looks like there's no more need to license Bink, which I'm quite happy about since that was never very impressive. Leveraging integrating Flash Video is awesome for full screen video and special effects in UI.</p>
<p>Anyways, I'll let you know when I hear more about AS3. So far we've been super happy with Scaleform's player, esp performance and memory of their new 3.0.</p>
|
Firefox plugin to capture signature (via stylus/tablet) <p>I am wondering if anyone has any experience capturing signatures with a tablet/stylus over the internet.<br />
How would you write a plug-in that uses an ActiveX control and can securely post the signature over the web?</p>
<p>Or maybe you've got a better idea how to handle this...</p>
<p>Thanks in advance.</p>
<p>[EDIT] To be more specific, I need something that can hook up to a signature pad like you would use at Best Buy to make a legal signature.</p>
| <p>I would somehow use flash that would draw to a bitmap, then encode them as an image then upload them to your server.</p>
<p>After a few minutes of googling, i found this.</p>
<p><a href="http://www.kirupa.com/developer/actionscript/drawingboard.htm" rel="nofollow">http://www.kirupa.com/developer/actionscript/drawingboard.htm</a></p>
<p><strong>Edit</strong>
<a href="http://www.topazsystems.com/" rel="nofollow">http://www.topazsystems.com/</a> has an activex control</p>
|
Iterating through a list of commands in a file in Shell Programming <p>I have a file containing a list of unix commands like "ls -la /etc/passwd". I want to iterate through this list of commands, and take appropriate action. </p>
<p>Currently, my code is something like:</p>
<pre><code>#!/bin/bash
clear
for cmds in `cat /tmp/cmd`
do
if [ $cmds ] ; then
echo $cmds;
fi
done
</code></pre>
<p>But, what I get is an output where the commands are broken up in different lines like</p>
<pre><code>ls
-la
/etc/passwd
ls
-la
/etc/shadow
</code></pre>
<p>and not </p>
<pre><code>ls -la /etc/passwd
ls -la /etc/shadow
</code></pre>
<p>Any ideas?</p>
| <p>Add this before your for loop:</p>
<pre><code>IFS='
'
</code></pre>
<p>Or in Bash:</p>
<pre><code>IFS=$'\n'
</code></pre>
<p><a href="http://www.gnu.org/software/bash/manual/bashref.html#Bourne-Shell-Variables" rel="nofollow"><code>IFS</code></a> contains a list of characters which are used to split input into fields; it defaults to including spaces, tabs, and linefeeds, which was why you were getting the incorrect behavior. Setting it to a newline will only split on newlines, which is what you want.</p>
|
Does each authenticated WCF client connection need a CAL? <p>Just like the title says. Does each authenticated WCF client connection to a WCF server that you have developed need a windows CAL?</p>
<p><a href="http://www.microsoft.com/windowsserver2008/en/us/client-licensing.aspx" rel="nofollow">http://www.microsoft.com/windowsserver2008/en/us/client-licensing.aspx</a></p>
<p>Microsoft's licensing on that page sure makes it sound like it, but I can't find anything out there that confirms, or even denies this.</p>
<p>Anyone know?</p>
| <p><strong>Yes</strong>, the answer is, you need a CAL or an external connector. If you have client systems or apps that access Windows Servers in an authenticated manner, then the clients need to be authorized either via a user-specific CAL, a device-specific CAL, or an external connector. </p>
<p>The CAL is appropriate for within-the-enterprise connections. The EC is for connections made from outside your enterprise, including partner companies, or the internet at large. </p>
<p>It does not matter whether you use WCF, DCOM, FTP, Telnet, or anything else to connect to Windows Server. For the purposes of licensing, the CAL-or-EC requirement doesn't distinguish between the technology used to communicate. The CAL-or-EC requirement comes in when you have <em>authenticated</em> access to the server, regardless of the kind. </p>
<p>Also according to the license, it does not matter if the authentication is performed by Active Directory. If you authenticate users with AD, then you need a CAL or EC, but if you authenticate with some other mechanism, for example, if you have an XML file with a list of users and password hashes, and your simple ASP.NET website authenticates users against that store, then you have authenticated access and you will need an EC or CAL for each user that authenticates. </p>
<p>The EC is not interchangeable with CALs. If you find that you have 500 internal users that need to authenticate, you cannot purchase a single EC and have them all covered according to the license. the External Connector is for <em>External</em> connections. Any licensing advisor that says an EC would be "a better solution" than buying CALs is misinformed. There is no decision to make. The Windows Server licensing terms are very clear (though maybe not broadly understood): </p>
<ul>
<li>If you have internal users, you must buy CALs for each of them (or for each device they use). </li>
<li>If you have external users, in which case you must buy an EC. Regardless if you have 3 or 3,000,000 external users, because they are external, you need an EC. </li>
</ul>
<p>There is no choice to be made on your part, according to the licensing of Windows Server, whether to purchase CALs or EC. The requirement is set by the affiliation of the user. In fact in some cases you will need both CALs and an EC, if both internal and external users will authenticate to the same Windows Server. </p>
<p>The External Connector has a "Estimated Retail Price" of $1999US, but through a software distributor you will be able to get it much cheaper, even in single-digit units. Like $1300 or so. Likewise CALs have an "ERP" but you will pay less than ERP from software resellers. </p>
|
Issues with C++ 'new' operator? <p>I've recently come across <a href="http://www.scs.stanford.edu/~dm/home/papers/c++-new.html" rel="nofollow">this rant</a>.</p>
<p>I don't quite understand a few of the points mentioned in the article:</p>
<ul>
<li>The author mentions the small annoyance of <code>delete</code> vs <code>delete[]</code>, but seems to argue that it is actually necessary (for the compiler), without ever offering a solution. Did I miss something?</li>
<li><p>In the section 'Specialized allocators', in function <code>f()</code>, it seems the problems can be solved with replacing the allocations with: (omitting alignment)</p>
<pre><code>// if you're going to the trouble to implement an entire Arena for memory,
// making an arena_ptr won't be much work. basically the same as an auto_ptr,
// except that it knows which arena to deallocate from when destructed.
arena_ptr<char> string(a); string.allocate(80);
// or: arena_ptr<char> string; string.allocate(a, 80);
arena_ptr<int> intp(a); intp.allocate();
// or: arena_ptr<int> intp; intp.allocate(a);
arena_ptr<foo> fp(a); fp.allocate();
// or: arena_ptr<foo>; fp.allocate(a);
// use templates in 'arena.allocate(...)' to determine that foo has
// a constructor which needs to be called. do something similar
// for destructors in '~arena_ptr()'.
</code></pre></li>
<li><p>In 'Dangers of overloading ::operator new[]', the author tries to do a <code>new(p) obj[10]</code>. Why not this instead (far less ambiguous):</p>
<pre><code>obj *p = (obj *)special_malloc(sizeof(obj[10]));
for(int i = 0; i < 10; ++i, ++p)
new(p) obj;
</code></pre></li>
<li><p>'Debugging memory allocation in C++'. Can't argue here.</p></li>
</ul>
<p>The entire article seems to revolve around classes with <em>significant</em> *constructors* and <em>destructors</em> located in a <em>custom memory management scheme</em>. While that could be useful, and I can't argue with it, it's pretty limited in commonality.</p>
<p>Basically, we have placement new and per-class allocators -- what problems can't be solved with these approaches?</p>
<p>Also, in case I'm just thick-skulled and crazy, in <strong>your</strong> ideal C++, what would replace <code>operator new</code>? Invent syntax as necessary -- what would be <strong>ideal</strong>, simply to help me understand these problems better.</p>
| <p>Well, the <em>ideal</em> would probably be to not need delete of any kind. Have a garbage-collected environment, let the programmer avoid the whole problem.</p>
<p>The complaints in the rant seem to come down to</p>
<ol>
<li>"I liked the way malloc does it"</li>
<li>"I don't like being forced to explicitly create objects of a known type"</li>
</ol>
<p>He's right about the annoying fact that you have to implement both <code>new</code> and <code>new[]</code>, but you're forced into that by Stroustrups' desire to maintain the core of C's semantics. Since you can't tell a pointer from an array, you have to tell the compiler yourself. You could fix that, but doing so would mean changing the semantics of the C part of the language radically; you could no longer make use of the identity</p>
<pre><code>*(a+i) == a[i]
</code></pre>
<p>which would break a very large subset of all C code.</p>
<p>So, you could have a language which</p>
<ul>
<li><p>implements a more complicated notion of an array, and eliminates the wonders of pointer arithmetic, implementing arrays with dope vectors or something similar.</p></li>
<li><p>is garbage collected, so you don't need your own <code>delete</code> discipline.</p></li>
</ul>
<p>Which is to say, you could download Java. You could then extend that by changing the language so it</p>
<ul>
<li>isn't strongly typed, so type checking the <code>void *</code> upcast is eliminated, </li>
</ul>
<p>...but that means that you can write code that transforms a Foo into a Bar without the compiler seeing it. This would also enable ducktyping, if you want it.</p>
<p>The thing is, once you've done those things, you've got Python or Ruby with a C-ish syntax.</p>
<p>I've been writing C++ since Stroustrup sent out tapes of cfront 1.0; a lot of the history involved in C++ as it is now comes out of the desire to have an OO language that could fit into the C world. There were plenty of other, more satisfying, languages that came out around the same time, like Eiffel. C++ seems to have won. I suspect that it won <em>because</em> it could fit into the C world.</p>
|
Realistic usage of the C99 'restrict' keyword? <p>I was browsing through some documentation and questions/answers and saw it mentioned. I read a brief description, stating that it would be basically a promise from the programmer that the pointer won't be used to point somewhere else. </p>
<p>Can anyone offer some realistic cases where its worth actually using this?</p>
| <p><code>restrict</code> says that the pointer is the only thing that accesses the underlying object. It eliminates the potential for pointer aliasing, enabling better optimization by the compiler.</p>
<p>For instance, suppose I have a machine with specialized instructions that can multiply vectors of numbers in memory, and I have the following code:</p>
<pre><code>void MultiplyArrays(int* dest, int* src1, int* src2, int n)
{
for(int i = 0; i < n; i++)
{
dest[i] = src1[i]*src2[i];
}
}
</code></pre>
<p>The compiler needs to properly handle if dest, src1, and src2 overlap, meaning it must do one multiplication at a time, from start to the end. By having <code>restrict</code>, the compiler is free to optimize this code to using the vector instructions.</p>
<p>EDIT: Wikipedia has an entry on <code>restrict</code>, with another example, <a href="http://en.wikipedia.org/wiki/Restrict">here</a>.</p>
|
How do I bind to a List<T> using DataContext? <p>I'm self-learning C#, OOP, and WPF so the potential for stuff ups is staggering.</p>
<p>So given that, can someone please explain why after clicking the button in my tiny test example the Name property appears in the TextBox but the ListBox shows nothing?</p>
<h2><strong>XAML:</strong></h2>
<pre><code><Window x:Class="BindingTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="BindingTest" Height="250" Width="300">
<Grid Name="mainGrid">
<Grid.RowDefinitions>
<RowDefinition Height="50" />
<RowDefinition Height="50" />
<RowDefinition Height="100" />
</Grid.RowDefinitions>
<Button
Grid.Row="0"
Name="MakeIntListButton"
Click="MakeIntListButton_Click">Make and Display Integer List</Button>
<TextBox Grid.Row="1" Text ="{Binding Path=Name}"
/>
<ListBox
Grid.Row="2"
ItemsSource="{Binding Path=MyIntegers}"
/>
</Grid>
</code></pre>
<p></p>
<h2><strong>C#:</strong></h2>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace BindingTest
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void MakeIntListButton_Click(object sender, RoutedEventArgs e)
{
AClass InstanceOfAClass = new AClass();
InstanceOfAClass.MyIntegers.Add(6);
InstanceOfAClass.MyIntegers.Add(7);
InstanceOfAClass.MyIntegers.Add(42);
InstanceOfAClass.Name = "Fred";
mainGrid.DataContext =InstanceOfAClass ;
}
}
public class AClass
{
public string Name {get;set;}
public List<int> MyIntegers = new List<int>();
}
}
</code></pre>
| <p>Part of me wonders whether it's something to do with the fact that "MyIntegers" is a public field rather than a property. Can you refactor you class to look like this and try it?</p>
<pre><code>public class AClass
{
private List<int> _ints = new List<int>();
public string Name { get; set; }
public List<int> MyIntegers
{
get { return _ints; }
}
}
</code></pre>
|
C - GLFW window doesn't open on Debian <p>I'm trying to get started with GLFW on Debian, I've tried compiling and running an example program but it refuses to run. With the help of a couple of printf statements I've found that when the program tries to open a GLFW window it fails, then exits - but I don't know why. Any help would be amazing.</p>
<pre><code>#include <stdlib.h> // For malloc() etc.
#include <stdio.h> // For printf(), fopen() etc.
#include <math.h> // For sin(), cos() etc.
#include <GL/glfw.h> // For GLFW, OpenGL and GLU
//----------------------------------------------------------------------
// Draw() - Main OpenGL drawing function that is called each frame
//----------------------------------------------------------------------
void Draw( void )
{
int width, height; // Window dimensions
double t; // Time (in seconds)
int k; // Loop counter
// Get current time
t = glfwGetTime();
// Get window size
glfwGetWindowSize( &width, &height );
// Make sure that height is non-zero to avoid division by zero
height = height < 1 ? 1 : height;
// Set viewport
glViewport( 0, 0, width, height );
// Clear color and depht buffers
glClearColor( 0.0f, 0.0f, 0.0f, 0.0f );
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
// Set up projection matrix
glMatrixMode( GL_PROJECTION ); // Select projection matrix
glLoadIdentity(); // Start with an identity matrix
gluPerspective( // Set perspective view
65.0, // Field of view = 65 degrees
(double)width/(double)height, // Window aspect (assumes square pixels)
1.0, // Near Z clipping plane
100.0 // Far Z clippling plane
);
// Set up modelview matrix
glMatrixMode( GL_MODELVIEW ); // Select modelview matrix
glLoadIdentity(); // Start with an identity matrix
gluLookAt( // Set camera position and orientation
0.0, 0.0, 10.0, // Camera position (x,y,z)
0.0, 0.0, 0.0, // View point (x,y,z)
0.0, 1.0, 0.0 // Up-vector (x,y,z)
);
// **** Draw a circle of points ***
// Save the current modelview matrix on the stack
glPushMatrix();
// Translate (move) the points to the upper left of the display
glTranslatef( -4.0f, 3.0f, 0.0f );
// Rotate the points about the z-axis and the x-axis
glRotatef( 35.0f * (float)t, 0.0f, 0.0f, 1.0f );
glRotatef( 60.0f * (float)t, 1.0f, 0.0f, 0.0f );
// Now draw the points - we use a for-loop to build a circle
glColor3f( 1.0f, 1.0f, 1.0f );
glBegin( GL_POINTS );
for( k = 0; k < 20; k ++ )
{
glVertex3f( 2.0f * (float)cos( 0.31416 * (double)k ),
2.0f * (float)sin( 0.31416 * (double)k ),
0.0f );
}
glEnd();
// Restore modelview matrix
glPopMatrix();
// **** Draw a circle of lines ***
// Save the current modelview matrix on the stack
glPushMatrix();
// Translate (move) the lines to the upper right of the display
glTranslatef( 4.0f, 3.0f, 0.0f );
// Rotate the points about the z-axis and the x-axis
glRotatef( 45.0f * (float)t, 0.0f, 0.0f, 1.0f );
glRotatef( 55.0f * (float)t, 1.0f, 0.0f, 0.0f );
// Now draw the lines - we use a for-loop to build a circle
glBegin( GL_LINE_LOOP );
for( k = 0; k < 20; k ++ )
{
glColor3f( 1.0f, 0.05f * (float)k, 0.0f );
glVertex3f( 2.0f * (float)cos( 0.31416 * (double)k ),
2.0f * (float)sin( 0.31416 * (double)k ),
0.0f );
}
glEnd();
// Restore modelview matrix
glPopMatrix();
// **** Draw a disc using trinagles ***
// Save the current modelview matrix on the stack
glPushMatrix();
// Translate (move) the triangles to the lower left of the display
glTranslatef( -4.0f, -3.0f, 0.0f );
// Rotate the triangles about the z-axis and the x-axis
glRotatef( 25.0f * (float)t, 0.0f, 0.0f, 1.0f );
glRotatef( 75.0f * (float)t, 1.0f, 0.0f, 0.0f );
// Now draw the triangles - we use a for-loop to build a disc
// Since we are building a triangle fan, we also specify a first
// vertex for the centre point of the disc.
glBegin( GL_TRIANGLE_FAN );
glColor3f( 0.0f, 0.5f, 1.0f );
glVertex3f( 0.0f, 0.0f, 0.0f );
for( k = 0; k < 21; k ++ )
{
glColor3f( 0.0f, 0.05f * (float)k, 1.0f );
glVertex3f( 2.0f * (float)cos( 0.31416 * (double)k ),
2.0f * (float)sin( 0.31416 * (double)k ),
0.0f );
}
glEnd();
// Restore modelview matrix
glPopMatrix();
// **** Draw a disc using a polygon ***
// Save the current modelview matrix on the stack
glPushMatrix();
// Translate (move) the polygon to the lower right of the display
glTranslatef( 4.0f, -3.0f, 0.0f );
// Rotate the polygon about the z-axis and the x-axis
glRotatef( 65.0f * (float)t, 0.0f, 0.0f, 1.0f );
glRotatef( -35.0f * (float)t, 1.0f, 0.0f, 0.0f );
// Now draw the polygon - we use a for-loop to build a disc
glBegin( GL_POLYGON );
for( k = 0; k < 20; k ++ )
{
glColor3f( 1.0f, 0.0f, 0.05f * (float)k );
glVertex3f( 2.0f * (float)cos( 0.31416 * (double)k ),
2.0f * (float)sin( 0.31416 * (double)k ),
0.0f );
}
glEnd();
// Restore modelview matrix
glPopMatrix();
// **** Draw a single quad ***
// Save the current modelview matrix on the stack
glPushMatrix();
// Rotate the quad about the y-axis
glRotatef( 60.0f * (float)t, 0.0f, 1.0f, 0.0f );
// Now draw the quad
glBegin( GL_QUADS );
glColor3f( 1.0f, 0.0f, 0.0f );
glVertex3f( -1.5f, -1.5f, 0.0f );
glColor3f( 1.0f, 1.0f, 0.0f );
glVertex3f( 1.5f, -1.5f, 0.0f );
glColor3f( 1.0f, 0.0f, 1.0f );
glVertex3f( 1.5f, 1.5f, 0.0f );
glColor3f( 0.0f, 0.0f, 1.0f );
glVertex3f( -1.5f, 1.5f, 0.0f );
glEnd();
// Restore modelview matrix
glPopMatrix();
}
//----------------------------------------------------------------------
// main() - Program entry point
//----------------------------------------------------------------------
int main( int argc, char **argv )
{
int ok; // Flag telling if the window was opened
int running; // Flag telling if the program is running
// Initialize GLFW
glfwInit();
// Open window
ok = glfwOpenWindow(
100, 100, // Width and height of window
8, 8, 8, // Number of red, green, and blue bits for color buffer
8, // Number of bits for alpha buffer
24, // Number of bits for depth buffer (Z-buffer)
0, // Number of bits for stencil buffer
GLFW_WINDOW // We want a desktop window (could be GLFW_FULLSCREEN)
);
printf("here");
// If we could not open a window, exit now
if( !ok )
{
glfwTerminate();
return 0;
}
printf("not here");
// Set window title
glfwSetWindowTitle( "My OpenGL program" );
// Enable sticky keys
glfwEnable( GLFW_STICKY_KEYS );
// Main rendering loop
do
{
// Call our rendering function
Draw();
// Swap front and back buffers (we use a double buffered display)
glfwSwapBuffers();
// Check if the escape key was pressed, or if the window was closed
running = !glfwGetKey( GLFW_KEY_ESC ) &&
glfwGetWindowParam( GLFW_OPENED );
}
while( running );
// Terminate GLFW
glfwTerminate();
// Exit program
return 0;
}
</code></pre>
| <p>You're sure it's glfwOpenWindow that's failing? I don't know why that might be, perhaps you're using too many bits for your z-buffer? That's the only thing I can think of. </p>
<p>Try this</p>
<pre><code>GLFWvidmode dvm;
glfwGetDesktopMode(&dvm);
glfwOpenWindow(winWidth, winHeight, dvm.RedBits, dvm.GreenBits, dvm.BlueBits, 0, 0, 0, GLFW_WINDOW);
</code></pre>
<p>And see if it still fails.</p>
|
ASP.NET: Scroll to control <p>I've got a particularly large form in an page. When the form is validated and a field is invalid, I want to scroll the window to that control. Calling the control's Focus() doesn't seem to do this. I've found a JavaScript workaround to scroll the window to the control, but is there anything built into ASP.NET?</p>
| <p>Are you using a Validation Summary on your page?</p>
<p>If so, ASP.NET <a href="http://stackoverflow.com/questions/699171/asp-net-validation-summary-causes-page-to-jump-to-top">renders some javascript to automatically scroll to the top of the page</a> which may well override the automatic behaviour of the client side validation to focus the last invalid control.</p>
<p>Also, have you turned client side validation off?</p>
<p>If you take a look at the javascript generated by the client side validation you should see methods like this:</p>
<pre><code>function ValidatorValidate(val, validationGroup, event) {
val.isvalid = true;
if ((typeof(val.enabled) == "undefined" || val.enabled != false) &&
IsValidationGroupMatch(val, validationGroup)) {
if (typeof(val.evaluationfunction) == "function") {
val.isvalid = val.evaluationfunction(val);
if (!val.isvalid && Page_InvalidControlToBeFocused == null &&
typeof(val.focusOnError) == "string" && val.focusOnError == "t") {
ValidatorSetFocus(val, event);
}
}
}
ValidatorUpdateDisplay(val);
}
</code></pre>
<p>Note the call to ValidatorSetFocus, which is a rather long method that attempts to set the focus to the control in question, or if you have multiple errors, to the last control that was validated, using (eventually) the following lines:</p>
<pre><code>if (typeof(ctrl.focus) != "undefined" && ctrl.focus != null) {
ctrl.focus();
Page_InvalidControlToBeFocused = ctrl;
}
</code></pre>
<p>To get this behaviour to work, you would ideally need to ensure that all your validators are set to be client-side - server side validators will obviously require a postback, and that might affect things (i.e. lose focus/position) - and setting MaintainScrollPositionOnPostBack to true would probably cause the page to reload to the submit button, rather than the invalid form element.</p>
<p>Using the server side .Focus method will cause ASP.NET to render out some javascript "on the page load" (i.e. near the bottom of the page) but this could be being overriden by one of the other mechanisms dicussed above.</p>
|
Undo SVN delete ./* --force <p>I didn't realize <code>svn delete</code> would delete my local copy, I just wanted it out of the repository. Now all my files are gone, and they aren't in the trash bin either. Is there any way I can recover them?</p>
<hr>
<p>I should clarify, these files <em>never</em> made it into the repository. I was trying to get rid of some old junk in the repository so that I could check these in.</p>
<p>I'm running Ubuntu on an ext3 filesystem. It's okay though.... I managed to redo what I deleted in about 2 hours.</p>
| <p><strong>Nope.</strong></p>
<p>Not unless they're still in use by some other application, sorry.</p>
|
Silverlight 3: ListBox DataTemplate HorizontalAlignment <p>I have a ListBox with it's ItemTemplate bound to a DataTemplate. My problem is I cannot get the elements in the template to stretch to the full width of the ListBox.</p>
<pre><code><ListBox x:Name="listPeople" VerticalAlignment="Stretch" HorizontalAlignment="Stretch"
Margin="0,0,0,0" Background="{x:Null}" SelectionMode="Extended" Grid.Row="1"
ItemTemplate="{StaticResource PersonViewModel.BrowserDataTemplate}"
ItemsSource="{Binding Mode=OneWay, Path=SearchResults}" >
</ListBox>
<DataTemplate x:Key="PersonViewModel.BrowserDataTemplate">
<ListBoxItem HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="5,5,5,5">
<Border Opacity=".1" x:Name="itemBorder" Background="#FF000000"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
CornerRadius="5,5,5,5" MinWidth="100" Height="50"/>
</Grid>
</ListBoxItem>
</DataTemplate>
</code></pre>
<p>As you can see, I have added a border within the grid to indicate the width of the template. My goal is to see this border expand to the full width of the listbox. Currently its width is determined by its contents or MinWidth, which is the only thing at the moment keeping it visible at all.</p>
| <p>I spent an hour trying to resolve this one. Very very frustrasting. You <strong>don't</strong> have to override the entire default style for the ListBoxItem. I couldn't get this to work. In the end I resolved the issue by simply overriding just the <strong>HorizontalContentAlignment</strong> property in my <strong>ListBox.ItemContainerStyle</strong> section e.g:</p>
<pre><code> <ListBox x:Name="ClassList" ItemsSource="{Binding LineClasses}"
ScrollViewer.VerticalScrollBarVisibility="Visible"
SelectionMode="Extended"
ScrollViewer.HorizontalScrollBarVisibility="Hidden" HorizontalContentAlignment="Stretch"
HorizontalAlignment="Stretch" Loaded="ClassList_Loaded"
VerticalAlignment="Stretch" Grid.Row="0">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Black" CornerRadius="3" Background="#FFE88D34"
BorderThickness="1" HorizontalAlignment="Stretch" >
<Grid Background="Transparent" HorizontalAlignment="Stretch" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock
Grid.Column="0" HorizontalAlignment="Stretch"
Margin="2"
FontSize="10"
Text="{Binding DisplayClassNm}"/>
</Grid>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</code></pre>
<p>This worked a treat for me.</p>
<p>Myles</p>
|
How to add these object with name to the array by this order? <p>I have some object with name , just like <code>button 1 , button 2 , button 11 ,button 111</code> , I want to add this object to a array by this order: <code>button 1 ,button 2 , button 11 , button 111</code> ,but I found that these object can add the array by this order: <code>button 1 , button 11,button 111 , button 2</code>.why ? Thank you for your answer!</p>
| <p>Use <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString%5FClass/Reference/NSString.html#//apple%5Fref/doc/c%5Fref/NSNumericSearch" rel="nofollow">the <code>NSNumericSearch</code> option</a> in your sort comparison.</p>
|
Copy constructors - c++ <p>Can I write a copy constructor by just passing in a pointer instead of the const reference? (Would it be ok if I make sure that I am not going to change any values though?)</p>
<p>Like so:</p>
<pre><code>SampleClass::SampleClass(SampleClass* p)
{
//do the necessary copy functionality
}
</code></pre>
<p>instead of:</p>
<pre><code>SampleClass::SampleClass(const SampleClass& copyObj)
{
//do the necessary copy
}
</code></pre>
<p>Thanks in advance.</p>
<hr>
<p>Thanks everyone. So, if I write a constructor that takes in a pointer( and thought that's my copy constructor), the compiler would still supply with the default copy constructor in which case my constructor( which i thought was my copy constructor) would not be called and the default copy constructor would be called. Got it.</p>
| <p>Yes, you can write a constructor that takes a pointer to the object. However, it cannot be called a copy constructor. The very <em>definition</em> of a copy constructor requires you to pass an object of the same class. If you are passing anything else, yes, it's a constructor alright, but not a copy constructor.</p>
|
Where do I save partial (views) in Zend Framework, to be accessible for all Views in my App? <p>I have several view Partials (like paginator partial) which I want them to be available
To all view scripts in my application.<br />
Is there a directory I can put partial vies in, and they will be available to all?<br />
Or, how do I define such a directory? </p>
| <p>You can create a folder in the views folder with any name and from your views you would call a partial using the following code and as the second argument pass an array of values which would be used within the partial.</p>
<pre><code>$this->partial('your-partial-dir/your-partial.phtml', array('var'=>$myVar));
</code></pre>
<p>Note that you can include and render any partial view from any view referring to the views folder as the root. And you would access variables within the partial using the $this identifier to refer to each variable as though it was a member of the partial object:</p>
<pre><code>//your-partial.phtml file
$this->var;
</code></pre>
<p>Alternatively you can also create a view helper - a view helper is a class that is declared and extended from the Zend_View_helper class and can be called from a view as though it was a member function.</p>
<p>For more on view helpers you can refer to this write up on Zend <a href="http://devzone.zend.com/article/3412-View-Helpers-in-Zend-Framework">http://devzone.zend.com/article/3412-View-Helpers-in-Zend-Framework</a></p>
|
Is ruby on rails plugin, acts_as_ferret, very buggy? <p>I am doing a very simple search on my DB using acts_as_ferret. I put this in my "Venue" model:</p>
<pre><code>acts_as_ferret :fields => [:name, :city]
</code></pre>
<p>And this is in my controller search action:</p>
<pre><code>@t = Venue.find_by_contents(params[:search]+'~')
</code></pre>
<p>and then I just render the results. </p>
<pre><code>render :text => @t.to_json, :success => true, :status => :ok
</code></pre>
<p>If I run a quick test:</p>
<pre><code>http://localhost:3000/venue/list?search=The
</code></pre>
<p>I see in my log that the proper query "The~" is being executed on the index. However, I get no results. I definitely have a few "Venues" with the word "The" in the name field.</p>
<p>Since this is a very simple search and acts_as_ferret is used quite a bit, I tried rebuilding the index to see if it was corrupted....no dice</p>
<p>Any ideas?</p>
<p>Thanks!</p>
| <p>Yes, Ferret has been very well known for corrupting indexes.</p>
<p>I recommend switching over to another searching plugin like <a href="http://ts.freelancing-gods.com/" rel="nofollow">Thinking Sphinx</a>. You can <a href="http://railscasts.com/episodes/120-thinking-sphinx" rel="nofollow">watch the Railscast about it</a> in order to learn more.</p>
|
How to overcome same type in two namespaces, System.Linq.Expressions.Expression<TDelegate>? <p>I am defining some Expression variables in my app and need to have a reference to Microsoft.Scripting.Core. That assembly includes the same namespace as the System.Core assembly from the main .Net framework.</p>
<p>I want to use the defintions from the System.Core assembly as it's stable whereas the Microsoft.Scripting.Core is alpha.</p>
<p>How do I tell my app to preference the System.Linq.Expressions namespace in System.Core instead of Microsoft.Scripting.Core but still be able to keep the reference to it?</p>
| <p>If they are the same namespace but different assemblies, then you may need to look at "extern alias", but that gets very messy very quickly.</p>
<p>If they are different namespaces, then simply use different <code>using</code> directives; you can also use <code>using</code> aliasing. However, lambdas will always (AFAIK) use the original namespace.</p>
|
Filtering fiddler to only capture requests for a certain domain <p>I'm not sure how to modify the CustomRules.js file to only show requests for a certain domain.</p>
<p>Does anyone know how to accomplish this?</p>
| <p>This is easy to do.
On the filters tab, click "show only if the filter contains, and then key in your domain.</p>
<p><img src="http://i.stack.imgur.com/HRoUS.png" alt="enter image description here"></p>
|
Data Binding Is More Complicated Than I'd Like <p>I have a form that will be populated by a bunch of information from a template, and then handed over to the user to fill out the rest. The thing is, the template and the object that holds the eventual result are DataRows, because it's all going into and out of a database (that I have no schema control over), so this seems like a great place to just bind all the controls and get on with more important things, right?</p>
<p>I can't get the controls to bind properly, and this is partly my fault because I wanted to just throw it a row, have it work out which columns from the row are important, and keep the values from those, so I'm frequently throwing it rows that don't have all the columns the controls expect, and so they throw an exception. But it's partly I-don't-know-who's fault because doing this:</p>
<pre><code>inProductName.DataBindings.Add("Text", TemplateBinder, "ProductName");
</code></pre>
<p>where TemplateBinder is a BindingSource object with the DataSource property set to the DataRow I want to trickle out, throws an exception when I go to show the form. Not really sure what I should do differently - the TemplateBinder won't contain any DataSource until I get the template row, and if I have to manage the bindings myself instead of setting them and forgetting them at the top of the page I'm not getting much value out of binding.</p>
<p>And this is just a test to see if what I'm trying to do is even feasible! I'm trying to pass the BindingSource a row that contains the values I want to propagate to the form, suspend binding, switch it out for a blank row from the table so the values I propagated out stay in the properties I've bound, show the form, let the user fill it out and then turn on binding again so the bound properties in the controls trickle into the blank row I've set as the BindingSource DataSource. I mean, there's no way that'll work, because that'd be too easy, but it'd sure be nice if I could do that instead of my old way which involved a 30-case switch statement.</p>
<p>I don't want to go too far down the rabbit hole here. There's a tempting button in Visual Studio that says it'll just set everything all up automatically, but I have experience with Visual Studio that suggests it won't like the idea that the schema of the database won't be changed through Visual Studio. In addition, I have no idea how to get the flexibility I (or rather, my clients) demand from this fancy automagic setup (I can't even see how to programmatically mess with the connection string). The copy-pasted code I have is probably less of a sin than killing features because I made a sweeping change behind the scenes that happens to make certain very handy features inconvenient. Copypasta can be turned into a function a lot quicker than it takes to rewrite the entire application. And then what if the database changes? Automagic code seems to prefer to throw an exception instead of just swallowing its pride and not doing anything if it doesn't have enough information to do something.</p>
<p>So, Stack Overflow, the tl;dr: I want to make data binding work for me instead of making me throw out everything I've done. Can I?</p>
| <p>I expect that for that to work, you'd need to use a <code>DataRowView</code>, not a <code>DataRow</code>; try getting this from the <code>DataView</code> rather than the <code>DataTable</code>. The default view is <code>table.DefaultView</code>.</p>
<p>For info; the reason it works when you use a <code>DataTable</code> as the binding-source is that <code>DataTable</code> implements <code>IListSource</code>, and returns (from <code>GetList()</code>) the default view - so actually, when you bind to a <code>DataTable</code>, you <em>actaully</em> end up binding to the default view (<code>DataView</code>).</p>
|
How to lose margin/padding in UITextView? <p>I have a <code>UITextView</code> in my iOS Application, which displays a large amount of text. I am then paging this text by using the offset margin parameter of the <code>UITextView</code>. My problem is that the padding of the <code>UITextView</code> is confusing my calculations as it seems to be different depending on the font size and typeface that I use.</p>
<p>Therefore, I pose the question: Is it possible to remove the padding surrounding the content of the <code>UITextView</code>?</p>
<p>Look forward to hearing your responses!</p>
| <p>For iOS 7.0, I've found that the contentInset trick no longer works. This is the code I used to get rid of the margin/padding in iOS 7.</p>
<p>This brings the left edge of the text to the left edge of the container:</p>
<pre><code>self.textView.textContainer.lineFragmentPadding = 0;
</code></pre>
<p>This causes the top of the text to align with the top of the container</p>
<pre><code>self.textView.textContainerInset = UIEdgeInsetsZero;
</code></pre>
<p>Both Lines are needed to completely remove the margin/padding.</p>
|
I have 15 minutes to present ASP.NET MVC to my colleagues. What topics should I focus on? <p>I've been using ASP.NET MVC for personal projects since before it hit RTM.</p>
<p>I am preparing a presentation for my colleagues to introduce them to basic concepts of ASP.NET MVC and show them how it could be used in our environment.</p>
<p>My presentation has a 15 minute limit. There is a lot of information to relay (especially if you factor in projects like MVCContrib and various blog posts).</p>
<p>What topics should I focus on?</p>
<p><strong>Some context:</strong> I work for a digital agency. My colleagues are .NET developers with 3+ years of ASP.NET experience.</p>
<p><strong>What's been suggested so far:</strong></p>
<ul>
<li>Reasons for wanting to switch to ASP.NET MVC</li>
<li>Routing</li>
<li>ActionResults (ability to serve different responses)</li>
<li>Request-Response internals</li>
<li>Testability</li>
<li>Scaffolding (T4 templates)</li>
<li>Fine-grained control over HTML output</li>
<li>Separation of concerns ()</li>
<li>Differences between ASP.NET WebForms and ASP.NET MVC</li>
</ul>
| <p>You only have time for 2 or 3 main points.</p>
<p>The most important concept to grasp is that requests arrive at controllers then the controller <strong>chooses</strong> what view to present the results the <strong>controller</strong> has generated.</p>
<p>The next important concept is that MVC has its big win over the "classic" ASP.NET when you create unit tests for your controllers and the model. Without this MVC is just another way to skin a cat.</p>
<p>For a final point I would focus on the structure of URLs not because its that important but because we like things that have a clean feel and MVC Urls can do that, this may help generate a positive response.</p>
<p>Avoid going on about there being no server controls (which isn't entirely true) since that is likely to elicite a negative response. In general avoid mentioning what is doesn't do compared with ASP.NET forms (although there not being any need for Viewstate is worth mentioning in passing). You know that the benefits out weigh the things that are missing (or unnecessary) but your audience does not. Keep it positive.</p>
|
jQuery UI, sortables and Cookie plugin with multiple lists <p>I'm using jQuery UI sortable plugin with the cookie plugin to set and get the list of two sortable lists.</p>
<p>I found this piece of code to set and get a cookie: <a href="http://www.shopdev.co.uk/blog/sortable-lists-using-jquery-ui/#comment-6441" rel="nofollow">http://www.shopdev.co.uk/blog/sortable-lists-using-jquery-ui/#comment-6441</a></p>
<p>It works as I want to for one list, but not two (I've made the changes listed in the comments but fail somewhere).</p>
<p>My guess is that I have to specify the first and the second list for the setSelector and not use a class for the list. I tried "var setSelector = "#first, #second"; but that that doesn't do it. </p>
<p>Ideas?</p>
<p>Thanks </p>
<p>$(function() {</p>
<pre><code>// set the list selector
var setSelector = ".sortable";
// set the cookie name
var setCookieName = "listOrder";
// set the cookie expiry time (days):
var setCookieExpiry = 7;
// function that writes the list order to a cookie
function getOrder() {
// save custom order to cookie
$.cookie(setCookieName, $(setSelector).sortable("toArray"), { expires: setCookieExpiry, path: "/" });
}
// function that restores the list order from a cookie
function restoreOrder() {
var list = $(setSelector);
if (list == null) return
// fetch the cookie value (saved order)
var cookie = $.cookie(setCookieName);
if (!cookie) return;
// make array from saved order
var IDs = cookie.split(",");
// fetch current order
var items = list.sortable("toArray");
// make array from current order
var rebuild = new Array();
for ( var v=0, len=items.length; v<len; v++ ){
rebuild[items[v]] = items[v];
}
for (var i = 0, n = IDs.length; i < n; i++) {
// item id from saved order
var itemID = IDs[i];
if (itemID in rebuild) {
// select item id from current order
var item = rebuild[itemID];
// select the item according to current order
var child = $("ul" + setSelector + ".ui-sortable").children("#" + item);
// select the item according to the saved order
var savedOrd = $("ul" + setSelector + ".ui-sortable").children("#" + itemID);
// remove all the items
child.remove();
// add the items in turn according to saved order
// we need to filter here since the "ui-sortable"
// class is applied to all ul elements and we
// only want the very first! You can modify this
// to support multiple lists - not tested!
$("ul" + setSelector + ".ui-sortable").filter(":first").append(savedOrd);
}
}
}
// code executed when the document loads
$(function() {
// here, we allow the user to sort the items
$(setSelector).sortable({
cursor: 'move',
items: 'li',
//axis: "y",
opacity: 0.6,
//revert: true,
scroll: true,
scrollSensitivity: 40,
placeholder: 'highlight',
update: function() { getOrder(); }
});
// here, we reload the saved order
restoreOrder();
});
</code></pre>
<p>});</p>
| <p>_http://code.google.com/p/cookies/</p>
<p>_http://noteskeeper.ru/article/save-state-jquery-ui-sortable/</p>
<pre><code> root = $("#sidebar");
$('> *', root).each(function (index) {
this.id = 'block-' + index;
});
root.sortable({
cursor: 'move',
revert: true,
placeholder: 'ui-state-highlight'
});
// function that writes the list order to a cookie
root.bind( "sortupdate", function (event, ui) {
// save custom order to cookie
var order = $(this).sortable('serialize');
$.cookies.set('sortable', order);
});
// here, we reload the saved order
// fetch the cookie value (saved order)
var c = $.cookies.get('sortable');
if (c) {
// function that restores the list order from a cookie
$.each(c.split('&'), function () {
var id = this.replace('[]=', '-');
$('#' + id).appendTo(root);
});
}
</code></pre>
|
FormsAuthentication.RedirectFromLoginPage is not working <p>I am working on a LoginPage.Everything related to database or C# code is working fine but after successul login I am unable to redirect to Home.aspx,am I missing Something? Pls help.
<strong>Code:</strong></p>
<p><strong>Web.Config:</strong></p>
<p>
</p>
<pre><code></authentication>
<authorization>
<deny users="*"/>
</authorization>
</code></pre>
<p><strong>C# Code:</strong></p>
<pre><code>protected void Button1_Click(object sender, EventArgs e)
{
string source = "server=localhost\\sqlexpress;Database=LogInDB;Trusted_Connection=True";
SqlConnection con = new SqlConnection(source);
con.Open();
SqlCommand cmd = new SqlCommand("proc_LogIn", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@ID", SqlDbType.Int).Value = TextBox1.Text;
cmd.Parameters.Add("@Password", SqlDbType.VarChar).Value = TextBox2.Text;
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
FormsAuthentication.RedirectFromLoginPage(TextBox1.Text, false);
}
else
{
Response.Write("Invalid credentials");
}
}
</code></pre>
| <p>It should be <code><deny users="?"/></code></p>
<pre><code>* means all
? means unauthenticated
</code></pre>
|
Asp .Net File Caching <p>is any way to cache a whole folder with resources in ASP.NET without write own HttpModule?
e.g.: folder with Wysiwyg editor javascript and styles</p>
| <p>The purpose of ASP.NET caching is so that the requests no longer need to be processed in full, meaning that the database doesn't have to be queried, the content doesn't have to be produced, templates instantiated, event handlers called, and so forth.</p>
<p>Caching static objects this way yields no performance improvement as there is no processing required for static content. ASP.NET doesn't process these items anyway. IIS will probably cache them through the OS's caching features.</p>
<p>I should note that caching is automatically done by clients for static content, so it's very unlikely that revisiting clients download the same object twice.</p>
|
Exporting Data Or Code To A .png <p>How Do you Export Code To A .png In Order To Make It Animated?
I Am Using VB.Net 2008 Express Edition.</p>
| <p>Create a page like "myimage.aspx" and in the codebehind (sorry, this is C#)</p>
<pre><code>Bitmap bmp = new Bitmap(width, height);
Graphics gfx = Graphics.FromImage(bmp);
gfx.FillRectangle(Brushes.White, 0, 0, bmp.Width, bmp.Height);
</code></pre>
<p>Use the gfx to draw on the image (see it's methods).
Then return the PNG in the response stream</p>
<pre><code>MemoryStream ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
Response.Clear();
Response.ContentType = "image/png";
Response.BinaryWrite(ms.GetBuffer());
Response.End();
</code></pre>
<p>You can then reference this in HTML like</p>
<pre><code><img src="myimage.aspx" />
</code></pre>
|
Getting number of certain days-of-the-week (weekend) from interval in PostgreSQL <p>Given 2 timestamps in postgres, how do you calculate the time difference without counting whole Saturdays and Sundays?</p>
<p>OR</p>
<p>How do you count the number of Saturdays and Sundays in a given time interval?</p>
| <p>The following function is returning the number of full weekend days between two dates. As you need full days, you can cast the timestamps to dates before calling the function. It returns 0 in case the first date is not strictly before the second.</p>
<pre><code>CREATE FUNCTION count_full_weekend_days(date, date)
RETURNS int AS
$BODY$
SELECT
($1 < $2)::int
*
(
(($2 - $1) / 7) * 2
+
(EXTRACT(dow FROM $1)<6 AND EXTRACT(dow FROM $2)>0 AND EXTRACT(dow FROM $1)>EXTRACT(dow FROM $2))::int * 2
+
(EXTRACT(dow FROM $1)=6 AND EXTRACT(dow FROM $2)>0)::int
+
(EXTRACT(dow FROM $2)=0 AND EXTRACT(dow FROM $1)<6)::int
);
$BODY$
LANGUAGE 'SQL' IMMUTABLE STRICT;
</code></pre>
<p>Examples:</p>
<pre><code>SELECT COUNT_FULL_WEEKEND_DAYS('2009-04-10', '2009-04-20');
# returns 4
SELECT COUNT_FULL_WEEKEND_DAYS('2009-04-11', '2009-04-20');
# returns 3 (11th is Saturday, so it shouldn't be counted as full day)
SELECT COUNT_FULL_WEEKEND_DAYS('2009-04-12', '2009-04-20');
# returns 2 (12th is Sunday, so it shouldn't be counted as full day)
SELECT COUNT_FULL_WEEKEND_DAYS('2009-04-13', '2009-04-20');
# returns 2
</code></pre>
<p>To obtain the number of days except full weekend days, simply subtract the number of days from the function above:</p>
<pre><code>SELECT
'2009-04-20'::date
-
'2009-04-13'::date
-
COUNT_FULL_WEEKEND_DAYS('2009-04-13', '2009-04-20');
</code></pre>
|
Bluetooth obex reception on 3rd edition device fails <p>I have got a mix of 2nd edition and 3rd edition s60 phones. I start custom obex listener on both phones using Python and try to send files to them. Though I can send files to 2nd edition phone; I can't send files to 3rd edition phone and the error being "Broken pipe".</p>
<p>Why this is so?</p>
| <p>At least in Symbian C++ SDK the API of Bluetooth was changed between 2nd to 3rd edition phones.
It probably affects also Python.</p>
|
How to manage process for single man project <p>We have a single developer working on 3 different projects. He used to work on bug fixes, maintenance and few feature implementation. In one specific project, he works with one more junior developer.</p>
<p>Our company wants to implement scrum for all the projects.. What is the best way to handle the scrum process for 1 or 2 person project?</p>
| <p>I agree it should be kept Simple Stupid, but most of the Scrum framework can be used here.</p>
<p>I had several people working in this fashion both on projects as well as on maintenance/operational work. </p>
<p>Product Owner/Backlog - There's still an owner thats in charge of defining the business value and prioritizing, right? The backlog should still be there.
If he's part of a bigger Scrum enterprise then he probably needs to feed on part of a bigger Product Backlog. </p>
<p>Scrum Team - yep, its either a 1 or 2-person team. So its really SELF-organization... but thats ok! Daily scrum? yes between the 2 persons, or if its just that 1 person at times, good time to go over tasks and problems, think about what impediments need to be surfaced to the Scrum of Scrum or to the Product Owner. </p>
<p>Sprint - Still a good idea, especially if part of a larger Scrum enterprise thats working in sprints, but even without it. Good chance to catch up with PO, demo what you got, energize yourself, retrospect and see what you can do better, plan for the next sprint.
Note that in case of working outside of a Scrum enterprise / Scrum of Scrum, sprints can benefit from being shorter than usual since the scope is probably smaller and the planning overhead lower. but it depends on the situation. </p>
<p>Retrospective - yes, it can be held alone. I think killer programmers need to retrospect on their own work/progress and take action on things that hold them back. Even keep a chart in your workspace to help you with making progress.</p>
<p>Task Board / Burndown - Yes, you need those. You can have them in your work space on the wall, they can be small, but they really help even if you're one person.
Why can GTD (Getting Things Done) help a single person and a TB/BDC not? If that person is doing project work then a Sprint Burndown and Release Burndown provide a lot of value. If he's doing operational/maintenance work its still a way to verify he's on track or not, and apply relevant measures accordingly. </p>
<p>Scrum Master - the person should be his own scrum master. </p>
<p>Coach - if the organization had a coach helping the teams/SMs/POs, then he should also help this scrum cell...</p>
<p>To sum up - its clear to me that the values and principles underlying Scrum/Agile apply for 1-2 person teams as well.
Its also clear that most of Scrum can be applied as well.</p>
<p>The questions is what the individuals involved think.</p>
<p>If the management, the developer, the PO are all on board and believe that the values/principles make sense, and strive to improve, it will work.
If they don't, then first get to the point where the overall thinking makes sense, then deal with the individual team...</p>
|
Accessing links from JS in a WebBrowser object <p>I need to automate some tasks on a website that does not have an API, and uses a substantial amount of JavaScript, without any graceful fall-back, so is it possible to parse over content added to a page via JS, with C#, I assumed that this would be done with a WebBrowser object but so far I've been unsuccessful.</p>
| <p>Try <a href="http://sourceforge.net/projects/ulti-swat" rel="nofollow">SWAT</a> or <a href="http://watin.sourceforge.net/" rel="nofollow">WatiN</a></p>
<p>Both are unit testing frameworks for automating web site front end testing, but can easily be used to traverse the DOM on a website as you want to do.</p>
|
Accessing a WPF GroupItem text for conversion in a template <p>I'm customising the appearance of grouping in a <code>ListBox</code>. In <code>ListBox.Resources</code>, I have declared something like (formatting removed):</p>
<pre><code><Style TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<StackPanel Orientation="Vertical">
<!-- Group label -->
<ContentPresenter />
<!-- Items in group -->
<ItemsPresenter />
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</code></pre>
<p>The actual group label is not very readable and I'd like to use a value converter to make it more presentable. However I cannot find a way to obtain this text and convert it. </p>
<p>I figure that a <code>Binding</code> would let me use a converter.</p>
<p>I've tried replacing the <code>ContentPresenter</code> above with the likes of...</p>
<pre><code><TextBlock Text="{TemplateBinding Content}"/>
<TextBlock Text="{Binding}"/>
</code></pre>
<p>...and numerous other things, but to no avail. Any suggestions?</p>
| <p>Well isn't that just typical. I found the answer shortly after posting...</p>
<pre><code><TextBlock Text="{Binding Path=Content.Name,
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=GroupItem},
Converter={StaticResource MyConverter}}"/>
</code></pre>
<p>Sometimes just the process of actually <em>asking</em> the question draws the answer out of thin air. In this case looking at the source code of <code>GroupItem</code> in <em>.NET Reflector</em> did the trick.</p>
<p>Hope someone else finds this edge case useful. Still, it would be a lot nicer if <code>GroupItem</code> exposed a property for this directly.</p>
<p>I'll still award a correct answer to anyone who knows a nicer way of doing this.</p>
|
What's wrong with calling Invoke, regardless of InvokeRequired? <p>I've seen the common setup for cross threading access to a GUI control, such as discussed here:
<a href="http://stackoverflow.com/questions/571706/shortest-way-to-write-a-thread-safe-access-method-to-a-windows-forms-control">http://stackoverflow.com/questions/571706/shortest-way-to-write-a-thread-safe-access-method-to-a-windows-forms-control</a></p>
<p>All the web hits I found describe a similar thing.</p>
<p>However, why do we need to check InvokeRequired? Can't we just call Invoke directly?</p>
<p>I assume the answer is no, so my real question is 'why'?</p>
| <p>From non-UI threads we can't touch the UI - very bad things can happen, since controls have thread affinity. So from a non-UI thread we must (at a minumum) call <code>Invoke</code> or <code>BeginInvoke</code>.</p>
<p>For UI-threads, however - we <em>don't</em> want to call <code>Invoke</code> lots of time; the issue is that if you <em>are</em> already on the UI thread, it still has the unnecessary overhead of sending a message to the form's pump and processing it.</p>
<p>In reality, in most threading code you <em>know</em> you expect a specific method to be called on a <strong>non</strong>-UI thread, so in those cases, there is no additional overhead: just call <code>Invoke</code>.</p>
|
Rails validation and 'fieldWithErrors' wrapping select tags <p>Is it normal behaviour to not get the <code><div class="fieldWithErrors"></code> wrapped arround select tags that have validation errors? I personally see no reason why the select tags should be treated differently than other form tags (input, textarea).</p>
<p>I <em>do</em> get the error in <code>error_messages_for</code> and <code>error_message_on</code> methods for that field.</p>
<p>PS. I have altered a bit the <code>ActionView::Base.field_error_proc</code> in order to get span tags instead of divs, but that isn't the problem.</p>
<pre><code>ActionView::Base.field_error_proc = Proc.new { |html_tag, instance|
#if I puts html_tag here I only get the <input> tags
"<span class=\"fieldWithErrors\">#{html_tag}</span>"
}
</code></pre>
| <p>The problem (for me at least) was that my <code>f.select :whatever_id</code> was looking in the <code>object.errors</code> object for a key of <code>:whatever_id</code> when my validation was actually on <code>:whatever</code>, not <code>:whatever_id</code>.</p>
<p>I worked around this annoying problem by changing</p>
<pre><code>object.errors.on(@method_name)
</code></pre>
<p>to</p>
<pre><code>object.errors.on(@method_name) || object.errors.on(@method_name.gsub(/_id$/, ''))
</code></pre>
<p>Here's the diff (against Rails 2.3.4):</p>
<pre><code>diff --git a/vendor/rails/actionpack/lib/action_view/helpers/active_record_helper.rb b/vendor/rails/actionpack/lib/action_view/helpers/active_record_helper.rb
index 541899e..5d5b27e 100644
--- a/vendor/rails/actionpack/lib/action_view/helpers/active_record_helper.rb
+++ b/vendor/rails/actionpack/lib/action_view/helpers/active_record_helper.rb
@@ -247,7 +247,7 @@ module ActionView
alias_method :tag_without_error_wrapping, :tag
def tag(name, options)
if object.respond_to?(:errors) && object.errors.respond_to?(:on)
- error_wrapping(tag_without_error_wrapping(name, options), object.errors.on(@method_name))
+ error_wrapping(tag_without_error_wrapping(name, options), object.errors.on(@method_name) || object.errors.on(@method_name.gsub(/_id$/, '')))
else
tag_without_error_wrapping(name, options)
end
@@ -256,7 +256,7 @@ module ActionView
alias_method :content_tag_without_error_wrapping, :content_tag
def content_tag(name, value, options)
if object.respond_to?(:errors) && object.errors.respond_to?(:on)
- error_wrapping(content_tag_without_error_wrapping(name, value, options), object.errors.on(@method_name))
+ error_wrapping(content_tag_without_error_wrapping(name, value, options), object.errors.on(@method_name) || object.errors.on(@method_name.gsub(/_id$/, '')))
else
content_tag_without_error_wrapping(name, value, options)
end
</code></pre>
|
Debugging on Linux for Windows Developer <p>Primarily I've done basic (novice level) software development on a Windows machine, but I've always had MS Visual Studio to help me step through the process of debugging. </p>
<p>Now, however, it looks like I will be on Linux, so in order to get ready for the jump I want to make sure I have a tool/tools lined up to help me step through the code and debug. </p>
<p>Unfortunately when I've verbally asked folks how they go about debugging on Linux, I typically get the following answer, "Oh, I just put a bunch of print statements." OMG! No way you say, but yes that is their answer. </p>
<p>Since it is on Linux, and will be working with C++ code on the CentOS 32-bit OS, I am hoping here is a preferred OpenSource solution. So, I guess I asking for the preferred OpenSource IDE for C++ code on CentOS Linux. </p>
<p>Thanks for any insight and suggestions.</p>
| <blockquote>
<p>Good question, of course, but its been
done before:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/408418/what-editor-ide-do-you-use-for-c-programming-on-linux-and-why-closed">http://stackoverflow.com/questions/408418/what-editor-ide-do-you-use-for-c-programming-on-linux-and-why-closed</a></li>
<li><a href="http://stackoverflow.com/questions/86676/is-there-a-good-and-free-ide-for-c-c-in-linux">http://stackoverflow.com/questions/86676/is-there-a-good-and-free-ide-for-c-c-in-linux</a></li>
<li><a href="http://stackoverflow.com/questions/149321/what-ide-would-be-good-for-linux-kernel-driver-development">http://stackoverflow.com/questions/149321/what-ide-would-be-good-for-linux-kernel-driver-development</a></li>
<li><a href="http://stackoverflow.com/questions/2756/lightweight-ide-for-linux">http://stackoverflow.com/questions/2756/lightweight-ide-for-linux</a></li>
<li><a href="http://stackoverflow.com/questions/524404/simple-gui-ide">http://stackoverflow.com/questions/524404/simple-gui-ide</a></li>
</ul>
</blockquote>
<p>(from: <a href="http://stackoverflow.com/questions/579219/best-unix-linux-c-debuger-ide-closed">http://stackoverflow.com/questions/579219/best-unix-linux-c-debuger-ide-closed</a>)</p>
|
Differences between JVM implementations <p>Where do JVM Implementations differ (except licensing)?
Does every JVM implement Type Erasure for the Generic handling?</p>
<p>Where are the differences between:</p>
<ul>
<li>JRockit</li>
<li>IBM JVM</li>
<li>SUN JVM</li>
<li>Open JDK</li>
<li>Blackdown </li>
<li>Kaffe</li>
</ul>
<p>.....
Deals one of them with Tail-Call-Optimization? </p>
| <p>JVM implementations can differ in the way they implement JIT compiling, optimizations, garbage collection, platforms supported, version of Java supported, etc. They all must meet set of features and behaviors so that it will execute your Java bytecodes correctly.</p>
<p>As you've pointed out, the major difference tends to be in licensing. Other non-technical differences tend to be in free/paid support options, integration with other technologies (usually J2EE servers), and access to source code.</p>
<p>Note: While a J2EE server runs on the JVM, some servers have integrated tools for monitoring, analyzing, and tweaking JVM performance.</p>
<p>As far as technical differences, those have grown less significant over the years. Once upon a time, the IBM and JRockit JVM's had far superior performance to the reference Sun implementation. This was due to significant differences in the types of runtime optimizations, differences in garbage collection, and differences in native-code (and how much native code various classes uses). These performance differences aren't as significant anymore.</p>
<p>Some JVM's also include or integrate with diagnostics and monitoring tools. JRockit includes a set of tools for monitoring your JVM performance. Sun provides various JMX-based tools with overlapping features to do the same. IBM Websphere once upon a time included a similar set of tools for their whole J2EE application server (not sure if they still do, but I would assume that's still true)...</p>
<p>Some of the open source JVM's tend to have a little slower performance because they have been redeveloped from the ground up. As such, they've got a bit more catching up to do. Last I checked about 2 years ago, Blackdown was significantly slower (1.5x-2x?) than the Sun JVM. It was also a bit behind of supported versions of Java.</p>
|
Refer to other SQL SELECT statements aliased as tables in FROM clause <p>I have a very large query that follows the format below:</p>
<pre><code>select ...
from ( select field1,
field2
from some_table ) table1,
( select field1,
field3
from other_table ) table2
where .....
</code></pre>
<p>Is is possible for me to refer to one of the tables "defined" in the from clause, lets say table1, in one of the other table definitions in the from clause?</p>
<p>For example:</p>
<pre><code>select ....
from ( select field1,
field2
from some_table ) table1,
( select table1.field1,
field3
from other_table,
table1 ) table2
where .....
</code></pre>
<p>Disclaimer: What I am trying to do is not as simple as the example above. The example is simply to illustrate the idea.</p>
| <pre><code>WITH
table1 AS
(
SELECT field1, field2
FROM some_table
),
table2 AS
(
SELECT field1, field2
FROM other_table, table1
)
SELECT *
FROM table2
</code></pre>
|
TypeDef as an overridable class feature <p>If I have a class that contains a number of <code>typedef</code>'d variables, like so:</p>
<pre><code>class X {
typedef token TokenType;
bool doStuff()
{
TokenType data;
fillData(&data);
return true;
}
};
</code></pre>
<p>Is there any way to override the <code>typedef</code> for <code>TokenType</code> in a derived class?</p>
<p>N.B. This is NOT a good place to use templates (This is already a templated class and any changes are likely to result in [EDIT: <em>infinite</em>] recursive definitions [<code>class X < class Y = class X < class Y . . .> ></code> etc.].)</p>
| <p>What you can do is shadow, but not override. That is: you can define a derived class Y with its own typedefs for TokenType, but that will only come into play if somebody references Y::TokenType directly or via an object statically typed as Y. Any code that references X::TokenType statically will do so even for objects of type Y. </p>
|
Building an API library package? <p>What do you guys use to build package (zip library, documentation example) of some API written in .NET? Right now I do it manually, building in vs , sandcastle and then zipping it together...</p>
| <p>I use <a href="http://nant.sourceforge.net" rel="nofollow">Nant</a> as a build tool, not only for libraries, but also for executables (installer and stuff).</p>
<p>Others use batch files as post-build events in Visual Studio (in a special configuration so that is not built every time you comile).</p>
|
What is the meaning of numeric_limits<double>::digits10 <p>What is the precise meaning of numeric_limits::digits10?
Some other related questions in stackoverflow made me think it is the maximum precision of a double, but </p>
<ul>
<li>The following prototype starts working (sucess is true) when precision is greater that 17 ( == 2+numeric_limits::digits10)</li>
<li>With STLPort, readDouble==infinity at the end; with microsoft's STL, readDouble == 0.0.</li>
<li>Has this prototype any kind of meaning :) ?</li>
</ul>
<p>Here is the prototype:</p>
<pre><code>#include <float.h>
#include <limits>
#include <math.h>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
int main(int argc, const char* argv[]) {
std::ostringstream os;
//int digit10=std::numeric_limits<double>::digits10; // ==15
//int digit=std::numeric_limits<double>::digits; // ==53
os << std::setprecision(17);
os << DBL_MAX;
std::cout << os.str();
std::stringbuf sb(os.str());
std::istream is(&sb);
double readDouble=0.0;
is >> readDouble;
bool success = fabs(DBL_MAX-readDouble)<0.1;
}
</code></pre>
| <p><code>numeric_limits::digits10</code> is the number of decimal digits that can be held without loss.</p>
<p>For example <code>numeric_limits<unsigned char>::digits10</code> is 2. This means that an unsigned char can hold 0..99 without loss. <strong><em>If</em></strong> it were 3 it could hold 0..999, but as we all know it can only hold 0..255.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/af6x78h6.aspx">This manual page</a> has an example for floating point numbers, which (when shortened) shows that</p>
<pre><code>cout << numeric_limits<float>::digits10 <<endl;
float f = (float)99999999; // 8 digits
cout.precision ( 10 );
cout << "The float is; " << f << endl;
</code></pre>
<p>prints</p>
<pre><code>6
The float is; 100000000
</code></pre>
|
selecting a log file <p>We have multiple log files like database log, weblog, quartzlog in our application.</p>
<p>Any log from files under package /app/database will go to database log.
Any log from files under package /app/offline will go to quartzlog log.</p>
<p>What we need now is - want to direct the log staments from one of the java file under /app/database to be outputted to quartzlog instead of database log.</p>
<p>How can we select a particular log file in java file?</p>
| <p>You need to define the appropriate appender that logs in the desired file. Read <a href="http://logging.apache.org/log4j/1.2/manual.html" rel="nofollow">this short introduction</a> to see how you can do it.</p>
<p>Then in the configuration file, you can instruct all messages from a specific package to go in the selected appender:</p>
<pre><code>log4j.logger.my.package = DEBUG, myFileAppender
</code></pre>
<p><strong>EDIT:</strong></p>
<p>I believe that in log4j only package resolution is possible - you can't use an appender per file or method. You could try to work around this by adding an extra layer on top of log4j or implementing your own appender.</p>
<p>For example, instead of log.debug use:</p>
<pre><code>my.loggerproxy.log.debug(message);
</code></pre>
<p>If you only need to do it from a single method, then the above will be enough. Just instruct the logger proxy package to be logged in a different file.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.