instruction
stringlengths
0
30k
|asp.net-mvc|
I'd like to have dashes separate words in my URLs. So instead of: /MyController/MyAction I'd like: /My-Controller/My-Action Is this possible?
I'm trying to make that same decision about ASP.NET MVC, [Juan Manuel][1]. I'm now waiting for the right bite-sized project to come along with which I can experiment. If the experiment goes well--my gut says it will--then I'm going to architect my new large projects around the framework. [1]: http://stackoverflow.com/users/1782/juan-manuel
I'm trying to make that same decision about ASP.NET MVC, [Juan Manuel][1]. I'm now waiting for the right bite-sized project to come along with which I can experiment. If the experiment goes well--my gut says it will--then I'm going to architect my new large projects around the framework. With ASP.NET MVC you lose the viewstate/postback model of ASP.NET Web Forms. Without that abstraction, you work much more closely with the HTML and the HTTP POST and GET commands. I believe the UI programming is somewhat in the direction of classic ASP. With that inconvenience, comes a greater degree of control. I've very often found myself fighting the psuedo-session garbage of ASP.NET and the prospect of regaining complete control of the output HTML seems very refreshing. It's perhaps either the best--or the worst--of both worlds. [1]: http://stackoverflow.com/users/1782/juan-manuel
A subselect is the standard way of doing this sort of thing. You just need a Unique Constraint on UserId, Code, and Date - and then you can run the following: SELECT * FROM Table JOIN ( SELECT UserId, Code, MAX(Date) as LastDate FROM Table GROUP BY UserId, Code ) as Latest ON Table.UserId = Latest.UserId AND Table.Code = Latest.Code AND Table.Date = Latest.Date WHERE UserId = @userId
On Mac OS X, I have used BBEdit since the early 1990's, so I use that as my reference for all other editors. I sometimes use BBEdit to edit files on a Linux box using ftp mode, and that works very well if you have a fast network connection to the Linux box. I learned emacs two years ago because the rest of the programming team I joined uses it. I find emacs powerful but annoyingly old-fashioned in many ways, but once you have learned emacs, you can use it on any platform (Linux, OS X, Windows). This is the editor I use almost exclusively at work now. It is going to take me years to master all its features, though. I have also used gedit on Linux and found it very usable, but I haven't tried to use it as my primary editor for any project. I have a colleague at work who uses Komodo Edit 4.4 (free from activestate.com), running it on a Windows computer but using it in ftp mode so she can edit files on our Linux server. Komodo Edit has many nice features, but it takes a looonnnggg time to launch the first time.
I use this code.It is VB code but you can easily translate it to C#. It works Function NumberToText(ByVal n As Integer) As String Select Case n Case 0 Return "" Case 1 To 19 Dim arr() As String = {"One","Two","Three","Four","Five","Six","Seven", _ "Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen", _ "Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"} Return arr(n-1) & " " Case 20 to 99 Dim arr() as String = {"Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"} Return arr(n\10 -2) & " " & NumberToText(n Mod 10) Case 100 to 199 Return "One Hundred " & NumberToText(n Mod 100) Case 200 to 999 Return NumberToText(n\100) & "Hundreds " & NumberToText(n mod 100) Case 1000 to 1999 Return "One Thousand " & NumberToText(n Mod 1000) Case 2000 to 999999 Return NumberToText(n\1000) & "Thousands " & NumberToText(n Mod 1000) Case 1000000 to 1999999 Return "One Million " & NumberToText(n Mod 1000000) Case 1000000 to 999999999 Return NumberToText(n\1000000) & "Millions " & NumberToText(n Mod 1000000) Case 1000000000 to 1999999999 Return "One Billion " & NumberTotext(n Mod 1000000000) Case Else Return NumberToText(n\1000000000) & "Billion " _ & NumberToText(n mod 1000000000) End Select End Function
+1 for XML Spy, I've used both the stand alone product and the visual studio plugin, and I've been impressed. In terms of FOSS, try [Notepad++](http://notepad-plus.sourceforge.net/uk/site.htm)
+1 for XML Spy, I've used both the stand alone product and the visual studio plugin, and I've been impressed. In terms of FOSS, I use [Notepad++](http://notepad-plus.sourceforge.net/uk/site.htm)
Peak detection of measured signal
|language-agnostic|algorithm|data|
We use a data acquisition card to take readings from a device that increases its signal to a peak and then falls back to near the original value. To find the peak value we currently search the array for the highest reading and use the index to determine the timing of the peak value which is used in our calculations. This works well if the highest value is the peak we are looking for but if the device is not working correctly we can see a second peak which can be higher than the initial peak. We take 10 readings a second from 16 devices over a 90 second period. My initial thoughts are to cycle through the readings checking to see if the previous and next points are less than the current to find a peak and construct an array of peaks. Maybe we should be looking at a average of a number of points either side of the current position to allow for noise in the system. Is this the best way to proceed or are there better techniques?
you could achive this in one query using 'UNION ALL' in MySQL. Just loop through the tokens in PHP creating a UNION ALL for each token: e.g if the tokens are 'x', 'y' and 'z' your query may look something like this SELECT * FROM `entries` WHERE token like "%x%" union all SELECT * FROM `entries` WHERE token like "%y%" union all SELECT * FROM `entries` WHERE token like "%z%" ORDER BY score ect... The order clause should operate on the entire result set as one, which is what you need. In terms of performance it won't be all that fast (I'm guessing), however with databases the main overhead in terms of speed is often sending the query to the database engine from PHP and receiving the results. With this technique this only happens once instead of once per token, so performance will increase, I just don't know if it'll be enough.
What version of Tomcat are you using? To me this sounds like a bug in Tomcat, I can't think of any reason why you're doFilter method should be called with a response that's already been committed (if that filter is the only one in the chain, are you sure about this?).
What version of Tomcat are you using? To me this sounds like a bug in Tomcat, I can't think of any reason why your doFilter method should be called with a response that's already been committed (if that filter is the only one in the chain, are you sure about this?).
User Authentication in Pylons + AuthKit
|python|authentication|pylons|sqlalchemy|authkit|
I am trying to create a web application using Pylons and the resources on the web point to the [PylonsBook][1] page which isn't of much help. I want authentication and authorisation and is there anyway to setup Authkit to work easily with Pylons? I tried downloading the [SimpleSiteTemplate][2] from the cheeseshop but wasn't able to run the setup-app command. It throws up an error: File "/home/cnu/env/lib/python2.5/site-packages/SQLAlchemy-0.4.7-py2.5.egg/sqlalchemy/schema.py", line 96, in __call__ table = metadata.tables[key] AttributeError: 'module' object has no attribute 'tables' I use Pylons 0.9.7rc1, SQLAlchemy 0.4.7, Authkit 0.4. [1]: http://pylonsbook.com/alpha1/authentication_and_authorization [2]: http://pypi.python.org/pypi/SimpleSiteTemplate/
It just depends on what type of testing you are doing. If you are doing behavior based testing you might want a dynamic mock so you can verify that some interaction with your dependancy occurs. But if you are doing state based testing you might want a stub so you verify values/etc
It just depends on what type of testing you are doing. If you are doing behavior based testing you might want a dynamic mock so you can verify that some interaction with your dependancy occurs. But if you are doing state based testing you might want a stub so you verify values/etc For example, in the below test you notice that I stub out the view so I can verify a property value is set (state based testing). I then create a dynamic mock of the service class so I can make sure a specific method gets called during the test (interaction / behavior based testing). <TestMethod()> _ Public Sub Should_Populate_Products_List_OnViewLoad_When_PostBack_Is_False() mMockery = New MockRepository() mView = DirectCast(mMockery.Stub(Of IProductView)(), IProductView) mProductService = DirectCast(mMockery.DynamicMock(Of IProductService)(), IProductService) mPresenter = New ProductPresenter(mView, mProductService) Dim ProductList As New List(Of Product)() ProductList.Add(New Product()) Using mMockery.Record() SetupResult.For(mView.PageIsPostBack).Return(False).Repeat.Once() Expect.Call(mProductService.GetProducts()).Return(ProductList).Repeat.Once() End Using Using mMockery.Playback() mPresenter.OnViewLoad() End Using 'Verify that we hit the service dependency during the method when postback is false Assert.AreEqual(1, mView.Products.Count) mMockery.VerifyAll() End Sub
I really like python, it's usually my language of choice these days for small (non-gui) stuff that I do on my own. However, for some larger Python projects I've tackled, I'm finding that it's not quite the same as programming in say, C++. I was working on a language parser, and needed to represent an AST in Python. This is certainly within the scope of what Python can do, but I had a bit of trouble with some refactoring. I was changing the representation of my AST and changing methods and classes around a lot, and I found I missed the strong typing that would be available to me in a C++ solution. Python's duck typing was almost *too* flexible and I found myself adding a lot of `assert` code to try to check my types as the program ran. And then I couldn't really be sure that everything was properly typed unless I had 100% code coverage testing (which I didn't at the time). Actually, that's another thing that I miss sometimes. It's possible to write syntactically correct code in Python that simply won't run. The compiler is incapable of telling you about it until it actually executes the code, so in infrequently-used code paths such as error handlers you can easily have unseen bugs lurking around. Even code that's as simple as printing an error message with a % format string can fail at runtime because of mismatched types. I haven't used Python for any GUI stuff so I can't comment on that aspect.
Gnome apps work on KDE desktops and vice versa; you won't be locking anyone out. As far as toolkits go, it's fairly subjective. All of the toolkits are fairly cross-platform. If you're not open source, then GTK+ would be the cheaper option, as Qt is only free for open source use, whereas GTK+ is LGPL.
How about a plugin for <a href="http://www.beagle-project.org/">Beagle</a> ? It already searches PDFs but you can add other file types. Here is the relevant wikipedia page : http://en.wikipedia.org/wiki/Beagle_(software)
How to embed user-specific data in .NET windows setup app at setup download time?
|.net|windows|installation|fogbugz|
I'd like to have a link in my ASP.NET web site that authenticated users click to download a windows app that is already pre-configured with their client ID and some site config data. My goal is no typing required for the user during the client app install, both for the user friendliness, and to avoid config errors from mis-typed technical bits. Ideally I'd like the web server-side code to run as part of the ASP.NET app. FogBugz seems to do something like this. There is a menu option within the web app to download a screenshot tool, and when you download and run the installer, it knows your particular FogBugz web address so it can send screenshots there. (Hey Joel, looking for a question to answer? hint hint)
If it helps RegexBuddy does this also.
+1 on the Clbuttic mistake, I think it is important for "bad word" filters to scan for both leading and trailing spaces (e.g., " ass ") as opposed for just the exact string so that we won't have words like clbuttic, clbuttes, buttert, buttess, etc.
You'll find mostly two answers to that &ndash; the religous one (Yes! Of course! It's the best language ever!) and the other religious one (you gotta be kidding me! Python? No... it's not mature enough). I will maybe skip the last religion (Python?! Use Ruby!). The truth, as always, is far from obvious. **Pros**: it's easy, readable, batteries included, has lots of good libraries for pretty much everything. It's expressive and dynamic typing makes it more concise in many cases. **Cons**: as a dynamic language, has way worse IDE support (proper syntax completion **requires** static typing, whether explicit in Java or inferred in SML), its object system is far from perfect (interfaces, anyone?) and it is easy to end up with messy code that has methods returning either int or boolean or object or some sort under unknown circumstances. My take &ndash; I love Python for scripting, automation, tiny webapps and other simple well defined tasks. In my opinion it is by far **the best** dynamic language on the planet. That said, I would **never** use it **any** dynamically typed language to develop an application of substantial size. Say &ndash; it would be fine to use it for Stack Overflow, which has three developers and I guess no more than 30k lines of code. For bigger things &ndash; first your development would be super fast, and then once team and codebase grow things are slowing down more than they would with Java or C#. You need to offset lack of compilation time checks by writing more unittests, refactorings get harder cause you never know what your refacoring broke until you run all tests or even the whole big app, etc. Now &ndash; decide on how big your team is going to be and how big the app is supposed to be once it is done. If you have 5 or less people and the target size is roughly Stack Overflow, go ahead, write in Python. You will finish in no time and be happy with good codebase. But if you want to write second Google or Yahoo, you will be much better with C# or Java. Side-note on C/C++ you have mentioned: if you are not writing performance critical software (say massive parallel raytracer that will run for three months rendering a film) or a very mission critical system (say Mars lander that will fly three years straight and has only one chance to land right or you lose $400mln) do not use it. For web apps, most desktop apps, most apps in general it is not a good choice. You will die debugging pointers and memory allocation in complex business logic.
I found that example through my Google searches too and did play with it. That wasn't the problem. I found my bug. No one would have been able to solve the problem. It turns out that right before I test my bounds I had centered my map with bad data. I did something like the lngSpan = northEast.lng() - southWest.lng(); however JavaScript interpreted my var as a string. So (maxLng-minLng)/2 + minLng returns something like "20.456-116.1178" as the lng. I centered my map on var centerPoint = new GLatLng(setLat, setLng); and after that the maps API gets a little strange ;) Thanks for the help though.
I found very insightful ideas about starting a new large project, based on - common good practices - Test Driven Development - and pragmatic approach in the book [Growing Object-Oriented Software, Guided by Tests][1]. It is still under development, but first 3 chapters may be what You are looking for and IMHO worth reading. [1]: http://www.mockobjects.com/2008/07/growing-object-oriented-software-guided.html
I have used [Komodo][1] and it's pretty good. I use textmate now. [1]: http://www.activestate.com/Products/komodo_ide/index.mhtml "Komodo"
Have you tried [Aptana][1]? Its based on Eclipse and they have a sweet [Rails][2] plugin. [1]: http://www.aptana.com/ [2]: http://www.aptana.com/rails
Powershell FINDSTR eqivalent?
|powershell|searching|
What's the DOS FINDSTR eqivalent for powershell? I need to search a bunch of log files for "ERROR"
|search|powershell|
Placement new itself is portable, but the assumptions you make about what it does with a specified block of memory are not portable. Like what was said before, if you were a compiler and were given a chunk of memory, how would you know how to allocate an array and properly destruct each element if all you had was a pointer? (See the interface of operator delete[].) Edit: And there actually is a placement delete, only it is only called when a constructor throws an exception while allocating an array with placement new[]. Whether new[] actually needs to keep track of the number of elements somehow is something that is left up to the standard, which leaves it up to the compiler. Unfortunately, in this case. MSN
How do you do a case insensitive search using a pattern modifier using less ?
|unix|searching|
It seems like the only way to do this is to pass the -i parameter in when you initially run less. Does anyone know of some secret hack to make something like this work /something to search for/i ?
It seems like the only way to do this is to pass the -i parameter in when you initially run less. Does anyone know of some secret hack to make something like this work /something to search for/i ? **Edit:** Wow how did I miss -i while less is running? Doh!
Which file are you calling the getcwd() in and is that file is included into the one you are running (e.g. running index.php, including startup.php which contains gwtcwd()). Is the file you are running in /dev-windows/ or /dev-windows-data/? It works on the file you are actually running. --- Here's an example of my current project: **index.php** <?php require_once('./includes/construct.php'); //snip ?> **includes/construct.php** <?php //snip (!defined('DIR')) ? define('DIR', getcwd()) : NULL; require_once(DIR . '/includes/functions.php'); //snip ?>
I use tables in two cases: 1) Tabular data 2) Any time I want my layout to dynamically size itself to its contents
How to store Application Messages for a .NET Website
|vb.net|website|storage|
I am looking for a method of storing Application Messages, such as * "You have logged in successfully" * "An error has occurred, please call the helpdesk on x100" * "You do not have the authority to reset all system passwords" etc So that "when" the users decide they don't like the wording of messages I don't have to change the source cdoe, recompile then redeploy - instead I just change the message store. I really like the way that I can easily access strings in the web.config using keys and values. > ConfigurationManager.AppSettings("LOGINSUCCESS") However as I could have a large number of application messages I didn't want to use the web.config directly. I was going to add a 2nd web config file and use that but of course you can only have one per virtual directory. Does anyone have any suggestions on how to do this without writing much custom code? Thanks
You could have an invisible div that gets shown via JavaScript when the page loads.
- Put the strings in an xml file and use a filewatcher to check for updates to the file - Put the strings in a database, cache them and set a reasonable expiration policy
In your Web.config, under appSettings, change it to: <appSettings file="StringKeys.config"> Then, create your StringKeys.config file and have all your keys in it. You can still use the AppSettings area in the main web.config for any real application related keys.
[Alex's article][1] springs to mind here, however it's only applicable if you're using ASP.NET - it could be emulated in JavaScript however but again you'd have to use document.write(); [1]: http://weblogs.asp.net/alex_papadimoulis/archive/2008/02/21/scriptonly-the-opposite-of-a-noscript.aspx
How can you test to see if two arrays are the same using CFML?
|cfml|
Using CFML (ColdFusion Markup Langauge, aka ColdFusion), how can you compare if two single dimension arrays are the same?
|coldfusion|
The primary reason stateless session beans are single threaded is to make them highly scalable for the container. The container can make a lot of simplifying assumptions about the runtime environment. A second reason is to make life easier for the developer because the developer doesn't have to worry about any synchronization or re-entrancy in his business logic because the bean will never be called in another thread context. I remember the reasoning being discussed in the reviews of the original EJB 1.0 specification. I would look at the goals section of the specification. See http://java.sun.com/products/ejb/docs.html for the list of specifications.
This is the version we use here. It works, and its fairly simple. Its the same idea as Jeff's but I think its a little clearer because it separates out the logic for subtracting one, so its a little easier to understand. public static int GetAge(this DateTime dateOfBirth, DateTime dateAsAt) { return dateAsAt.Year - dateOfBirth.Year - (dateOfBirth.DayOfYear < dateAsAt.DayOfYear ? 0 : 1); } You could expand the ternary operator to make it even clearer, if you think that sort of thing is unclear. Obviously this is done as an extension method on DateTime, but clearly you can grab that one line of code that does the work and put it anywhere. Here we have another overload of the Extension method that passes in DateTime.Now, just for completeness.
Some solutions I have seen involve adding a version number to the end of the file in the form of a query string. <script type="text/javascript" src="funkycode.js?v1"> Could could use the SVN revision number to automate this for you: [http://stackoverflow.com/questions/2308/aspnet-display-svn-revision-number][1] Firefox also allows pressing CTRL + R to reload everything on a particular page. [1]: http://stackoverflow.com/questions/2308/aspnet-display-svn-revision-number
Some solutions I have seen involve adding a version number to the end of the file in the form of a query string. <script type="text/javascript" src="funkycode.js?v1"> You could use the SVN revision number to automate this [for you][1] by including the word **LastChangedRevision** in your html file after where v1 appears above. You must also setup your repository to do this. I hope this further clarifies my answer? Firefox also allows pressing CTRL + R to reload everything on a particular page. [1]: http://stackoverflow.com/questions/2308/aspnet-display-svn-revision-number
The Stack Overflow podcast is the reason I'm now here. Jeff, unfortunately, is a poor project manager in terms of managing expectations and setting timelines -- yet the beta has arrived, and it's pretty decent! The .NET world is alien to me, so I've enjoyed the Stack Overflow podcast. This Week in Tech is another podcast I listen to regularly. Unfortunately, I feel that none of the panelists other than Leo Laporte does any homework prior to the show, so many of the opinions (especially John C. Dvorak's) are uninformed. I recently started listening to IT Conversations podcasts, and I got enough good information that I donated. The selection is mixed, but I really like talks from various conferences that I was unable to attend. Thanks to other people who responded with links to other podcasts I haven't heard of. I'm a newbie, so I can't bump up scores yet.
.htaccess directives to *not* redirect certain URLs
|.htaccess|apache|mod-rewrite|
In an application that heavily relies on .htaccess RewriteRules for its PrettyURLs (CakePHP in my case), how do I correctly set up directives to exclude certain directories from this rewriting? I.e.: /appRoot/.htaccess app/ static/ By default every request to /appRoot/* is being rewritten to be picked up by app/webroot/index.php, where it's being analysed and corresponding controller actions are being invoked. This is done by these directives in .htaccess: RewriteBase /appRoot RewriteRule ^$ app/webroot/ [L] RewriteRule (.*) app/webroot/$1 [L] I now want to exclude a few directories like static/ from this rewriting. I tried with this *before* the Cake RewriteRules: RewriteCond $1 ^(static|otherDir).*$ [NC] RewriteRule (.*) - [L] It works in so far that requests are no longer rewritten, but now **all** requests are being skipped, even legitimate Cake requests which should not match ^(static|otherDir).*$. I tried several variations of these rules but can't get it to work the way I want.
.NET - Throwing Exceptions best practices
|.net|error-handling|
What are the best practices to consider when catching exceptions, and re-throwing them. I want to make sure that the Exception object's InnerException and stack trace are preserved. Is there a difference between the following code blocks in how they handle this? try { //some code } catch (Exception ex) { throw ex; } //...... try { //some code } catch { throw; }
|c#|.net|error-handling|
I would definitely use: try { //some code } catch { throw; } That will preserve your stack.
AT&T's [Synaptic Hosting](http://arstechnica.com/news.ars/post/20080806-atampt-has-head-in-the-clouds-with-synaptic-hosting.html) allows this, though I'm sure you'll pay through the nose, as it's all "enterprise" an' shit.
[Easy Git][1] has a nice page comparing actual usage of [Git and SVN][2] which will give you an idea of what things Git can do (or do more easily) compared to SVN. (Technically, this is based on Easy Git, which is a lightweight wrapper on top of Git.) [1]: http://www.gnome.org/~newren/eg/ [2]: http://www.gnome.org/~newren/eg/git-for-svn-users.html
At a former job we had a cluster of web servers with an F5 load balancer in front of them. We had a very similar problem in that our applications allowed users to upload content which might include photo's and such. These were legacy applications and we did not want to edit them to use a database and a SAN solution was too expensive for our situation. We ended up using a file replication service on the two clustered servers. This ran as a service on both machines using an account that had network access to paths on the opposite server. When a file was uploaded, this backend service sync'd the data in the file system folders making it available to be served from either web server. Two of the products we reviewed were [ViceVersa][1] and [PeerSync][2]. I think we ended up using PeerSync. ---------- [1]: http://www.tgrmn.com/ [2]: http://www.peersoftware.com/products/peersync/peersync.aspx
I've run OSX under VMWare, and I can tell you with confidence that it is not an environment that you would find comfortable for developing applications in. It was barely (not really) usable for testing Mac specific browser bugs that couldn't be reproduced in Safari on Windows. On the other hand, if your hardware is supported by OSx86, you can run it natively at reasonable speeds, and I would expect it to make a fairly nice dev environment. For all cases, I'm going to assume that you have a legal OS X license, and don't mind the legal ambiguity of running it on hardware which the license explicitly forbids (the legality is unclear, imo, but I really think you'd be ok as long as its not a pirated copy).
You're spoilt for choice in terms of options here. If you are using Sybase or SQL Server 2008 you can create variables of type date and assign them your datetime values. The database engine gets rid of the time for you. Here's a quick and dirty test to illustrate (Code is in Sybase dialect): declare @date1 date declare @date2 date set @date1='2008-1-1 10:00' set @date2='2008-1-1 22:00' if @date1=@date2 print 'Equal' else print 'Not equal' For SQL 2005 and earlier what you can do is convert the date to a varchar in a format that does not have the time component. For instance the following returns 2008.08.22 select convert(varchar,'2008-08-22 18:11:14.133',102) The 102 part specifies the formatting (Books online can list for you all the available formats) So, what you can do is write a function that takes a datetime and extracts the date element and discards the time. Like so: create function MakeDate (@InputDate datetime) returns datetime as begin return cast(convert(varchar,@InputDate,102) as datetime); end You can then use the function for companions Select * from Orders where dbo.MakeDate(OrderDate) = dbo.MakeDate(DeliveryDate)
Does the information need to be secure? If not, ClickOnce can use URL-based parameters. [Here's an article about that on MSDN][1]. [1]: http://msdn.microsoft.com/en-us/library/ms172242.aspx
Have you thought of using Mono? Programs like Paint.NET work great under Linux & Windows.
I recommend <a href="http://www.wxwidgets.org/">wxWidgets</a> or <a href="http://www.trolltech.no/">Qt</a>. They are both mature, well-structured and cross-platform, with decent documentation and sample source code.
How Do Sites Supress Pasting Text?
|javascript|onlinebanking|web-applications|
I've noticed that some sites (usually banks) supress the ability to paste text into text fields. How is this done? I know that JavaScript can be used to swallow the keyboard shortcut for paste, but what about the right-click menu item?
|javascript|web-applications|onlinebanking|
How Do Sites Suppress Pasting Text?
I've noticed that some sites (usually banks) suppress the ability to paste text into text fields. How is this done? I know that JavaScript can be used to swallow the keyboard shortcut for paste, but what about the right-click menu item?
There are [Unicode box drawing characters](http://www.unicode.org/charts/symbols.html) (look for Box Drawing under Geometrical Symbols - the [chart itself](http://www.unicode.org/charts/PDF/U2500.pdf) is a PDF). I don't have any idea how widely supported those characters are, though.
Rather than port the GUI code from whatever it is now to GTK or Qt, your best bet may be to port it to a cross-platform widget library such as [wxWidgets](http://en.wikipedia.org/wiki/WxWidgets), which would give you portability to any platform wxWidgets supports. It's also important to make the distinction between Gnome libraries and GTK, and likewise KDE libraries and Qt. If you write the code to use GTK or Qt, it should work fine for users of any desktop environment, including less popular ones like XFCE. If you use other Gnome or KDE-specific libraries to do non-widget-related tasks, your app would be less portable between desktop environments.
Your best bet may be to port it to a cross-platform widget library such as [wxWidgets](http://en.wikipedia.org/wiki/WxWidgets), which would give you portability to any platform wxWidgets supports. It's also important to make the distinction between Gnome libraries and GTK, and likewise KDE libraries and Qt. If you write the code to use GTK or Qt, it should work fine for users of any desktop environment, including less popular ones like XFCE. If you use other Gnome or KDE-specific libraries to do non-widget-related tasks, your app would be less portable between desktop environments.
XML serialization in Java?
|java|xml|serialization|
Here's my split button implementation. It does not draw the arrow, and the focus/unfocus behavior is a little different. Both mine and the originals handle visual styles and look great with Aero. **Based on [http://wyday.com/blog/csharp-splitbutton][1]** using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Windows.Forms.VisualStyles; using System.Drawing; using System.ComponentModel; using System.Diagnostics; // Original: http://blogs.msdn.com/jfoscoding/articles/491523.aspx // Wyatt's fixes: http://wyday.com/blog/csharp-splitbutton // Trimmed down and redone significantly from that version (Nick 5/6/08) namespace DF { public class SplitButton : Button { private ContextMenuStrip m_SplitMenu = null; private const int SplitSectionWidth = 14; private static int BorderSize = SystemInformation.Border3DSize.Width * 2; private bool mBlockClicks = false; private Timer mTimer; public SplitButton() { this.AutoSize = true; mTimer = new Timer(); mTimer.Interval = 100; mTimer.Tick += new EventHandler(mTimer_Tick); } private void mTimer_Tick(object sender, EventArgs e) { mBlockClicks = false; mTimer.Stop(); } #region Properties [DefaultValue(null)] public ContextMenuStrip SplitMenu { get { return m_SplitMenu; } set { if (m_SplitMenu != null) m_SplitMenu.Closing -= new ToolStripDropDownClosingEventHandler(m_SplitMenu_Closing); m_SplitMenu = value; if (m_SplitMenu != null) m_SplitMenu.Closing += new ToolStripDropDownClosingEventHandler(m_SplitMenu_Closing); } } private void m_SplitMenu_Closing(object sender, ToolStripDropDownClosingEventArgs e) { HideContextMenuStrip(); // block click events for 0.5 sec to prevent re-showing the menu } private PushButtonState _state; private PushButtonState State { get { return _state; } set { if (!_state.Equals(value)) { _state = value; Invalidate(); } } } #endregion Properties protected override void OnEnabledChanged(EventArgs e) { if (Enabled) State = PushButtonState.Normal; else State = PushButtonState.Disabled; base.OnEnabledChanged(e); } protected override void OnMouseClick(MouseEventArgs e) { if (e.Button != MouseButtons.Left) return; if (State.Equals(PushButtonState.Disabled)) return; if (mBlockClicks) return; if (!State.Equals(PushButtonState.Pressed)) ShowContextMenuStrip(); else HideContextMenuStrip(); } protected override void OnMouseEnter(EventArgs e) { if (!State.Equals(PushButtonState.Pressed) && !State.Equals(PushButtonState.Disabled)) { State = PushButtonState.Hot; } } protected override void OnMouseLeave(EventArgs e) { if (!State.Equals(PushButtonState.Pressed) && !State.Equals(PushButtonState.Disabled)) { if (Focused) { State = PushButtonState.Default; } else { State = PushButtonState.Normal; } } } protected override void OnPaint(PaintEventArgs pevent) { base.OnPaint(pevent); Graphics g = pevent.Graphics; Rectangle bounds = this.ClientRectangle; // draw the button background as according to the current state. if (State != PushButtonState.Pressed && IsDefault && !Application.RenderWithVisualStyles) { Rectangle backgroundBounds = bounds; backgroundBounds.Inflate(-1, -1); ButtonRenderer.DrawButton(g, backgroundBounds, State); // button renderer doesnt draw the black frame when themes are off =( g.DrawRectangle(SystemPens.WindowFrame, 0, 0, bounds.Width - 1, bounds.Height - 1); } else { ButtonRenderer.DrawButton(g, bounds, State); } StringFormat format = new StringFormat(); format.Alignment = StringAlignment.Center; format.LineAlignment = StringAlignment.Center; g.DrawString(Text, Font, SystemBrushes.ControlText, bounds, format); } private void ShowContextMenuStrip() { State = PushButtonState.Pressed; if (m_SplitMenu != null) { m_SplitMenu.Show(this, new Point(0, Height), ToolStripDropDownDirection.BelowRight); } } private void HideContextMenuStrip() { State = PushButtonState.Normal; m_SplitMenu.Hide(); mBlockClicks = true; mTimer.Start(); } } } [1]: http://wyday.com/blog/csharp-splitbutton
You can do model-view-controller or model-view-presenter type architectures without using a full blown framework. You already found out that unit-testing ui-components is difficult. There are ways around that but you probably don't want to go that route. Usually this will make your tests very hard to maintain, more maintenance nightmare's is something programmers can do without :-) Try to separate out the functionality you want to test in a "controller" or "presenter" class. Then test that class. To make it more testable you can hide the usercontrol class (the view) behind an interface and make the controller or presenter talk to the view through the interface. That way you can mock up the view in your tests. I know this sounds like a lot of work and it seems like a workaround but if you get used to this it's a realy nice architecture that makes it far easier to change ui behaviour. You can always start using a "real" mvc framework when you realy need it :-)
OK, I found through Google the same page that Lars mentioned, and I believe it's a great explanation for people that don't quite know how memory works (like me). http://shsc.info/WindowsMemoryManagement My short conclusion was: - Private Bytes = The Memory my process has requested to store data. Some of it may be paged to disk or not. This is the information I was looking for. - Virtual Bytes = The Private Bytes, plus the space shared with other processes for loaded DLLs, etc. - Working Set = The portion of ALL the memory of my process that has not been paged to disk. So the amount paged to disk should be (Virtual - Working Set). Thanks all for your help!
You're going from classic ASP to ASP with 3.5 without just re-writing? Skillz. I've had to deal with some legacy ASP @work and I think it's just easier to parse it and re-write it.
The MVC framework mentioned above is the best way to test what the control does. However testing how it works is a bit different. This is totally off the cuff but you could make the user control expose some protected methods and properties to return validation information and then have a testing user control inherit it. That control could populate fields, press buttons and what not. Kind of messy but it could work.
Use namespaces to make a collection of functions: namespace Console { void WriteLine(...) // ... } As for memory, functions use the same amount outside a function, as a static member function or in a namespace. That is: no memory other that the code itself.
> After I have everything coded I'll do a few passes at refactoring/testing. I'm just wondering if anyone has any tips on how to make this process a little easier/more efficient. ![Doing it wrong](http://www.cartoonstock.com/lowres/cga0226l.jpg) Normally I'm not a fan of TDD, but in the case of refactoring it really is the way to go. Write some tests first which verify what the bit you're looking at is actually doing. Then refactor. This is a LOT more reliable than just 'it looks like it still works.' The other huge benefit to this is that when you're refactoring something which is further down the page, or in a shared library or something, you can just re-run the tests, as opposed to finding out the hard way that a seemingly unrelated change _was_ actually related
It just depends on what type of testing you are doing. If you are doing behavior based testing you might want a dynamic mock so you can verify that some interaction with your dependancy occurs. But if you are doing state based testing you might want a stub so you verify values/etc For example, in the below test you notice that I stub out the view so I can verify a property value is set (state based testing). I then create a dynamic mock of the service class so I can make sure a specific method gets called during the test (interaction / behavior based testing). <TestMethod()> _ Public Sub Should_Populate_Products_List_OnViewLoad_When_PostBack_Is_False() mMockery = New MockRepository() mView = DirectCast(mMockery.Stub(Of IProductView)(), IProductView) mProductService = DirectCast(mMockery.DynamicMock(Of IProductService)(), IProductService) mPresenter = New ProductPresenter(mView, mProductService) Dim ProductList As New List(Of Product)() ProductList.Add(New Product()) Using mMockery.Record() SetupResult.For(mView.PageIsPostBack).Return(False) Expect.Call(mProductService.GetProducts()).Return(ProductList).Repeat.Once() End Using Using mMockery.Playback() mPresenter.OnViewLoad() End Using 'Verify that we hit the service dependency during the method when postback is false Assert.AreEqual(1, mView.Products.Count) mMockery.VerifyAll() End Sub
From the simple test I have tried, aku is right, dispose is called as soon as the foreach block exit. @David : However the object state is kept during the iteration, so the connection would not be closed. Here is a simple program I tried to test the behavior... class Program { static void Main(string[] args) { foreach (int v in getValues()) { Console.WriteLine(v); } Console.ReadKey(); foreach (int v in getValues()) { Console.WriteLine(v); break; } Console.ReadKey(); } public static IEnumerable<int> getValues() { using (TestDisposable t = new TestDisposable()) { for(int i = 0; i<10; i++) yield return t.GetValue(); } } } public class TestDisposable : IDisposable { private int value; public void Dispose() { Console.WriteLine("Disposed"); } public int GetValue() { value += 1; return value; } }
From the simple test I have tried, aku is right, dispose is called as soon as the foreach block exit. @David : However call stack is kept between call, so the connection would not be closed because on the next call we would return to the next instruction after the yield, which is the while block. My understanding is that when the iterator is disposed, the connection would also be disposed with it. Here is a simple program I tried to test the behavior... class Program { static void Main(string[] args) { foreach (int v in getValues()) { Console.WriteLine(v); } Console.ReadKey(); foreach (int v in getValues()) { Console.WriteLine(v); break; } Console.ReadKey(); } public static IEnumerable<int> getValues() { using (TestDisposable t = new TestDisposable()) { for(int i = 0; i<10; i++) yield return t.GetValue(); } } } public class TestDisposable : IDisposable { private int value; public void Dispose() { Console.WriteLine("Disposed"); } public int GetValue() { value += 1; return value; } }
|apache|mod-rewrite|.htaccess|
In an application that heavily relies on .htaccess RewriteRules for its PrettyURLs (CakePHP in my case), how do I correctly set up directives to exclude certain directories from this rewriting? I.e.: /appRoot/.htaccess app/ static/ By default every request to /appRoot/* is being rewritten to be picked up by app/webroot/index.php, where it's being analysed and corresponding controller actions are being invoked. This is done by these directives in .htaccess: RewriteBase /appRoot RewriteRule ^$ app/webroot/ [L] RewriteRule (.*) app/webroot/$1 [L] I now want to exclude a few directories like static/ from this rewriting. I tried with this *before* the Cake RewriteRules: RewriteCond $1 ^(static|otherDir).*$ [NC] RewriteRule (.*) - [L] It works in so far that requests are no longer rewritten, but now **all** requests are being skipped, even legitimate Cake requests which should not match ^(static|otherDir).*$. I tried several variations of these rules but can't get it to work the way I want.
Remove the [L] from the previous rules: RewriteBase &nbsp; &nbsp;/appRoot RewriteRule &nbsp; &nbsp;^$ app/webroot/ &nbsp; &nbsp; RewriteRule &nbsp; &nbsp;(.*) app/webroot/$1 [L] means "Stop the rewriting process here and don't apply any more rewriting rules."