instruction stringlengths 0 30k ⌀ |
|---|
it's a list of public objects of that module -- it overrides the default of hiding everything that begins with an underscore |
There are several other answers already, but I'd like to show you the approach I took to solve it:
First, let's check out how Stack Overflow handles normal cases and edge cases. Each of my pages displays 10 results, so to find out what it does for 1 page, find a tag that has less than 11 entries: [usability][1] works today. We can see nothing is displayed, which makes sense.
How about 2 pages? Find a tag that has between 11 and 20 entries ([emacs][2] works today). We see: "**1** 2 Next" or "Prev 1 **2**", depending on which page we're on.
3 pages? "**1** 2 3 ... 3 Next", "Prev 1 **2** 3 Next", and "Prev 1 ... 2 **3**". Interestingly, we can see that Stack Overflow itself doesn't handle this edge case very well: it should display "**1** 2 ... 3 Next"
4 pages? "**1** 2 3 ... 4 Next", "Prev 1 **2** 3 ... 4 Next", "Prev 1 ... 2 **3** 4 Next" and "Prev 1 ... 3 **4**"
Finally let's look at the general case, N pages: "**1** 2 3 ... N Next", "Prev 1 **2** 3 ... N Next", "Prev 1 ... 2 **3** 4 ... N Next", "Prev 1 ... 3 **4** 5 ... N Next", etc.
Let's generalize based on what we've seen:
The algorithm seems to have these traits in common:
- If we're not on the first page, display link to Prev
- Always display the first page number
- Always display the current page number
- Always display the page before this page, and the page after this page.
- Always display the last page number
- If we're not on the last page, display link to Next
Let's ignore the edge case of a single page and make a good first attempt at the algorithm: (As has been mentioned, the code to actually print out the links would be more complicated. Imagine each place we place a page number, Prev or Next as a function call that will return the correct URL.)
function printPageLinksFirstTry(num totalPages, num currentPage)
if ( currentPage > 1 )
print "Prev"
print "1"
print "..."
print currentPages - 1
print currentPages
print currentPages + 1
print "..."
print totalPages
if ( currentPage < totalPages )
print "Next"
endFunction
This function works ok, but it doesn't take into account whether we're near the first or last page. Looking at the above examples, we only want to display the ... if the current page is two or more away.
function printPageLinksHandleCloseToEnds(num totalPages, num currentPage)
if ( currentPage > 1 )
print "Prev"
print "1"
if ( currentPage > 2 )
print "..."
if ( currentPage > 2 )
print currentPages - 1
print currentPages
if ( currentPage < totalPages - 1 )
print currentPages + 1
if ( currentPage < totalPages - 1 )
print "..."
print totalPages
if ( currentPage < totalPages )
print "Next"
endFunction
As you can see, we have some duplication here. We can go ahead and clean that up for readibility:
function printPageLinksCleanedUp(num totalPages, num currentPage)
if ( currentPage > 1 )
print "Prev"
print "1"
if ( currentPage > 2 )
print "..."
print currentPages - 1
print currentPages
if ( currentPage < totalPages - 1 )
print currentPages + 1
print "..."
print totalPages
if ( currentPage < totalPages )
print "Next"
endFunction
There are only two problems left. First, we don't print out correctly for one page, and secondly, we'll print out "1" twice if we're on the first or last page. Let's clean those both up in one go:
function printPageLinksFinal(num totalPages, num currentPage)
if ( totalPages == 1 )
return
if ( currentPage > 1 )
print "Prev"
print "1"
if ( currentPage > 2 )
print "..."
print currentPages - 1
if ( currentPage != 1 and currentPage != totalPages )
print currentPage
if ( currentPage < totalPages - 1 )
print currentPages + 1
print "..."
print totalPages
if ( currentPage < totalPages )
print "Next"
endFunction
Actually, I lied: We have one remaining issue. When you have at least 4 pages and are on the first or last page, you get an extra page in your display. Instead of "**1** 2 ... 10 Next" you get "**1** 2 3 ... 10 Next". To match what's going on at Stack Overflow exactly, you'll have to check for this situation:
function printPageLinksFinalReally(num totalPages, num currentPage)
if ( totalPages == 1 )
return
if ( currentPage > 1 )
print "Prev"
print "1"
if ( currentPage > 2 )
print "..."
if ( currentPage == totalPages and totalPages > 3 )
print currentPage - 2
print currentPage - 1
if ( currentPage != 1 and currentPage != totalPages )
print currentPage
if ( currentPage < totalPages - 1 )
print currentPages + 1
if ( currentPage == 1 and totalPages > 3 )
print currentPage + 2
print "..."
print totalPages
if ( currentPage < totalPages )
print "Next"
endFunction
I hope this helps!
[1]: http://stackoverflow.com/questions/tagged/usability
[2]: http://stackoverflow.com/questions/tagged/emacs |
Are you executing the programs directly or going through the shell? If you always launch an external program by giving the full path name to the executable and leaving the shell out of the equation, then you aren't really susceptible to any kind of command line injection. |
The rule of thumb is to use the function most suited to your needs.
If you just want the keys and do not plan to ever *read* any of the values, use keys():
foreach my $key (keys %hash) { ... }
If you just want the values, use values():
foreach my $val (values %hash) { ... }
If you need the keys *and* the values, use each():
while(my($k, $v) = each %hash) { ... }
If you plan to change the keys of the hash in any way *except* for deleting the current key during the iteration, then you must not use each(). For example, this code to create a new set of uppercase keys with doubled values works fine using keys():
%h = (a => 1, b => 2);
foreach my $k (keys %h)
{
$h{uc $k} = $h{$k} * 2;
}
producing the expected resulting hash:
(a => 1, A => 2, b => 2, B => 4)
But using each() to do the same thing:
%h = (a => 1, b => 2);
while(my($k, $v) = each %h)
{
$h{uc $k} = $h{$k} * 2; # BAD IDEA!
}
produces incorrect results in hard-to-predict ways. For example:
(a => 1, A => 2, b => 2, B => 8)
This, however, is safe:
while(my($k, $v) = each %h)
{
if(...)
{
delete $h{$k}; # This is safe
}
}
All of this is described in the perl documentation:
% perldoc -f keys
% perldoc -f each |
Or, using a little jQuery:
$('#fieldID').css('background-color', '#FF6600'); |
Big O gives the upper bound for time complexity of an algorithm. It is usually used in conjunction with processing data sets (lists) but can be used elsewhere.
A few examples of how it's used in C code.
Say we have an array of n elements
int array[n];
If we wanted to access the first element of the array this would be O(1) since it doesn't matter how big the array is, it always takes the same constant time to get the first item.
x = array[0];
If we wanted to find a number in the list:
for(int i = 0; i < n; i++){
if(array[i] == numToFind){ return i; }
}
This would be O(n) since at most we would have to look through the entire list to find our number. The Big-O is still O(n) even though we might find our number the first try and run through the loop once because Big-O describes the upper bound for an algorithm (omega is for lower bound and theta is for tight bound).
When we get to nested loops:
for(int i = 0; i < n; i++){
for(int j = i; j < n; j++){
array[j] += 2;
}
}
This is O(n^2) since for each pass of the outer loop ( O(n) ) we have to go through the entire list again so the n's multiply leaving us with n squared.
This is barely scratching the surface but when you get to analyzing more complex algorithms complex math involving proofs comes into play. Hope this familiarizes you with the basics at least though. |
Instead of learning APIs to each map service provider ( like Gmaps, Ymaps api) Its good to learn [Mapstraction][1]
"Mapstraction is a library that provides a common API for various javascript mapping APIs"
I would suggest you go to the URL and learn a general API. There is good amount of How-Tos too.
[1]: http://www.mapstraction.com/doc/ |
The previous answer is fine, but I'm one of those guys that's firmly against mixing behavior with presentation (putting JavaScript in my HTML) so I prefer to put my event handling logic in my JavaScript files. Additionally, not all browsers implement event (or e) the same way. You may want to do a check prior to running any logic:
document.onkeydown = TabExample;
function TabExample(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
if(evt.keycode == 9) {
// do work
}
} |
It may be easier to serialise the classes to/from xml, you can then simply pass the XmlReader (which is reading your config file) to the deserializer and it will do the rest for you..
[This is a pretty good article on serialization](http://www.diranieh.com/NETSerialization/XMLSerialization.htm) |
It may be easier to serialise the classes to/from xml, you can then simply pass the XmlReader (which is reading your config file) to the deserializer and it will do the rest for you..
[This is a pretty good article on serialization](http://www.diranieh.com/NETSerialization/XMLSerialization.htm)
##Edit
One thing I would like to add, even though reflection is powerful, it requires you to know some stuff about the type, such as parameters etc.
Serializing to XML doesnt need any of that, and you can still have type safety by ensuring you write the fully qualified type name to the XML file, so the same type is automatically loaded. |
I have experimented a little with the BDD approach and my premature conclusion is that BDD is well suited to use case implementation, but not on the underlying details. TDD still rock on that level.
BDD is also used as a communication tool. The goal is to write executable specifications which can be understood by the domain experts. |
hmm, if you've serialized an object with the `StudentId` property then I think that it will be:
var studentId;
function(json) {
if (json.length > 0)
studentId = json[0].StudentId;
}
But if you're just returning the `StudentId` itself maybe it's:
var studentId;
function(json) {
if (json.length > 0)
studentId = json[0];
}
Edit: Or maybe `.length` isn't even required (I've only returned generic collections in JSON). |
hmm, if you've serialized an object with the `StudentId` property then I think that it will be:
var studentId;
function(json) {
if (json.length > 0)
studentId = json[0].StudentId;
}
But if you're just returning the `StudentId` itself maybe it's:
var studentId;
function(json) {
if (json.length > 0)
studentId = json[0];
}
Edit: Or maybe `.length` isn't even required (I've only returned generic collections in JSON).
Edit #2, this works, I just tested:
var studentId;
jQuery.getJSON(url, data, function(json) {
if (json)
studentId = json;
});
Edit #3, here's the actual JS I used:
$.ajax({
type: "POST",
url: pageName + "/GetStudentTest",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{id: '" + someId + "'}",
success: function(json) {
alert(json);
}
});
And in the aspx.vb:
<System.Web.Services.WebMethod()> _
<System.Web.Script.Services.ScriptMethod()> _
Public Shared Function GetStudentTest(ByVal id As String) As Integer
Return 42
End Function |
RoR is actually one of the things the GWT is made to work well with, as long as you're using REST properly. It's in the Google Web Toolkit Applications book, and you can see a demo from the book using this kind of idea [here][1]. That's not to say that you won't have any problems, but I think the support is definitely out there for it.
[1]: http://www.gwtapps.com/?page_id=33 |
Using Guids as primary keys is acceptable and is considered a fairly standard practice for the same reasons that you are considering them. They can be overused which can make things a bit tedious to debug and manage, so try to keep them out of code tables and other reference data if at all possible.
The thing that you have to concern yourself with is the human readable identifier. Guids cannot be exchanged by people - can you imagine trying to confirm your order number over the phone if it is a guid? So in an offline scenario you may still have to generate **something** - like a publisher (workstation/user) id and some sequence number, so the order number may be 123-5678 <publisher>-<seq>.
However this may not satisfy business requirements of having a sequential number. In fact regulatory requirements can be and influence - some regulations (SOX maybe) require that invoice numbers are sequential. In such cases it may be neccessary to generate a sort of proforma number which is fixed up later when the systems synchronise. You may land up with tables having OrderId (Guid), OrderNo (int), ProformaOrderNo (varchar) - some complexity may creep in. |
Using Guids as primary keys is acceptable and is considered a fairly standard practice for the same reasons that you are considering them. They can be overused which can make things a bit tedious to debug and manage, so try to keep them out of code tables and other reference data if at all possible.
The thing that you have to concern yourself with is the human readable identifier. Guids cannot be exchanged by people - can you imagine trying to confirm your order number over the phone if it is a guid? So in an offline scenario you may still have to generate **something** - like a publisher (workstation/user) id and some sequence number, so the order number may be 123-5678 <publisher>-<seq>.
However this may not satisfy business requirements of having a sequential number. In fact regulatory requirements can be and influence - some regulations (SOX maybe) require that invoice numbers are sequential. In such cases it may be neccessary to generate a sort of proforma number which is fixed up later when the systems synchronise. You may land up with tables having OrderId (Guid), OrderNo (int), ProformaOrderNo (varchar) - some complexity may creep in.
At least having guids as primary keys means that you don't have to do a whole lot of cascading updates when the sync does eventually happen - you simply update the human readable number. |
Eric Lippert did a series of articles on creating a [C# implemention of A*][1], which might be more efficient.
[1]: http://blogs.msdn.com/ericlippert/archive/tags/AStar/default.aspx |
You should post more information.
For instance, is this C#? It looks like it, but I might be wrong.
Also, you say you get an exception, what is the exception type and message?
In any case, you can't redirect to a page for POST, you need to submit it from the browser, not from the server redirect, so if you want to automate this, I would guess you would need to generate a html page with a form tag, with some hidden input fields, and then submit it with javascript. |
sql missing rows when grouped by DAY, MONTH, YEAR |
|t-sql|date|grouping| |
RoR is actually one of the things the GWT is made to work well with, as long as you're using REST properly. It's in the Google Web Toolkit Applications book, and you can see a demo from the book using this kind of idea [here][1]. That's not to say that you won't have any problems, but I think the support is definitely out there for it.
There's a neat project for making RoR/GWT easy that you can find [here][2] (MIT license). I haven't had a chance to try it out yet, but it looks like a good amount of thought has been put into it. One catch is that it looks like it hasn't been fully tested with 2.1 Rails yet, just 2.0, so you may run into a few (probably minor and fixable) errors.
[1]: http://www.gwtapps.com/?page_id=33
[2]: http://code.google.com/p/gwt-on-rails/ |
Don't forget refactoring support. ReSharper on .NET provides automatic refactoring and quick fixes for missing code. That means if you write a call to something that does not exist, ReSharper will ask if you want to create the missing piece. |
VMWare Tools for Ubuntu Hardy |
|vmware-tools|ubuntu|hardy|vmware|virtualization| |
I've been having a very tough time with VMWare tools for Ubuntu Hardy.
For some reason, vmware-install.pl finds fault with my linux headers. Saying the "address space size" doesn't match. I have resorted to vmware-any-any-update117 and here is the error I am getting now:
<pre>
In file included from include/asm/page.h:3,
from /tmp/vmware-config0/vmmon-only/common/hostKernel.h:56,
from /tmp/vmware-config0/vmmon-only/common/task.c:30:
include/asm/page_32.h: In function ‘pte_t native_make_pte(long unsigned int)’:
include/asm/page_32.h:112: error: expected primary-expression before ‘)’ token
include/asm/page_32.h:112: error: expected ‘;’ before ‘{’ token
include/asm/page_32.h:112: error: expected primary-expression before ‘.’ token
include/asm/page_32.h:112: error: expected `;' before ‘}’ token
</pre>
|
|vmware|ubuntu|virtualization|vmware-tools| |
You're on the right track.
Cocoa's collection classes — which all have mutable an immutable variants — are:
- NSArray: ordered, can contain an object multiple times
- NSDictionary: unordered, mapping from keys to values, keys are copied
- NSSet: unordered, can contain an object only once
- NSCountedSet: unordered, can contain an object multiple times
The immutable variants help a lot with efficiency. The standard pattern for accessors of classes that have mutable variants is to copy rather than retain. This is codified in the `@property` mechanism, by using the `copy` attribute on the property:
// Department.h
@interface Department : NSObject
@property (readwrite, copy) NSSet *employees;
@end
This means that if you pass a mutable array to something that takes an array, it will be copied, and if you pass that to something else, it will be copied again. The trick is though that "copying" an immutable object really just retains it, so you only take a hit for that first copy. You probably **want** to make a copy that first time anyway so you don't pass a mutable array to something else, then mutate it behind the back of whatever you passed it to.
For Cocoa on Mac OS X, I'd also strongly encourage you to take a look at Core Data. It's an alternative to the "data set" pattern you might be used to from .NET/ADO/etc. With Core Data, you don't "get all customers" and then pass that collection around. Instead you query for the customers you care about, and as you traverse relationships of the objects you've queried for, other objects will be pulled in for you automatically.
Core Data also gets you features like visual modeling of your entities, automatic generation of property getters & setters, fine-grained control over migration from one schema version to another, and so on. |
A short list might be:
- Avoid memory leaks through use shared pointers to manage memory allocation and cleanup
- Use the Resource Acquisition is Initialization (RAII) idiom to manage resource cleanup - especially in the presence of exceptions
- Avoid calling virtual functions in constructors
- Employ minimalist coding techniques where possible - for example declaring variables only when needed, scoping variables, early-out design where possible.
- Truly understand the exception handling in your code - both with regard to exceptions you throw, as well as ones thrown by classes you may be using indirectly. This is especially important in the presence of templates.
RAII, shared pointers and minimalist coding are of course not specific to C++, but they help avoid problems that do frequently crop up when developing in the language.
Some excellent books on this subject are:
- Effective C++ - Scott Meyers
- More Effective C++ - Scott Meyers
- C++ Coding Standards - Sutter & Alexandrescu
- C++ FAQs - Cline
Reading these books has helped me more than anything else to avoid the kind of pitfalls you are asking about. |
Try IE7.js. Should fix your problem without having to make any modifications.
Link: [IE7.js][1]
[1]: http://code.google.com/p/ie7-js/ |
There is a very rough percentage of browsers with *some* JRE available at [The Counter][1], though I wouldn't trust it. Sun has a few useful [stats from 2007][2], but their [stats from 2008][3] are much less detailed. They suggest that in 2007 "92%...of JRE installs...are now Java SE 6", but who knows what highly technical site they surveyed to get that number.
[1]: http://www.thecounter.com/stats/2008/August/java.php
[2]: http://www.sun.com/aboutsun/media/presskits/javaone2007/index.jsp#stats
[3]: http://www.sun.com/aboutsun/media/presskits/javaone2008/index.jsp#stats |
The most important pitfalls for beginning developers is to avoid confusion between C and C++. C++ should never be treated as a mere better C or C with classes because this prunes its power and can make it even dangerous (especially when using memory as in C). |
I would go with a 1 GB for /boot, 100 GB for /, and the rest for /home. 1 GB is probably too high for /boot, but it's not like you'll miss it. 100 GB might seem like a lot for everything outside home, until you start messing around with Databases and realize that MySQL keeps databases in /var. Best to leave some room to grow in that area. The reason that I recommend using a separtate partition for /home, is that when you want to completely switch distros, or if the upgrade option on your distro of choice, for whatever reason doesn't work, or if you just want to start from scratch and do a clean system install, you can just format / and /boot, and leave home with all the user data intact. |
yes, vs2008 can "[target](http://weblogs.asp.net/scottgu/archive/2007/06/20/vs-2008-multi-targeting-support.aspx)" a framework, but i think by default, if converting from vs2005 - vs2008 it just keeps it at framework 2.0 |
There's also Exchange Web Services in newer versions of Exchange.
If you need to use Outlook Express and talk to an Exchange server which doesn't support IMAP/POP3, you're stuck, sadly. |
A magic number is a sequence of characters at the start of a file format, or protocol exchange. This number serves as a sanity check.
Example:
Open up any GIF file, you will see at the very start: GIF89. "GIF89" being the magic number.
Other programs can read the first few characters of a file and properly identify GIFs.
The danger is that random binary data can contain these same characters. But it is very unlikely.
As for protocol exchange, you can use it to quickly identify that the current 'message' that is being passed to you is corrupted or not valid.
Magic numbers are still useful. |
SEO Superstitions: Are <script> tags really bad? |
|seo| |
We have an SEO team at my office, and one of their dictums is that having lots of <script> blocks inline with the HTML is apocalypticly bad. As a developer that makes no sense to me at all. Surely the Google search engineers, who are the smartest people on the planet, know how to skip over such blocks? <br />
My gut instinct is that minimizing script blocks is a superstition that comes from the early ages of search engine optimizations, and that in today's world it means nothing. Does anyone have any insight on this? |
@kronoz
I would say YES.
The neat thing about MSBuild is that if you modify your csproj files to include custom build steps then those steps will happen from within VS or from MSBuild. Also if you ever have a build server you will not need to install full VS, only the SDK to build your projects. |
Have you taken a look at the wikipedia entry for [magic number?][1]
It goes into a bit of detail about all of the ways the magic number reference is made. Here's a quote about magic number as a bad programming practice
> The term magic number also refers to the bad programming practice of using numbers directly in source code without explanation. In most cases this makes programs harder to read, understand, and maintain. Although most guides make an exception for the numbers zero and one, it is a good idea to define all other numbers in code as named constants.
[1]: http://en.wikipedia.org/wiki/Magic_number_(programming) |
I assume this is a response to my [answer][1] to your earlier question. In programming, a magic number is an embedded numerical constant that appears without explanation. If it appears in two distinct locations, it can lead to circumstances where one instance is changed and not another. For both these reasons, it's important to isolate and define the numerical constants outside the places where they're used.
[1]: http://stackoverflow.com/questions/47878/codereview-tiny-encryption-algorithm-for-arbitrary-sized-data#47880 |
A Magic Number is a hardcoded value that may change at a later stage, but that can be therefore hard to update.
For example, let's say you have a Page that displays the last 50 Orders in a "Your Orders" Overview Page. 50 is the Magic Number here, because it's not set through standard or convention, it's a number that you made up for reasons outlined in the spec.
Now, what you do is you have the 50 in different places - your SQL script (SELECT TOP 50 * FROM orders), your Website (Your Last 50 Orders), your order login (for i=0;i<50;i++) and possibly many other places.
Now, what happens when someone decides to change 50 to 25? or 75? or 153? You now have to replace the 50 in all the places, and you are very likely to miss it. Find/Replace may not work, because 50 may be used for other things, and blindly replacing 50 with 25 can have some other bad side effects (i.e. your Session.Timeout = 50 call, which is also set to 25 and users start reporting too frequent timeouts).
Also, the code can be hard to understand, i.e. "if a < 50 then bla" - if you encounter that in the middle of a complicated function, other developers who are not familiar with the code may ask themselves "WTF is 50???"
That's why it's best to have such ambigous and arbitary numbers in exactly 1 place - "const int NumOrdersToDisplay = 50", because that makes the code more readable ("if a < NumOrdersToDisplay", it also means you only need to change it in 1 well defined place.
Places where Magic Numbers are appropriate is everything that is defined through a standard, i.e. SmtpClient.DefaultPort = 25 or TCPPacketSize = whatever (not sure if that is standardized). Also, everything only defined within 1 function might be acceptable, but that depends on Context. |
Are you executing the programs directly or going through the shell? If you always launch an external program by giving the full path name to the executable and leaving the shell out of the equation, then you aren't really susceptible to any kind of command line injection.
EDIT: DrFloyd, the shell is responsible for evaluating things like the backtick. No shell, no shell evaluation. Obviously, you've still got to be aware of any potential security gotchas in the programs that you're calling -- but I don't think this question is about that.
|
Substitution Control at the User Control Level? |
|asp.net|caching|user-controls| |
I am trying to create some cached user controls. Basically Header and Footer are static.
Except the footer has one link that reads in the url of the page and puts it into the javascript for sending a link to a friend. So I need that link to be dynamic.
I set up a substitution control and had the static method return the dynamic link.
Go to run and find that substitution controls are not supported at the user control level.
Is there any work around to this? Is there another control like substitution that works on the User Controls that I am not aware of? |
@Orion Edwards
I take your point about an exception being thrown in the finally block.
However, I think there is a way - using yet another thread - of using this exception-as-interrupt idea.
Thread A:
At some random time, throw an exception on thread C:
Thread B:
try {
Signal thread C that exceptions may be thrown
//do stuff, without needing to check exit conditions
Signal thread C that exceptions may no longer be thrown
}
catch {
// exception/interrupt occurred handle...
}
finally {
// ...and clean up
CloseResourceOne();
CloseResourceTwo();
}
Thread C:
while(thread-B-wants-exceptions) {
try {
Thread.Sleep(1)
}
catch {
// exception was thrown...
if Thread B still wants to handle exceptions
throw-in-B
}
}
Or is that just silly?
|
Yes, you can.
The boost.ptr_container library provides polymorphic value semantic versions of the standard containers. You only have to pass in a pointer to a heap-allocated object, and the container will take ownership and all further operations will provide value semantics , except for reclaiming ownership, which gives you almost all the benefits of value semantics by using a smart pointer. |
If you have a mix of unix and Windows users working with the repository, I urge you to use the *[case-insensitive.py][1]* pre-commit hook-script as a precautionary measure. It prevents hard-to-sort-out situations where svn [updates fail for Windows users because of a file rename which only changed the case of the file name][2]. Believe me, there is a good chance it will save you trouble.
[1]: http://svn.collab.net/viewvc/svn/trunk/contrib/hook-scripts/case-insensitive.py?view=markup
[2]: http://subversion.tigris.org/faq.html#case-change |
@[Domenic][1], I've considered, but I'd prefer to stay legal, and I'm fairly sure the information would have to be embedded into the framework anyway.
[1]: http://stackoverflow.com/questions/44795/how-can-i-determine-whether-a-given-date-is-in-daylight-saving-time-for-a-given#44819 |
I'm late to this party, so my first choices are already taken. But I didn't see anyone mention this gem yet:
[Parallel Extensions to the .Net Framework][1]
It has things like replace with Parallel.For or foreach with Parallel.ForEach
[1]: http://msdn.microsoft.com/en-us/concurrency/default.aspx |
Fast SQL Server 2005 script generation |
|sql-server|scripting| |
It seems like the generation of SQL scripts from the SQL Server Management Studio is terribly slow. I think that the old Enterprise Manager could run laps around the newer script generation tool. I've seen a few posts here and there with other folks complaining about the speed, but I haven't seen much offered in the way of alternatives.
Is there a low-cost/free tool for scripting an entire SQL Server 2005 database that will perform better that SSMS? It would be hard to do worse. |
Cannot access a webservice from mobile device |
|mobile| |
I developed a program in a mobile device (Pocket PC 2003) to access a web service, the web service is installed on a Windows XP SP2 PC with IIS, the PC has the IP 192.168.5.2.
The device obtains from the wireless network the IP 192.168.5.118 and the program works OK, it calls the method from the web service and executes the action that is needed. This program is going to be used in various buildings.
Now I have this problem, it turns that when I try to test it in another building (distances neraly about 100 mts. or 200 mts.) connected with the network, the program cannot connect to the webservice, at this moment the device gets from an Access Point the IP 192.168.10.25, and it accesses the same XP machine I stated before (192.168.5.2). I made a mobile aspx page to verify that I can reach the web server over the network and it loads it in the device, I even made a winform that access the same webservice in a PC from that building and also works there so I don't understand what is going on. I also tried to ping that 192.168.5.2 PC and it responds alive.
After that fail I returned to the original place where I tested the program before and it happens that it works normally.
The only thing that I look different here is that the third number in the IP is 10 instead of 5, another observation is that I can't ping to the mobile device. I feel confused I don't know what happens here? What could be the problem?
This is how I call the web service;
//Connect to webservice
svc = new TheWebService();
svc.Credentials = new System.Net.NetworkCredential(Settings.UserName, Settings.Password);
svc.AllowAutoRedirect = false;
svc.UserAgent = Settings.UserAgent;
svc.PreAuthenticate = true;
svc.Url = Settings.Url;
svc.Timeout = System.Threading.Timeout.Infinite;
//Send information to webservice
svc.ExecuteMethod(info);
the content of the app.config in the mobile device is;
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="UserName" value="administrator" />
<add key="Password" value="************" />
<add key="UserAgent" value="My User Agent" />
<add key="Url" value="http://192.168.5.2/WebServices/TWUD.asmx" />
</appSettings>
</configuration>
Does anyone have an idea what is going on? |
If I select from a table group by the month, day, year,
it only returns rows with records and leaves out combinations without any records, making it appear at a glance that every day or month has activity, you have to look at the date column actively for gaps. How can I get a row for every day/month/year, even when no data is present, in T-SQL? |
@pek - That won't work, as your array keys are 0 and 1, not 'home' and 'page'.
This code should do the trick, I believe:
<?php
$whitelist = array(
'home',
'page',
);
if(in_array($_GET['page'], $whitelist)) {
include($_GET['page'] . '.php');
} else {
include('home.php');
}
?>
As you've a whitelist, there shouldn't be a need for `file_exists()` either. |
First thought that comes to mind: Hasn't MS designed the DataSet and DataAdapter model to support scenarios like this?
I believe I read that MS changed their ADO recordset model to the current DataSet model so it works great offline too. And there's also this [Sync Services for ADO.NET][1]
I believe I have seen code that utilizes the DataSet model which also uses foreign keys and they still sync perfectly when using the DataAdapter. Havn't try out the Sync Services though but I think you might be able to benefit from that too.
Hope this helps.
[1]: http://msdn.microsoft.com/en-us/sync/bb887608.aspx |
Create a calendar table and outer join on that table |
Google Chrome looks promising. It is of course in an early beta so it's missing a lot of the things people would need or at least feel they need, like plugins, cross-machine synchronization of data (could be done with plugins), cross-platform support (ie. Linux and Mac versions).
So far it renders Gmail like a bat out of hell, so I'm going to pay very close attention to it.
---
**Edit**: In fact, these posts are done using it, and except for some minor issues like smaller font in input fields, it works as I expect it to. Fast, stable (already tested it with a javascript killer-page I have for some test applications). |
I've had luck just copying `signons2.txt` and `key3.db` over from one profile to another. See also [the documentation on MozillaZine][1].
[1]: http://kb.mozillazine.org/Signons.txt |
I think they mean they don't want you to use URL parameters (GET). If you use http headers, it's not really querying through POST any more. |
What language/framework?
Using Python and httplib2, you should be able to do something like:
http = httplib2.Http()
http.request(url, 'POST', headers={'key': 'value'}, body=urllib.urlencode(''))
|
By default (i.e. out of the box) net.tcp services are unsecured and don't perform any authentication at all. So you won't need (and in fact can't) set a service principal name.
If you need to authenticate, then check the [net.tcp security][1] modes on MSDN. The best way to understand the different combinations is to experiment!
[1]: http://msdn.microsoft.com/en-us/library/system.servicemodel.nettcpsecurity.aspx |
I believe that the Request object would only accept a certain set of predefined headers.
There's an enumeration that lists all the supported HTTP Headers too.
But I can't remember it at the moment... I'll look it up in a sec... |
[Hotwire](http://hotwire-shell.org) is an attempt to combine the power of the traditional command line interface with GUI elements. So it has a GUI side, and tries to be helpful in suggesting commands, and in showing you possible matches from your history. (While there are keyboard shortcuts to do this in bash and other shells, you have to know them ...)
You can use all your common system commands, but a number of key ones have new versions by default which use an object pipeline, and are displayed with a nice GUI view. In particular ls (aka dir) shows lists files and shows them in columns. You can sort by clicking on the column headers, double click on files to open, or double click on directories to move to that directory. The proc command allows you to right click on a process and one of the options is to kill it.
The object pipeline works in a similar way to Microsoft Powershell, allowing commands in the pipe to access object properties directly rather than having to do text processing to extract it.
Hotwire is cross platform ([Linux, BSD](http://code.google.com/p/hotwire-shell/wiki/HotwireUnixLinux), [Windows](http://code.google.com/p/hotwire-shell/wiki/HotwireWindows), [Mac](http://code.google.com/p/hotwire-shell/wiki/HotwireMacOSX)), though it is at an early stage of development. To learn more, install (click on the link for your platform) and work through the simple [getting started](http://code.google.com/p/hotwire-shell/wiki/GettingStarted0700) page.
If you don't like hotwire, you could also look at the list of [related projects and ideas](http://code.google.com/p/hotwire-shell/wiki/RelatedProjectsAndIdeas) maintained on the hotwire wiki. |
It is possible to have a 2.0 project in VS 2008. You would just target .NET Framework 2.0 under the project properties.
Your solution will have to be converted to a VS9 solution however. |
The best way to learn anything is to start with the basic. You can find any good text book to explain what programming is, memory, algorithms.
The next step select the language which it just depends on what the teacher knows or why the student wants to learn.
Then it is just code, code, code. Code every example right from the book. Then change it slightly to do another action. Learning to program is an active process not a passive one. You can't just read C++ How to Program by Dietal and then expect to code C++ without having actively done it while reading.
Even if you are an experienced coder it helps to write the code in the book to learn something new. |
Yes you can run 2.0 with VS2008. Be sure to select that when you convert, however. When converting a project, I mistakenly left in the ASP.NET 3.5 conversion, and then all new files contained references to Linq, so it was a little bit of a pain to switch back to 2.0 when I realized the mistake. |
tesseract interface |
|c#|tesseract| |
How do you OCR an tiff file using tesseract's interface in c#? Currently only know how to do it using the executable. |
OCR with the Tesseract interface |
|c#|ocr|tesseract| |
To summarize:
This behavior will be going away in version 1.9, in which the character itself is returned, but in previous versions, trying to reference a single character of a string by it's character posision will return its character value (so "ABC"[2] returns 67)
There are a number of methods that return a range of characters from a string (see the Ruby docs on the String [slice method][1]) All of the following return "C":
"ABC"[2,1]
"ABC"[2..2]
"ABC".slice(2,1)
I find the range selector to be the easiest to read. Can anyone speak to whether it is less efficient?
[1]: http://www.ruby-doc.org/core/classes/String.html#M000786 |
Note that the performance of Enum.Parse() is awful, because it is implemented via reflection. (The same is true of Enum.ToString, which goes the other way.)
If you need to convert strings to Enums in performance-sensitive code, your best bet is to create a `Dictionary<String,YourEnum>` at startup and use that to do your conversions. |
I've had success with running a wget and sending the result to /dev/null on a shared server. |
@SCdF is correct. From [the horse's mouth][1]:
> A Macromedia Flash movie cannot
> communicate directly with a database.
> However, Macromedia Flash movies can
> "talk" to server-side applications
> (also referred to as "middleware").
> Middleware can query a database and
> relay data back and forth. There are
> many server applications available.
> Some of the most common are CGI, ASP,
> PHP, ColdFusion and Tango.
[1]: http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_14482&sliceId=2 |
[@SCdF][1] is correct. From [the horse's mouth][2]:
> A Macromedia Flash movie cannot
> communicate directly with a database.
> However, Macromedia Flash movies can
> "talk" to server-side applications
> (also referred to as "middleware").
> Middleware can query a database and
> relay data back and forth. There are
> many server applications available.
> Some of the most common are CGI, ASP,
> PHP, ColdFusion and Tango.
[1]: http://stackoverflow.com/questions/38674/does-adobe-flash-support-databases#38675
[2]: http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_14482&sliceId=2 |
LINQ to SQL doesn't really have a n-tier story that I've seen, since the objects that it creates are created in the class with the rest of it, you don't really have an assembly that you can nicely reference through something like Web Services, etc.
The only way I'd really consider it is using the datacontext to fetch data, then fill an intermediary data model, passing that through, and referencing it on both sides, and using that in your client side - then passing them back and pushing the data back into a new Datacontext or intellgently updating rows after you refetch them.
That's if I'm understanding what you're trying to get at :\
I asked ScottGu the same question on his blog when I first started looking at it - but I haven't seen a single scenario or app in the wild that uses LINQ to SQL in this way. Websites like Rob Connery's Storefront are closer to the provider. |
Batch (NT):
@echo off
set n=%1
set result=1
for /l %%i in (%n%, -1, 1) do (
set /a result=result * %%i
)
echo %result%
Usage:
C:\>factorial.bat 15 |
You have four options that I can think of, three of which have already been named by others:
1. Go the factory route, as suggested by several others here. One disadvantage to this is that you can't have consistent naming via overloading (or else you'd have the same problem), so it's superficially less clean. Another, larger, disadvantage is that it precludes the possibility of allocating directly on the stack. Everything will be allocated on the heap if you take this approach.
2. Custom object wrappers. This is a good approach, and the one I would recommend if you are starting from scratch. If you have a lot of code using, e.g., badges as strings, then rewriting code may make this a non-viable option.
3. Add an enumeration to the method, specifying how to treat the string. This works, but requires that you rewrite all the existing calls to include the new enumeration (though you can provide a default if desired to avoid some of this).
4. Add a dummy parameter that is unused to distinguish between the two overloads. e.g. Tack a `bool` onto the method. This approach is taken by the standard library in a few places, e.g. `std::nothrow` is a dummy parameter for `operator new`. The disadvantages of this approach are that it's ugly and that it doesn't scale.
If you already have a large base of existing code, I'd recommend either adding the enumeration (possibly with a default value) or adding the dummy parameter. Neither is beautiful, but both are fairly simple to retrofit.
If you are starting from scratch, or only have a small amount of code, I'd recommend the custom object wrappers.
The factory methods would be an option if you have code which heavily uses the raw `badge`/`logonName` strings, but doesn't heavily use the `Person` class. |
Ok, I've solved my own problem.
To get that "authdata" string, you need to configure your client to how you need to authenticate.
Then navigate to c:\[users directory]\[username]\Local Settings\Application Data\plastic.
Pick up the client.conf and extract the string from the SecurityConfig element in the XML. |
I don't know what is "terribly slow" for you, but I have a decent performance with SQL 2005 Management Studio. In either case, [RedGate][1] products are very cool. Unfortunately it's not free.
[1]: http://www.red-gate.com/ |
I guess you have considered the reads of Scott Ambler?
http://www.agiledata.org/essays/databaseRefactoring.html
|
I used the draggable search in Spy++ (installed with VS) to look at the split open button on the file-open dialog of VS.
This revealed that it's an ordinary windows button with a style which includes BS_DEFSPLITBUTTON. That's a magic keyword which gets you to some interesting places, including
http://www.codeplex.com/windowsformsaero/SourceControl/FileView.aspx?itemId=212902&changeSetId=9930
and here
http://msdn.microsoft.com/en-us/library/bb775949(VS.85).aspx
Hope this helps you.
|
I used the draggable search in Spy++ (installed with VS) to look at the split open button on the file-open dialog of VS.
This revealed that it's an ordinary windows button with a style which includes BS_DEFSPLITBUTTON. That's a magic keyword which gets you to some interesting places, including
http://www.codeplex.com/windowsformsaero/SourceControl/FileView.aspx?itemId=212902&changeSetId=9930
and here
http://msdn.microsoft.com/en-us/library/bb775949.aspx#using_splits
Hope this helps you.
EDIT:
I've actually just tried that code from CodePlex and it does create a split button - but you do have to make sure you've set the button's FlatStyle to 'System' rather than 'Standard' which is the default. I've not bothered to hook-up the event handling stuff for the drop-down, but that's covered in the MSDN link, I think.
|
These articles may help:
- [Git vs. Mercurial: Please Relax][1] (Git is MacGyver and Mercurial is James Bond)
- [The Differences Between Mercurial and Git][2]
[1]: http://importantshock.wordpress.com/2008/08/07/git-vs-mercurial/
[2]: http://www.rockstarprogrammer.org/post/2008/apr/06/differences-between-mercurial-and-git/ |
At work we use friends extensively for out testing code. It means we can provide proper encapsulation and information hiding for the main application code. But also we can have seperate test code that uses friends to inspect internal state and data for testing.
Suffice to say I wouldn't use the friend keyword as an essential component of your design. |
What logging is good logging for your app? |
|.net|logging|client-applications| |
So we've discussed logging in passing at my place of work and I was wondering if some of you guys here could give me some ideas of your approaches?
Typically our scenario is, no logging really at all, and mostly .NET apps, winforms/WPF clients talking through web services or direct to a db.
So, the real question is, where or what would you log? At the moment we have users reporting error messages - so I would assume log startups/shutdowns, exceptions...
Do you take it to calls to the web services or db? Page loads?
How do you get a good idea of what the user was trying to do at the time?
Is it better to go all the way and log everything across multiple attempts/days, or log only what you need to (given hdd is cheap).
I guess that's a few questions, but I wanted to get more of an idea of what the actual practice is out there in larger shops! |
I think the VB6 units are not the same with the VB.Net one. So you have to do a conversion. |
Sometime last year I evaluated both git and hg for my own use, and decided to go with hg. I felt it looked like a cleaner solution, and worked better on more platforms at the time. It was mostly a toss-up, though.
More recently, I started using git because of git-svn and the ability to act as a Subversion client. This won me over and I've now switched completely to git. I think it's got a slightly higher learning curve (especially if you need to poke around the insides), but it really is a great system. I'm going to go read those two comparison articles that John posted now. |
This is what I use:
def shellquote(s):
return "'" + s.replace("'", "'\\''") + "'"
The shell will always accept a quoted filename and remove the surrounding quotes before passing it to the program in question. Notably, this avoids problems with filenames that contain spaces or any other kind of nasty shell metacharacter. |
Perhaps you have a specific reason for using os.system(). But if not you should probably be using the subprocess [module][1]. You can specify the pipes directly and avoid using the shell.
The following is from [PEP324][2]
> Replacing shell pipe line
> -------------------------
>
> output=`dmesg | grep hda`
> ==>
> p1 = Popen(["dmesg"], stdout=PIPE)
> p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
> output = p2.communicate()[0]
[1]: http://docs.python.org/lib/module-subprocess.html
[2]: http://www.python.org/dev/peps/pep-0324/ |
@[Domenic][1], I've considered, but I'd prefer to stay legal, and I'm fairly sure the information would have to be embedded into the framework anyway, or grabbed from the registry in some sneaky way that doesn't throw exceptions...
[1]: http://stackoverflow.com/questions/44795/how-can-i-determine-whether-a-given-date-is-in-daylight-saving-time-for-a-given#44819 |
@[Domenic][1], I've considered, but I'd prefer to stay legal, and I'm fairly sure the information would have to be embedded into the framework anyway, or grabbed from the registry in some sneaky way that doesn't require permissions...
[1]: http://stackoverflow.com/questions/44795/how-can-i-determine-whether-a-given-date-is-in-daylight-saving-time-for-a-given#44819 |