instruction
stringlengths
0
30k
|language-agnostic|education|
|language-agnostic|education|
The *implements mouselistener, mousemotionlistener* just allows the displayArea class to listen to some, to be defined, Swing component's mouse events. You have to explicitly define what it should be listening at. So I suppose you could at something like this to the constructor: this.addMouseListener(this); this.addMouseMotionListener(this);
The *implements mouselistener, mousemotionlistener* just allows the displayArea class to listen to some, to be defined, Swing component's mouse events. You have to explicitly define what it should be listening at. So I suppose you could add something like this to the constructor: this.addMouseListener(this); this.addMouseMotionListener(this);
Trouble with parallel make not always starting another job when one finishes
|makefile|
I'm working on a system with four logical CPS (two dual-core CPUs if it matters). I'm using make to parallelize twelve trivially parallelizable tasks and doing it from cron. The invocation looks like: make -C [dir] -j 4 -l 3.99 [12 targets] The trouble I'm running into is that sometimes one job will finish but the next one won't startup even though it shouldn't be stopped by the load average limiter. Each target takes about four hours to complete and I'm wondering if this might be part of the problem.
I'm working on a system with four logical CPS (two dual-core CPUs if it matters). I'm using make to parallelize twelve trivially parallelizable tasks and doing it from cron. The invocation looks like: make -k -j 4 -l 3.99 -C [dir] [12 targets] The trouble I'm running into is that sometimes one job will finish but the next one won't startup even though it shouldn't be stopped by the load average limiter. Each target takes about four hours to complete and I'm wondering if this might be part of the problem. Edit: Sometimes a target does fail but I use the -k option to have the rest of the make still run. I haven't noticed any correlation with jobs failing and the next job not starting.
It looks like most of your CSS info is in some *.css files. There is also some inline Style info on the page. Your style for the static info comes from the in-line stuff. I am not sure how Drupal generates the page but the place to start looking is for any properties for "ultima-edicao". That is what the surrounding DIV is called.
If you really want to get into the details of communication between threads via shared memory, even declaring a variable volatile won't be enough, even if the compiler does use appropriate access semantics to ensure that it won't get a stale version of data after checking the flag. The CPU can issue reads and writes out of order as long (x86 usually doesn't, but PPC definitely does) and there is nothing in C++9x that allows the compiler to generate code to order memory accesses appropriately. [Herb Sutter's Effective Concurrency][1] series has an extremely in depth look at how the C++ world intersects the multicore/multiprocessor world. MSN [1]: http://www.gotw.ca/publications/index.htm
This is a conflict between your graphics driver and Visual Studio. Go to your driver settings page (Control panel) and disable the display rotation shortcuts. With this conflict removed, the shortcut will work in Visual Studio.
What's the BEST way to remove the time portion of a datetime value (SQL Server)
|sql-server|
Here's what I use: SELECT CAST(FLOOR(CAST(getdate() as FLOAT)) as DATETIME) I'm thinking there may be a better/more elegant way. Requirements: - it has to be as fast as possible (the less casting the better) - final result has to be a datetime type, not a string
If you use SVN for source control, definitely get VisualSVN. It enables TortoiseSVN interactions from within the Visual Studio IDE. I also echo the Resharper comment. Retail price is a little steep, but if you're a student or otherwise educationally affiliated, it's actually pretty cheap.
Allright, I figured it out! This is a hard bug to catch, but results from the way pipes are handled in Unix. Every element of a pipeline runs in a separate process. When the read command sets var1 and var2, is sets them it its own subshell, not the parent shell. So when the subshell exits, the values of var1 and var2 are lost. You can, however, try doing var1 = $(echo "Hello") echo var1 which returns the expected answer. Unfortunately this only works for single variables, you can't set many at a time. In order to set multiple variables at a time you must either read into one variable and chop it up into multiple variables or use something like this: set -- $(echo "Hello World") var1="$1" var2="$2" echo $var1 echo $var2 While I admit it's not as elegant as using a pipe, it works. Of course you should keep in mind that read was meant to read from files into variables, so making it read from standard input should be a little harder.
You need to handle the System.Windows.Forms.Application.ThreadException event for winforms. This article really helped me: [http://bytes.com/forum/thread236199.html][1]. [1]: http://bytes.com/forum/thread236199.html
Your CAST-FLOOR-CAST already seems to be the optimum way, at least on MSSQL 2005. Some other solutions i've seen have a string-conversion like Select Convert(varchar(11), getdate(),101) in them, which is slower by a factor of 10.
emacs has been used by linux programmers for decades. It features syntax highlighting, it's fast, and there are a million tutorials out there you can find.
What's the best setup for Mono development on Windows?
|windows|mono|
I started trying to play with Mono, mostly for fun at the moment. I first tried to use the VS plugin that will convert a csproj into a makefile, but there seemed to be no version available for VS2005. I also read about the MonoDevelop IDE, which sounded nice. Unfortunately, there's no pre-fab Windows package for it. I tried to follow some instructions to build it by combining dependencies from other semi-related installs. It didn't work, but that's probably because I'm a Windows-oriented guy and can barely spell "makefile". So, my question is this: what's the lowest-energy way to get up and running to try some Mono-based development on Windows? thanks! Chris
|wpf|validation|data-binding|
I have a databound TextBox in my application like so: (The type of `Height` is `decimal?`) <TextBox Text="{Binding Height, UpdateSourceTrigger=PropertyChanged, ValidatesOnExceptions=True, Converter={StaticResource NullConverter}}" /> public class NullableConverter : IValueConverter { public object Convert(object o, Type type, object parameter, CultureInfo culture) { return o; } public object ConvertBack(object o, Type type, object parameter, CultureInfo culture) { if (o as string == null || (o as string).Trim() == string.Empty) return null; return o; } } Configured this way, any non-empty strings which cannot be converted to decimal result in a validation error which will immediately highlight the textbox. However, the TextBox can still lose focus and remain in an invalid state. What I would like to do is either: 1. Not allow the TextBox to lose focus until it contains a valid value. 2. Revert the value in the TextBox to the last valid value. What is the best way to do this?
I have a databound TextBox in my application like so: (The type of `Height` is `decimal?`) <TextBox Text="{Binding Height, UpdateSourceTrigger=PropertyChanged, ValidatesOnExceptions=True, Converter={StaticResource NullConverter}}" /> public class NullableConverter : IValueConverter { public object Convert(object o, Type type, object parameter, CultureInfo culture) { return o; } public object ConvertBack(object o, Type type, object parameter, CultureInfo culture) { if (o as string == null || (o as string).Trim() == string.Empty) return null; return o; } } Configured this way, any non-empty strings which cannot be converted to decimal result in a validation error which will immediately highlight the textbox. However, the TextBox can still lose focus and remain in an invalid state. What I would like to do is either: 1. Not allow the TextBox to lose focus until it contains a valid value. 2. Revert the value in the TextBox to the last valid value. What is the best way to do this? **Update:** I've found a way to do #2. I don't love it, but it works: private void TextBox_LostKeyboardFocus(object sender, RoutedEventArgs e) { var box = sender as TextBox; var binding = box.GetBindingExpression(TextBox.TextProperty); if (binding.HasError) binding.UpdateTarget(); } Does anyone know how to do this better? (Or do #1.)
I have also seen octal used in aircraft transponders. A mode-3a transponder code is a 12-bit number that everyone deals with as 4 octal numbers. There is a bit more information on [Wikipedia](http://en.wikipedia.org/wiki/Transponder_%28aviation%29). I know it's not generally computer related, but the FAA uses computers too :).
You can use various ways to handle this situation, depending on your source control system. Private branches: Allow you to check in and work on code while you go, merging back and forth at appropriate times. Shelvesets/pacakaged changesets: Allow you to store changesets and send them around for review - ensuring they're production ready before check in. As to whether this is an appropriate way to work, we don't allow check-in to main branches without prior review. To pass review your code must pass various automated tools, and then must be acceptable to your peer reviewer. For some definitions of "production ready" - this is it. Therefore, we do something like what you do. However, we use private branches to ensure that check-ins can still be made while this is in progress, and that other check-ins don't have to interfere. If production ready means tested in an integration environment, then it sounds like you may need staging branches or something similar.
> Maybe a bonnet, lap or a tree is not a chair but they all are ISittable. Yes, but only ex post facto. They're ISittable because someone sat on them.
I don't think there's a built-in control that can do it in .NET. I'm poking around in the MSDN documentation for the standard Windows Button control, but it doesn't look like it's there. I did find a [Code Project article][1] with a custom implementation; this might help a little. [1]:http://www.codeproject.com/KB/buttons/SplitButton.aspx
The problem with static functions is that they can lead to a design that breaks encapsulation. For example, if you find yourself writing something like: public class TotalManager { public double getTotal(Hamburger burger) { return burger.getPrice() + burget.getTax(); } } ...then you might need to rethink your design. Static functions often require you to use setters and getters which clutter a Class's API and makes things more complicated in general. In my example, it might be better to remove Hamburger's getters and just move the getTotal() class into Hamburger itself.
LinqBridge works fine under .NET 2.0, and you get all the Linq extensions and query language. You need VS 2008 in order to use it, but you already knew that. However, Linq it not an ORM. It's a query syntax. If you want to use Linq to query a database, you will need .NET 3.5. That's because 2.0 does not provide the mechanism needed to convert Linq code to your favorite database query language. In other words, if an ORM is what you need, *LinqBridge will not help you*. You need to check out some of the other suggestions provided.
I recently came across [divascheme](http://www.cs.brown.edu/research/plt/software/divascheme/) - an alternative set of key bindings for [DrScheme](http://www.drscheme.org/). This is modal, and part of the justification is to do with RSI - specifically avoiding lots of wrist twisting to hit Ctrl-Alt-Shift-something. The coder has done an informal survey of fellow coders and found that emacs users suffered from more wrist pain than vi coders. You can see him doing a [short talk](http://video.google.com/videoplay?docid=-2721456512458968128&hl=en) at [LugRadio Live USA](http://lugradio.org/live/USA2008/). (The video is a series of 5 minute talks and I can't remember how far through it is, sorry - if someone watches it and posts that here I'll edit this post to say when in the video it is). Note I have not used divascheme.
you could always write one yourself: def iterattr(iterator, attributename): for obj in iterator: yield getattr(obj, attributename) will work with anything that iterates, be it a tuple, list, or whatever. I love python, it makes stuff like this very simple and no more of a hassle than neccessary, and in use stuff like this is hugely elegant.
I've never worked anywhere that had a formalized policy, but practically every manager I've ever had has allowed me to spend some time on things that weren't directly related to the current project or fighting a fire. I think the key is to talk about the things you'd like to try. Most managers want their teams to do something cool, something extraordinary, so if you can convince them that you might deliver something, you might get the chance. Or they might let you do it just to keep you happy.
I would definitely break down the jobs. Chances are you're likely to make changes in the builds, and it'll be easier to track down issues if you have smaller tasks instead of searching through one monolithic build. You should be able to create one big job from the smaller pieces, anyways.
Best practice for dynamically added Web.UI.ITemplate classes
|.net|asp.net|
We have a couple of ASP.Net dataview column templates that are dynamically added to the dataview depending on columns selected by users. These templated cells need to handle custom databindings: public class CustomColumnTemplate: ITemplate { public void InstantiateIn( Control container ) { //create a new label Label contentLabel = new Label(); //add a custom data binding contentLabel.DataBinding += ( sender, e ) => { //do custom stuff at databind time contentLabel.Text = //bound content }; //add the label to the cell container.Controls.Add( contentLabel ); } } ... myGridView.Columns.Add( new TemplateField { ItemTemplate = new CustomColumnTemplate(), HeaderText = "Custom column" } ); Firstly this seems rather messy, but there is also a resource issue. The `Label` is generated, and can't be disposed in the `InstantiateIn` because then it wouldn't be there to databind. Is there a better pattern for these controls? Is there a way to make sure that the label is disposed after the databind and render?
What on Earth are you all Word-is-binary-so-no-diff people talking about? TortoiseSVN, for example, integrates right out of the box with Word and enables you to use Word's built-in diff and merge functionality. It works just fine. I have worked on projects that store documents in version control. It has worked out pretty well, although if people are unfamiliar with version control, they are probably going to have conceptual difficulties with things like "working copy" and "merge" and "conflict". Don't overestimate the users' capabilities when you plan your document management system. I believe there exist big and powerful commercial solutions for all of this, as well. I'm sure if you have enough kilodollars, you can get something that fits your needs perfectly. Document management systems are a big business for big enterprise.
You definitely want to break up the tasks. Here is a nice example of CruiseControl.NET configuration that has different targets (tasks) for each step. It also uses a common.build file which can be shared among projects with little customization. <http://code.google.com/p/dot-net-reference-app/source/browse/#svn/trunk>
Try Thread.Sleep(10 * 60 * 1000)
Or how about logging to a queue? That way you can switch out pollers whenever you like to log to different things. It makes things like rolling over and archiving log files very easy. It's also nice because you can add pollers that log to different things, for example: * a poller that looks for error messages and posts them to your FogBugz account * a poller that looks for access violations ('x tried to access /foo/y/bar.html') to a 'hacking attempts' file * etc.
Scott Hanselman / Stuart Celarier / Patrick Cauldwell's [poster][1] with ndepend metrics has some useful information on it. Rather than trying to break down all the heuristics being used I'd focus on only a few at a time starting with "zone of pain / zone of uselessness" and cyclomatic complexity. There is also a [podcast][2] which covers some of the basics of the tool. Between that and running nDepend on a few different projects you may be able to start gathering useful data that you can make into insights. [1]: http://www.hanselman.com/blog/EducatingProgrammersWithPlacematsNDependStaticAnalysisPoster.aspx [2]: http://www.hanselman.com/blog/HanselminutesPodcast51StaticCodeAnalysisWithNDepend.aspx
.NET Development on a Mac Tips
|macos|.net|vmware|
I have just got a MacBook Pro and have been using it (+Fusion) to develop on for about a month now. The purpose of this question is similar to [Hidden Features of C#](http://stackoverflow.com/questions/9033/hidden-features-of-c#35342); to become a how-to of tips and trick for windows development on a mac. My environment is as follows * MacBook Pro 15" 2.4Ghz 2GB RAM (Going to upgrade to 4GB soon) * VMWare Fusion 2.0 Beta * Windows XP Pro SP3 (Slipstreamed BEFORE install) Tips: * Use Windows Steady State to keep OS consistent * Use svn+ssh to connect to the mac for small repositories then use time machine to backup. * Use spaces.
|macos|.net|vmware|virtualization|
|.net|macos|vmware|virtualization|
I have just got a MacBook Pro and have been using it (+Fusion) to develop on for about a month now. The purpose of this question is similar to [Hidden Features of C#](http://stackoverflow.com/questions/9033/hidden-features-of-c#35342); to become a how-to of tips and trick for windows development on a mac. I should clarify that I am aware of boot camp but do not use it (nor do I have any interest to), hence my use of steady state to make sure nothing happens to my OS partition without my knowledge. However; as Sara pointed out, Apple makes great hardware and I absolutely **LOVE** the form factor of my MBP so for someone who is looking for a windows only laptop a mac with boot camp should not be overlooked as the hardware is amazing. My environment is as follows * MacBook Pro 15" 2.4Ghz 2GB RAM (Going to upgrade to 4GB soon) * VMWare Fusion 2.0 Beta * Windows XP Pro SP3 (Slipstreamed BEFORE install) Tips: * Use Windows Steady State to keep OS consistent * Use svn+ssh to connect to the mac for small repositories then use time machine to backup. * Use spaces.
Flash has some neat security measures in place. Allowing users to upload swf's to your site and embedding them is unsafe, you're basically setting yourself up for an XSS attack. However, allowing them to hotlink should not be a problem. The swf will be locked to the domain that is hosting it and is not allowed calling url's outside of that space. It will still be open to "evil links" (i'm sure theres a proper word for them), and by that I mean having regular links to yoursite.com/admin/deleteallpages.php which it tries to load "as" you. I will not however be able to use this data in any way, it'll basically be the same as a normal link, and I'd guess modern cms' are protected from that type of attacks. You could get the same protection by hosting your flashes on a different subdomain, since flash considers this the same as a completely different domain.
How to return status 401 instead of redirecting to login page for select actions
|asp.net-mvc|forms-authentication|asp.net|
I'm writing an app using asp.net-mvc deploying to iis6. I'm using forms authentication. Usually when a user tries to access a resource without proper authorization I want them to be redirected to a login page. FormsAuth does this for me easy enough. Problem: Now I have an action being accessed by a console app. Whats the quickest way to have this action respond w/ status 401 instead of redirecting the request to the login page? I want the console app to be able to react to this 401 StatusCode instead of it being transparent. I'd also like to keep the default, redirect unauthorized requests to login page behavior.
How do I bypass forms auth's interception of 401 responses
I'm writing an app using asp.net-mvc deploying to iis6. I'm using forms authentication. Usually when a user tries to access a resource without proper authorization I want them to be redirected to a login page. FormsAuth does this for me easy enough. Problem: Now I have an action being accessed by a console app. Whats the quickest way to have this action respond w/ status 401 instead of redirecting the request to the login page? I want the console app to be able to react to this 401 StatusCode instead of it being transparent. I'd also like to keep the default, redirect unauthorized requests to login page behavior. BTW, do i understand this right? Isn't forms auth intercepting responses tagged with 401 status and changing them to a login page response?
Bypass Forms Authentication, How to?
Bypass Forms Authentication auto redirect to login, How to?
|asp.net|asp.net-mvc|forms-authentication|
I'm writing an app using asp.net-mvc deploying to iis6. I'm using forms authentication. Usually when a user tries to access a resource without proper authorization I want them to be redirected to a login page. FormsAuth does this for me easy enough. Problem: Now I have an action being accessed by a console app. Whats the quickest way to have this action respond w/ status 401 instead of redirecting the request to the login page? I want the console app to be able to react to this 401 StatusCode instead of it being transparent. I'd also like to keep the default, redirect unauthorized requests to login page behavior. Note: As a test I added this to my global.asax and it still didn't bypass forms auth: protected void Application_AuthenticateRequest(object sender, EventArgs e) { HttpContext.Current.SkipAuthorization = true; }
I'm writing an app using asp.net-mvc deploying to iis6. I'm using forms authentication. Usually when a user tries to access a resource without proper authorization I want them to be redirected to a login page. FormsAuth does this for me easy enough. Problem: Now I have an action being accessed by a console app. Whats the quickest way to have this action respond w/ status 401 instead of redirecting the request to the login page? I want the console app to be able to react to this 401 StatusCode instead of it being transparent. I'd also like to keep the default, redirect unauthorized requests to login page behavior. Note: As a test I added this to my global.asax and it didn't bypass forms auth: protected void Application_AuthenticateRequest(object sender, EventArgs e) { HttpContext.Current.SkipAuthorization = true; }
I would second the recommendation for [PCRE][1]. I have used it in C++ projects in Windows and it works great. It's free, even for building commercial software. It also implements something of a de facto standard regular expression language, which will be welcome to your users. PCRE is of course Perl-compatible, and Python also uses the same library. The native PCRE interface is a bit awkward and very C-style, so it's probably worth writing a nice C++ wrapper around it. There is very likely already is one out there, but I'm not familiar with any. [1]: http://pcre.org
One of the debugging techniques that I use frequently (except in cases of the most extreme weirdness) is to divide and conquer. If your program currently fails with some specific error, then divide it in half in some way and see if it still has the same error. Obviously the trick is to decide where to divide your program! Your example as given doesn't show enough context to determine where the error might be. If anybody else were to try your example, it would work fine. So, in your program, try removing as much of the extra stuff you didn't show us and see if it works then. If so, then add the other code back in a bit at a time until it starts failing. Then, the thing you just added is probably the problem. Note that if your program is multithreaded, then you probably have larger problems. If not, then you should be able to narrow it down in this way. Good luck!
Thanks for the answer, great! I did some research myself and found [ListNanny][1] - also super simple to use and tells you the type of bounce. Will write some proof of concept and see which one I like better... [1]: http://www.advancedintellect.com/product.aspx?listnanny
Then you'll have to warp CURRENT in another function that you'll call from the first (but this is a hack on the previous hack ...).
As tweakt said, Amazon S3 is a good model to work with. Their request signatures do have some features (such as incorporating a timestamp) that help guard against both accidental and malicious request replaying. The nice thing about HTTP Basic is that virtually all HTTP libraries support it. You will, of course, need to require SSL in this case because sending plaintext passwords over the net is almost universally a bad thing. Basic is preferable to Digest when using SSL because even if the caller already knows that credentials are required, Digest requires an extra roundtrip to exchange the nonce value. With Basic, the callers simply sends the credentials the first time. Once the identity of the client is established, authorization is really just an implementation problem. However, you could delegate the authorization to some other component with an existing authorization model. Again the nice thing about Basic here is your server ends up with a plaintext copy of the client's password that you can simply pass on to another component within your infrastructure as needed.
With javascript alone, it's **not possible**. Javascript is not intended to do such things and is severely crippled in the way it can interact with anything other than the webbrowser it lives in, (for good reason!). Think about it: a spammer writing a website with client side javascript which will automatically mail to thousands of random email addresses. If people should go to that site they would all be participating in a distributed mass mailing scam, with their own computer... no infection or user interaction needed!
I've never worked anywhere that had a formalized policy, but practically every manager I've ever had has allowed me to spend some time on things that weren't directly related to the current project or fighting a fire. I think the key is to talk about the things you'd like to try. Most managers want their teams to do something cool, something extraordinary, so if you can convince them that you might deliver something, you might get the chance. Or they might let you do it just to keep you happy. Now that I'm a contractor rather than an employee, I don't get paid to do fun stuff, but I generally only work 30-35 hours per week, so I still have time to learn and to play.
Enforcing web standards
|css|xhtml|coding-style|
The HTML standard defines a clear separation of concerns between CSS (presentation) and HTML (semantics or structure). Does anyone use a coding standards document for CSS and XHTML that has clauses which help to maintain this separation? What would be good clauses to include in such a coding standards document?
Yes! jQuery.fn.exists = function(){return jQuery(this).length>0;} There you go! This is in response to: [Herding Code podcast with Jeff Atwood][1] [1]: http://herdingcode.com/?p=36
Yes! jQuery.fn.exists = function(){return jQuery(this).length>0;} if ($(selector).exists()) { // Do something } There you go! This is in response to: [Herding Code podcast with Jeff Atwood][1] [1]: http://herdingcode.com/?p=36
Accessing a Component on an inherited form from the base form
|.net|winforms|reflection|inheritance|
A number of forms in my project inherit from a base form. It is easy to get at the Controls collection of the derived forms, but I have not found a simple way to access the Components collection, since VS marks this as private. I assume this could be done with reflection, but I'm not really sure how best to go about it, not having worked with reflection before. Right now, I'm using a sort of clunky workaround, in which I override a function GetComponents and return an array of the components I'm interested in. This is obviously prone to errors, since it's easy to forget to implement the overridden function or update it when components are added. If anyone has any tips or can suggest a better way, I'd be glad to hear.
Short of any other answers, I would try attaching to the executable process in Visual Studio, setting a break point in your code and when you step into the process you don't have source to, it should ask for a source file.
I've not familiar with using either of these, but try searching msdn for splitbutton or dropdownbutton. I think those are similar to what you're looking for.
You can try something like: InputStream stream = this.getClass().getClassLoader().getResourceAsStream("/images/image.jpg"); In your JAR file, you might have a directory structure of: > MyJAR.jar - com (class files in here) - images ----image.jpg
Apologies if I've missed the real point of the question but, if I was using sh/bash/etc., then I would probably use *find* to do the job: find . -name '*.rb' -type f Globs can get a bit nasty when used from within a script and *find* is much more flexible.
public void PageLinks(int currentPage, int lastPage) { if (currentPage > 2) Add([1], ...); for(int i=Math.Max(1, currentPage-1); i< Math.Min(currentPage+1, lastPage); i++) Add([i]); if (currentPage < lastPage-1) Add(..., [lastpage]); } lastPage is calculated as Math.Ceiling(totalRecords/RecordsPerPage). hmmm. actually, in the case that currentpage is 3, it still shows [1]...[2][3][4]...[xxx] i think the ellipses are superfluous in that case. But that's how it works.
<pre><code> public void PageLinks(int currentPage, int lastPage) { if (currentPage > 2) Add('[1]', '...'); for(int i=Math.Max(1, currentPage-1); i< Math.Min(currentPage+1, lastPage); i++) Add('[i]'); if (currentPage < lastPage-1) Add('...', '[lastpage]'); } </code></pre> lastPage is calculated as Math.Ceiling(totalRecords/RecordsPerPage). hmmm. actually, in the case that currentpage is 3, it still shows [1]...[2][3][4]...[xxx] i think the ellipses are superfluous in that case. But that's how it works. Edit: the preview formats the codeblock correctly, why does it get mangled? sure, its just pseudocode.... but still....
public void PageLinks(int currentPage, int lastPage) { if (currentPage > 2) Add('[1]', '...'); for(int i=Math.Max(1, currentPage-1); i< Math.Min(currentPage+1, lastPage); i++) Add('[i]'); if (currentPage < lastPage-1) Add('...', '[lastpage]'); } lastPage is calculated as Math.Ceiling(totalRecords/RecordsPerPage). hmmm. actually, in the case that currentpage is 3, it still shows [1]...[2][3][4]...[xxx] i think the ellipses are superfluous in that case. But that's how it works. Edit: the preview formats the codeblock correctly, why does it get mangled? sure, its just pseudocode.... but still....
This may be missing the point, but how about naming the tests so they indicate what they test - then you may not even need the message. If it proves to be absolutely necessary, I think you'll need to produce your own testrunner that would (off the top of my head) read an additional attribute off the TestCase and attach it to the output.
I would go with the second version. The first one looks like the kind of code smell that Visitor is supposed to solve: long if-else-if or switch-case statements.
Is there a good method in C# for throwing an exception on a given thread
|c#|exception|multithreading|
The code that I want to write is like this: void MethodOnThreadA() { for (;;) { // Do stuff if (ErrorConditionMet) ThrowOnThread(threadB, new MyException(...)); } } void MethodOnThreadB() { try { for (;;) { // Do stuff } } catch (MyException ex) { // Do the right thing for this exception. } } I know I can have thread B periodically check, in thread safe way, to see if a flag has been set by thread A, but that makes the code more complicated. Is there a better mechanism that I can use? Here is a more fleshed out example of periodically checking: Dictionary<Thread, Exception> exceptionDictionary = new Dictionary<Thread, Exception>(); void ThrowOnThread(Thread thread, Exception ex) { // the exception passed in is going to be handed off to another thread, // so it needs to be thread safe. lock (exceptionDictionary) { exceptionDictionary[thread] = ex; } } void ExceptionCheck() { lock (exceptionDictionary) { Exception ex; if (exceptionDictionary.TryGetValue(Thread.CurrentThread, out ex)) throw ex; } } void MethodOnThreadA() { for (;;) { // Do stuff if (ErrorConditionMet) ThrowOnThread(threadB, new MyException(...)); } } void MethodOnThreadB() { try { for (;;) { // Do stuff ExceptionCheck(); } } catch (MyException ex) { // Do the right thing for this exception. } }
C2143 basically says that the compiler got a token that it thinks is illegal in the current context. One of the implications of this error is that the actual problem may exist before the line that triggers the compiler error. As Greg said I think we need to see more of your code to diagnose this problem. I'm also not sure why you think the fact that this is valid C++ code is helpful when attempting to figure out why it doesn't compile as C? C++ is (largely) a superset of C so there's any number of reasons why valid C++ code might not be syntactically correct C code, not least that C++ treats structs as classes!
In all cases here is actual code that runs ... doesn't mean much but produces output and hopefully can get you started ... use XML::Parser; package MyNode::inner; sub doSomething { my $self = shift; print "This is an inner node containing : "; print $self->{Kids}->[0]->{Text}; print "\n"; } package MyNode::Characters; sub doSomething {} package MyNode::foo; sub doSomething { my $self = shift; print "This is an external node\n"; for $kid (@ { $self->{Kids} }) { $kid->doSomething(); } } package main; my $p = XML::Parser->new(Style => 'Objects', Pkg => 'MyNode'); my $tree = $p->parsefile('foo.xml'); for (@$tree) { $_->doSomething(); } with foo.xml <foo> <inner>some text</inner> <inner>something else</inner></foo> which outputs >perl -w "tree.pl" This is an external node This is an inner node containing : some text This is an inner node containing : something else Hope that helps.
`ldiv` ? Edit: reread title, so you might want to ignore this. Or not, depending on if it has an appropriate non-library version. MSN
okay found out what was the problem... forgot that in C you have to declare all your variables before any code.
Exception in Web Service locks DLL and prevents publishing. Workaround?
|c#|asp.net|visual-studio|web-services|iis|
I'm using a native DLL (FastImage.dll) in a C# ASP.NET Web Service that sometimes locks (can't delete it---says access denied); this requires stopping IIS to delete the DLL. The inability to delete this DLL in the bin folder of my published Web Service prevents me from publishing successfully (even though it thinks it published successfully!), which makes development and fixing the bug difficult (especially when it just happily runs old code since my changes may not be reflected on the server!). Note that the bug causing the Web Service to bomb and lock up the DLL is in my code, which is outside of said DLL, so I think this is a more general problem than just the FreeImage library (not to bring them any heat). 1. Has anyone experienced this? 2. Is there a way to make sure that when it says "Publish succeeded" from the VS IDE that it really means it, or to run sort of script to check that the files are really deleted before it attempts to Publish (like a pre-build step in VC++). (Right now I manually delete the files before publishing to make sure that I know the DLLs were replaced, instead of running old DLLs. It's still a problem, though if I can't delete the DLL.) 3. How would I detect whether a file was successfully deleted from a batch file? (so I can stop and start IIS if it fails) 4. Is it possible to stop and start IIS from a script (preferably from the Publish... action in the VS IDE) and if so, how?
You should consider writing your code in such a way that you can mock your I/O completion port. Make an interface/abstract class that exposes the methods you need on the I/O object, and write and test implementation that does things like it's supposed to (and an option to simulate failure perhaps). AFAIK it's a common practice to mock external resources when unit testing, to minimize dependencies.
It is definitely worthwhile to test failure conditions, both that your class properly throws an exception when you want it to and that exceptions are handled properly in the class. This can easily be done if you are acting on an object passed in to the constructor... just pass in a mock. If not, I tend to prefer to have the functionality moved to a protected method, and override the protected method to evoke my failure case. I will use Java as an example, but it should be easy enough to port the ideas to a C# case: public class MyClass { public MyClass() throws ExpectedException { // Whatever, including a call to invokeCreateIoCompletionPort } protected int invokeCreateIoCompletionPort(String str, int i) { return StaticClass.createIoCompletionPort(str, i); } } public class MyTest { public void myTest() { try { new MyClass(); fail("MyClassException was not thrown!"); } catch (MyClassException e) { } } private static class MyClassWrapper extends MyClass { @Override protected int invokeCreateIoCompletionPort(String str, int i) { throw new ExpectedException(); } } } As you can see, it is pretty easy to test whether an exception is being thrown by the constructor or method you are testing, and it is also pretty easy to inject an exception from an external class that can throw an exception. Sorry I'm not using your actual method, I just used the name to illustrate how it sounded like you are using it, and how I would test the cases it sounded you wanted to test. Basically, any API details you expose can usually be tested, and if you want to KNOW that exceptional cases work as they should, you probably will want to test it.
It is definitely worthwhile to test failure conditions, both that your class properly throws an exception when you want it to and that exceptions are handled properly in the class. This can easily be done if you are acting on an object passed in to the constructor... just pass in a mock. If not, I tend to prefer to have the functionality moved to a protected method, and override the protected method to evoke my failure case. I will use Java as an example, but it should be easy enough to port the ideas to a C# case: public class MyClass { public MyClass() throws MyClassException { // Whatever, including a call to invokeCreateIoCompletionPort } protected int invokeCreateIoCompletionPort(String str, int i) { return StaticClass.createIoCompletionPort(str, i); } } public class MyTest { public void myTest() { try { new MyClass(); fail("MyClassException was not thrown!"); } catch (MyClassException e) { } } private static class MyClassWrapper extends MyClass { @Override protected int invokeCreateIoCompletionPort(String str, int i) { throw new ExpectedException(); } } } As you can see, it is pretty easy to test whether an exception is being thrown by the constructor or method you are testing, and it is also pretty easy to inject an exception from an external class that can throw an exception. Sorry I'm not using your actual method, I just used the name to illustrate how it sounded like you are using it, and how I would test the cases it sounded you wanted to test. Basically, any API details you expose can usually be tested, and if you want to KNOW that exceptional cases work as they should, you probably will want to test it.
any of the popular editors can be turned into an ide. I use Vi on the console and have used various gui editors over the years. This doesn't just go for linux I use Crimson Editor on windows as a C/python/z80asm ide.
In addition (or instead) of adding a .0 to the number, in my opinion it is also desirable to be as explicit as possible, for understandability and aid to your fellow programmers that eventually will read your code =). Using decimal.ToDouble(), like so: double transperancy = trackBar1.Value/5000; this.Opacity = decimal.ToDouble(transperancy); or, even this.Opacity = decimal.ToDouble(trackBar1.Value/5000);
If you're using VB.NET, you can tap into the very convenient ApplicationEvents.vb. This file comes for free with a VB.NET WinForms project and contains a method for handling unhandled exceptions. If you're not using VB.NET, then yeah, it's handling [Application.ThreadException][1]. [1]: http://msdn.microsoft.com/en-us/library/system.windows.forms.application.threadexception.aspx