instruction stringlengths 0 30k ⌀ |
|---|
You don't want to use a Webforms button in ASP.NET MVC. MVC is a completely different way of working, and you no longer have the WebForms abstraction.
You have 2 different options you can either replace your asp:Button with an input tag or use a standard hyperlink instead. If you use the input option then you will need to wrap in a form element. The form action should point to a Controller action.
|
I have recently started having problems with TortoiseCVS, or more specifically with plink, the SSH application that comes with it. The IP address it tries to connect to can not be changed and is stuck with the old CVS repository's IP. Downloading plink from it's home site and calling from the command line still has this problem.
TortoiseCVS has the option to choose the SSH application it uses and I was wondering which other alternatives there are that I can use instead? |
It might be worth trying Tunnelier from [www.bitvise.com][1]
[1]: http://www.bitvise.com |
For benchmarking, like in your example, I use the [pear Benchmark][1] package. You set markers for measuring. The class also provides a few presentation helpers, or you can process the data as you see fit.
I actually have it wrapped in another class with a __destruct method. When a script exits, the output is logged via log4php to syslog, so I have a lot of performance data to work from.
[1]: http://pear.php.net/package/Benchmark |
There can be, but that's a conscious choice you make as the developer. You can use new Vista stuff, like UAC and CommandLinks and Aero and so forth. But you don't have to (even UAC can be programmed around -- just don't do anything that needs admin privileges). If you choose to ignore all of the Vista stuff, then there's absolutely no difference between the two.
If you do want to include that stuff in your app, it makes a difference. But I'd say not a huge one. And if you abstract away the differences (for example, write your own function that shows a TaskDialog for Vista, but which dumbs down the input you give it into a MesssageBox on XP), then you'll only be writing against your own code, and the differences will seem like almost nothing.
Also, a lot of Vista's new stuff (for example, UAC or Aero) is stuff that you worry about once, when you create the first piece of functionality that uses it, get it working, and then never think about again while you're developing the app. |
[XDebug][1] is essential for development. I install it before any other extension. It gives you stack traces on any error and you can enable profiling easily.
For a quick look at a data structure use [var_dump()][2]. Don't use print_r() because you'll have to surround it with <pre> and only prints one var at a time.
<?php var_dump(__FILE__, __LINE__, $_REQUEST); ?>
For a real debugging environment the best I've found is [Komodo IDE][3] but it costs $$.
[1]: http://www.xdebug.org/
[2]: http://www.php.net/manual/en/function.var-dump.php
[3]: http://www.activestate.com/Products/komodo_ide/index.mhtml |
Putty is probably the best SSH client out there:
http://www.chiark.greenend.org.uk/~sgtatham/putty/
|
You have two options:
- Store the adjusted time for the mail action into the database for each user. Then just compare server time with stored time. To avoid confusion and portability issues, I would store all times in UTC. So, send mail when SERVER_UTC_TIME() == storedUtcTime.
- Store the local time for each mail action into the database, then convert on-the-fly. Send mail when SERVER_UTC_TIME() == TO_UTC_TIME(storedLocalTime, userTimeZone).
You should decide what makes most sense for your application. For example if the mailing time is always the same for all users, it makes more sense to go with option (2). If the events times can change between users and even per user, it may make development and debugging easier if you choose option (1). Either way you will need to know the user's time zone.
*These function calls are obviously pseudo, since I don't know their invocations in T-SQL, but they should exist. |
Use `EnclosingClass.this` |
Believe me, I know _exactly_ where you are coming from.. I am currently migrating a large app from ASP classic to .NET.. And I am still learning ASP.NET! :S (yes, I am terrified!).
The main things I have kept in my mind is this:
* I dont stray _too_ far from the current design (i.e. no massive "lets rip ALL of this out and make it ASP.NET magical!) due to the incredibly high amount of coupling that ASP classic tends to have, this would be very dangerous. Of course, if you are confident, fill your boots :) This can always be refactored later.
* Back everything up with tests, tests and more tests! I am really trying hard to get into TDD, but its very difficult to test existing apps, so every time I remove a chunk of classic and replace with .NET, I ensure I have as much green-light tests backing me as possible.
* Research a lot, there are some MAJOR changes between classic and .NET and sometimes what can be many lines of code and includes in classic can be achieved in a few lines of code, _think_ before coding.. I've learnt this the hard way, several times :D
Its very much like playing [Jenga](http://www.amazon.co.uk/Hasbro-14569186-Jenga/dp/B00004XQW9) with your code :)
Best of luck with the project, any more questions, then please ask :) |
> : are lambda expressions useful for anything other than querying
Lamba expressions are nothing much other than a convenient way of writing a function 'in-line'.
So they're useful any place you wanted a bit of code which can be called as though it's a separate function but which is actually written inside its caller. (In addition to keeping related code in the same location in a file, this also allows you to play fun games with variable scoping - see 'closures' for a reference.
An example of a non-query-related use of a lamba might be a bit of code which does something asynchronously that you start with ThreadPool.QueueUserWorkItem. The important point is that you could also write this using anonymous delegates (which were a C#2 introduction), or just a plain separate class member function.
This http://blogs.msdn.com/jomo_fisher/archive/2005/09/13/464884.aspx is a superb step-by-step introduction into all this stuff, which might help you.
|
> : are lambda expressions useful for anything other than querying
Lamba expressions are nothing much other than a convenient way of writing a function 'in-line'.
So they're useful any place you wanted a bit of code which can be called as though it's a separate function but which is actually written inside its caller. (In addition to keeping related code in the same location in a file, this also allows you to play fun games with variable scoping - see 'closures' for a reference.)
An example of a non-query-related use of a lamba might be a bit of code which does something asynchronously that you start with ThreadPool.QueueUserWorkItem. The important point is that you could also write this using anonymous delegates (which were a C#2 introduction), or just a plain separate class member function.
This http://blogs.msdn.com/jomo_fisher/archive/2005/09/13/464884.aspx is a superb step-by-step introduction into all this stuff, which might help you.
|
Response.Redirect using ~ Path |
|c#|asp.net|response.redirect| |
There's the non-standard element <wbr /> that is supported by at least
Firefox, http://developer.mozilla.org/En/HTML/Element
Internet Explorer, http://msdn.microsoft.com/en-us/library/ms535917(VS.85).aspx
and Opera. |
There's the non-standard element wbr that is supported by at least
Firefox, http://developer.mozilla.org/En/HTML/Element
Internet Explorer, http://msdn.microsoft.com/en-us/library/ms535917(VS.85).aspx
and Opera. |
Regardless of the number of CPUs available, if you require preemptive multitasking and/or applications with asynchronous components (i.e. pretty much anything that combines a responsive GUI with a non-trivial amount of computation or continuous I/O processing), multithreading performs much better than the alternative, which is to use multiple processes for each application.
This is because threads in the same process can exchange data much more efficiently than can multiple processes, because they share the same memory context.
See [this Wikipedia article on computer multitasking][1] for a fairly concise discussion of these issues.
[1]: http://en.wikipedia.org/wiki/Computer_multitasking |
I would suggest using compression at the transport layer, and eliminating whitespace from the HTML, but not sacrificing the semantics of your markup in the interest of speed. In fact, the better you "compress" your markup, the less effective the transport layer compression will be. Or, to put it a better way, let the gzip transfer-coding slim your HTML for you, and pour your energy into writing clean markup that renders quickly once it hits the browser. |
>In PHP, you can send POST data with cURL. Is there something comparable for .NET?
Yes, HttpWebRequest, see my post below. |
What platform are you attempting this on? Most debuggers allow you to attach to a running process by using the process id.
You can either output the process id via logging or using something like Task Manager.
Once that is achieved it will be possible to inspect individual threads and their call stacks. |
What platform are you attempting this on? Most debuggers allow you to attach to a running process by using the process id.
You can either output the process id via logging or using something like Task Manager.
Once that is achieved it will be possible to inspect individual threads and their call stacks.
EDIT: I don't have any experience with GNU Debugger (GDB), which is cross platform, however I found this [link](http://wiki.python.org/moin/DebuggingWithGdb) and it may start you on the right path. It explains how to add debug symbols (handy for reading stack traces) and how to instruct gdb to attach to a running python process. |
Have you seen [VCDiff][1]? It is part of a Misc library that appears to be fairly active (last release r259, April 23rd 2008). I haven't used it, but thought it was worth mentioning.
[1]: http://www.yoda.arachsys.com/csharp/miscutil/usage/vcdiff.html |
Getting the base element from a jQuery object |
|jquery| |
I'm struggling to find the right terminology here, but if you have jQuery object...
$('#MyObject')
...is it possible to extract the base element? Meaning, the equivalent of this:
document.getElementById('MyObject') |
Ok, per Sparks' and Dave's answers it looks like there are two ways to do this:
----------
**Make an Alias:**
(my personal preferred method)
1. Starting ~line 200, copy everything between <Directory "C:/xampp/htdocs"> and </Directory> (~line 232) and paste it immediately below with C:/xampp/htdocs replaced with your desired directory (in this case C:/Projects) to give your server the correct permissions for the new directory.
2. Find the <IfModule alias_module></IfModule> section (~line 300) and add Alias /transitCalculator C:/Projects/transitCalculator/trunk (or whatever is relevant to your desires) below the "Alias" comment block.
----------
*-or-*
**Change your document root:**
1. Edit line 176 in C:\xampp\apache\conf\httpd.conf; change DocumentRoot "C:/xampp/htdocs" to #DocumentRoot "C:/Projects" (or whatever you want).
2. Edit line 203 to match your new location (in this case C:/Projects)
----------
**Notes:**
* You have to use forward slashes "/" instead of back slashes "\"
* don't include the trailing "/" at the end
* *restart your server*. |
Ok, per [Sparks][1]' and [Dave][2]'s answers it looks like there are two ways to do this:
----------
**Make an Alias:**
(my personal preferred method)
1. Starting ~line 200, copy everything between <Directory "C:/xampp/htdocs"> and </Directory> (~line 232) and paste it immediately below with C:/xampp/htdocs replaced with your desired directory (in this case C:/Projects) to give your server the correct permissions for the new directory.
2. Find the <IfModule alias_module></IfModule> section (~line 300) and add Alias /transitCalculator C:/Projects/transitCalculator/trunk (or whatever is relevant to your desires) below the "Alias" comment block.
----------
*-or-*
**Change your document root:**
1. Edit line 176 in C:\xampp\apache\conf\httpd.conf; change DocumentRoot "C:/xampp/htdocs" to #DocumentRoot "C:/Projects" (or whatever you want).
2. Edit line 203 to match your new location (in this case C:/Projects)
----------
**Notes:**
* You have to use forward slashes "/" instead of back slashes "\"
* don't include the trailing "/" at the end
* *restart your server*.
[1]: http://stackoverflow.com/questions/1408/#1413
[2]: http://stackoverflow.com/questions/1408/#1414 |
Ok, per [pix0r][1]'s, [Sparks][2]' and [Dave][3]'s answers it looks like there are three ways to do this:
----------
[Virtual Hosts][1]
-------------
1. Open C:\xampp\apache\conf\extra\httpd-vhosts.conf
2. Un-comment line 19 (NameVirtualHost *:80)
3. Add your virtual host (~line 36):
> <VirtualHost *:80>
> >DocumentRoot C:\Projects\transitCalculator\trunk
> > ServerName transitcalculator.localhost
>
> > <Directory C:\Projects\transitCalculator\trunk>
> > > Order allow,deny
> > > Allow from all
> > </Directory>
> </VirtualHost>
4. Open your hosts file (C:\Windows\System32\drivers\etc\hosts)
5. Add 127.0.0.1 transitcalculator.localhost #transitCalculator to the end of the file (before the Spybot - Search & Destroy stuff if you have that installed)
6. Save (You might have to save it to the desktop, change the permissions on the old hosts file (right click > properties), and copy the new one into the directory over the old one (or rename the old one) if you are using Vista and have trouble)
7. Restart Apache
Now you can access that directory by browsing to http://transitcalculator.localhost/
----------
*-or-*
[Make an Alias][2]
-------------
1. Starting ~line 200, copy everything between <Directory "C:/xampp/htdocs"> and </Directory> (~line 232) and paste it immediately below with C:/xampp/htdocs replaced with your desired directory (in this case C:/Projects) to give your server the correct permissions for the new directory.
2. Find the <IfModule alias_module></IfModule> section (~line 300) and add Alias /transitCalculator C:/Projects/transitCalculator/trunk (or whatever is relevant to your desires) below the "Alias" comment block.
----------
*-or-*
[Change your document root][3]
-------------------------
1. Edit line 176 in C:\xampp\apache\conf\httpd.conf; change DocumentRoot "C:/xampp/htdocs" to #DocumentRoot "C:/Projects" (or whatever you want).
2. Edit line 203 to match your new location (in this case C:/Projects)
----------
**Notes:**
* You have to use forward slashes "/" instead of back slashes "\"
* don't include the trailing "/" at the end
* *restart your server*.
[1]: http://stackoverflow.com/questions/1408/#2471
[2]: http://stackoverflow.com/questions/1408/#1413
[3]: http://stackoverflow.com/questions/1408/#1414 |
Komodo IDE works well with xdebug, even for the remore debugging. It needs minimum amount of configuration. All you need is a version of php that Komodo can use locally to step through the code on a breakpoint. If you have the script imported into komodo project, then you can set breakpoints with a mouse-click just how you would set it inside eclipse for debugging a java program.
Remote debugging is obviously more tricky to get it to work correctly ( you might have to map the remote url with a php script in your workspace ) than a local debugging setup which is pretty easy to configure if you are on a MAC or a linux desktop.
|
Are you sure this is a problem with plink? It sounds to me like you have CVS/Root files lying around that still point to the old cvs ip address. In general, CVS doesn't make changing repositories into a fun process. Since you are using Windows, if you install WinCVS with macros support (Python module loaded) it has a macro that can be used to mass change CVS roots.
Otherwise, its up to you to script the process.
FWIW, I've used plink quite a bit and never had a similar problem. |
For what it's worth, [plink](http://the.earth.li/~sgtatham/putty/latest/x86/plink.exe) is just a command-line version of putty written by the same guy.
I think [jsight](http://stackoverflow.com/questions/22687/alternative-ssh-application-to-plink#22700) probably has the right idea. |
Sometimes I see the `ItemAdded` or `ItemUpdated` firing twice for a single operation.
You can try to put a breakpoint in the `ItemAdded()` method to confirm that.
The solution in my case was to single thread the `ItemAdded()` method:
private static object myLock = new object();
public override void ItemAdded(SPItemEventProperties properties) {
if (System.Threading.Monitor.TryEnter(myLock, TimeSpan.FromSeconds(30))
{
//do your stuff here.
System.Threading.Monitor.Exit(myLock);
}
}
|
- Yes. Unless there's a feature we really need in a beta version.
- There's no point using a beta version in dev if you aren't certain you'll use it in production. That just seems like a wasted exercise
- I'll use the patch. Why write code for something you've paid for? |
If you need to store lots of images on the file system a couple of things to think about include:
* Backup and restore. How do you keep the images in sync.
* Filesystem performance. Depends on what you are doing and the filesystem, but you may want to implement a hashing mechanism so that you don't have a single directory with billions of files.
* Replication. Do you need to keep the files in sync between multiple servers? |
The way to preserve the stack trace is through the use of the throw; This is valid as well
try {
// something that boms here
} catch (Exception ex)
{
throw;
}
throw ex; is basically like throwing an exception from that point, so the stack trace would only go to where you are issuing the throw ex; statement |
The way to preserve the stack trace is through the use of the throw; This is valid as well
try {
// something that boms here
} catch (Exception ex)
{
throw;
}
throw ex; is basically like throwing an exception from that point, so the stack trace would only go to where you are issuing the throw ex; statement
[@Mike](http://stackoverflow.com/questions/22623/net-throwing-exceptions-best-practices#22649) is also correct, assuming the exception allows you to pass an exception (which is recommended).
[Karl Seguin](http://codebetter.com/blogs/karlseguin/) has a [great write up on exception handling](http://codebetter.com/blogs/karlseguin/archive/2008/05/29/foundations-of-programming-pt-8-back-to-basics-exceptions.aspx) in his [foundations of programming e-book](http://codebetter.com/files/folders/codebetter_downloads/entry179694.aspx) as well, which is a great read. |
Check out <http://hotwire-shell.org/> |
It usually arrives within the first hour. BUt the fact that it reads me@mycompany.com could either because you put it there to protect your privacy (in which case forget about this) or that the system didn't catch your email and they sent it to me@mycompany.com.
If the email address was ok and you didn't get it, somehow it bounced or it won't arrive. I'd suggest you contact them again providing an alternate email (gmail or such) to make sure that you don't experience any problems.
Last time I received a hotfix it took them 10 minutes.
Good luck with that! |
PowerShell V2 is developing a graphical command shell, but I don't think that is what you are looking for.
PowerShell as a command shell is very forgiving for new users and is easy to learn. There is an add-on product (it is a commercial product) called PowerGadgets that would let you pipe file sizes into a pie chart or other types of displays. Information about that can be found [here][1].
As for ease of use, PowerShell command follow a Verb-Noun pattern (along with aliases for ease of use from the command line) and is very discoverable. Check out some screencasts I did on using PowerShell at [PowerShell Basics][2].
[1]: http://www.softwarefx.com/sfxSqlProducts/powerGadgets/
[2]: http://powershell-basics.com |
Might be overkill for your project, but [Dean Edwards' IE7 javascript adds support for fixed positioning to IE6][1].
[1]: http://dean.edwards.name/IE7/ |
Is this for Python in particular, or are you just interested in *any* command shell that has a GUI interface?
If the idea of piping file sizes into a pie chart interests you, you might try [PowerGUI][1], a GUI layer on Microsoft's PowerShell command shell. PowerShell also lets you pipe data from commands into XML, CSV, and other formats that are understood by GUI programs.
[1]: http://powergui.org/ |
@[Mark](#30531)
Well that's just plain wierd! What's your `include_path` - that could be messing thigns around. I've personally ditched it in favour of contants as it's just so temperamental (or I've never learned how to do it justice). |
You could set the visibility of a paragraph|div to 'hidden'.
Then in the 'onload' function, you could set the visibility to 'visible'.
Something like:
<body onload="javascript:document.getElementById(rec).style.visibility=visible">
<p style="visibility: visible" id="rec">This text to be hidden unless javascript available.</p>
|
@LKM AJAX is the clear winner here. This will also allow you to follow the [DRY][1] principle. Why would you want to write your parsing code in Javascript **and** PHP?
[1]: http://en.wikipedia.org/wiki/Don%27t_repeat_yourself |
Took about a day for me when I requested one so I suspect some sort of manual/semi-automated process has to complete before you get the e-mail.
Give it a day before you start bugging them ;) |
There are both zip and unzip executables (as well as a boat load of other useful applications) in the UnxUtils package available on SourceForge ([http://sourceforge.net/projects/unxutils][1]). Copy them to a location in your PATH, such as 'c:\windows', and you will be able to include them in your scripts.
This is not the perfect solution (or the one you asked for) but a decent work-a-round.
[1]: http://sourceforge.net/projects/unxutils |
I have a method that where I want to redirect the user back to a login page located at the root of my web application.
I'm using the following code:
Response.Redirect("~/Login.aspx?ReturnPath=" + Request.Url.ToString());
This doesn't work though. My assumption was that ASP.NET would automatically resolve the URL into the correct path. Normally, I would just use
Response.Redirect("../Login.aspx?ReturnPath=" + Request.Url.ToString());
but this code is on a master page, and can be executed from any folder level. How do I get around this issue? |
No.
You might consider a flag field (enum for readability) and then have the constructor use htat to determine what you meant. |
Only thing I can think of to handle what you're wanting to do is to have to params, one that describes the param type (an enum with LogonName, BadgeNumer, etc) and the second is the param value. |
distutils really isn't all that difficult once you get the hang of it. It's really just a matter of putting in some meta-information (program name, author, version, etc) and then selecting what files you want to include. For example, here's a sample distutils setup.py module from a decently complex python library:
[Kamaelia setup.py][1]
Note that this doesn't deal with any data files or or whatnot, so YMMV.
On another note, I agree that the distutils documentation is probably some of python's worst documentation. It is extremely inclusive in some areas, but neglects some really important information in others.
[1]: http://code.google.com/p/kamaelia/source/browse/trunk/Code/Python/Kamaelia/setup.py |
That won't work. You might consider making a class called BadgeNumber that wraps a string in order to avoid this ambiguity. |
You could perhaps use factory methods instead?
public static Person fromId(int id) {
Person p = new Person();
p.Load(id);
return p;
}
public static Person fromLogonName(string logonName) {
Person p = new Person();
p.Load(logonName);
return p;
}
public static Person fromBadgeNumber(string badgeNumber) {
Person p = new Person();
// load logic
return p;
}
private Person() {} |
You cannot have two different constructors/methods with the same signature, otherwise, how can the compiler determine which method to run.
As [Zack said](http://stackoverflow.com/questions/31215/constructors-with-the-same-argument-type#31220), I would consider creating an "options" class where you could actually pass the parameters contained in a custom type. This means you can pretty much pass as many parameters as you like, and do what you like with the options, just be careful you dont create a monolithic method that tries to do everything..
Either that, or vote for the [factory pattern](http://en.wikipedia.org/wiki/Factory_method_pattern).. |
I'd suggest to also monitor how often pagefaults happen. A pagefault happens when you try to access some data that have been moved from physical memory to swap file and system has to read page from disk before you can access this data. |
You could use a static factory method:
public static Person fromLogon(String logon) { return new Person(logon, null); }
public static Person fromBadge(String badge) { return new Person(null, badge); }
|
Ok, per [pix0r][1]'s, [Sparks][2]' and [Dave][3]'s answers it looks like there are three ways to do this:
----------
[Virtual Hosts][1]
-------------
1. Open C:\xampp\apache\conf\extra\httpd-vhosts.conf
2. Un-comment line 19 (NameVirtualHost *:80)
3. Add your virtual host (~line 36):
> <VirtualHost *:80>
> >DocumentRoot C:\Projects\transitCalculator\trunk
> > ServerName transitcalculator.localhost
>
> > <Directory C:\Projects\transitCalculator\trunk>
> > > Order allow,deny
> > > Allow from all
> > </Directory>
> </VirtualHost>
4. Open your hosts file (C:\Windows\System32\drivers\etc\hosts)
5. Add 127.0.0.1 transitcalculator.localhost #transitCalculator to the end of the file (before the Spybot - Search & Destroy stuff if you have that installed)
6. Save (You might have to save it to the desktop, change the permissions on the old hosts file (right click > properties), and copy the new one into the directory over the old one (or rename the old one) if you are using Vista and have trouble)
7. Restart Apache
Now you can access that directory by browsing to http://transitcalculator.localhost/
----------
[Make an Alias][2]
-------------
1. Starting ~line 200, copy everything between <Directory "C:/xampp/htdocs"> and </Directory> (~line 232) and paste it immediately below with C:/xampp/htdocs replaced with your desired directory (in this case C:/Projects) to give your server the correct permissions for the new directory.
2. Find the <IfModule alias_module></IfModule> section (~line 300) and add Alias /transitCalculator C:/Projects/transitCalculator/trunk (or whatever is relevant to your desires) below the "Alias" comment block.
----------
[Change your document root][3]
-------------------------
1. Edit line 176 in C:\xampp\apache\conf\httpd.conf; change DocumentRoot "C:/xampp/htdocs" to #DocumentRoot "C:/Projects" (or whatever you want).
2. Edit line 203 to match your new location (in this case C:/Projects)
----------
**Notes:**
* You have to use forward slashes "/" instead of back slashes "\"
* don't include the trailing "/" at the end
* *restart your server*.
[1]: http://stackoverflow.com/questions/1408/#2471
[2]: http://stackoverflow.com/questions/1408/#1413
[3]: http://stackoverflow.com/questions/1408/#1414 |
Thanks a lot. Also, the following also made it work:
host_name = Socket.getaddrinfo(current_ip,nil)
append_to_file("#{host_name[0][2]} - #{current_ip} - #{mac_addr}\n")
I'm not sure why gethostbyaddr didn't also work. |
This should work reasonably well:
public static class HumanFriendlyInteger
{
static string[] ones = new string[] { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" };
static string[] teens = new string[] { "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
static string[] tens = new string[] { "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
private static string FriendlyIntegerLessThan100(int n)
{
if (n >= 100 || n < 0)
{
throw new ArgumentOutOfRangeException();
}
if (n < 10)
{
return ones[n];
}
else if (n < 20)
{
return teens[n - 10];
}
else
{
return tens[n / 10 - 2] + (n%10 == 0 ? "" : " " + ones[n % 10]);
}
}
private static string FriendlyIntegerLessThan1000(int n)
{
if (n >= 1000 || n < 0)
{
throw new ArgumentOutOfRangeException();
}
string hundreds = "";
if (n >= 100)
{
hundreds = ones[n / 100] + " Hundred";
if (n % 100 == 0)
{
return hundreds;
}
hundreds += " ";
}
return hundreds + FriendlyIntegerLessThan100(n % 100);
}
public static string IntegerToWritten(int n)
{
string billions = "";
if (n >= 1000000000)
{
billions = FriendlyIntegerLessThan1000((int)(n % 1000000000000) / 1000000000) + " Billion";
if (n % 1000000000 == 0)
{
return billions;
}
billions += " ";
}
string millions = "";
if (n >= 1000000)
{
millions = FriendlyIntegerLessThan1000((int)(n % 1000000000) / 1000000) + " Million";
if (n % 1000000 == 0)
{
return billions + millions;
}
millions += " ";
}
string thousands = "";
if (n >= 1000)
{
thousands = FriendlyIntegerLessThan1000((int)(n % 1000000) / 1000) + " Thousand";
if (n % 1000 == 0)
{
return billions + millions + thousands;
}
thousands += " ";
}
return billions + millions + thousands + FriendlyIntegerLessThan1000(n % 1000);
}
} |
It seems like the answer is in the question - the method you suggested seems to be the right direction to go, except that if you have a big number of those shared members you might want to gather them into a struct or class and past that as the argument to the constructor of the base class.
If you insist on having the "shared" members implemented as static members of the derived class, you might be able to auto-generate the code of the derived classes. XSLT is a great tool for auto-generating simple classes.
In general, the example doesn't show a need for "virtual static" members, because for purposes like these you don't actually need inheritance - instead you should use the base class and have it accept the appropriate values in the constructor - maybe creating a single instance of the arguments for each "sub-type" and passing a pointer to it to avoid duplication of the shared data. Another similar approach is to use templates and pass as the template argument a class that provides all the relevant values (this is commonly referred to as the "Policy" pattern).
To conclude - for the purpose of the original example, there is no need for such "virtual static" members. If you still think they are needed for the code you are writing, please try to elaborate and add more context.
Example of what I described above:
class BaseClass {
public:
BaseClass(const Descriptor& desc) : _desc(desc) {}
string GetName() const { return _desc.name; }
int GetId() const { return _desc.Id; }
X GetX() connst { return _desc.X; }
virtual void UseClass() = 0;
private:
const Descriptor _desc;
};
class DerivedClass : public BaseClass {
public:
DerivedClass() : BaseClass(Descriptor("abc", 1,...)) {}
virtual void UseClass() { /* do something */ }
};
class DerDerClass : public BaseClass {
public:
DerivedClass() : BaseClass("Wowzer", 843,...) {}
virtual void UseClass() { /* do something */ }
};
I'd like to elaborate on this solution, and maybe give a solution to the de-initialization problem:
With a small change, you can implement the design described above without necessarily create a new instance of the "descriptor" for each instance of a derived class.
You can create a singleton object, DescriptorMap, that will hold the single instance of each descriptor, and use it when constructing the derived objects like so:
enum InstanceType {
Yellow,
Big,
BananaHammoc
}
class DescriptorsMap{
public:
static Descriptor* GetDescriptor(InstanceType type) {
if ( _instance.Get() == null) {
_instance.reset(new DescriptorsMap());
}
return _instance.Get()-> _descriptors[type];
}
private:
DescriptorsMap() {
descriptors[Yellow] = new Descriptor("Yellow", 42, ...);
descriptors[Big] = new Descriptor("InJapan", 17, ...)
...
}
~DescriptorsMap() {
/*Delete all the descriptors from the map*/
}
static autoptr<DescriptorsMap> _instance;
map<InstanceType, Descriptor*> _descriptors;
}
Now we can do this:
class DerivedClass : public BaseClass {
public:
DerivedClass() : BaseClass(DescriptorsMap.GetDescriptor(InstanceType.BananaHammoc)) {}
virtual void UseClass() { /* do something */ }
};
class DerDerClass : public BaseClass {
public:
DerivedClass() : BaseClass(DescriptorsMap.GetDescriptor(InstanceType.Yellow)) {}
virtual void UseClass() { /* do something */ }
};
At the end of execution, when the C runtime performs uninitializations, it also calls the destructor of static objects, including our autoptr, which in deletes our instance of the DescriptorsMap.
So now we have a single instance of each descriptor that is also being deleted at the end of execution.
Note that if the only purpose of the derived class is to supply the relevant "descriptor" data (i.e. as opposed to implementing virtual functions) then you should make do with making the base class non-abstract, and just creating an instance with the appropriate descriptor each time. |
Database: What is Multiversion Concurrency Control (MVCC) and which databases support it? |
|database|deadlock| |
Recently Jeff has [posted][1] regarding his trouble with database deadlocks related to reading. Multiversion Concurrency Control claims to solve this problem. What is it, and what databases support it?
[1]: http://www.codinghorror.com/blog/archives/001166 |
Database: What is Multiversion Concurrency Control (MVCC) and who supports it? |
|database|deadlock|glossary| |
Recently Jeff has [posted][1] regarding his trouble with database deadlocks related to reading. Multiversion Concurrency Control claims to solve this problem. What is it, and what databases support it?
[1]: http://www.codinghorror.com/blog/archives/001166.html |
Recently Jeff has [posted][1] regarding his trouble with database deadlocks related to reading. Multiversion Concurrency Control claims to solve this problem. What is it, and what databases support it?
update: fixed link
[1]: http://www.codinghorror.com/blog/archives/001166.html |
Recently Jeff has [posted][1] regarding his trouble with database deadlocks related to reading. Multiversion Concurrency Control claims to solve this problem. What is it, and what databases support it?
updated: these support it (which others?)
- oracle
- postgresql
[1]: http://www.codinghorror.com/blog/archives/001166.html |
|database|glossary|deadlock| |
Recently Jeff has [posted][1] regarding his trouble with database deadlocks related to reading. Multiversion Concurrency Control claims to solve this problem. What is it, and what databases support it?
updated: these support it (which others?)
- oracle
- postgresql
[1]: http://www.codinghorror.com/blog/archives/001166.html |
Recently Jeff has [posted][1] regarding his trouble with database deadlocks related to reading. Multiversion Concurrency Control claims to solve this problem. What is it, and what databases support it?
updated: these support it (which others?)
- oracle
- postgresql
[1]: http://www.codinghorror.com/blog/archives/001166.html |
I use the [GeSHi Syntax Highlighter Plugin][1] in [my blog][2] and I find it works well. Which highlighter you use tends to depend on which languages you use most frequently and how good the support is for them.
[1]: http://qbnz.com/highlighter/index.php
[2]: http://blog.cdleary.com |
I use the [GeSHi Syntax Highlighter Plugin][1] in [my blog][2] and I find it works well. Which highlighter you use tends to depend on which languages you use most frequently and how good the support is for them.
[Edit] I forgot that GeSHi is the highlighter associated with the [Wordpress SyntaxHighlighter plugin][3]. :/
[1]: http://qbnz.com/highlighter/index.php
[2]: http://blog.cdleary.com
[3]: http://wordpress.org/extend/plugins/syntaxhighlighter/ |
YUI Reset CSS Makes strong and em not work |
|css| |
This line in YUI's Reset CSS is causing trouble for me:
address,caption,cite,code,dfn,em,strong,th,var {
font-style:normal;
font-weight:normal;
}
It makes my <code>em</code> not italic and my <code>strong</code> not bold. Which is okay. I know how to override that in my own stylesheet.
strong, b
{
font-weight: bold;
}
em, i
{
font-style: italic;
}
The problem comes in when I have text that's both <code>em</code> and <code>strong</code>.
<strong><em>Should be bold and italicized, but it's not bold.</em></strong>
My rule for <code>strong</code> makes it bold, but YUI's rule for <code>em</code> makes it normal again. How do I fix that?
|
YUI Reset CSS Makes <strong><em>this not work</em></strong> |
This line in YUI's Reset CSS is causing trouble for me:
address,caption,cite,code,dfn,em,strong,th,var {
font-style:normal;
font-weight:normal;
}
It makes my <code>em</code> not italic and my <code>strong</code> not bold. Which is okay. I know how to override that in my own stylesheet.
strong, b
{
font-weight: bold;
}
em, i
{
font-style: italic;
}
The problem comes in when I have text that's both <code>em</code> and <code>strong</code>.
<strong>This is bold, <em>and this is italic, but not bold</em></strong>
My rule for <code>strong</code> makes it bold, but YUI's rule for <code>em</code> makes it normal again. How do I fix that?
|
If you don't want an event interfering, you can set up the Validation Rule property for the textbox to be
NOT LIKE "*"+Chr(10)+"*" OR "*"+Chr(13)+"*"
You will probably also want to set the Validation Text to explain specifically why Access is throwing up an error box.
|
I've used beta libraries in commercial projects before but mostly during development and when the vendor is likely to release a final version before I finish the product.
For example, I developed a small desktop application using Visual Studio 2005 Beta 2 because I knew that the RTM version would be available before the final release of my app. Also I used a beta version of FirebirdSQL ADO.NET Driver during development of another project.
For bugs I try to post complete bug reports whenever there's a way to reproduce it but most of the time you have to find a workaround to release the application ASAP. |
import urllib2
response = urllib2.urlopen('http://www.example.com/')
html = response.read() |
Use urllib2 which comes with the standard library.
import urllib2
response = urllib2.urlopen('http://www.example.com/')
html = response.read()
This is the most basic way to use the library. You can also do more complex stuff such as changing headers. The documentation can be found [here.][1]
[1]: http://docs.python.org/lib/module-urllib2.html |
Use urllib2 which comes with the standard library.
import urllib2
response = urllib2.urlopen('http://www.example.com/')
html = response.read()
This is the most basic way to use the library, minus any error handling. You can also do more complex stuff such as changing headers. The documentation can be found [here.][1]
[1]: http://docs.python.org/lib/module-urllib2.html |
You could switch to a factory style pattern.
public class Person {
private Person() {}
public static PersonFromID(int personId)
{
Person p = new Person().
person.Load(personID);
return p;
this.Load(personId);
}
public static PersonFromID(string name)
{
Person p = new Person().
person.LoadFromName(name);
return p;
}
...
}
Or, as suggested, use custom types. You can also hack something using generics, but I wouldn't recommend it for readability. |
XML is an *external* format, not *internal*.
What's wrong with [XHTML](http://www.w3.org/TR/xhtml1/)? It's simple and it's ubiquitous (at least HTML is). Your implementation would be easy to debug, and your users will be eternally greatful. |
This is probably not always faster but more optimistic about that you find a big prime divisor:
1. `N` is your number
2. If it is prime then `return(N)`
3. Calculate primes up until `Sqrt(N)`
4. Go through the primes in descending order (largest first)
* If `N is divisible by Prime` then `Return(Prime)`
Edit: In step 3 you can use the Sieve of Eratosthenes or Sieve of Atkins or whatever you like, but by itself the sieve won't find you the biggest prime factor. (Thats why I wouldn't choose SQLMenace's post as an official answer...) |
Sounds like you have a pretty good handle on things. I've seen a lot of people try to do a straight-line transliteration, includes and all, and it just doesn't work. You need to have a good understanding of how ASP.Net wants to work, because it's _much_ different from Classic ASP, and it sounds like maybe you have that.
For larger files, I'd try to get a higher level view first. For example, one thing I've noticed is that Classic ASP was horrible about function calls. You'd be reading through some code and find a call to a function with no clue as to where it might be implemented. As a result, Classic ASP code tended to have long functions and scripts to avoid those nasty jumps. I remember seeing a function that printed out to 40 pages! Parsing straight through that much code is no fun.
ASP.Net makes it easier to follow function calls around, so you might start by breaking out your larger code blocks into several smaller functions. |
C#: instantiating classes from XML |
|c#|xml| |
What I have is a collection of classes that all implement the same interface but can be pretty wildly different under the hood. I want to have a config file control which of the classes go into the collection upon starting the program, taking something that looks like
<class1 prop1="foo" prop2="bar"/>
and turning that into
blah = new class1();
blah.prop1="foo";
blah.prop2="bar";
in a very generic way. The thing I don't know how to do is take the string "prop1" in the config file and turn that into the actual property accessor in the code. Are there any metaprogramming facilities in C# to allow that?
|
As has been suggested, custom types is the way to go in this case. |
You might consider using custom types.
For example, create LogonName and BadgeNumber classes.
Then your function declarations look like...
public Person(LogonName ln)
{
//load logic here...
}
public Person(BadgeNumber bn)
{
//load logic here...
}
|
This should work reasonably well:
public static class HumanFriendlyInteger
{
static string[] ones = new string[] { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" };
static string[] teens = new string[] { "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
static string[] tens = new string[] { "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
static string[] thousandsGroups = { "", " Thousand", " Million", " Billion" };
private static string FriendlyInteger(int n, string leftDigits, int thousands)
{
if (n == 0)
{
return leftDigits;
}
string friendlyInt = leftDigits;
if (friendlyInt.Length > 0)
{
friendlyInt += " ";
}
if (n < 10)
{
friendlyInt += ones[n];
}
else if (n < 20)
{
friendlyInt += teens[n - 10];
}
else if (n < 100)
{
friendlyInt += FriendlyInteger(n % 10, tens[n / 10 - 2], 0);
}
else if (n < 1000)
{
friendlyInt += FriendlyInteger(n % 100, (ones[n / 100] + " Hundred"), 0);
}
else
{
friendlyInt += FriendlyInteger(n % 1000, FriendlyInteger(n / 1000, "", thousands+1), 0);
}
return friendlyInt + thousandsGroups[thousands];
}
public static string IntegerToWritten(int n)
{
if (n == 0)
{
return "Zero";
}
else if (n < 0)
{
return "Negative " + IntegerToWritten(-n);
}
return FriendlyInteger(n, "", 0);
}
}
(Edited to make it considerably more concise.) |
You could try <http://selenium.openqa.org/> it is more for GUI testing rather than a data layer testing application but does record your actions which then can be played back to automate tests across different platforms. |
You'd be looking to static link (as opposed to dynamically link)
I'm not sure how many of the MS redistributables statically link in. |
It's a tricky question. Since lisp is already structurally so close to a parse tree the difference between a large number of macros and implementing your own mini-language in a parser generator isn't very clear. But, except for the opening and closing paren, you could very easily end up with something that looks nothing like lisp. |
The Array.zip function does an elementwise combination of arrays. It's not quite as clean as the Python syntax, but here's one approach you could use:
weights = [1, 2, 3]
data = [4, 5, 6]
result = Array.new
a.zip(b) { |x, y| result << x * y } # For just the one operation
sum = 0
a.zip(b) { |x, y| sum += x * y } # For both operations |
As the compiler is telling you, you need to change your return type to IEnumerable<TextBox>. That is how the yield return syntax works. |
Ruby has a <code>map</code> method (a.k.a. the <code>collect</code> method), which can be applied to any <code>Enumerable</code> object. If <code>numbers</code> is an array of numbers, the following line in Ruby:
numbers.map{|x| x + 5}
is the equivalent of the following line in Python:
map(lambda x: x + 5, numbers)
For more details, see [here][1] or [here][2].
[1]: http://www.globalnerdy.com/2008/06/25/enumerating-enumerable-enumerablecollectenumerablemap/ "Enumerable#collect / Enumerable#map"
[2]: http://www.ruby-doc.org/core/classes/Enumerable.html#M001146 |
Justification for Reflection in C# |
|c#|.net|reflection| |