question_id
int64
4
6.31M
answer_id
int64
7
6.31M
title
stringlengths
9
150
question_body
stringlengths
0
28.8k
answer_body
stringlengths
60
27.2k
question_text
stringlengths
40
28.9k
combined_text
stringlengths
124
39.6k
tags
listlengths
1
6
question_score
int64
0
26.3k
answer_score
int64
0
28.8k
view_count
int64
15
14M
answer_count
int64
0
182
favorite_count
int64
0
32
question_creation_date
stringdate
2008-07-31 21:42:52
2011-06-10 18:12:18
answer_creation_date
stringdate
2008-07-31 22:17:57
2011-06-10 18:14:17
25,614
25,701
Which Java DOM Wrapper is the Best or Most Popular?
I've used jdom in the past, and have looked briefly at XOM and DOM4j. Each seems to provide essentially the same thing, as they each provide a simplified wrapper over the (very obtuse) standard W3C DOM APIs. I know that JDOM went through some effort to develop a JSR and standardization process at one point, but as far as I know that effort never went anywhere. All of the project appear to be in stasis with little new development in the past several years. Is there a consensus as to which is the best? Also what are the pros and cons of each?
I like XOM, because I like the way Elliotte Rusty Harold thinks. Of the ones you mention I belive it's the one that strays away from the DOM standard API:s the most, but I consider that a benefit. I once implemented a DOM library for Cocoa, and XOM was my inspiration. I've worked with JDOM as well, and there's absolutely nothing wrong with it, although I do prefer XOM.
Which Java DOM Wrapper is the Best or Most Popular? I've used jdom in the past, and have looked briefly at XOM and DOM4j. Each seems to provide essentially the same thing, as they each provide a simplified wrapper over the (very obtuse) standard W3C DOM APIs. I know that JDOM went through some effort to develop a JSR and standardization process at one point, but as far as I know that effort never went anywhere. All of the project appear to be in stasis with little new development in the past several years. Is there a consensus as to which is the best? Also what are the pros and cons of each?
TITLE: Which Java DOM Wrapper is the Best or Most Popular? QUESTION: I've used jdom in the past, and have looked briefly at XOM and DOM4j. Each seems to provide essentially the same thing, as they each provide a simplified wrapper over the (very obtuse) standard W3C DOM APIs. I know that JDOM went through some effort to develop a JSR and standardization process at one point, but as far as I know that effort never went anywhere. All of the project appear to be in stasis with little new development in the past several years. Is there a consensus as to which is the best? Also what are the pros and cons of each? ANSWER: I like XOM, because I like the way Elliotte Rusty Harold thinks. Of the ones you mention I belive it's the one that strays away from the DOM standard API:s the most, but I consider that a benefit. I once implemented a DOM library for Cocoa, and XOM was my inspiration. I've worked with JDOM as well, and there's absolutely nothing wrong with it, although I do prefer XOM.
[ "java", "xml", "dom" ]
3
5
2,592
3
0
2008-08-25T03:11:58.497000
2008-08-25T05:52:22.433000
25,637
25,644
Shutting down a computer
Is there a way to shutdown a computer using a built-in Java method?
Create your own function to execute an OS command through the command line? For the sake of an example. But know where and why you'd want to use this as others note. public static void main(String arg[]) throws IOException{ Runtime runtime = Runtime.getRuntime(); Process proc = runtime.exec("shutdown -s -t 0"); System.exit(0); }
Shutting down a computer Is there a way to shutdown a computer using a built-in Java method?
TITLE: Shutting down a computer QUESTION: Is there a way to shutdown a computer using a built-in Java method? ANSWER: Create your own function to execute an OS command through the command line? For the sake of an example. But know where and why you'd want to use this as others note. public static void main(String arg[]) throws IOException{ Runtime runtime = Runtime.getRuntime(); Process proc = runtime.exec("shutdown -s -t 0"); System.exit(0); }
[ "java", "cross-platform", "shutdown" ]
72
96
109,231
9
0
2008-08-25T04:01:40.920000
2008-08-25T04:08:28.970000
25,652
25,673
Height of NSTextView with one line?
I want to programatically create an NSTextView. How can I determine the correct frame height so that the view displays one line of text in the current default font?
The NSFont class has a method that can give you the size of a rectangle that would enclose a specific attributed string. Get the font used by your text view, create a string that serves as a reasonable example of what will be in the text view, and use that to inform your frame height. (The frame height will need to be some number of points larger than the actual rectangle the string would be displayed in.) Alternately, you can get the various metrics from the font and attempt to calculate a reasonable frame from that. That might or might not work; for example, a font like Apple Chancery has a huge amount of variation depending on the glyphs that are being rendered, where they are in a word, and so on; I don't know that you can calculate what the needed size would be in advance without knowing exactly what you were going to render.
Height of NSTextView with one line? I want to programatically create an NSTextView. How can I determine the correct frame height so that the view displays one line of text in the current default font?
TITLE: Height of NSTextView with one line? QUESTION: I want to programatically create an NSTextView. How can I determine the correct frame height so that the view displays one line of text in the current default font? ANSWER: The NSFont class has a method that can give you the size of a rectangle that would enclose a specific attributed string. Get the font used by your text view, create a string that serves as a reasonable example of what will be in the text view, and use that to inform your frame height. (The frame height will need to be some number of points larger than the actual rectangle the string would be displayed in.) Alternately, you can get the various metrics from the font and attempt to calculate a reasonable frame from that. That might or might not work; for example, a font like Apple Chancery has a huge amount of variation depending on the glyphs that are being rendered, where they are in a word, and so on; I don't know that you can calculate what the needed size would be in advance without knowing exactly what you were going to render.
[ "cocoa", "macos" ]
2
4
2,893
2
0
2008-08-25T04:19:25.777000
2008-08-25T05:00:04.977000
25,653
25,667
Hide a column in ASP.NET Dynamic Data
Is there any way to apply an attribute to a model file in ASP.NET Dynamic Data to hide the column? For instance, I can currently set the display name of a column like this: [DisplayName("Last name")] public object Last_name { get; set; } Is there a similar way to hide a column? Edit: Many thanks to Christian Hagelid for going the extra mile and giving a spot-on answer:-)
Had no idea what ASP.NET Dynamic Data was so you promted me to so some research:) Looks like the property you are looking for is [ScaffoldColumn(false)] There is also a similar property for tables [ScaffoldTable(false)] source
Hide a column in ASP.NET Dynamic Data Is there any way to apply an attribute to a model file in ASP.NET Dynamic Data to hide the column? For instance, I can currently set the display name of a column like this: [DisplayName("Last name")] public object Last_name { get; set; } Is there a similar way to hide a column? Edit: Many thanks to Christian Hagelid for going the extra mile and giving a spot-on answer:-)
TITLE: Hide a column in ASP.NET Dynamic Data QUESTION: Is there any way to apply an attribute to a model file in ASP.NET Dynamic Data to hide the column? For instance, I can currently set the display name of a column like this: [DisplayName("Last name")] public object Last_name { get; set; } Is there a similar way to hide a column? Edit: Many thanks to Christian Hagelid for going the extra mile and giving a spot-on answer:-) ANSWER: Had no idea what ASP.NET Dynamic Data was so you promted me to so some research:) Looks like the property you are looking for is [ScaffoldColumn(false)] There is also a similar property for tables [ScaffoldTable(false)] source
[ "asp.net", "dynamic-data" ]
14
20
6,967
2
0
2008-08-25T04:21:05.913000
2008-08-25T04:47:22.323000
25,665
25,689
Python module for converting PDF to text
Is there any python module to convert PDF files into text? I tried one piece of code found in Activestate which uses pypdf but the text generated had no space between and was of no use.
Try PDFMiner. It can extract text from PDF files as HTML, SGML or "Tagged PDF" format. The Tagged PDF format seems to be the cleanest, and stripping out the XML tags leaves just the bare text. A Python 3 version is available under: https://github.com/pdfminer/pdfminer.six
Python module for converting PDF to text Is there any python module to convert PDF files into text? I tried one piece of code found in Activestate which uses pypdf but the text generated had no space between and was of no use.
TITLE: Python module for converting PDF to text QUESTION: Is there any python module to convert PDF files into text? I tried one piece of code found in Activestate which uses pypdf but the text generated had no space between and was of no use. ANSWER: Try PDFMiner. It can extract text from PDF files as HTML, SGML or "Tagged PDF" format. The Tagged PDF format seems to be the cleanest, and stripping out the XML tags leaves just the bare text. A Python 3 version is available under: https://github.com/pdfminer/pdfminer.six
[ "python", "pdf", "text-extraction", "pdf-scraping" ]
418
159
458,243
13
0
2008-08-25T04:44:06.090000
2008-08-25T05:21:22.927000
25,672
26,725
ColdFusion - When to use the "request" scope?
Been going over my predecessor's code and see usage of the "request" scope frequently. What is the appropriate usage of this scope?
There are several scopes that are available to any portion of your code: Session, Client, Cookie, Application, and Request. Some are inadvisable to use in certain ways (i.e. using Request or Application scope inside your Custom Tags or CFC's; this is coupling, violates encapsulation principles, and is considered a bad practice), and some have special purposes: Cookie is persisted on the client machine as physical cookies, and Session scoped variables are user-specific and expire with the user's session on the website. If a variable is extremely unlikely to change (constant for all intents and purposes) and can simply be initialized on application startup and never written again, generally you should put it into Application scope because this persists it between every user and every session. When properly implemented it is written once and read N times. A proper implementation of Application variables in Application.cfm might look like this: Note that the existence of the variable in the application scope is checked before and after the lock, so that if two users create a race condition at application startup, only one of them will end up setting the application variables. The benefit of this approach is that it won't constantly refresh these stored variables on every request, wasting the user's time and the server's processing cycles. The trade-off is that it is a little verbose and complex. This was greatly simplified with the addition of Application.cfc. Now, you can specify which variables are created on application startup and don't have to worry about locking and checking for existence and all of that fun stuff: For more information on Application.cfc including all of the various special functions available and every little detail about what and how to use it, I recommend this post on Raymond Camden's blog. To summarize, request scope is available everywhere in your code, but that doesn't necessarily make it "right" to use it everywhere. Chances are that your predecessor was using it to break encapsulation, and that can be cumbersome to refactor out. You may be best off leaving it as-is, but understanding which scope is the best tool for the job will definitely make your future code better.
ColdFusion - When to use the "request" scope? Been going over my predecessor's code and see usage of the "request" scope frequently. What is the appropriate usage of this scope?
TITLE: ColdFusion - When to use the "request" scope? QUESTION: Been going over my predecessor's code and see usage of the "request" scope frequently. What is the appropriate usage of this scope? ANSWER: There are several scopes that are available to any portion of your code: Session, Client, Cookie, Application, and Request. Some are inadvisable to use in certain ways (i.e. using Request or Application scope inside your Custom Tags or CFC's; this is coupling, violates encapsulation principles, and is considered a bad practice), and some have special purposes: Cookie is persisted on the client machine as physical cookies, and Session scoped variables are user-specific and expire with the user's session on the website. If a variable is extremely unlikely to change (constant for all intents and purposes) and can simply be initialized on application startup and never written again, generally you should put it into Application scope because this persists it between every user and every session. When properly implemented it is written once and read N times. A proper implementation of Application variables in Application.cfm might look like this: Note that the existence of the variable in the application scope is checked before and after the lock, so that if two users create a race condition at application startup, only one of them will end up setting the application variables. The benefit of this approach is that it won't constantly refresh these stored variables on every request, wasting the user's time and the server's processing cycles. The trade-off is that it is a little verbose and complex. This was greatly simplified with the addition of Application.cfc. Now, you can specify which variables are created on application startup and don't have to worry about locking and checking for existence and all of that fun stuff: For more information on Application.cfc including all of the various special functions available and every little detail about what and how to use it, I recommend this post on Raymond Camden's blog. To summarize, request scope is available everywhere in your code, but that doesn't necessarily make it "right" to use it everywhere. Chances are that your predecessor was using it to break encapsulation, and that can be cumbersome to refactor out. You may be best off leaving it as-is, but understanding which scope is the best tool for the job will definitely make your future code better.
[ "coldfusion", "railo", "cfml" ]
14
21
20,732
4
0
2008-08-25T04:59:25.180000
2008-08-25T19:54:19.210000
25,675
25,678
MVC - where to implement form validation (server-side)?
In coding a traditional MVC application, what is the best practice for coding server-side form validations? Does the code belong in the controller, or the model layer? And why?
From Wikipedia: Model-view-controller (MVC) is an architectural pattern used in software engineering. Successful use of the pattern isolates business logic from user interface considerations, resulting in an application where it is easier to modify either the visual appearance of the application or the underlying business rules without affecting the other. In MVC, the model represents the information (the data) of the application and the business rules used to manipulate the data; the view corresponds to elements of the user interface such as text, checkbox items, and so forth; and the controller manages details involving the communication to the model of user actions such as keystrokes and mouse movements. Thus, model - it holds the application and the business rules.
MVC - where to implement form validation (server-side)? In coding a traditional MVC application, what is the best practice for coding server-side form validations? Does the code belong in the controller, or the model layer? And why?
TITLE: MVC - where to implement form validation (server-side)? QUESTION: In coding a traditional MVC application, what is the best practice for coding server-side form validations? Does the code belong in the controller, or the model layer? And why? ANSWER: From Wikipedia: Model-view-controller (MVC) is an architectural pattern used in software engineering. Successful use of the pattern isolates business logic from user interface considerations, resulting in an application where it is easier to modify either the visual appearance of the application or the underlying business rules without affecting the other. In MVC, the model represents the information (the data) of the application and the business rules used to manipulate the data; the view corresponds to elements of the user interface such as text, checkbox items, and so forth; and the controller manages details involving the communication to the model of user actions such as keystrokes and mouse movements. Thus, model - it holds the application and the business rules.
[ "model-view-controller", "validation", "forms" ]
9
4
1,902
4
0
2008-08-25T05:04:30.923000
2008-08-25T05:09:41.800000
25,730
25,831
What is the best free memory leak detector for a C/C++ program and its plug-in DLLs?
I have a.exe and many plug-in.dll modules that the.exe loads. (I have source for both.) A cross-platform (with source) solution would be ideal, but the platform can be narrowed to WinXP and Visual Studio (7.1/2003 in my case). The built-in VS leak detector only gives the line where new/malloc was called from, but I have a wrapper for allocations, so a full symbolic stack trace would be best. The detector would also be able to detect for a leak in both the.exe and its accompanying plug-in.dll modules.
I personally use Visual Leak Detector, though it can cause large delays when large blocks are leaked (it displays the contents of the entire leaked block).
What is the best free memory leak detector for a C/C++ program and its plug-in DLLs? I have a.exe and many plug-in.dll modules that the.exe loads. (I have source for both.) A cross-platform (with source) solution would be ideal, but the platform can be narrowed to WinXP and Visual Studio (7.1/2003 in my case). The built-in VS leak detector only gives the line where new/malloc was called from, but I have a wrapper for allocations, so a full symbolic stack trace would be best. The detector would also be able to detect for a leak in both the.exe and its accompanying plug-in.dll modules.
TITLE: What is the best free memory leak detector for a C/C++ program and its plug-in DLLs? QUESTION: I have a.exe and many plug-in.dll modules that the.exe loads. (I have source for both.) A cross-platform (with source) solution would be ideal, but the platform can be narrowed to WinXP and Visual Studio (7.1/2003 in my case). The built-in VS leak detector only gives the line where new/malloc was called from, but I have a wrapper for allocations, so a full symbolic stack trace would be best. The detector would also be able to detect for a leak in both the.exe and its accompanying plug-in.dll modules. ANSWER: I personally use Visual Leak Detector, though it can cause large delays when large blocks are leaked (it displays the contents of the entire leaked block).
[ "c++", "c", "visual-studio", "memory-leaks" ]
51
37
117,013
7
0
2008-08-25T07:31:46.110000
2008-08-25T10:03:23.780000
25,746
25,798
What's the difference between a string constant and a string literal?
I'm learning objective-C and Cocoa and have come across this statement: The Cocoa frameworks expect that global string constants rather than string literals are used for dictionary keys, notification and exception names, and some method parameters that take strings. I've only worked in higher level languages so have never had to consider the details of strings that much. What's the difference between a string constant and string literal?
In Objective-C, the syntax @"foo" is an immutable, literal instance of NSString. It does not make a constant string from a string literal as Mike assume. Objective-C compilers typically do intern literal strings within compilation units — that is, they coalesce multiple uses of the same literal string — and it's possible for the linker to do additional interning across the compilation units that are directly linked into a single binary. (Since Cocoa distinguishes between mutable and immutable strings, and literal strings are always also immutable, this can be straightforward and safe.) Constant strings on the other hand are typically declared and defined using syntax like this: // MyExample.h - declaration, other code references this extern NSString * const MyExampleNotification; // MyExample.m - definition, compiled for other code to reference NSString * const MyExampleNotification = @"MyExampleNotification"; The point of the syntactic exercise here is that you can make uses of the string efficient by ensuring that there's only one instance of that string in use even across multiple frameworks (shared libraries) in the same address space. (The placement of the const keyword matters; it guarantees that the pointer itself is guaranteed to be constant.) While burning memory isn't as big a deal as it may have been in the days of 25MHz 68030 workstations with 8MB of RAM, comparing strings for equality can take time. Ensuring that most of the time strings that are equal will also be pointer-equal helps. Say, for example, you want to subscribe to notifications from an object by name. If you use non-constant strings for the names, the NSNotificationCenter posting the notification could wind up doing a lot of byte-by-byte string comparisons when determining who is interested in it. If most of these comparisons are short-circuited because the strings being compared have the same pointer, that can be a big win.
What's the difference between a string constant and a string literal? I'm learning objective-C and Cocoa and have come across this statement: The Cocoa frameworks expect that global string constants rather than string literals are used for dictionary keys, notification and exception names, and some method parameters that take strings. I've only worked in higher level languages so have never had to consider the details of strings that much. What's the difference between a string constant and string literal?
TITLE: What's the difference between a string constant and a string literal? QUESTION: I'm learning objective-C and Cocoa and have come across this statement: The Cocoa frameworks expect that global string constants rather than string literals are used for dictionary keys, notification and exception names, and some method parameters that take strings. I've only worked in higher level languages so have never had to consider the details of strings that much. What's the difference between a string constant and string literal? ANSWER: In Objective-C, the syntax @"foo" is an immutable, literal instance of NSString. It does not make a constant string from a string literal as Mike assume. Objective-C compilers typically do intern literal strings within compilation units — that is, they coalesce multiple uses of the same literal string — and it's possible for the linker to do additional interning across the compilation units that are directly linked into a single binary. (Since Cocoa distinguishes between mutable and immutable strings, and literal strings are always also immutable, this can be straightforward and safe.) Constant strings on the other hand are typically declared and defined using syntax like this: // MyExample.h - declaration, other code references this extern NSString * const MyExampleNotification; // MyExample.m - definition, compiled for other code to reference NSString * const MyExampleNotification = @"MyExampleNotification"; The point of the syntactic exercise here is that you can make uses of the string efficient by ensuring that there's only one instance of that string in use even across multiple frameworks (shared libraries) in the same address space. (The placement of the const keyword matters; it guarantees that the pointer itself is guaranteed to be constant.) While burning memory isn't as big a deal as it may have been in the days of 25MHz 68030 workstations with 8MB of RAM, comparing strings for equality can take time. Ensuring that most of the time strings that are equal will also be pointer-equal helps. Say, for example, you want to subscribe to notifications from an object by name. If you use non-constant strings for the names, the NSNotificationCenter posting the notification could wind up doing a lot of byte-by-byte string comparisons when determining who is interested in it. If most of these comparisons are short-circuited because the strings being compared have the same pointer, that can be a big win.
[ "objective-c", "string" ]
62
87
40,542
3
0
2008-08-25T07:54:29.080000
2008-08-25T08:51:58.443000
25,749
25,784
What does the @ symbol represent in objective-c?
I'm learning objective-c and keep bumping into the @ symbol. It is used in different scenarios, for example at the start of a string or to synthesise accessor methods. What's does the @ symbol mean in objective-c?
The @ character isn't used in C or C++ identifiers, so it's used to introduce Objective-C language keywords in a way that won't conflict with the other languages' keywords. This enables the "Objective" part of the language to freely intermix with the C or C++ part. Thus with very few exceptions, any time you see @ in some Objective-C code, you're looking at Objective-C constructs rather than C or C++ constructs. The major exceptions are id, Class, nil, and Nil, which are generally treated as language keywords even though they may also have a typedef or #define behind them. For example, the compiler actually does treat id specially in terms of the pointer type conversion rules it applies to declarations, as well as to the decision of whether to generate GC write barriers. Other exceptions are in, out, inout, oneway, byref, and bycopy; these are used as storage class annotations on method parameter and return types to make Distributed Objects more efficient. (They become part of the method signature available from the runtime, which DO can look at to determine how to best serialize a transaction.) There are also the attributes within @property declarations, copy, retain, assign, readonly, readwrite, nonatomic, getter, and setter; those are only valid within the attribute section of a @property declaration.
What does the @ symbol represent in objective-c? I'm learning objective-c and keep bumping into the @ symbol. It is used in different scenarios, for example at the start of a string or to synthesise accessor methods. What's does the @ symbol mean in objective-c?
TITLE: What does the @ symbol represent in objective-c? QUESTION: I'm learning objective-c and keep bumping into the @ symbol. It is used in different scenarios, for example at the start of a string or to synthesise accessor methods. What's does the @ symbol mean in objective-c? ANSWER: The @ character isn't used in C or C++ identifiers, so it's used to introduce Objective-C language keywords in a way that won't conflict with the other languages' keywords. This enables the "Objective" part of the language to freely intermix with the C or C++ part. Thus with very few exceptions, any time you see @ in some Objective-C code, you're looking at Objective-C constructs rather than C or C++ constructs. The major exceptions are id, Class, nil, and Nil, which are generally treated as language keywords even though they may also have a typedef or #define behind them. For example, the compiler actually does treat id specially in terms of the pointer type conversion rules it applies to declarations, as well as to the decision of whether to generate GC write barriers. Other exceptions are in, out, inout, oneway, byref, and bycopy; these are used as storage class annotations on method parameter and return types to make Distributed Objects more efficient. (They become part of the method signature available from the runtime, which DO can look at to determine how to best serialize a transaction.) There are also the attributes within @property declarations, copy, retain, assign, readonly, readwrite, nonatomic, getter, and setter; those are only valid within the attribute section of a @property declaration.
[ "objective-c" ]
154
164
56,970
5
0
2008-08-25T07:57:59.183000
2008-08-25T08:36:29.887000
25,752
25,758
How do I put a space character before option text in a HTML select element?
In a drop down list, I need to add spaces in front of the options in the list. I am trying Sample for adding two spaces but it displays no spaces. How can I add spaces before option texts?
Isn't the entity for space? option 1 option 2 Works for me... EDIT: Just checked this out, there may be compatibility issues with this in older browsers, but all seems to work fine for me here. Just thought I should let you know as you may want to replace with
How do I put a space character before option text in a HTML select element? In a drop down list, I need to add spaces in front of the options in the list. I am trying Sample for adding two spaces but it displays no spaces. How can I add spaces before option texts?
TITLE: How do I put a space character before option text in a HTML select element? QUESTION: In a drop down list, I need to add spaces in front of the options in the list. I am trying Sample for adding two spaces but it displays no spaces. How can I add spaces before option texts? ANSWER: Isn't the entity for space? option 1 option 2 Works for me... EDIT: Just checked this out, there may be compatibility issues with this in older browsers, but all seems to work fine for me here. Just thought I should let you know as you may want to replace with
[ "html", "html-select" ]
33
31
90,138
15
0
2008-08-25T08:02:43.367000
2008-08-25T08:06:18.490000
25,765
25,768
Java configuration framework
I'm in the process of weeding out all hardcoded values in a Java library and was wondering what framework would be the best (in terms of zero- or close-to-zero configuration) to handle run-time configuration? I would prefer XML-based configuration files, but it's not essential. Please do only reply if you have practical experience with a framework. I'm not looking for examples, but experience...
If your hardcoded values are just simple key-value pairs, you should look at java.util.Properties. It's a lot simpler than xml, easier to use, and mind-numbingly trivial to implement. If you are working with Java and the data you are storing or retrieving from disk is modeled as a key value pair (which it sounds like it is in your case), then I really can't imagine a better solution. I have used properties files for simple configuration of small packages in a bigger project, and as a more global configuration for a whole project, and I have never had problems with it. Of course this has the huge benefit of not requiring any 3rd party libraries to utilize.
Java configuration framework I'm in the process of weeding out all hardcoded values in a Java library and was wondering what framework would be the best (in terms of zero- or close-to-zero configuration) to handle run-time configuration? I would prefer XML-based configuration files, but it's not essential. Please do only reply if you have practical experience with a framework. I'm not looking for examples, but experience...
TITLE: Java configuration framework QUESTION: I'm in the process of weeding out all hardcoded values in a Java library and was wondering what framework would be the best (in terms of zero- or close-to-zero configuration) to handle run-time configuration? I would prefer XML-based configuration files, but it's not essential. Please do only reply if you have practical experience with a framework. I'm not looking for examples, but experience... ANSWER: If your hardcoded values are just simple key-value pairs, you should look at java.util.Properties. It's a lot simpler than xml, easier to use, and mind-numbingly trivial to implement. If you are working with Java and the data you are storing or retrieving from disk is modeled as a key value pair (which it sounds like it is in your case), then I really can't imagine a better solution. I have used properties files for simple configuration of small packages in a bigger project, and as a more global configuration for a whole project, and I have never had problems with it. Of course this has the huge benefit of not requiring any 3rd party libraries to utilize.
[ "java", "xml", "configuration", "frameworks", "configurationmanager" ]
76
29
30,830
14
0
2008-08-25T08:17:54.297000
2008-08-25T08:23:22.227000
25,767
25,805
Most efficient way to get data from the database to session
What is the quickest way to get a large amount of data (think golf) and the most efficient (think performance) to get a large amount of data from a MySQL database to a session without having to continue doing what I already have: $sql = "SELECT * FROM users WHERE username='". mysql_escape_string($_POST['username']). "' AND password='". mysql_escape_string(md5($_POST['password'])). "'"; $result = mysql_query($sql, $link) or die("There was an error while trying to get your information.\n "); if(mysql_num_rows($result) < 1) { $_SESSION['username'] = $_POST['username']; redirect('index.php?p=signup'); } $_SESSION['id'] = mysql_result($result, '0', 'id'); $_SESSION['fName'] = mysql_result($result, '0', 'fName'); $_SESSION['lName'] = mysql_result($result, '0', 'lName');... And before anyone asks yes I do really need to 'SELECT Edit: Yes, I am sanitizing the data, so that there can be no SQL injection, that is further up in the code.
I came up with this and it appears to work. while($row = mysql_fetch_assoc($result)) { $_SESSION = array_merge_recursive($_SESSION, $row); }
Most efficient way to get data from the database to session What is the quickest way to get a large amount of data (think golf) and the most efficient (think performance) to get a large amount of data from a MySQL database to a session without having to continue doing what I already have: $sql = "SELECT * FROM users WHERE username='". mysql_escape_string($_POST['username']). "' AND password='". mysql_escape_string(md5($_POST['password'])). "'"; $result = mysql_query($sql, $link) or die("There was an error while trying to get your information.\n "); if(mysql_num_rows($result) < 1) { $_SESSION['username'] = $_POST['username']; redirect('index.php?p=signup'); } $_SESSION['id'] = mysql_result($result, '0', 'id'); $_SESSION['fName'] = mysql_result($result, '0', 'fName'); $_SESSION['lName'] = mysql_result($result, '0', 'lName');... And before anyone asks yes I do really need to 'SELECT Edit: Yes, I am sanitizing the data, so that there can be no SQL injection, that is further up in the code.
TITLE: Most efficient way to get data from the database to session QUESTION: What is the quickest way to get a large amount of data (think golf) and the most efficient (think performance) to get a large amount of data from a MySQL database to a session without having to continue doing what I already have: $sql = "SELECT * FROM users WHERE username='". mysql_escape_string($_POST['username']). "' AND password='". mysql_escape_string(md5($_POST['password'])). "'"; $result = mysql_query($sql, $link) or die("There was an error while trying to get your information.\n "); if(mysql_num_rows($result) < 1) { $_SESSION['username'] = $_POST['username']; redirect('index.php?p=signup'); } $_SESSION['id'] = mysql_result($result, '0', 'id'); $_SESSION['fName'] = mysql_result($result, '0', 'fName'); $_SESSION['lName'] = mysql_result($result, '0', 'lName');... And before anyone asks yes I do really need to 'SELECT Edit: Yes, I am sanitizing the data, so that there can be no SQL injection, that is further up in the code. ANSWER: I came up with this and it appears to work. while($row = mysql_fetch_assoc($result)) { $_SESSION = array_merge_recursive($_SESSION, $row); }
[ "php", "mysql", "session" ]
3
1
3,320
10
0
2008-08-25T08:23:14.957000
2008-08-25T09:05:49.067000
25,803
25,820
How do I intercept a method call in C#?
For a given class I would like to have tracing functionality i.e. I would like to log every method call (method signature and actual parameter values) and every method exit (just the method signature). How do I accomplish this assuming that: I don't want to use any 3rd party AOP libraries for C#, I don't want to add duplicate code to all the methods that I want to trace, I don't want to change the public API of the class - users of the class should be able to call all the methods in exactly the same way. To make the question more concrete let's assume there are 3 classes: public class Caller { public static void Call() { Traced traced = new Traced(); traced.Method1(); traced.Method2(); } } public class Traced { public void Method1(String name, Int32 value) { } public void Method2(Object object) { } } public class Logger { public static void LogStart(MethodInfo method, Object[] parameterValues); public static void LogEnd(MethodInfo method); } How do I invoke Logger.LogStart and Logger.LogEnd for every call to Method1 and Method2 without modifying the Caller.Call method and without adding the calls explicitly to Traced.Method1 and Traced.Method2? Edit: What would be the solution if I'm allowed to slightly change the Call method?
C# is not an AOP oriented language. It has some AOP features and you can emulate some others but making AOP with C# is painful. I looked up for ways to do exactly what you wanted to do and I found no easy way to do it. As I understand it, this is what you want to do: [Log()] public void Method1(String name, Int32 value); and in order to do that you have two main options Inherit your class from MarshalByRefObject or ContextBoundObject and define an attribute which inherits from IMessageSink. This article has a good example. You have to consider nontheless that using a MarshalByRefObject the performance will go down like hell, and I mean it, I'm talking about a 10x performance lost so think carefully before trying that. The other option is to inject code directly. In runtime, meaning you'll have to use reflection to "read" every class, get its attributes and inject the appropiate call (and for that matter I think you couldn't use the Reflection.Emit method as I think Reflection.Emit wouldn't allow you to insert new code inside an already existing method). At design time this will mean creating an extension to the CLR compiler which I have honestly no idea on how it's done. The final option is using an IoC framework. Maybe it's not the perfect solution as most IoC frameworks works by defining entry points which allow methods to be hooked but, depending on what you want to achive, that might be a fair aproximation.
How do I intercept a method call in C#? For a given class I would like to have tracing functionality i.e. I would like to log every method call (method signature and actual parameter values) and every method exit (just the method signature). How do I accomplish this assuming that: I don't want to use any 3rd party AOP libraries for C#, I don't want to add duplicate code to all the methods that I want to trace, I don't want to change the public API of the class - users of the class should be able to call all the methods in exactly the same way. To make the question more concrete let's assume there are 3 classes: public class Caller { public static void Call() { Traced traced = new Traced(); traced.Method1(); traced.Method2(); } } public class Traced { public void Method1(String name, Int32 value) { } public void Method2(Object object) { } } public class Logger { public static void LogStart(MethodInfo method, Object[] parameterValues); public static void LogEnd(MethodInfo method); } How do I invoke Logger.LogStart and Logger.LogEnd for every call to Method1 and Method2 without modifying the Caller.Call method and without adding the calls explicitly to Traced.Method1 and Traced.Method2? Edit: What would be the solution if I'm allowed to slightly change the Call method?
TITLE: How do I intercept a method call in C#? QUESTION: For a given class I would like to have tracing functionality i.e. I would like to log every method call (method signature and actual parameter values) and every method exit (just the method signature). How do I accomplish this assuming that: I don't want to use any 3rd party AOP libraries for C#, I don't want to add duplicate code to all the methods that I want to trace, I don't want to change the public API of the class - users of the class should be able to call all the methods in exactly the same way. To make the question more concrete let's assume there are 3 classes: public class Caller { public static void Call() { Traced traced = new Traced(); traced.Method1(); traced.Method2(); } } public class Traced { public void Method1(String name, Int32 value) { } public void Method2(Object object) { } } public class Logger { public static void LogStart(MethodInfo method, Object[] parameterValues); public static void LogEnd(MethodInfo method); } How do I invoke Logger.LogStart and Logger.LogEnd for every call to Method1 and Method2 without modifying the Caller.Call method and without adding the calls explicitly to Traced.Method1 and Traced.Method2? Edit: What would be the solution if I'm allowed to slightly change the Call method? ANSWER: C# is not an AOP oriented language. It has some AOP features and you can emulate some others but making AOP with C# is painful. I looked up for ways to do exactly what you wanted to do and I found no easy way to do it. As I understand it, this is what you want to do: [Log()] public void Method1(String name, Int32 value); and in order to do that you have two main options Inherit your class from MarshalByRefObject or ContextBoundObject and define an attribute which inherits from IMessageSink. This article has a good example. You have to consider nontheless that using a MarshalByRefObject the performance will go down like hell, and I mean it, I'm talking about a 10x performance lost so think carefully before trying that. The other option is to inject code directly. In runtime, meaning you'll have to use reflection to "read" every class, get its attributes and inject the appropiate call (and for that matter I think you couldn't use the Reflection.Emit method as I think Reflection.Emit wouldn't allow you to insert new code inside an already existing method). At design time this will mean creating an extension to the CLR compiler which I have honestly no idea on how it's done. The final option is using an IoC framework. Maybe it's not the perfect solution as most IoC frameworks works by defining entry points which allow methods to be hooked but, depending on what you want to achive, that might be a fair aproximation.
[ "c#", "reflection", "aop" ]
163
74
109,880
16
0
2008-08-25T09:00:23.883000
2008-08-25T09:31:40.953000
25,807
25,815
Python super class reflection
If I have Python code class A(): pass class B(): pass class C(A, B): pass and I have class C, is there a way to iterate through it's super classed ( A and B )? Something like pseudocode: >>> magicGetSuperClasses(C) (, ) One solution seems to be inspect module and getclasstree function. def magicGetSuperClasses(cls): return [o[0] for o in inspect.getclasstree([cls]) if type(o[0]) == type] but is this a "Pythonian" way to achieve the goal?
C.__bases__ is an array of the super classes, so you could implement your hypothetical function like so: def magicGetSuperClasses(cls): return cls.__bases__ But I imagine it would be easier to just reference cls.__bases__ directly in most cases.
Python super class reflection If I have Python code class A(): pass class B(): pass class C(A, B): pass and I have class C, is there a way to iterate through it's super classed ( A and B )? Something like pseudocode: >>> magicGetSuperClasses(C) (, ) One solution seems to be inspect module and getclasstree function. def magicGetSuperClasses(cls): return [o[0] for o in inspect.getclasstree([cls]) if type(o[0]) == type] but is this a "Pythonian" way to achieve the goal?
TITLE: Python super class reflection QUESTION: If I have Python code class A(): pass class B(): pass class C(A, B): pass and I have class C, is there a way to iterate through it's super classed ( A and B )? Something like pseudocode: >>> magicGetSuperClasses(C) (, ) One solution seems to be inspect module and getclasstree function. def magicGetSuperClasses(cls): return [o[0] for o in inspect.getclasstree([cls]) if type(o[0]) == type] but is this a "Pythonian" way to achieve the goal? ANSWER: C.__bases__ is an array of the super classes, so you could implement your hypothetical function like so: def magicGetSuperClasses(cls): return cls.__bases__ But I imagine it would be easier to just reference cls.__bases__ directly in most cases.
[ "python", "reflection" ]
33
37
16,847
4
0
2008-08-25T09:06:16.087000
2008-08-25T09:22:22.147000
25,823
25,835
Multiple YACC grammars in one program
How do I compile, link and call different YACC grammars using yyparse() in one program?
Use the -p option for each separate yacc grammar generation -p prefix Use prefix instead of yy as the prefix for all external names produced by yacc. For X/Open compliance, when the environment variable _XPG is set, then the -p option will work as described in the previous sentence. If the environment variable _XPG is not set, then the -p option will work as described below in the -P option.
Multiple YACC grammars in one program How do I compile, link and call different YACC grammars using yyparse() in one program?
TITLE: Multiple YACC grammars in one program QUESTION: How do I compile, link and call different YACC grammars using yyparse() in one program? ANSWER: Use the -p option for each separate yacc grammar generation -p prefix Use prefix instead of yy as the prefix for all external names produced by yacc. For X/Open compliance, when the environment variable _XPG is set, then the -p option will work as described in the previous sentence. If the environment variable _XPG is not set, then the -p option will work as described below in the -P option.
[ "yacc" ]
10
7
670
1
0
2008-08-25T09:38:36.243000
2008-08-25T10:12:12.667000
25,833
58,286
How to open VS 2008 solution in VS 2005?
I have seen Solutions created in Visual Studio 2008 cannot be opened in Visual Studio 2005 and tried workaround 1. Yet to try the workaround 2. But as that link was bit old and out of desperation asking here: Is there any convertor available? I dont have VS2008 yet and i wanted to open an opensource solution which was done in vs2008. Guess i have to fiddle around or wait till the vs2008 is shipped.
I have a project that I work on in both VS 2005 and VS 2008. The trick is just to have to different solution files, and to make sure they stay in sync. Remember that projects keep track of their files, so the main thing solutions do is keep track of which projects they contain; pretty easy to keep in sync. So just create a new blank solution in VS 2005, and then add each of your projects to it, one by one. Be sure to name the solutions appropriately. (I call mine ProjectName.sln and ProjectNameVs2008.sln.) Which is a long way of saying you should try workaround #2.
How to open VS 2008 solution in VS 2005? I have seen Solutions created in Visual Studio 2008 cannot be opened in Visual Studio 2005 and tried workaround 1. Yet to try the workaround 2. But as that link was bit old and out of desperation asking here: Is there any convertor available? I dont have VS2008 yet and i wanted to open an opensource solution which was done in vs2008. Guess i have to fiddle around or wait till the vs2008 is shipped.
TITLE: How to open VS 2008 solution in VS 2005? QUESTION: I have seen Solutions created in Visual Studio 2008 cannot be opened in Visual Studio 2005 and tried workaround 1. Yet to try the workaround 2. But as that link was bit old and out of desperation asking here: Is there any convertor available? I dont have VS2008 yet and i wanted to open an opensource solution which was done in vs2008. Guess i have to fiddle around or wait till the vs2008 is shipped. ANSWER: I have a project that I work on in both VS 2005 and VS 2008. The trick is just to have to different solution files, and to make sure they stay in sync. Remember that projects keep track of their files, so the main thing solutions do is keep track of which projects they contain; pretty easy to keep in sync. So just create a new blank solution in VS 2005, and then add each of your projects to it, one by one. Be sure to name the solutions appropriately. (I call mine ProjectName.sln and ProjectNameVs2008.sln.) Which is a long way of saying you should try workaround #2.
[ "visual-studio-2008", "visual-studio-2005", "projects-and-solutions" ]
7
4
8,594
5
0
2008-08-25T10:06:45.800000
2008-09-12T04:15:22.373000
25,865
25,886
What is a language binding?
My good friend, Wikipedia, didn't give me a very good response to that question. So: What are language bindings? How do they work? Specifically accessing functions from code written in language X of a library written in language Y.
Let's say you create a C library to post stuff to stackoverflow. Now you want to be able to use the same library from Python. In this case, you will write Python bindings for your library. Also see SWIG: http://www.swig.org
What is a language binding? My good friend, Wikipedia, didn't give me a very good response to that question. So: What are language bindings? How do they work? Specifically accessing functions from code written in language X of a library written in language Y.
TITLE: What is a language binding? QUESTION: My good friend, Wikipedia, didn't give me a very good response to that question. So: What are language bindings? How do they work? Specifically accessing functions from code written in language X of a library written in language Y. ANSWER: Let's say you create a C library to post stuff to stackoverflow. Now you want to be able to use the same library from Python. In this case, you will write Python bindings for your library. Also see SWIG: http://www.swig.org
[ "language-agnostic", "glossary", "language-binding" ]
69
44
28,621
4
0
2008-08-25T11:13:29.993000
2008-08-25T11:33:02.677000
25,921
25,958
What is ASP.NET?
I've been strictly in a C++ environment for years (and specialized statistical languages). Visual Studio until 2001, and Borland since. Mostly specialized desktop applications for clients. I'm not remaining willfully ignorant of it, but over the years when I've dipped into other things, I've spent my time playing around with JavaScript, PHP, and a lot of Python. Is " ASP.NET " the language? Is C# the language and "ASP.NET" the framework? What's a good answer to "What is ASP.NET"? Is there a correspondence between ASP.NET and anything I'd be familiar with in C++? I know I can google the same title, but I'd rather see answers from this crowd. (Besides, in the future, I think that Google should point here for questions like that.)
ASP.NET is a web application framework developed and marketed by Microsoft, that programmers can use to build dynamic web sites, web applications and web services. It was first released in January 2002 with version 1.0 of the.NET Framework, and is the successor to Microsoft's Active Server Pages (ASP) technology. ASP.NET is built on the Common Language Runtime (CLR), allowing programmers to write ASP.NET code using any supported.NET language. ASP.NET (Wikipedia) That's on the second result searching on Google so I'm guessing (half-expecting) that you don't understand what that means either. Webpage development started with simple static HTML pages. That meant the client asked for a page by means of an URL and the server sent the page back to him/her exactly as it has been designed. Sometime after that several technologies emerged in order to provide a more "dynamic" or personalized experience. Several "server side languages" were developed (PHP, Perl, ASP...) which allowed the server to process the Web page before sending it back to the client. This way when a client requested a webpage the server could interpret the request, process it (for example connecting to a database and fetching some results) and send it back modifying the contents and making them "dynamic". The fact that the process took place on the server stands for the name of "server side". So the original ASP (predecessor of the ASP.NET) was a server side language that was focused on serving web pages. In such way it supported several shortcuts such as the possibility to intercalate HTML and ASP source into the file which was on that time much popular due to PHP implementation. It was also (as most of these languages) a dynamic language and it was interpreted. ASP.NET is an evolution of that original ASP with some improvements. First it does truly (try to) separate the presentation (HTML) from the code (.cs) which may be implemented by using Visual Basic or C# syntax. It also incorporate some sort of compilation to the final ASP pages, encapsulating them into assemblies and thus improving performance. Finally it has access to the full.NET framework which supports a wide number of helper classes. So, summing up, it is a programming language located on the server and designed to make webpages.
What is ASP.NET? I've been strictly in a C++ environment for years (and specialized statistical languages). Visual Studio until 2001, and Borland since. Mostly specialized desktop applications for clients. I'm not remaining willfully ignorant of it, but over the years when I've dipped into other things, I've spent my time playing around with JavaScript, PHP, and a lot of Python. Is " ASP.NET " the language? Is C# the language and "ASP.NET" the framework? What's a good answer to "What is ASP.NET"? Is there a correspondence between ASP.NET and anything I'd be familiar with in C++? I know I can google the same title, but I'd rather see answers from this crowd. (Besides, in the future, I think that Google should point here for questions like that.)
TITLE: What is ASP.NET? QUESTION: I've been strictly in a C++ environment for years (and specialized statistical languages). Visual Studio until 2001, and Borland since. Mostly specialized desktop applications for clients. I'm not remaining willfully ignorant of it, but over the years when I've dipped into other things, I've spent my time playing around with JavaScript, PHP, and a lot of Python. Is " ASP.NET " the language? Is C# the language and "ASP.NET" the framework? What's a good answer to "What is ASP.NET"? Is there a correspondence between ASP.NET and anything I'd be familiar with in C++? I know I can google the same title, but I'd rather see answers from this crowd. (Besides, in the future, I think that Google should point here for questions like that.) ANSWER: ASP.NET is a web application framework developed and marketed by Microsoft, that programmers can use to build dynamic web sites, web applications and web services. It was first released in January 2002 with version 1.0 of the.NET Framework, and is the successor to Microsoft's Active Server Pages (ASP) technology. ASP.NET is built on the Common Language Runtime (CLR), allowing programmers to write ASP.NET code using any supported.NET language. ASP.NET (Wikipedia) That's on the second result searching on Google so I'm guessing (half-expecting) that you don't understand what that means either. Webpage development started with simple static HTML pages. That meant the client asked for a page by means of an URL and the server sent the page back to him/her exactly as it has been designed. Sometime after that several technologies emerged in order to provide a more "dynamic" or personalized experience. Several "server side languages" were developed (PHP, Perl, ASP...) which allowed the server to process the Web page before sending it back to the client. This way when a client requested a webpage the server could interpret the request, process it (for example connecting to a database and fetching some results) and send it back modifying the contents and making them "dynamic". The fact that the process took place on the server stands for the name of "server side". So the original ASP (predecessor of the ASP.NET) was a server side language that was focused on serving web pages. In such way it supported several shortcuts such as the possibility to intercalate HTML and ASP source into the file which was on that time much popular due to PHP implementation. It was also (as most of these languages) a dynamic language and it was interpreted. ASP.NET is an evolution of that original ASP with some improvements. First it does truly (try to) separate the presentation (HTML) from the code (.cs) which may be implemented by using Visual Basic or C# syntax. It also incorporate some sort of compilation to the final ASP pages, encapsulating them into assemblies and thus improving performance. Finally it has access to the full.NET framework which supports a wide number of helper classes. So, summing up, it is a programming language located on the server and designed to make webpages.
[ "asp.net", "glossary" ]
9
5
1,492
6
0
2008-08-25T12:14:39.580000
2008-08-25T12:38:41.223000
25,938
30,841
Summary fields in Crystal Report VS2008
I need to have a summary field in each page of the report and in page 2 and forward the same summary has to appear at the top of the page. Anyone know how to do this? Ex: > > Page 1 > > Name Value > a 1 > b 3 > Total 4 > > Page 2 > Name Value > Total Before 4 > c 5 > d 1 > Total 10
Create a new Running Total Field called, for example "RTotal". In "Field to summarize" select "Value", in "Type of summary" select "sum", under "Evaluate" select "For each record". You can then drag this field into your report to use as the "Total" at the bottom of each page. You cannot use this running total field in the page header too, however, because Crystal will add the value in the first row on the page to it first (so in your example it would show 9 rather than 4 at the top of page 2). To work around this, create a formula field which subtracts the current value of the Value field from the running total (e.g. {#RTotal}-{TableName.Value}), and put this formula field in your page header.
Summary fields in Crystal Report VS2008 I need to have a summary field in each page of the report and in page 2 and forward the same summary has to appear at the top of the page. Anyone know how to do this? Ex: > > Page 1 > > Name Value > a 1 > b 3 > Total 4 > > Page 2 > Name Value > Total Before 4 > c 5 > d 1 > Total 10
TITLE: Summary fields in Crystal Report VS2008 QUESTION: I need to have a summary field in each page of the report and in page 2 and forward the same summary has to appear at the top of the page. Anyone know how to do this? Ex: > > Page 1 > > Name Value > a 1 > b 3 > Total 4 > > Page 2 > Name Value > Total Before 4 > c 5 > d 1 > Total 10 ANSWER: Create a new Running Total Field called, for example "RTotal". In "Field to summarize" select "Value", in "Type of summary" select "sum", under "Evaluate" select "For each record". You can then drag this field into your report to use as the "Total" at the bottom of each page. You cannot use this running total field in the page header too, however, because Crystal will add the value in the first row on the page to it first (so in your example it would show 9 rather than 4 at the top of page 2). To work around this, create a formula field which subtracts the current value of the Value field from the running total (e.g. {#RTotal}-{TableName.Value}), and put this formula field in your page header.
[ "visual-studio-2008", "crystal-reports" ]
0
1
2,994
2
0
2008-08-25T12:23:47.657000
2008-08-27T18:40:52.333000
25,952
2,707,368
Best programming based games
Back when I was at school, I remember tinkering with a Mac game where you programmed little robots in a sort of pseudo-assembler language which could then battle each other. They could move themselves around the arena, look for opponents in different directions, and fire some sort of weapon. Pretty basic stuff, but I remember it quite fondly, even if I can't remember the name. Are there any good modern day equivalents?
The game in question was definitely Robowar for the Mac. My son had a lot of fun with it and went on to program real robots. As mentioned earlier by Proud, there is a wiki page for it: http://en.wikipedia.org/wiki/RoboWar Although there has not been a lot of activity surrounding the game over the last few years, there was a tournament held recently, and there is a yahoo email group.
Best programming based games Back when I was at school, I remember tinkering with a Mac game where you programmed little robots in a sort of pseudo-assembler language which could then battle each other. They could move themselves around the arena, look for opponents in different directions, and fire some sort of weapon. Pretty basic stuff, but I remember it quite fondly, even if I can't remember the name. Are there any good modern day equivalents?
TITLE: Best programming based games QUESTION: Back when I was at school, I remember tinkering with a Mac game where you programmed little robots in a sort of pseudo-assembler language which could then battle each other. They could move themselves around the arena, look for opponents in different directions, and fire some sort of weapon. Pretty basic stuff, but I remember it quite fondly, even if I can't remember the name. Are there any good modern day equivalents? ANSWER: The game in question was definitely Robowar for the Mac. My son had a lot of fun with it and went on to program real robots. As mentioned earlier by Proud, there is a wiki page for it: http://en.wikipedia.org/wiki/RoboWar Although there has not been a lot of activity surrounding the game over the last few years, there was a tournament held recently, and there is a yahoo email group.
[ "artificial-intelligence" ]
113
13
104,687
43
0
2008-08-25T12:34:43.323000
2010-04-25T06:22:48.567000
25,969
25,971
Insert into ... values ( SELECT ... FROM ... )
I am trying to INSERT INTO a table using the input from another table. Although this is entirely feasible for many database engines, I always seem to struggle to remember the correct syntax for the SQL engine of the day ( MySQL, Oracle, SQL Server, Informix, and DB2 ). Is there a silver-bullet syntax coming from an SQL standard (for example, SQL-92 ) that would allow me to insert the values without worrying about the underlying database?
Try: INSERT INTO table1 ( column1 ) SELECT col1 FROM table2 This is standard ANSI SQL and should work on any DBMS It definitely works for: Oracle MS SQL Server MySQL Postgres SQLite v3 Teradata DB2 Sybase Vertica HSQLDB H2 AWS RedShift SAP HANA Google Spanner
Insert into ... values ( SELECT ... FROM ... ) I am trying to INSERT INTO a table using the input from another table. Although this is entirely feasible for many database engines, I always seem to struggle to remember the correct syntax for the SQL engine of the day ( MySQL, Oracle, SQL Server, Informix, and DB2 ). Is there a silver-bullet syntax coming from an SQL standard (for example, SQL-92 ) that would allow me to insert the values without worrying about the underlying database?
TITLE: Insert into ... values ( SELECT ... FROM ... ) QUESTION: I am trying to INSERT INTO a table using the input from another table. Although this is entirely feasible for many database engines, I always seem to struggle to remember the correct syntax for the SQL engine of the day ( MySQL, Oracle, SQL Server, Informix, and DB2 ). Is there a silver-bullet syntax coming from an SQL standard (for example, SQL-92 ) that would allow me to insert the values without worrying about the underlying database? ANSWER: Try: INSERT INTO table1 ( column1 ) SELECT col1 FROM table2 This is standard ANSI SQL and should work on any DBMS It definitely works for: Oracle MS SQL Server MySQL Postgres SQLite v3 Teradata DB2 Sybase Vertica HSQLDB H2 AWS RedShift SAP HANA Google Spanner
[ "sql", "database", "syntax", "database-agnostic", "ansi-sql-92" ]
1,838
2,023
3,387,963
27
0
2008-08-25T12:45:56.930000
2008-08-25T12:47:54.460000
25,975
25,987
How can I get the name of the executing .exe?
The Compact Framework doesn't support Assembly.GetEntryAssembly to determine the launching.exe. So is there another way to get the name of the executing.exe? EDIT: I found the answer on Peter Foot's blog: http://peterfoot.net/default.aspx Here is the code: byte[] buffer = new byte[MAX_PATH * 2]; int chars = GetModuleFileName(IntPtr.Zero, buffer, MAX_PATH); if (chars > 0) { string assemblyPath = System.Text.Encoding.Unicode.GetString(buffer, 0, chars * 2); } [DllImport("coredll.dll", SetLastError = true)] private static extern int GetModuleFileName(IntPtr hModule, byte[] lpFilename, int nSize);
I am not sure whether it works from managed code (or even the compact framework), but in Win32 you can call GetModuleFileName to find the running exe file. MSDN: GetModuleFileName
How can I get the name of the executing .exe? The Compact Framework doesn't support Assembly.GetEntryAssembly to determine the launching.exe. So is there another way to get the name of the executing.exe? EDIT: I found the answer on Peter Foot's blog: http://peterfoot.net/default.aspx Here is the code: byte[] buffer = new byte[MAX_PATH * 2]; int chars = GetModuleFileName(IntPtr.Zero, buffer, MAX_PATH); if (chars > 0) { string assemblyPath = System.Text.Encoding.Unicode.GetString(buffer, 0, chars * 2); } [DllImport("coredll.dll", SetLastError = true)] private static extern int GetModuleFileName(IntPtr hModule, byte[] lpFilename, int nSize);
TITLE: How can I get the name of the executing .exe? QUESTION: The Compact Framework doesn't support Assembly.GetEntryAssembly to determine the launching.exe. So is there another way to get the name of the executing.exe? EDIT: I found the answer on Peter Foot's blog: http://peterfoot.net/default.aspx Here is the code: byte[] buffer = new byte[MAX_PATH * 2]; int chars = GetModuleFileName(IntPtr.Zero, buffer, MAX_PATH); if (chars > 0) { string assemblyPath = System.Text.Encoding.Unicode.GetString(buffer, 0, chars * 2); } [DllImport("coredll.dll", SetLastError = true)] private static extern int GetModuleFileName(IntPtr hModule, byte[] lpFilename, int nSize); ANSWER: I am not sure whether it works from managed code (or even the compact framework), but in Win32 you can call GetModuleFileName to find the running exe file. MSDN: GetModuleFileName
[ ".net", "compact-framework", "windows-ce" ]
4
4
2,983
3
0
2008-08-25T12:51:33.127000
2008-08-25T12:56:35.267000
25,977
26,061
How can I measure the similarity between two images?
I would like to compare a screenshot of one application (could be a Web page) with a previously taken screenshot to determine whether the application is displaying itself correctly. I don't want an exact match comparison, because the aspect could be slightly different (in the case of a Web app, depending on the browser, some element could be at a slightly different location). It should give a measure of how similar are the screenshots. Is there a library / tool that already does that? How would you implement it?
This depends entirely on how smart you want the algorithm to be. For instance, here are some issues: cropped images vs. an uncropped image images with a text added vs. another without mirrored images The easiest and simplest algorithm I've seen for this is just to do the following steps to each image: scale to something small, like 64x64 or 32x32, disregard aspect ratio, use a combining scaling algorithm instead of nearest pixel scale the color ranges so that the darkest is black and lightest is white rotate and flip the image so that the lighest color is top left, and then top-right is next darker, bottom-left is next darker (as far as possible of course) Edit A combining scaling algorithm is one that when scaling 10 pixels down to one will do it using a function that takes the color of all those 10 pixels and combines them into one. Can be done with algorithms like averaging, mean-value, or more complex ones like bicubic splines. Then calculate the mean distance pixel-by-pixel between the two images. To look up a possible match in a database, store the pixel colors as individual columns in the database, index a bunch of them (but not all, unless you use a very small image), and do a query that uses a range for each pixel value, ie. every image where the pixel in the small image is between -5 and +5 of the image you want to look up. This is easy to implement, and fairly fast to run, but of course won't handle most advanced differences. For that you need much more advanced algorithms.
How can I measure the similarity between two images? I would like to compare a screenshot of one application (could be a Web page) with a previously taken screenshot to determine whether the application is displaying itself correctly. I don't want an exact match comparison, because the aspect could be slightly different (in the case of a Web app, depending on the browser, some element could be at a slightly different location). It should give a measure of how similar are the screenshots. Is there a library / tool that already does that? How would you implement it?
TITLE: How can I measure the similarity between two images? QUESTION: I would like to compare a screenshot of one application (could be a Web page) with a previously taken screenshot to determine whether the application is displaying itself correctly. I don't want an exact match comparison, because the aspect could be slightly different (in the case of a Web app, depending on the browser, some element could be at a slightly different location). It should give a measure of how similar are the screenshots. Is there a library / tool that already does that? How would you implement it? ANSWER: This depends entirely on how smart you want the algorithm to be. For instance, here are some issues: cropped images vs. an uncropped image images with a text added vs. another without mirrored images The easiest and simplest algorithm I've seen for this is just to do the following steps to each image: scale to something small, like 64x64 or 32x32, disregard aspect ratio, use a combining scaling algorithm instead of nearest pixel scale the color ranges so that the darkest is black and lightest is white rotate and flip the image so that the lighest color is top left, and then top-right is next darker, bottom-left is next darker (as far as possible of course) Edit A combining scaling algorithm is one that when scaling 10 pixels down to one will do it using a function that takes the color of all those 10 pixels and combines them into one. Can be done with algorithms like averaging, mean-value, or more complex ones like bicubic splines. Then calculate the mean distance pixel-by-pixel between the two images. To look up a possible match in a database, store the pixel colors as individual columns in the database, index a bunch of them (but not all, unless you use a very small image), and do a query that uses a range for each pixel value, ie. every image where the pixel in the small image is between -5 and +5 of the image you want to look up. This is easy to implement, and fairly fast to run, but of course won't handle most advanced differences. For that you need much more advanced algorithms.
[ "algorithm", "language-agnostic", "image", "image-processing" ]
103
77
117,877
17
0
2008-08-25T12:51:49.053000
2008-08-25T13:53:36.627000
25,982
27,450
What's the simplest way to connect to a .NET remote server object
Given that my client code knows everything it needs to about the remoting object, what's the simplest way to connect to it? This is what I'm doing at the moment: ChannelServices.RegisterChannel(new HttpChannel(), false); RemotingConfiguration.RegisterWellKnownServiceType( typeof(IRemoteServer), "RemoteServer.rem", WellKnownObjectMode.Singleton); MyServerObject = (IRemoteServer)Activator.GetObject( typeof(IRemoteServer), String.Format("tcp://{0}:{1}/RemoteServer.rem", server, port));
The first two lines are in the server-side code, for marshaling out the server object, yes? In that case, yes, the third line is the simplest you can get at client-side. In addition, you can serve out additional server-side objects from the MyServerObject instance, if you include public accessors for them in IRemoteServer interface, so, accessing those objects become the simple matter of method calls or property accesses on your main server object, so you don't have to use activator for every single thing: //obtain another marshalbyref object of the type ISessionManager: ISessionManager = MyServerObject.GetSessionManager();
What's the simplest way to connect to a .NET remote server object Given that my client code knows everything it needs to about the remoting object, what's the simplest way to connect to it? This is what I'm doing at the moment: ChannelServices.RegisterChannel(new HttpChannel(), false); RemotingConfiguration.RegisterWellKnownServiceType( typeof(IRemoteServer), "RemoteServer.rem", WellKnownObjectMode.Singleton); MyServerObject = (IRemoteServer)Activator.GetObject( typeof(IRemoteServer), String.Format("tcp://{0}:{1}/RemoteServer.rem", server, port));
TITLE: What's the simplest way to connect to a .NET remote server object QUESTION: Given that my client code knows everything it needs to about the remoting object, what's the simplest way to connect to it? This is what I'm doing at the moment: ChannelServices.RegisterChannel(new HttpChannel(), false); RemotingConfiguration.RegisterWellKnownServiceType( typeof(IRemoteServer), "RemoteServer.rem", WellKnownObjectMode.Singleton); MyServerObject = (IRemoteServer)Activator.GetObject( typeof(IRemoteServer), String.Format("tcp://{0}:{1}/RemoteServer.rem", server, port)); ANSWER: The first two lines are in the server-side code, for marshaling out the server object, yes? In that case, yes, the third line is the simplest you can get at client-side. In addition, you can serve out additional server-side objects from the MyServerObject instance, if you include public accessors for them in IRemoteServer interface, so, accessing those objects become the simple matter of method calls or property accesses on your main server object, so you don't have to use activator for every single thing: //obtain another marshalbyref object of the type ISessionManager: ISessionManager = MyServerObject.GetSessionManager();
[ "c#", ".net", "remoting", "remote-server" ]
1
1
1,029
2
0
2008-08-25T12:54:52.307000
2008-08-26T05:31:49.867000
25,999
145,450
Secure Online Highscore Lists for Non-Web Games
I'm playing around with a native (non-web) single-player game I'm writing, and it occured to me that having a daily/weekly/all-time online highscore list (think Xbox Live Leaderboard) would make the game much more interesting, adding some (small) amount of community and competition. However, I'm afraid people would see such a feature as an invitation to hacking, which would discourage regular players due to impossibly high scores. I thought about the obvious ways of preventing such attempts (public/private key encryption, for example), but I've figured out reasonably simple ways hackers could circumvent all of my ideas (extracting the public key from the binary and thus sending fake encrypted scores, for example). Have you ever implemented an online highscore list or leaderboard? Did you find a reasonably hacker-proof way of implementing this? If so, how did you do it? What are your experiences with hacking attempts?
At the end of the day, you are relying on trusting the client. If the client sends replays to the server, it is easy enough to replicable or modify a successful playthrough and send that to the server. Your best bet is to raise the bar for cheating above what a player would deem worth surmounting. To do this, there are a number of proven (but oft-unmentioned) techniques you can use: Leave blacklisted cheaters in a honeypot. They can see their own scores, but no one else can. Unless they verify by logging in with a different account, they think they have successfully hacked your game. When someone is flagged as a cheater, defer any account repercussions from transpiring until a given point in the future. Make this point random, within one to three days. Typically, a cheater will try multiple methods and will eventually succeed. By deferring account status feedback until a later date, they fail to understand what got them caught. Capture all game user commands and send them to the server. Verify them against other scores within a given delta. For instance, if the player used the shoot action 200 times, but obtained a score of 200,000, but the neighboring players in the game shot 5,000 times to obtain a score of 210,000, it may trigger a threshold that flags the person for further or human investigation. Add value and persistence to your user accounts. If your user accounts have unlockables for your game, or if your game requires purchase, the weight of a ban is greater as the user cannot regain his previous account status by simply creating a new account through a web-based proxy.
Secure Online Highscore Lists for Non-Web Games I'm playing around with a native (non-web) single-player game I'm writing, and it occured to me that having a daily/weekly/all-time online highscore list (think Xbox Live Leaderboard) would make the game much more interesting, adding some (small) amount of community and competition. However, I'm afraid people would see such a feature as an invitation to hacking, which would discourage regular players due to impossibly high scores. I thought about the obvious ways of preventing such attempts (public/private key encryption, for example), but I've figured out reasonably simple ways hackers could circumvent all of my ideas (extracting the public key from the binary and thus sending fake encrypted scores, for example). Have you ever implemented an online highscore list or leaderboard? Did you find a reasonably hacker-proof way of implementing this? If so, how did you do it? What are your experiences with hacking attempts?
TITLE: Secure Online Highscore Lists for Non-Web Games QUESTION: I'm playing around with a native (non-web) single-player game I'm writing, and it occured to me that having a daily/weekly/all-time online highscore list (think Xbox Live Leaderboard) would make the game much more interesting, adding some (small) amount of community and competition. However, I'm afraid people would see such a feature as an invitation to hacking, which would discourage regular players due to impossibly high scores. I thought about the obvious ways of preventing such attempts (public/private key encryption, for example), but I've figured out reasonably simple ways hackers could circumvent all of my ideas (extracting the public key from the binary and thus sending fake encrypted scores, for example). Have you ever implemented an online highscore list or leaderboard? Did you find a reasonably hacker-proof way of implementing this? If so, how did you do it? What are your experiences with hacking attempts? ANSWER: At the end of the day, you are relying on trusting the client. If the client sends replays to the server, it is easy enough to replicable or modify a successful playthrough and send that to the server. Your best bet is to raise the bar for cheating above what a player would deem worth surmounting. To do this, there are a number of proven (but oft-unmentioned) techniques you can use: Leave blacklisted cheaters in a honeypot. They can see their own scores, but no one else can. Unless they verify by logging in with a different account, they think they have successfully hacked your game. When someone is flagged as a cheater, defer any account repercussions from transpiring until a given point in the future. Make this point random, within one to three days. Typically, a cheater will try multiple methods and will eventually succeed. By deferring account status feedback until a later date, they fail to understand what got them caught. Capture all game user commands and send them to the server. Verify them against other scores within a given delta. For instance, if the player used the shoot action 200 times, but obtained a score of 200,000, but the neighboring players in the game shot 5,000 times to obtain a score of 210,000, it may trigger a threshold that flags the person for further or human investigation. Add value and persistence to your user accounts. If your user accounts have unlockables for your game, or if your game requires purchase, the weight of a ban is greater as the user cannot regain his previous account status by simply creating a new account through a web-based proxy.
[ "encryption", "leaderboard" ]
25
42
9,476
10
0
2008-08-25T13:10:37.997000
2008-09-28T08:04:12.063000
26,002
26,005
Develop on local Oracle instance
I want our team to develop against local instances of an Oracle database. With MS SQL, I can use SQL Express Edition. What are my options?
Oracle has an express edition as well. I believe it is more limited though (IIRC, you can only have one database on an instance) Oracle XE
Develop on local Oracle instance I want our team to develop against local instances of an Oracle database. With MS SQL, I can use SQL Express Edition. What are my options?
TITLE: Develop on local Oracle instance QUESTION: I want our team to develop against local instances of an Oracle database. With MS SQL, I can use SQL Express Edition. What are my options? ANSWER: Oracle has an express edition as well. I believe it is more limited though (IIRC, you can only have one database on an instance) Oracle XE
[ "oracle" ]
27
21
15,056
6
0
2008-08-25T13:14:00.687000
2008-08-25T13:16:42.863000
26,007
26,018
Iterating over a complex Associative Array in PHP
Is there an easy way to iterate over an associative array of this structure in PHP: The array $searches has a numbered index, with between 4 and 5 associative parts. So I not only need to iterate over $searches[0] through $searches[n], but also $searches[0]["part0"] through $searches[n]["partn"]. The hard part is that different indexes have different numbers of parts (some might be missing one or two). Thoughts on doing this in a way that's nice, neat, and understandable?
Nest two foreach loops: foreach ($array as $i => $values) { print "$i {\n"; foreach ($values as $key => $value) { print " $key => $value\n"; } print "}\n"; }
Iterating over a complex Associative Array in PHP Is there an easy way to iterate over an associative array of this structure in PHP: The array $searches has a numbered index, with between 4 and 5 associative parts. So I not only need to iterate over $searches[0] through $searches[n], but also $searches[0]["part0"] through $searches[n]["partn"]. The hard part is that different indexes have different numbers of parts (some might be missing one or two). Thoughts on doing this in a way that's nice, neat, and understandable?
TITLE: Iterating over a complex Associative Array in PHP QUESTION: Is there an easy way to iterate over an associative array of this structure in PHP: The array $searches has a numbered index, with between 4 and 5 associative parts. So I not only need to iterate over $searches[0] through $searches[n], but also $searches[0]["part0"] through $searches[n]["partn"]. The hard part is that different indexes have different numbers of parts (some might be missing one or two). Thoughts on doing this in a way that's nice, neat, and understandable? ANSWER: Nest two foreach loops: foreach ($array as $i => $values) { print "$i {\n"; foreach ($values as $key => $value) { print " $key => $value\n"; } print "}\n"; }
[ "php", "arrays", "associative-array" ]
21
43
59,714
7
0
2008-08-25T13:17:17.590000
2008-08-25T13:24:28.990000
26,020
26,035
What is the best way to connect and use a sqlite database from C#
I've done this before in C++ by including sqlite.h but is there a similarly easy way in C#?
Microsoft.Data.Sqlite by Microsoft has over 9000 downloads every day, so I think you are safe using that one. Example usage from the documentation: using (var connection = new SqliteConnection("Data Source=hello.db")) { connection.Open(); var command = connection.CreateCommand(); command.CommandText = @" SELECT name FROM user WHERE id = $id "; command.Parameters.AddWithValue("$id", id); using (var reader = command.ExecuteReader()) { while (reader.Read()) { var name = reader.GetString(0); Console.WriteLine($"Hello, {name}!"); } } }
What is the best way to connect and use a sqlite database from C# I've done this before in C++ by including sqlite.h but is there a similarly easy way in C#?
TITLE: What is the best way to connect and use a sqlite database from C# QUESTION: I've done this before in C++ by including sqlite.h but is there a similarly easy way in C#? ANSWER: Microsoft.Data.Sqlite by Microsoft has over 9000 downloads every day, so I think you are safe using that one. Example usage from the documentation: using (var connection = new SqliteConnection("Data Source=hello.db")) { connection.Open(); var command = connection.CreateCommand(); command.CommandText = @" SELECT name FROM user WHERE id = $id "; command.Parameters.AddWithValue("$id", id); using (var reader = command.ExecuteReader()) { while (reader.Read()) { var name = reader.GetString(0); Console.WriteLine($"Hello, {name}!"); } } }
[ "c#", "sqlite" ]
58
50
139,175
10
0
2008-08-25T13:25:44.230000
2008-08-25T13:34:49.043000
26,021
26,046
How is data compression more effective than indexing for search performance?
For our application, we keep large amounts of data indexed by three integer columns (source, type and time). Loading significant chunks of that data can take some time and we have implemented various measures to reduce the amount of data that has to be searched and loaded for larger queries, such as storing larger granularities for queries that don't require a high resolution (time-wise). When searching for data in our backup archives, where the data is stored in bzipped text files, but has basically the same structure, I noticed that it is significantly faster to untar to stdout and pipe it through grep than to untar it to disk and grep the files. In fact, the untar-to-pipe was even noticeably faster than just grepping the uncompressed files (i. e. discounting the untar-to-disk). This made me wonder if the performance impact of disk I/O is actually much heavier than I thought. So here's my question: Do you think putting the data of multiple rows into a (compressed) blob field of a single row and search for single rows on the fly during extraction could be faster than searching for the same rows via the table index? For example, instead of having this table CREATE TABLE data ( `source` INT, `type` INT, `timestamp` INT, `value` DOUBLE); I would have CREATE TABLE quickdata ( `source` INT, `type` INT, `day` INT, `dayvalues` BLOB ); with approximately 100-300 rows in data for each row in quickdata and searching for the desired timestamps on the fly during decompression and decoding of the blob field. Does this make sense to you? What parameters should I investigate? What strings might be attached? What DB features (any DBMS) exist to achieve similar effects?
This made me wonder if the performance impact of disk I/O is actually much heavier than I thought. Definitely. If you have to go to disk, the performance hit is many orders of magnitude greater than memory. This reminds me of the classic Jim Gray paper, Distributed Computing Economics: Computing economics are changing. Today there is rough price parity between (1) one database access, (2) ten bytes of network traffic, (3) 100,000 instructions, (4) 10 bytes of disk storage, and (5) a megabyte of disk bandwidth. This has implications for how one structures Internet-scale distributed computing: one puts computing as close to the data as possible in order to avoid expensive network traffic. The question, then, is how much data do you have and how much memory can you afford? And if the database gets really big -- as in nobody could ever afford that much memory, even in 20 years -- you need clever distributed database systems like Google's BigTable or Hadoop.
How is data compression more effective than indexing for search performance? For our application, we keep large amounts of data indexed by three integer columns (source, type and time). Loading significant chunks of that data can take some time and we have implemented various measures to reduce the amount of data that has to be searched and loaded for larger queries, such as storing larger granularities for queries that don't require a high resolution (time-wise). When searching for data in our backup archives, where the data is stored in bzipped text files, but has basically the same structure, I noticed that it is significantly faster to untar to stdout and pipe it through grep than to untar it to disk and grep the files. In fact, the untar-to-pipe was even noticeably faster than just grepping the uncompressed files (i. e. discounting the untar-to-disk). This made me wonder if the performance impact of disk I/O is actually much heavier than I thought. So here's my question: Do you think putting the data of multiple rows into a (compressed) blob field of a single row and search for single rows on the fly during extraction could be faster than searching for the same rows via the table index? For example, instead of having this table CREATE TABLE data ( `source` INT, `type` INT, `timestamp` INT, `value` DOUBLE); I would have CREATE TABLE quickdata ( `source` INT, `type` INT, `day` INT, `dayvalues` BLOB ); with approximately 100-300 rows in data for each row in quickdata and searching for the desired timestamps on the fly during decompression and decoding of the blob field. Does this make sense to you? What parameters should I investigate? What strings might be attached? What DB features (any DBMS) exist to achieve similar effects?
TITLE: How is data compression more effective than indexing for search performance? QUESTION: For our application, we keep large amounts of data indexed by three integer columns (source, type and time). Loading significant chunks of that data can take some time and we have implemented various measures to reduce the amount of data that has to be searched and loaded for larger queries, such as storing larger granularities for queries that don't require a high resolution (time-wise). When searching for data in our backup archives, where the data is stored in bzipped text files, but has basically the same structure, I noticed that it is significantly faster to untar to stdout and pipe it through grep than to untar it to disk and grep the files. In fact, the untar-to-pipe was even noticeably faster than just grepping the uncompressed files (i. e. discounting the untar-to-disk). This made me wonder if the performance impact of disk I/O is actually much heavier than I thought. So here's my question: Do you think putting the data of multiple rows into a (compressed) blob field of a single row and search for single rows on the fly during extraction could be faster than searching for the same rows via the table index? For example, instead of having this table CREATE TABLE data ( `source` INT, `type` INT, `timestamp` INT, `value` DOUBLE); I would have CREATE TABLE quickdata ( `source` INT, `type` INT, `day` INT, `dayvalues` BLOB ); with approximately 100-300 rows in data for each row in quickdata and searching for the desired timestamps on the fly during decompression and decoding of the blob field. Does this make sense to you? What parameters should I investigate? What strings might be attached? What DB features (any DBMS) exist to achieve similar effects? ANSWER: This made me wonder if the performance impact of disk I/O is actually much heavier than I thought. Definitely. If you have to go to disk, the performance hit is many orders of magnitude greater than memory. This reminds me of the classic Jim Gray paper, Distributed Computing Economics: Computing economics are changing. Today there is rough price parity between (1) one database access, (2) ten bytes of network traffic, (3) 100,000 instructions, (4) 10 bytes of disk storage, and (5) a megabyte of disk bandwidth. This has implications for how one structures Internet-scale distributed computing: one puts computing as close to the data as possible in order to avoid expensive network traffic. The question, then, is how much data do you have and how much memory can you afford? And if the database gets really big -- as in nobody could ever afford that much memory, even in 20 years -- you need clever distributed database systems like Google's BigTable or Hadoop.
[ "database", "performance" ]
3
4
392
2
0
2008-08-25T13:26:15.947000
2008-08-25T13:43:41.643000
26,025
29,748
Cleanest & Fastest server setup for Django
I'm about to deploy a mediumsized site powered by Django. I have a dedicated Ubuntu Server. I'm really confused over which serversoftware to use. So i thought to myself: why not ask stackoverflow. What i'm looking for is: Easy to set up Fast and easy on resources Can serve mediafiles Able to serve multiple djangosites on same server I would rather not install PHP or anything else that sucks resources, and for which I have no use for. I have heard of mod_wsgi and mod_python on Apache, nginx and lighty. Which are the pros and cons of these and have i missed someone? @Barry: Somehow i feel like Apache is to bloated for me. What about the alternatives? @BrianLy: Ok I'll check out mod_wsgi some more. But why do i need Apache if i serve static files with lighty? I have also managed to serve the django app itself with lighty. Is that bad in anyway? Sorry for beeing so stupid:-) UPDATE: What about lighty and nginx - which are the uses-cases when these are the perfect choice?
Since I was looking for some more in-depth answers, I decided to research the issue myself in depth. Please let me know if I've misunderstood anything. Some general recommendation are to use a separate webserver for handling media. By separate, I mean a webserver which is not running Django. This server can be for instance: Lighttpd (Lighty) Nginx (EngineX) Or some other light-weight server Then, for Django, you can go down different paths. You can either: Serve Django via Apache and: mod_python This is the stable and recommended/well documented way. Cons: uses a lot of memory. mod_wsgi From what I understand, mod_wsgi is a newer alternative. It appears to be faster and easier on resources. mod_fastcgi When using FastCGI you are delegating the serving of Django to another process. Since mod_python includes a python interpreter in every request it uses a lot of memory. This is a way to bypass that problem. Also there is some security concerns. What you do is that you start your Django FastCGI server in a separate process and then configures apache via rewrites to call this process when needed. Or you can: Serve Django without using Apache but with another server that supports FastCGI natively: (The documentation mentions that you can do this if you don't have any Apache specific needs. I guess the reason must be to save memory.) Lighttpd This is the server that runs Youtube. It seems fast and easy to use, however i've seen reports on memoryleaks. nginx I've seen benchmarks claiming that this server is even faster than lighttpd. It's mostly documented in Russian though. Another thing, due to limitations in Python your server should be running in forked mode, not threaded. So this is my current research, but I want more opinions and experiences.
Cleanest & Fastest server setup for Django I'm about to deploy a mediumsized site powered by Django. I have a dedicated Ubuntu Server. I'm really confused over which serversoftware to use. So i thought to myself: why not ask stackoverflow. What i'm looking for is: Easy to set up Fast and easy on resources Can serve mediafiles Able to serve multiple djangosites on same server I would rather not install PHP or anything else that sucks resources, and for which I have no use for. I have heard of mod_wsgi and mod_python on Apache, nginx and lighty. Which are the pros and cons of these and have i missed someone? @Barry: Somehow i feel like Apache is to bloated for me. What about the alternatives? @BrianLy: Ok I'll check out mod_wsgi some more. But why do i need Apache if i serve static files with lighty? I have also managed to serve the django app itself with lighty. Is that bad in anyway? Sorry for beeing so stupid:-) UPDATE: What about lighty and nginx - which are the uses-cases when these are the perfect choice?
TITLE: Cleanest & Fastest server setup for Django QUESTION: I'm about to deploy a mediumsized site powered by Django. I have a dedicated Ubuntu Server. I'm really confused over which serversoftware to use. So i thought to myself: why not ask stackoverflow. What i'm looking for is: Easy to set up Fast and easy on resources Can serve mediafiles Able to serve multiple djangosites on same server I would rather not install PHP or anything else that sucks resources, and for which I have no use for. I have heard of mod_wsgi and mod_python on Apache, nginx and lighty. Which are the pros and cons of these and have i missed someone? @Barry: Somehow i feel like Apache is to bloated for me. What about the alternatives? @BrianLy: Ok I'll check out mod_wsgi some more. But why do i need Apache if i serve static files with lighty? I have also managed to serve the django app itself with lighty. Is that bad in anyway? Sorry for beeing so stupid:-) UPDATE: What about lighty and nginx - which are the uses-cases when these are the perfect choice? ANSWER: Since I was looking for some more in-depth answers, I decided to research the issue myself in depth. Please let me know if I've misunderstood anything. Some general recommendation are to use a separate webserver for handling media. By separate, I mean a webserver which is not running Django. This server can be for instance: Lighttpd (Lighty) Nginx (EngineX) Or some other light-weight server Then, for Django, you can go down different paths. You can either: Serve Django via Apache and: mod_python This is the stable and recommended/well documented way. Cons: uses a lot of memory. mod_wsgi From what I understand, mod_wsgi is a newer alternative. It appears to be faster and easier on resources. mod_fastcgi When using FastCGI you are delegating the serving of Django to another process. Since mod_python includes a python interpreter in every request it uses a lot of memory. This is a way to bypass that problem. Also there is some security concerns. What you do is that you start your Django FastCGI server in a separate process and then configures apache via rewrites to call this process when needed. Or you can: Serve Django without using Apache but with another server that supports FastCGI natively: (The documentation mentions that you can do this if you don't have any Apache specific needs. I guess the reason must be to save memory.) Lighttpd This is the server that runs Youtube. It seems fast and easy to use, however i've seen reports on memoryleaks. nginx I've seen benchmarks claiming that this server is even faster than lighttpd. It's mostly documented in Russian though. Another thing, due to limitations in Python your server should be running in forked mode, not threaded. So this is my current research, but I want more opinions and experiences.
[ "python", "django", "apache", "hosting" ]
47
27
24,341
13
0
2008-08-25T13:28:41.150000
2008-08-27T08:41:53.070000
26,028
27,325
Upgrading Sharepoint 3.0 to SQL 2005 Backend?
We're trying to get rid of all of our SQL Server 2000 databases to re purpose our old DB server... Sharepoint 3.0 is being a showstopper. I've looked at a lot of guides from Microsoft and tried the instructions in those. I've also just tried the good ol' exec sp_detach_db / sp_attach_db with no luck. Has anyone actually done this?
my boss has. it was a real pain. permissions issues. he used the built in sharepoint backup tool. I can more details tomorrow if need. I'll check back. I'm back. Here's the steps he used. install an instance of sql server 2005 on the sql 2000 box (side-by-side) back up the sharepoint site using the sharepoint admin tools. This will create a one mother of a large xml file w/ the whole kit and kaboodle (the site & all it's content) delete the old-n-busted sharepoint site create a new hotness sharepoint site using the sql server 2005 as the database. do a restore from the xml backup using the admin tools - this will take hours to run (thank you xml...) Bingo! P.S. I forgot, the account you use to do the restore must be an 'sa' account.
Upgrading Sharepoint 3.0 to SQL 2005 Backend? We're trying to get rid of all of our SQL Server 2000 databases to re purpose our old DB server... Sharepoint 3.0 is being a showstopper. I've looked at a lot of guides from Microsoft and tried the instructions in those. I've also just tried the good ol' exec sp_detach_db / sp_attach_db with no luck. Has anyone actually done this?
TITLE: Upgrading Sharepoint 3.0 to SQL 2005 Backend? QUESTION: We're trying to get rid of all of our SQL Server 2000 databases to re purpose our old DB server... Sharepoint 3.0 is being a showstopper. I've looked at a lot of guides from Microsoft and tried the instructions in those. I've also just tried the good ol' exec sp_detach_db / sp_attach_db with no luck. Has anyone actually done this? ANSWER: my boss has. it was a real pain. permissions issues. he used the built in sharepoint backup tool. I can more details tomorrow if need. I'll check back. I'm back. Here's the steps he used. install an instance of sql server 2005 on the sql 2000 box (side-by-side) back up the sharepoint site using the sharepoint admin tools. This will create a one mother of a large xml file w/ the whole kit and kaboodle (the site & all it's content) delete the old-n-busted sharepoint site create a new hotness sharepoint site using the sql server 2005 as the database. do a restore from the xml backup using the admin tools - this will take hours to run (thank you xml...) Bingo! P.S. I forgot, the account you use to do the restore must be an 'sa' account.
[ "sql-server-2005", "sharepoint", "sql-server-2000" ]
1
1
745
1
0
2008-08-25T13:29:54.953000
2008-08-26T03:05:38.847000
26,062
163,041
Can DTS Test for Presence of MS-Access Table
I have an Access database in which I drop the table and then create the table afresh. However, I need to be able to test for the table in case the table gets dropped but not created (i.e. when someone stops the DTS package just after it starts -roll-eyes- ). If I were doing this in the SQL database I would just do: IF (EXISTS (SELECT * FROM sysobjects WHERE name = 'Table-Name-to-look-for')) BEGIN drop table 'Table-Name-to-look-for' END But how do I do that for an Access database? Optional answer: is there a way to have the DTS package ignore the error and just go to the next step rather than checking to see if it exists? SQL Server 2000
I'm not sure whether you can query the system objects table in an Access database from a DTS package. If that doesn't work, why not just try doing a SELECT * from the Access table in question and then catch the error if it fails?
Can DTS Test for Presence of MS-Access Table I have an Access database in which I drop the table and then create the table afresh. However, I need to be able to test for the table in case the table gets dropped but not created (i.e. when someone stops the DTS package just after it starts -roll-eyes- ). If I were doing this in the SQL database I would just do: IF (EXISTS (SELECT * FROM sysobjects WHERE name = 'Table-Name-to-look-for')) BEGIN drop table 'Table-Name-to-look-for' END But how do I do that for an Access database? Optional answer: is there a way to have the DTS package ignore the error and just go to the next step rather than checking to see if it exists? SQL Server 2000
TITLE: Can DTS Test for Presence of MS-Access Table QUESTION: I have an Access database in which I drop the table and then create the table afresh. However, I need to be able to test for the table in case the table gets dropped but not created (i.e. when someone stops the DTS package just after it starts -roll-eyes- ). If I were doing this in the SQL database I would just do: IF (EXISTS (SELECT * FROM sysobjects WHERE name = 'Table-Name-to-look-for')) BEGIN drop table 'Table-Name-to-look-for' END But how do I do that for an Access database? Optional answer: is there a way to have the DTS package ignore the error and just go to the next step rather than checking to see if it exists? SQL Server 2000 ANSWER: I'm not sure whether you can query the system objects table in an Access database from a DTS package. If that doesn't work, why not just try doing a SELECT * from the Access table in question and then catch the error if it fails?
[ "sql-server", "ms-access", "dts" ]
0
1
681
3
0
2008-08-25T13:54:05.583000
2008-10-02T15:34:39.370000
26,074
27,403
How can I figure out how much memory a .Net Appdomain is consuming?
I'm trying to programmatically restrict the memory consumption of plugins running in a.Net AppDomain, but I can't find any setup parameters for this, nor can I find a way to query an AppDomain to figure out how much memory it is consuming. Any ideas?
Here's the documentation for querying a process's memory usage. Not the same as the AppDomain, but it might be a place to start. http://msdn.microsoft.com/en-us/library/s80a75e5(VS.80).aspx You can ask the GC what it thinks is currently allocated also. http://msdn.microsoft.com/en-us/library/system.gc.gettotalmemory(VS.71).aspx
How can I figure out how much memory a .Net Appdomain is consuming? I'm trying to programmatically restrict the memory consumption of plugins running in a.Net AppDomain, but I can't find any setup parameters for this, nor can I find a way to query an AppDomain to figure out how much memory it is consuming. Any ideas?
TITLE: How can I figure out how much memory a .Net Appdomain is consuming? QUESTION: I'm trying to programmatically restrict the memory consumption of plugins running in a.Net AppDomain, but I can't find any setup parameters for this, nor can I find a way to query an AppDomain to figure out how much memory it is consuming. Any ideas? ANSWER: Here's the documentation for querying a process's memory usage. Not the same as the AppDomain, but it might be a place to start. http://msdn.microsoft.com/en-us/library/s80a75e5(VS.80).aspx You can ask the GC what it thinks is currently allocated also. http://msdn.microsoft.com/en-us/library/system.gc.gettotalmemory(VS.71).aspx
[ ".net", "clr" ]
8
0
4,233
4
0
2008-08-25T14:06:38.640000
2008-08-26T04:16:20.597000
26,075
26,700
Resize Infragistics GanttChart task with the mouse
I loaded a custom DataTable into an UltraChart of type GanttChart. The data loads successfully. Do you know if it possible to add support for mouse resize(drag) to the tasks that show up into the chart? I have not been able to figure out if this is supported by the Infragistics control. ­­­­­­­­­­­­­­­­­­­­­­­­­­­
In this forum post, an Infragistics employee states that this is not implemented (as of Feb '08), but may be doable handling FillSceneGraph.
Resize Infragistics GanttChart task with the mouse I loaded a custom DataTable into an UltraChart of type GanttChart. The data loads successfully. Do you know if it possible to add support for mouse resize(drag) to the tasks that show up into the chart? I have not been able to figure out if this is supported by the Infragistics control. ­­­­­­­­­­­­­­­­­­­­­­­­­­­
TITLE: Resize Infragistics GanttChart task with the mouse QUESTION: I loaded a custom DataTable into an UltraChart of type GanttChart. The data loads successfully. Do you know if it possible to add support for mouse resize(drag) to the tasks that show up into the chart? I have not been able to figure out if this is supported by the Infragistics control. ­­­­­­­­­­­­­­­­­­­­­­­­­­­ ANSWER: In this forum post, an Infragistics employee states that this is not implemented (as of Feb '08), but may be doable handling FillSceneGraph.
[ "winforms", "charts", "infragistics", "gantt-chart" ]
0
1
873
1
0
2008-08-25T14:07:31.213000
2008-08-25T19:39:16.047000
26,079
26,097
In a PHP5 class, when does a private constructor get called?
Let's say I'm writing a PHP (>= 5.0) class that's meant to be a singleton. All of the docs I've read say to make the class constructor private so the class can't be directly instantiated. So if I have something like this: class SillyDB { private function __construct() { } public static function getConnection() { } } Are there any cases where __construct() is called other than if I'm doing a new SillyDB() call inside the class itself? And why am I allowed to instantiate SillyDB from inside itself at all?
__construct() would only be called if you called it from within a method for the class containing the private constructor. So for your Singleton, you might have a method like so: class DBConnection { private static $Connection = null; public static function getConnection() { if(!isset(self::$Connection)) { self::$Connection = new DBConnection(); } return self::$Connection; } private function __construct() { } } $dbConnection = DBConnection::getConnection(); The reason you are able/would want to instantiate the class from within itself is so that you can check to make sure that only one instance exists at any given time. This is the whole point of a Singleton, after all. Using a Singleton for a database connection ensures that your application is not making a ton of DB connections at a time. Edit: Added $, as suggested by @emanuele-del-grande
In a PHP5 class, when does a private constructor get called? Let's say I'm writing a PHP (>= 5.0) class that's meant to be a singleton. All of the docs I've read say to make the class constructor private so the class can't be directly instantiated. So if I have something like this: class SillyDB { private function __construct() { } public static function getConnection() { } } Are there any cases where __construct() is called other than if I'm doing a new SillyDB() call inside the class itself? And why am I allowed to instantiate SillyDB from inside itself at all?
TITLE: In a PHP5 class, when does a private constructor get called? QUESTION: Let's say I'm writing a PHP (>= 5.0) class that's meant to be a singleton. All of the docs I've read say to make the class constructor private so the class can't be directly instantiated. So if I have something like this: class SillyDB { private function __construct() { } public static function getConnection() { } } Are there any cases where __construct() is called other than if I'm doing a new SillyDB() call inside the class itself? And why am I allowed to instantiate SillyDB from inside itself at all? ANSWER: __construct() would only be called if you called it from within a method for the class containing the private constructor. So for your Singleton, you might have a method like so: class DBConnection { private static $Connection = null; public static function getConnection() { if(!isset(self::$Connection)) { self::$Connection = new DBConnection(); } return self::$Connection; } private function __construct() { } } $dbConnection = DBConnection::getConnection(); The reason you are able/would want to instantiate the class from within itself is so that you can check to make sure that only one instance exists at any given time. This is the whole point of a Singleton, after all. Using a Singleton for a database connection ensures that your application is not making a ton of DB connections at a time. Edit: Added $, as suggested by @emanuele-del-grande
[ "php", "oop", "constructor" ]
40
65
26,700
1
0
2008-08-25T14:11:10.160000
2008-08-25T14:22:09.227000
26,098
26,121
Overloaded functions in C++ DLL def file
I'm writing a C/C++ DLL and want to export certain functions which I've done before using a.def file like this LIBRARY "MyLib" EXPORTS Foo Bar with the code defined as this, for example: int Foo(int a); void Bar(int foo); However, what if I want to declare an overloaded method of Foo() like: int Foo(int a, int b); As the def file only has the function name and not the full prototype I can't see how it would handle the overloaded functions. Do you just use the one entry and then specify which overloaded version you want when passing in the properly prototyped function pointer to LoadLibrary()? Edit: To be clear, this is on Windows using Visual Studio 2005 Edit: Marked the non-def (__declspec) method as the answer...I know this doesn't actually solve the problem using def files as I wanted, but it seems that there is likely no (official) solution using def files. Will leave the question open, however, in case someone knows something we don't have overloaded functions and def files.
In the code itself, mark the functions you want to export using __declspec(dllexport). For example: #define DllExport __declspec(dllexport) int DllExport Foo( int a ) { // implementation } int DllExport Foo( int a, int b ) { // implementation } If you do this, you do not need to list the functions in the.def file. Alternatively, you may be able to use a default parameter value, like: int Foo( int a, int b = -1 ) This assumes that there exists a value for b that you can use to indicate that it is unused. If -1 is a legal value for b, or if there isn't or shouldn't be a default, this won't work. Edit (Adam Haile): Corrected to use __declspec as __dllspec was not correct so I could mark this as the official answer...it was close enough. Edit (Graeme): Oops - thanks for correcting my typo!
Overloaded functions in C++ DLL def file I'm writing a C/C++ DLL and want to export certain functions which I've done before using a.def file like this LIBRARY "MyLib" EXPORTS Foo Bar with the code defined as this, for example: int Foo(int a); void Bar(int foo); However, what if I want to declare an overloaded method of Foo() like: int Foo(int a, int b); As the def file only has the function name and not the full prototype I can't see how it would handle the overloaded functions. Do you just use the one entry and then specify which overloaded version you want when passing in the properly prototyped function pointer to LoadLibrary()? Edit: To be clear, this is on Windows using Visual Studio 2005 Edit: Marked the non-def (__declspec) method as the answer...I know this doesn't actually solve the problem using def files as I wanted, but it seems that there is likely no (official) solution using def files. Will leave the question open, however, in case someone knows something we don't have overloaded functions and def files.
TITLE: Overloaded functions in C++ DLL def file QUESTION: I'm writing a C/C++ DLL and want to export certain functions which I've done before using a.def file like this LIBRARY "MyLib" EXPORTS Foo Bar with the code defined as this, for example: int Foo(int a); void Bar(int foo); However, what if I want to declare an overloaded method of Foo() like: int Foo(int a, int b); As the def file only has the function name and not the full prototype I can't see how it would handle the overloaded functions. Do you just use the one entry and then specify which overloaded version you want when passing in the properly prototyped function pointer to LoadLibrary()? Edit: To be clear, this is on Windows using Visual Studio 2005 Edit: Marked the non-def (__declspec) method as the answer...I know this doesn't actually solve the problem using def files as I wanted, but it seems that there is likely no (official) solution using def files. Will leave the question open, however, in case someone knows something we don't have overloaded functions and def files. ANSWER: In the code itself, mark the functions you want to export using __declspec(dllexport). For example: #define DllExport __declspec(dllexport) int DllExport Foo( int a ) { // implementation } int DllExport Foo( int a, int b ) { // implementation } If you do this, you do not need to list the functions in the.def file. Alternatively, you may be able to use a default parameter value, like: int Foo( int a, int b = -1 ) This assumes that there exists a value for b that you can use to indicate that it is unused. If -1 is a legal value for b, or if there isn't or shouldn't be a default, this won't work. Edit (Adam Haile): Corrected to use __declspec as __dllspec was not correct so I could mark this as the official answer...it was close enough. Edit (Graeme): Oops - thanks for correcting my typo!
[ "c++", "c", "dll" ]
11
10
14,632
6
0
2008-08-25T14:22:21.257000
2008-08-25T14:32:33.180000
26,111
1,474,502
Failed to load resources from resource file
Get the following error periodically in an IIS application: Failed to load resources from resource file. The full error message in the Application Event Log is: Event Type: Error Event Source:.NET Runtime Event Category: None Event ID: 0 Date: 8/8/2008 Time: 8:8:8 AM User: N/A Computer: BLAH123 Description: The description for Event ID ( 0 ) in Source (.NET Runtime ) cannot be found. The >local computer may not have the necessary registry information or message DLL files to >display messages from a remote computer. You may be able to use the /AUXSOURCE= flag to retrieve this description; see Help and Support for details. The following information is part of the event:.NET Runtime version 1.1.4322.2407- Setup Error: Failed to load resources from resource file Please check your Setup. Application is written in.NET 1.1 but the server runs ASP.NET 2.0. Thanx. Update: Meant to say ASP.NET 2.0 is installed but the default website folder, and the websites inside the folder, are set to ASP.NET 1.1. On the website folder the ISAPI Filter is set to ASP.NET 2.0. My first guess about the problem was having ASP.NET 1.1 and ASP.NET 2.0 running side by side. Update 2: ASP.NET 2.0 is installed but all the websites run only ASP.NET 1.1 (long story and happened before I started).
Question was asked before Server Fault, where it probably belongs. Anyway, I never did figure out the error so assume it's closed.
Failed to load resources from resource file Get the following error periodically in an IIS application: Failed to load resources from resource file. The full error message in the Application Event Log is: Event Type: Error Event Source:.NET Runtime Event Category: None Event ID: 0 Date: 8/8/2008 Time: 8:8:8 AM User: N/A Computer: BLAH123 Description: The description for Event ID ( 0 ) in Source (.NET Runtime ) cannot be found. The >local computer may not have the necessary registry information or message DLL files to >display messages from a remote computer. You may be able to use the /AUXSOURCE= flag to retrieve this description; see Help and Support for details. The following information is part of the event:.NET Runtime version 1.1.4322.2407- Setup Error: Failed to load resources from resource file Please check your Setup. Application is written in.NET 1.1 but the server runs ASP.NET 2.0. Thanx. Update: Meant to say ASP.NET 2.0 is installed but the default website folder, and the websites inside the folder, are set to ASP.NET 1.1. On the website folder the ISAPI Filter is set to ASP.NET 2.0. My first guess about the problem was having ASP.NET 1.1 and ASP.NET 2.0 running side by side. Update 2: ASP.NET 2.0 is installed but all the websites run only ASP.NET 1.1 (long story and happened before I started).
TITLE: Failed to load resources from resource file QUESTION: Get the following error periodically in an IIS application: Failed to load resources from resource file. The full error message in the Application Event Log is: Event Type: Error Event Source:.NET Runtime Event Category: None Event ID: 0 Date: 8/8/2008 Time: 8:8:8 AM User: N/A Computer: BLAH123 Description: The description for Event ID ( 0 ) in Source (.NET Runtime ) cannot be found. The >local computer may not have the necessary registry information or message DLL files to >display messages from a remote computer. You may be able to use the /AUXSOURCE= flag to retrieve this description; see Help and Support for details. The following information is part of the event:.NET Runtime version 1.1.4322.2407- Setup Error: Failed to load resources from resource file Please check your Setup. Application is written in.NET 1.1 but the server runs ASP.NET 2.0. Thanx. Update: Meant to say ASP.NET 2.0 is installed but the default website folder, and the websites inside the folder, are set to ASP.NET 1.1. On the website folder the ISAPI Filter is set to ASP.NET 2.0. My first guess about the problem was having ASP.NET 1.1 and ASP.NET 2.0 running side by side. Update 2: ASP.NET 2.0 is installed but all the websites run only ASP.NET 1.1 (long story and happened before I started). ANSWER: Question was asked before Server Fault, where it probably belongs. Anyway, I never did figure out the error so assume it's closed.
[ ".net", "iis" ]
1
0
7,923
4
0
2008-08-25T14:28:03.940000
2009-09-24T22:23:23.223000
26,113
27,096
What is your best tool or techniques for getting the same display on IE6/7 and Firefox?
I'm not talking about tools that let one view a page in combinations of operating systems and browsers like crossbrowsertesting.com but in creating or figuring out the actual CSS.
If you guys are still coding for IE6, you're making a mistake. I use IE7.js to get IE6 to render pages like IE7. IE7 is not perfect, but at least it has some semblance of standards. Since I only have to code for IE7 and FF it makes me 33% more efficient in terms of testing against browsers, something I think makes good business sense. Link: IE7.js
What is your best tool or techniques for getting the same display on IE6/7 and Firefox? I'm not talking about tools that let one view a page in combinations of operating systems and browsers like crossbrowsertesting.com but in creating or figuring out the actual CSS.
TITLE: What is your best tool or techniques for getting the same display on IE6/7 and Firefox? QUESTION: I'm not talking about tools that let one view a page in combinations of operating systems and browsers like crossbrowsertesting.com but in creating or figuring out the actual CSS. ANSWER: If you guys are still coding for IE6, you're making a mistake. I use IE7.js to get IE6 to render pages like IE7. IE7 is not perfect, but at least it has some semblance of standards. Since I only have to code for IE7 and FF it makes me 33% more efficient in terms of testing against browsers, something I think makes good business sense. Link: IE7.js
[ "css", "internet-explorer", "firefox", "cross-browser" ]
8
3
252
8
0
2008-08-25T14:28:47.980000
2008-08-25T23:10:00.580000
26,123
26,135
Accessing .NET components from Powershell
I want to use Powershell to write some utilities, leveraging our own.NET components to handle the actual work. This is in place of writing a small console app to tie the calls together. My question is where I would find a good source of documentation or tutorial material to help me fast track this?
If you want to load an assembly into your PowerShell session, you can use reflection and load the assembly. [void][System.Reflection.Assembly]::LoadFrom(PathToYourAssembly) After you load your assembly, you can call static methods and create new instances of a class. A good tutorial can be found here. Both books mentioned by EBGreen are excellent. The PowerShell Cookbook is very task oriented and PowerShell in Action is a great description of the language, its focus and useability. PowerShell in Action is one of my favorite books.:)
Accessing .NET components from Powershell I want to use Powershell to write some utilities, leveraging our own.NET components to handle the actual work. This is in place of writing a small console app to tie the calls together. My question is where I would find a good source of documentation or tutorial material to help me fast track this?
TITLE: Accessing .NET components from Powershell QUESTION: I want to use Powershell to write some utilities, leveraging our own.NET components to handle the actual work. This is in place of writing a small console app to tie the calls together. My question is where I would find a good source of documentation or tutorial material to help me fast track this? ANSWER: If you want to load an assembly into your PowerShell session, you can use reflection and load the assembly. [void][System.Reflection.Assembly]::LoadFrom(PathToYourAssembly) After you load your assembly, you can call static methods and create new instances of a class. A good tutorial can be found here. Both books mentioned by EBGreen are excellent. The PowerShell Cookbook is very task oriented and PowerShell in Action is a great description of the language, its focus and useability. PowerShell in Action is one of my favorite books.:)
[ "powershell", "components" ]
14
16
7,281
3
0
2008-08-25T14:33:18.327000
2008-08-25T14:38:13.963000
26,137
26,181
VBScript/ASP Classic
I have a couple of questions regarding VBScript and ASP Classic: What is the preferred way to access an MS SQL Server database in VBScript/ASP? What are best practices in regards to separating model from view from controller? Any other things I should know about either VBScript or ASP? If you haven't noticed, I'm new at VBScript coding. I realize numbers 2 & 3 are kind of giant "black hole" questions that are overly general, so don't think that I'm expecting to learn everything there is to know about those two questions from here.
ADO is an excellent way to access a database in VBScript/Classic ASP. Dim db: Set db = Server.CreateObject("ADODB.Connection") db.Open "yourconnectionstring -> see connectionstrings.com" Dim rs: Set rs = db.Execute("SELECT firstName from Employees") While Not rs.EOF Response.Write rs("firstName") rs.MoveNext Wend rs.Close More info here: http://www.technowledgebase.com/2007/06/12/vbscript-how-to-create-an-ado-connection-and-run-a-query/ One caveat is that if you are returning a MEMO field in a recordset, be sure you only select ONE MEMO field at a time, and make sure it is the LAST column in your query. Otherwise you will run into problems. (Reference: http://lists.evolt.org/archive/Week-of-Mon-20040329/157305.html )
VBScript/ASP Classic I have a couple of questions regarding VBScript and ASP Classic: What is the preferred way to access an MS SQL Server database in VBScript/ASP? What are best practices in regards to separating model from view from controller? Any other things I should know about either VBScript or ASP? If you haven't noticed, I'm new at VBScript coding. I realize numbers 2 & 3 are kind of giant "black hole" questions that are overly general, so don't think that I'm expecting to learn everything there is to know about those two questions from here.
TITLE: VBScript/ASP Classic QUESTION: I have a couple of questions regarding VBScript and ASP Classic: What is the preferred way to access an MS SQL Server database in VBScript/ASP? What are best practices in regards to separating model from view from controller? Any other things I should know about either VBScript or ASP? If you haven't noticed, I'm new at VBScript coding. I realize numbers 2 & 3 are kind of giant "black hole" questions that are overly general, so don't think that I'm expecting to learn everything there is to know about those two questions from here. ANSWER: ADO is an excellent way to access a database in VBScript/Classic ASP. Dim db: Set db = Server.CreateObject("ADODB.Connection") db.Open "yourconnectionstring -> see connectionstrings.com" Dim rs: Set rs = db.Execute("SELECT firstName from Employees") While Not rs.EOF Response.Write rs("firstName") rs.MoveNext Wend rs.Close More info here: http://www.technowledgebase.com/2007/06/12/vbscript-how-to-create-an-ado-connection-and-run-a-query/ One caveat is that if you are returning a MEMO field in a recordset, be sure you only select ONE MEMO field at a time, and make sure it is the LAST column in your query. Otherwise you will run into problems. (Reference: http://lists.evolt.org/archive/Week-of-Mon-20040329/157305.html )
[ "sql-server", "model-view-controller", "asp-classic", "vbscript" ]
9
20
6,265
10
0
2008-08-25T14:38:38.580000
2008-08-25T15:04:33.867000
26,145
40,209
Cannot add a launch shortcut (Eclipse Plug-in)
I'm making a simple extra java app launcher for Eclipse 3.2 (JBuilder 2007-8) for internal use. So I looked up all the documentations related, including this one The Launching Framework from eclipse.org and have managed to make everything else working with the exception of the launch shortcut. This is the part of my plugin.xml. The configuration name in the category section is correct and the class in the class section, i believe, is correctly implemented. (basically copied from org.eclipse.jdt.debug.ui.launchConfigurations.JavaApplicationLaunchShortcut) I'm really not sure if I'm supposed to write a follow-up here but let me clarify my question more. I've extended org.eclipse.jdt.debug.ui.launchConfigurations.JavaLaunchShortcut. Plus, I've added my own logger to constructors and methods, but the class seems like it's never even instantiating.
I had to add contextualLaunch under org.eclipse.debug.ui.launchShortcuts. The old way seems like it's deprecated a long ago. For other people who are working on the same subject, you might want to extend org.eclipse.ui.commands and bindings, too. I cannot choose this answer but this is the answer that I (the questioner) was looking for.
Cannot add a launch shortcut (Eclipse Plug-in) I'm making a simple extra java app launcher for Eclipse 3.2 (JBuilder 2007-8) for internal use. So I looked up all the documentations related, including this one The Launching Framework from eclipse.org and have managed to make everything else working with the exception of the launch shortcut. This is the part of my plugin.xml. The configuration name in the category section is correct and the class in the class section, i believe, is correctly implemented. (basically copied from org.eclipse.jdt.debug.ui.launchConfigurations.JavaApplicationLaunchShortcut) I'm really not sure if I'm supposed to write a follow-up here but let me clarify my question more. I've extended org.eclipse.jdt.debug.ui.launchConfigurations.JavaLaunchShortcut. Plus, I've added my own logger to constructors and methods, but the class seems like it's never even instantiating.
TITLE: Cannot add a launch shortcut (Eclipse Plug-in) QUESTION: I'm making a simple extra java app launcher for Eclipse 3.2 (JBuilder 2007-8) for internal use. So I looked up all the documentations related, including this one The Launching Framework from eclipse.org and have managed to make everything else working with the exception of the launch shortcut. This is the part of my plugin.xml. The configuration name in the category section is correct and the class in the class section, i believe, is correctly implemented. (basically copied from org.eclipse.jdt.debug.ui.launchConfigurations.JavaApplicationLaunchShortcut) I'm really not sure if I'm supposed to write a follow-up here but let me clarify my question more. I've extended org.eclipse.jdt.debug.ui.launchConfigurations.JavaLaunchShortcut. Plus, I've added my own logger to constructors and methods, but the class seems like it's never even instantiating. ANSWER: I had to add contextualLaunch under org.eclipse.debug.ui.launchShortcuts. The old way seems like it's deprecated a long ago. For other people who are working on the same subject, you might want to extend org.eclipse.ui.commands and bindings, too. I cannot choose this answer but this is the answer that I (the questioner) was looking for.
[ "eclipse", "plugins" ]
3
4
2,331
2
0
2008-08-25T14:45:15.910000
2008-09-02T18:27:40.167000
26,147
31,912
Is it possible to Embed Gecko or Webkit in a Windows Form just like a WebView?
I'd love to know if there is such a thing as a Gecko.NET;) I mean, just like we can embed a WebView and that is an "instance" of IE7 inside any Windows Forms application (and tell it to navigateto(fancy_url); ). I'd love to use Firefox or WebKit. Anybody tried this? UPDATE: Please bear in mind that although it is possible to embed Gecko using the mentioned controls, it is still impossible to print while using Gecko. UPDATE March 2010: It’s still not possible to print natively using GeckoFX, however a couple of methods exist that may be enough, depending upon what you’re trying to do. See: http://geckofx.org/viewtopic.php?id=796 for more information. UPDATE October 2013: I am no longer doing Windows development so I have no interest in this, but seems like the development of Gecko can be found here: https://bitbucket.org/geckofx and it seems to be recently updated. Leaving this here for future Windows devs;) UPDATE January 2017: I have gotten an email from a company called TeamDev. They created a Chromium-based.NET browser component called "DotNetBrowser" which can be used to display modern web pages in Windows Forms applications. To quote the email directly: Here are some details about the component, which might be helpful: DotNetBrowser is based on Chromium, thus supporting HTML5, CSS3, JS and the latest web standards. The underlying Chromium version of the library is regularly updated. The component is suitable for WPF as well as Windows Forms desktop applications, and works both for C# and VB.NET. The library is licensed commercially, however free licences are provided for Open Source and academic projects. Disclaimer: I have not used this DotNetBrowser for I no longer do Windows Development but may be worth checking if you're looking for a solution to this.
http://code.google.com/p/geckofx/ This is a nice.NET-wrapped version of Gecko
Is it possible to Embed Gecko or Webkit in a Windows Form just like a WebView? I'd love to know if there is such a thing as a Gecko.NET;) I mean, just like we can embed a WebView and that is an "instance" of IE7 inside any Windows Forms application (and tell it to navigateto(fancy_url); ). I'd love to use Firefox or WebKit. Anybody tried this? UPDATE: Please bear in mind that although it is possible to embed Gecko using the mentioned controls, it is still impossible to print while using Gecko. UPDATE March 2010: It’s still not possible to print natively using GeckoFX, however a couple of methods exist that may be enough, depending upon what you’re trying to do. See: http://geckofx.org/viewtopic.php?id=796 for more information. UPDATE October 2013: I am no longer doing Windows development so I have no interest in this, but seems like the development of Gecko can be found here: https://bitbucket.org/geckofx and it seems to be recently updated. Leaving this here for future Windows devs;) UPDATE January 2017: I have gotten an email from a company called TeamDev. They created a Chromium-based.NET browser component called "DotNetBrowser" which can be used to display modern web pages in Windows Forms applications. To quote the email directly: Here are some details about the component, which might be helpful: DotNetBrowser is based on Chromium, thus supporting HTML5, CSS3, JS and the latest web standards. The underlying Chromium version of the library is regularly updated. The component is suitable for WPF as well as Windows Forms desktop applications, and works both for C# and VB.NET. The library is licensed commercially, however free licences are provided for Open Source and academic projects. Disclaimer: I have not used this DotNetBrowser for I no longer do Windows Development but may be worth checking if you're looking for a solution to this.
TITLE: Is it possible to Embed Gecko or Webkit in a Windows Form just like a WebView? QUESTION: I'd love to know if there is such a thing as a Gecko.NET;) I mean, just like we can embed a WebView and that is an "instance" of IE7 inside any Windows Forms application (and tell it to navigateto(fancy_url); ). I'd love to use Firefox or WebKit. Anybody tried this? UPDATE: Please bear in mind that although it is possible to embed Gecko using the mentioned controls, it is still impossible to print while using Gecko. UPDATE March 2010: It’s still not possible to print natively using GeckoFX, however a couple of methods exist that may be enough, depending upon what you’re trying to do. See: http://geckofx.org/viewtopic.php?id=796 for more information. UPDATE October 2013: I am no longer doing Windows development so I have no interest in this, but seems like the development of Gecko can be found here: https://bitbucket.org/geckofx and it seems to be recently updated. Leaving this here for future Windows devs;) UPDATE January 2017: I have gotten an email from a company called TeamDev. They created a Chromium-based.NET browser component called "DotNetBrowser" which can be used to display modern web pages in Windows Forms applications. To quote the email directly: Here are some details about the component, which might be helpful: DotNetBrowser is based on Chromium, thus supporting HTML5, CSS3, JS and the latest web standards. The underlying Chromium version of the library is regularly updated. The component is suitable for WPF as well as Windows Forms desktop applications, and works both for C# and VB.NET. The library is licensed commercially, however free licences are provided for Open Source and academic projects. Disclaimer: I have not used this DotNetBrowser for I no longer do Windows Development but may be worth checking if you're looking for a solution to this. ANSWER: http://code.google.com/p/geckofx/ This is a nice.NET-wrapped version of Gecko
[ "c#", ".net", "winforms", "webkit", "gecko" ]
71
49
96,506
10
0
2008-08-25T14:45:27.080000
2008-08-28T09:40:18.537000
26,151
26,162
Template typedefs - What's your work around?
C++ 0x has template aliases (sometimes referred to as template typedefs). See here. Current spec of C++ does not. What do you like to use as work around? Container objects or Macros? Do you feel its worth it?
What do you like to use as work around? Container objects or Macros? Do you feel its worth it? The canonical way is to use a metafunction like thus: template struct my_string_map { typedef std::map type; }; // Invoke: my_string_map::type my_str_int_map; This is also used in the STL ( allocator::rebind ) and in many libraries including Boost. We use it extensively in a bioinformatical library. It's bloated, but it's the best alternative 99% of the time. Using macros here is not worth the many downsides. (EDIT: I've amended the code to reflect Boost/STL conventions as pointed out by Daniel in his comment.)
Template typedefs - What's your work around? C++ 0x has template aliases (sometimes referred to as template typedefs). See here. Current spec of C++ does not. What do you like to use as work around? Container objects or Macros? Do you feel its worth it?
TITLE: Template typedefs - What's your work around? QUESTION: C++ 0x has template aliases (sometimes referred to as template typedefs). See here. Current spec of C++ does not. What do you like to use as work around? Container objects or Macros? Do you feel its worth it? ANSWER: What do you like to use as work around? Container objects or Macros? Do you feel its worth it? The canonical way is to use a metafunction like thus: template struct my_string_map { typedef std::map type; }; // Invoke: my_string_map::type my_str_int_map; This is also used in the STL ( allocator::rebind ) and in many libraries including Boost. We use it extensively in a bioinformatical library. It's bloated, but it's the best alternative 99% of the time. Using macros here is not worth the many downsides. (EDIT: I've amended the code to reflect Boost/STL conventions as pointed out by Daniel in his comment.)
[ "c++", "templates", "type-safety" ]
73
106
41,328
3
0
2008-08-25T14:47:00.853000
2008-08-25T14:51:01.920000
26,158
27,132
How does a "stack overflow" occur and how do you prevent it?
How does a stack overflow occur and what are the ways to make sure it doesn't happen, or ways to prevent one?
Stack A stack, in this context, is the last in, first out buffer you place data while your program runs. Last in, first out (LIFO) means that the last thing you put in is always the first thing you get back out - if you push 2 items on the stack, 'A' and then 'B', then the first thing you pop off the stack will be 'B', and the next thing is 'A'. When you call a function in your code, the next instruction after the function call is stored on the stack, and any storage space that might be overwritten by the function call. The function you call might use up more stack for its own local variables. When it's done, it frees up the local variable stack space it used, then returns to the previous function. Stack overflow A stack overflow is when you've used up more memory for the stack than your program was supposed to use. In embedded systems you might only have 256 bytes for the stack, and if each function takes up 32 bytes then you can only have function calls 8 deep - function 1 calls function 2 who calls function 3 who calls function 4.... who calls function 8 who calls function 9, but function 9 overwrites memory outside the stack. This might overwrite memory, code, etc. Many programmers make this mistake by calling function A that then calls function B, that then calls function C, that then calls function A. It might work most of the time, but just once the wrong input will cause it to go in that circle forever until the computer recognizes that the stack is overblown. Recursive functions are also a cause for this, but if you're writing recursively (ie, your function calls itself) then you need to be aware of this and use static/global variables to prevent infinite recursion. Generally, the OS and the programming language you're using manage the stack, and it's out of your hands. You should look at your call graph (a tree structure that shows from your main what each function calls) to see how deep your function calls go, and to detect cycles and recursion that are not intended. Intentional cycles and recursion need to be artificially checked to error out if they call each other too many times. Beyond good programming practices, static and dynamic testing, there's not much you can do on these high level systems. Embedded systems In the embedded world, especially in high reliability code (automotive, aircraft, space) you do extensive code reviews and checking, but you also do the following: Disallow recursion and cycles - enforced by policy and testing Keep code and stack far apart (code in flash, stack in RAM, and never the twain shall meet) Place guard bands around the stack - empty area of memory that you fill with a magic number (usually a software interrupt instruction, but there are many options here), and hundreds or thousands of times a second you look at the guard bands to make sure they haven't been overwritten. Use memory protection (ie, no execute on the stack, no read or write just outside the stack) Interrupts don't call secondary functions - they set flags, copy data, and let the application take care of processing it (otherwise you might get 8 deep in your function call tree, have an interrupt, and then go out another few functions inside the interrupt, causing the blowout). You have several call trees - one for the main processes, and one for each interrupt. If your interrupts can interrupt each other... well, there be dragons... High-level languages and systems But in high level languages run on operating systems: Reduce your local variable storage (local variables are stored on the stack - although compilers are pretty smart about this and will sometimes put big locals on the heap if your call tree is shallow) Avoid or strictly limit recursion Don't break your programs up too far into smaller and smaller functions - even without counting local variables each function call consumes as much as 64 bytes on the stack (32 bit processor, saving half the CPU registers, flags, etc) Keep your call tree shallow (similar to the above statement) Web servers It depends on the 'sandbox' you have whether you can control or even see the stack. Chances are good you can treat web servers as you would any other high level language and operating system - it's largely out of your hands, but check the language and server stack you're using. It is possible to blow the stack on your SQL server, for instance.
How does a "stack overflow" occur and how do you prevent it? How does a stack overflow occur and what are the ways to make sure it doesn't happen, or ways to prevent one?
TITLE: How does a "stack overflow" occur and how do you prevent it? QUESTION: How does a stack overflow occur and what are the ways to make sure it doesn't happen, or ways to prevent one? ANSWER: Stack A stack, in this context, is the last in, first out buffer you place data while your program runs. Last in, first out (LIFO) means that the last thing you put in is always the first thing you get back out - if you push 2 items on the stack, 'A' and then 'B', then the first thing you pop off the stack will be 'B', and the next thing is 'A'. When you call a function in your code, the next instruction after the function call is stored on the stack, and any storage space that might be overwritten by the function call. The function you call might use up more stack for its own local variables. When it's done, it frees up the local variable stack space it used, then returns to the previous function. Stack overflow A stack overflow is when you've used up more memory for the stack than your program was supposed to use. In embedded systems you might only have 256 bytes for the stack, and if each function takes up 32 bytes then you can only have function calls 8 deep - function 1 calls function 2 who calls function 3 who calls function 4.... who calls function 8 who calls function 9, but function 9 overwrites memory outside the stack. This might overwrite memory, code, etc. Many programmers make this mistake by calling function A that then calls function B, that then calls function C, that then calls function A. It might work most of the time, but just once the wrong input will cause it to go in that circle forever until the computer recognizes that the stack is overblown. Recursive functions are also a cause for this, but if you're writing recursively (ie, your function calls itself) then you need to be aware of this and use static/global variables to prevent infinite recursion. Generally, the OS and the programming language you're using manage the stack, and it's out of your hands. You should look at your call graph (a tree structure that shows from your main what each function calls) to see how deep your function calls go, and to detect cycles and recursion that are not intended. Intentional cycles and recursion need to be artificially checked to error out if they call each other too many times. Beyond good programming practices, static and dynamic testing, there's not much you can do on these high level systems. Embedded systems In the embedded world, especially in high reliability code (automotive, aircraft, space) you do extensive code reviews and checking, but you also do the following: Disallow recursion and cycles - enforced by policy and testing Keep code and stack far apart (code in flash, stack in RAM, and never the twain shall meet) Place guard bands around the stack - empty area of memory that you fill with a magic number (usually a software interrupt instruction, but there are many options here), and hundreds or thousands of times a second you look at the guard bands to make sure they haven't been overwritten. Use memory protection (ie, no execute on the stack, no read or write just outside the stack) Interrupts don't call secondary functions - they set flags, copy data, and let the application take care of processing it (otherwise you might get 8 deep in your function call tree, have an interrupt, and then go out another few functions inside the interrupt, causing the blowout). You have several call trees - one for the main processes, and one for each interrupt. If your interrupts can interrupt each other... well, there be dragons... High-level languages and systems But in high level languages run on operating systems: Reduce your local variable storage (local variables are stored on the stack - although compilers are pretty smart about this and will sometimes put big locals on the heap if your call tree is shallow) Avoid or strictly limit recursion Don't break your programs up too far into smaller and smaller functions - even without counting local variables each function call consumes as much as 64 bytes on the stack (32 bit processor, saving half the CPU registers, flags, etc) Keep your call tree shallow (similar to the above statement) Web servers It depends on the 'sandbox' you have whether you can control or even see the stack. Chances are good you can treat web servers as you would any other high level language and operating system - it's largely out of your hands, but check the language and server stack you're using. It is possible to blow the stack on your SQL server, for instance.
[ "memory", "stack-overflow" ]
146
166
144,978
9
0
2008-08-25T14:49:29.847000
2008-08-25T23:55:39.397000
26,176
26,270
Why is Harvest being purchased at all?
Does your work environment use Harvest SCM? I've used this now at two different locations and find it appalling. In one situation I wrote a conversion script so I could use CVS locally and then daily import changes to the Harvest system while I was sleeping. The corp was fanatic about using Harvest, despite 80% of the programmers crying for something different. It was needlessly complicated, slow and heavy. It is now a job requirement for me that Harvest is not in use where I work. Has anyone else used Harvest before? What's your experience? As bad as mine? Did you employ other, different workarounds? Why is this product still purchased today?
Chances are, your company has some sort of contract with CA - are you using a lot of other CA software in-house? Edit: Guess so!
Why is Harvest being purchased at all? Does your work environment use Harvest SCM? I've used this now at two different locations and find it appalling. In one situation I wrote a conversion script so I could use CVS locally and then daily import changes to the Harvest system while I was sleeping. The corp was fanatic about using Harvest, despite 80% of the programmers crying for something different. It was needlessly complicated, slow and heavy. It is now a job requirement for me that Harvest is not in use where I work. Has anyone else used Harvest before? What's your experience? As bad as mine? Did you employ other, different workarounds? Why is this product still purchased today?
TITLE: Why is Harvest being purchased at all? QUESTION: Does your work environment use Harvest SCM? I've used this now at two different locations and find it appalling. In one situation I wrote a conversion script so I could use CVS locally and then daily import changes to the Harvest system while I was sleeping. The corp was fanatic about using Harvest, despite 80% of the programmers crying for something different. It was needlessly complicated, slow and heavy. It is now a job requirement for me that Harvest is not in use where I work. Has anyone else used Harvest before? What's your experience? As bad as mine? Did you employ other, different workarounds? Why is this product still purchased today? ANSWER: Chances are, your company has some sort of contract with CA - are you using a lot of other CA software in-house? Edit: Guess so!
[ "version-control", "harvest" ]
25
24
17,149
7
0
2008-08-25T14:59:49.853000
2008-08-25T15:37:36.223000
26,195
26,708
vimdiff and CVS integration
I've always wanted to be able to get a reasonably elegant way of getting vimdiff to work with a CVS controlled file. I've found numerous (somewhat hacky) scripts around the internet (best example here ) that basically check out the file you are editing from CVS to a temp file, and vimdiff the two. None of these take into account branches, and always assume you're working from MAIN, which for me is completely useless. So, my question is this: has anyone out there found a decent solution for this that does more than this script? Or failing that, does anyone have any ideas of how they would implement this, or suggestions for what features you would consider vital for something that does this? My intention is that, if no one can suggest an already built solution to either use or build from, we start building one from here.
I've been working on a similar script here: http://github.com/ghewgill/vim-scmdiff (in fact, they may have the same ancestry). I haven't used scmdiff with cvs, but it should do a diff against the branch you have checked out. You can also specify that you want to diff against a particular revision (with:D revision ). Hopefully this helps, and feel free to contribute if you've got improvements!
vimdiff and CVS integration I've always wanted to be able to get a reasonably elegant way of getting vimdiff to work with a CVS controlled file. I've found numerous (somewhat hacky) scripts around the internet (best example here ) that basically check out the file you are editing from CVS to a temp file, and vimdiff the two. None of these take into account branches, and always assume you're working from MAIN, which for me is completely useless. So, my question is this: has anyone out there found a decent solution for this that does more than this script? Or failing that, does anyone have any ideas of how they would implement this, or suggestions for what features you would consider vital for something that does this? My intention is that, if no one can suggest an already built solution to either use or build from, we start building one from here.
TITLE: vimdiff and CVS integration QUESTION: I've always wanted to be able to get a reasonably elegant way of getting vimdiff to work with a CVS controlled file. I've found numerous (somewhat hacky) scripts around the internet (best example here ) that basically check out the file you are editing from CVS to a temp file, and vimdiff the two. None of these take into account branches, and always assume you're working from MAIN, which for me is completely useless. So, my question is this: has anyone out there found a decent solution for this that does more than this script? Or failing that, does anyone have any ideas of how they would implement this, or suggestions for what features you would consider vital for something that does this? My intention is that, if no one can suggest an already built solution to either use or build from, we start building one from here. ANSWER: I've been working on a similar script here: http://github.com/ghewgill/vim-scmdiff (in fact, they may have the same ancestry). I haven't used scmdiff with cvs, but it should do a diff against the branch you have checked out. You can also specify that you want to diff against a particular revision (with:D revision ). Hopefully this helps, and feel free to contribute if you've got improvements!
[ "vim", "cvs", "vimdiff" ]
6
3
2,542
4
0
2008-08-25T15:10:27.380000
2008-08-25T19:45:43.333000
26,196
26,203
Filtering collections in C#
I am looking for a very fast way to filter down a collection in C#. I am currently using generic List collections, but am open to using other structures if they perform better. Currently, I am just creating a new List and looping thru the original list. If the filtering criteria matches, I put a copy into the new list. Is there a better way to do this? Is there a way to filter in place so there is no temporary list required?
If you're using C# 3.0 you can use linq, which is way better and way more elegant: List myList = GetListOfIntsFromSomewhere(); // This will filter ints that are not > 7 out of the list; Where returns an // IEnumerable, so call ToList to convert back to a List. List filteredList = myList.Where(x => x > 7).ToList(); If you can't find the.Where, that means you need to import using System.Linq; at the top of your file.
Filtering collections in C# I am looking for a very fast way to filter down a collection in C#. I am currently using generic List collections, but am open to using other structures if they perform better. Currently, I am just creating a new List and looping thru the original list. If the filtering criteria matches, I put a copy into the new list. Is there a better way to do this? Is there a way to filter in place so there is no temporary list required?
TITLE: Filtering collections in C# QUESTION: I am looking for a very fast way to filter down a collection in C#. I am currently using generic List collections, but am open to using other structures if they perform better. Currently, I am just creating a new List and looping thru the original list. If the filtering criteria matches, I put a copy into the new list. Is there a better way to do this? Is there a way to filter in place so there is no temporary list required? ANSWER: If you're using C# 3.0 you can use linq, which is way better and way more elegant: List myList = GetListOfIntsFromSomewhere(); // This will filter ints that are not > 7 out of the list; Where returns an // IEnumerable, so call ToList to convert back to a List. List filteredList = myList.Where(x => x > 7).ToList(); If you can't find the.Where, that means you need to import using System.Linq; at the top of your file.
[ "c#", "collections", "filtering" ]
189
306
377,821
9
0
2008-08-25T15:11:10.093000
2008-08-25T15:13:51.927000
26,229
27,059
Visio and Forward-Engineering
Do you know if I can use Visio to forward-engineer a sequence diagram into code (c#)? Can it be done with Visio alone or do I need a plugin? What about other diagrams?
You have to get the Visio that for users of Visual Studio. See this link: Visio for Enterprise Architects for more details. The code generation capabilities are fairly weak and you might end up getting Visio into an inconsistent state. I know that Visio will let you forward and reverse engineer both code and databases, but both capabilities are very limited and I don't recommend doing it. In my opinion, Visio is a diagramming tool and it should be treated as such.
Visio and Forward-Engineering Do you know if I can use Visio to forward-engineer a sequence diagram into code (c#)? Can it be done with Visio alone or do I need a plugin? What about other diagrams?
TITLE: Visio and Forward-Engineering QUESTION: Do you know if I can use Visio to forward-engineer a sequence diagram into code (c#)? Can it be done with Visio alone or do I need a plugin? What about other diagrams? ANSWER: You have to get the Visio that for users of Visual Studio. See this link: Visio for Enterprise Architects for more details. The code generation capabilities are fairly weak and you might end up getting Visio into an inconsistent state. I know that Visio will let you forward and reverse engineer both code and databases, but both capabilities are very limited and I don't recommend doing it. In my opinion, Visio is a diagramming tool and it should be treated as such.
[ "c#", "visio", "forward-engineer" ]
1
1
2,289
3
0
2008-08-25T15:22:17.430000
2008-08-25T22:42:59.057000
26,230
26,236
Revoke shared folders in windows
Over the last few months/years, I have shared a folder or two with numerous people on my domain. How do I easily revoke those shares to keep access to my system nice and tidy?
Using computer management (an MMC snap-in. See Control Panel Administrative tools) you can see a list of all folders that are shared. You could delete the shares or change the permissions on the share to only allow access for certain people or groups.
Revoke shared folders in windows Over the last few months/years, I have shared a folder or two with numerous people on my domain. How do I easily revoke those shares to keep access to my system nice and tidy?
TITLE: Revoke shared folders in windows QUESTION: Over the last few months/years, I have shared a folder or two with numerous people on my domain. How do I easily revoke those shares to keep access to my system nice and tidy? ANSWER: Using computer management (an MMC snap-in. See Control Panel Administrative tools) you can see a list of all folders that are shared. You could delete the shares or change the permissions on the share to only allow access for certain people or groups.
[ "windows", "networking", "directory", "shared", "smb" ]
1
3
915
3
0
2008-08-25T15:22:19.193000
2008-08-25T15:24:04.257000
26,233
26,238
Fastest C# Code to Download a Web Page
Given a URL, what would be the most efficient code to download the contents of that web page? I am only considering the HTML, not associated images, JS and CSS.
public static void DownloadFile(string remoteFilename, string localFilename) { WebClient client = new WebClient(); client.DownloadFile(remoteFilename, localFilename); }
Fastest C# Code to Download a Web Page Given a URL, what would be the most efficient code to download the contents of that web page? I am only considering the HTML, not associated images, JS and CSS.
TITLE: Fastest C# Code to Download a Web Page QUESTION: Given a URL, what would be the most efficient code to download the contents of that web page? I am only considering the HTML, not associated images, JS and CSS. ANSWER: public static void DownloadFile(string remoteFilename, string localFilename) { WebClient client = new WebClient(); client.DownloadFile(remoteFilename, localFilename); }
[ "c#" ]
65
71
78,831
7
0
2008-08-25T15:23:05.273000
2008-08-25T15:24:22.883000
26,255
60,396
Reserved keywords in JavaScript
What JavaScript keywords (function names, variables, etc) are reserved?
We should be linking to the actual sources of info, rather than just the top google hit. http://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Reserved_Words JScript 8.0: http://msdn.microsoft.com/en-us/library/ttyab5c8.aspx
Reserved keywords in JavaScript What JavaScript keywords (function names, variables, etc) are reserved?
TITLE: Reserved keywords in JavaScript QUESTION: What JavaScript keywords (function names, variables, etc) are reserved? ANSWER: We should be linking to the actual sources of info, rather than just the top google hit. http://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Reserved_Words JScript 8.0: http://msdn.microsoft.com/en-us/library/ttyab5c8.aspx
[ "javascript", "reserved-words" ]
169
112
71,632
8
0
2008-08-25T15:29:39.907000
2008-09-13T07:54:42.603000
26,260
26,310
Asp.net website first start is very slow
The first time I load the website in the production web server, it start very slow, subsequent pages load very quickly (included the home page). I precompiled the site, but nothing changes. I don't have any code at Application start. I don't have cached items. Any ideas? How can I find out what is happening?
It's just your app domain loading up and loading any binaries into memory. Also, it's initializing static variables, so if you have a static variable that loads up a lot of data from the db, it might take a bit.
Asp.net website first start is very slow The first time I load the website in the production web server, it start very slow, subsequent pages load very quickly (included the home page). I precompiled the site, but nothing changes. I don't have any code at Application start. I don't have cached items. Any ideas? How can I find out what is happening?
TITLE: Asp.net website first start is very slow QUESTION: The first time I load the website in the production web server, it start very slow, subsequent pages load very quickly (included the home page). I precompiled the site, but nothing changes. I don't have any code at Application start. I don't have cached items. Any ideas? How can I find out what is happening? ANSWER: It's just your app domain loading up and loading any binaries into memory. Also, it's initializing static variables, so if you have a static variable that loads up a lot of data from the db, it might take a bit.
[ "asp.net" ]
13
12
13,530
11
0
2008-08-25T15:32:46.967000
2008-08-25T16:00:59.363000
26,301
26,337
Your favourite algorithm and the lesson it taught you
What algorithm taught you the most about programming or a specific language feature? We have all had those moments where all of a sudden we know, just know, we have learned an important lesson for the future based on finally understanding an algorithm written by a programmer a couple of steps up the evolutionary ladder. Whose ideas and code had the magic touch on you?
"To iterate is human, to recurse divine" - quoted in 1989 at college. P.S. Posted by Woodgnome while waiting for invite to join
Your favourite algorithm and the lesson it taught you What algorithm taught you the most about programming or a specific language feature? We have all had those moments where all of a sudden we know, just know, we have learned an important lesson for the future based on finally understanding an algorithm written by a programmer a couple of steps up the evolutionary ladder. Whose ideas and code had the magic touch on you?
TITLE: Your favourite algorithm and the lesson it taught you QUESTION: What algorithm taught you the most about programming or a specific language feature? We have all had those moments where all of a sudden we know, just know, we have learned an important lesson for the future based on finally understanding an algorithm written by a programmer a couple of steps up the evolutionary ladder. Whose ideas and code had the magic touch on you? ANSWER: "To iterate is human, to recurse divine" - quoted in 1989 at college. P.S. Posted by Woodgnome while waiting for invite to join
[ "algorithm", "language-agnostic" ]
27
19
9,684
33
0
2008-08-25T15:55:42.403000
2008-08-25T16:20:15.620000
26,305
26,318
How can I play sound in Java?
I want to be able to play sound files in my program. Where should I look?
I wrote the following code that works fine. But I think it only works with.wav format. public static synchronized void playSound(final String url) { new Thread(new Runnable() { // The wrapper thread is unnecessary, unless it blocks on the // Clip finishing; see comments. public void run() { try { Clip clip = AudioSystem.getClip(); AudioInputStream inputStream = AudioSystem.getAudioInputStream( Main.class.getResourceAsStream("/path/to/sounds/" + url)); clip.open(inputStream); clip.start(); } catch (Exception e) { System.err.println(e.getMessage()); } } }).start(); }
How can I play sound in Java? I want to be able to play sound files in my program. Where should I look?
TITLE: How can I play sound in Java? QUESTION: I want to be able to play sound files in my program. Where should I look? ANSWER: I wrote the following code that works fine. But I think it only works with.wav format. public static synchronized void playSound(final String url) { new Thread(new Runnable() { // The wrapper thread is unnecessary, unless it blocks on the // Clip finishing; see comments. public void run() { try { Clip clip = AudioSystem.getClip(); AudioInputStream inputStream = AudioSystem.getAudioInputStream( Main.class.getResourceAsStream("/path/to/sounds/" + url)); clip.open(inputStream); clip.start(); } catch (Exception e) { System.err.println(e.getMessage()); } } }).start(); }
[ "java", "audio" ]
194
148
401,766
12
0
2008-08-25T16:00:04.127000
2008-08-25T16:03:41.073000
26,323
26,339
Regex to Parse Hyperlinks and Descriptions
C#: What is a good Regex to parse hyperlinks and their description? Please consider case insensitivity, white-space and use of single quotes (instead of double quotes) around the HREF tag. Please also consider obtaining hyperlinks which have other tags within the tags such as and. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
As long as there are no nested tags (and no line breaks), the following variant works well: (.*?) As soon as nested tags come into play, regular expressions are unfit for parsing. However, you can still use them by applying more advanced features of modern interpreters (depending on your regex machine). E.g..NET regular expressions use a stack; I found this: (?:.*?)[""'].*?>)(? (?> (? )| (?<-DEPTH>)|.)+)(?(DEPTH)(?!))(?: ) Source: http://weblogs.asp.net/scottcate/archive/2004/12/13/281955.aspx
Regex to Parse Hyperlinks and Descriptions C#: What is a good Regex to parse hyperlinks and their description? Please consider case insensitivity, white-space and use of single quotes (instead of double quotes) around the HREF tag. Please also consider obtaining hyperlinks which have other tags within the tags such as and. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
TITLE: Regex to Parse Hyperlinks and Descriptions QUESTION: C#: What is a good Regex to parse hyperlinks and their description? Please consider case insensitivity, white-space and use of single quotes (instead of double quotes) around the HREF tag. Please also consider obtaining hyperlinks which have other tags within the tags such as and. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­ ANSWER: As long as there are no nested tags (and no line breaks), the following variant works well: (.*?) As soon as nested tags come into play, regular expressions are unfit for parsing. However, you can still use them by applying more advanced features of modern interpreters (depending on your regex machine). E.g..NET regular expressions use a stack; I found this: (?:.*?)[""'].*?>)(? (?> (? )| (?<-DEPTH>)|.)+)(?(DEPTH)(?!))(?: ) Source: http://weblogs.asp.net/scottcate/archive/2004/12/13/281955.aspx
[ "html", "regex" ]
5
6
16,227
6
0
2008-08-25T16:05:29.587000
2008-08-25T16:21:47.833000
26,354
28,168
Print a barcode to a Intermec PB20 via the LinePrinter API
Does anyone know how to print a barcode to the Intermec PB20 bluetooth printer from a Windows Compact Framework application? We are currently using the Intermec LinePrinter API but have been unable to find a way to print a barcode. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
Thank you all for your thoughts. Printing directly to the serial port is likely the most flexible method. In this case we didn't want to replicate all of the work that was already built into the Intermec dll for handling the port, printer errors, etc. We were able to get this working by sending the printer the appropriate codes to switch it into a different mode and then pass direct printer commands that way. Here was our solution in case anyone else happens to encounter a similar issue working with Intermec Printers. The following code is a test case that doesn't catch printer errors and retry, etc. (See Intermec code examples.) Intermec.Print.LinePrinter lp; int escapeCharacter = int.Parse("1b", NumberStyles.HexNumber); char[] toEzPrintMode = new char[] { Convert.ToChar(num2), 'E', 'Z' }; lp = new Intermec.Print.LinePrinter("Printer_Config.XML", "PrinterPB20_40COL"); lp.Open(); lp.Write(charArray2); //switch to ez print mode string testBarcode = "{PRINT:@75,10:PD417,YDIM 6,XDIM 2,COLUMNS 2, SECURITY 3|ABCDEFGHIJKL|}"; lp.Write(testBarcode); lp.Write("{LP}"); //switch from ez print mode back to line printer mode lp.NewLine(); lp.Write("Test"); //verify line printer mode is working There is a technical document on Intermec's support site called the "Technical Manual" that describes the code for directly controlling the printer. The section about Easy Print describes how to print a variety of barcodes.
Print a barcode to a Intermec PB20 via the LinePrinter API Does anyone know how to print a barcode to the Intermec PB20 bluetooth printer from a Windows Compact Framework application? We are currently using the Intermec LinePrinter API but have been unable to find a way to print a barcode. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
TITLE: Print a barcode to a Intermec PB20 via the LinePrinter API QUESTION: Does anyone know how to print a barcode to the Intermec PB20 bluetooth printer from a Windows Compact Framework application? We are currently using the Intermec LinePrinter API but have been unable to find a way to print a barcode. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­ ANSWER: Thank you all for your thoughts. Printing directly to the serial port is likely the most flexible method. In this case we didn't want to replicate all of the work that was already built into the Intermec dll for handling the port, printer errors, etc. We were able to get this working by sending the printer the appropriate codes to switch it into a different mode and then pass direct printer commands that way. Here was our solution in case anyone else happens to encounter a similar issue working with Intermec Printers. The following code is a test case that doesn't catch printer errors and retry, etc. (See Intermec code examples.) Intermec.Print.LinePrinter lp; int escapeCharacter = int.Parse("1b", NumberStyles.HexNumber); char[] toEzPrintMode = new char[] { Convert.ToChar(num2), 'E', 'Z' }; lp = new Intermec.Print.LinePrinter("Printer_Config.XML", "PrinterPB20_40COL"); lp.Open(); lp.Write(charArray2); //switch to ez print mode string testBarcode = "{PRINT:@75,10:PD417,YDIM 6,XDIM 2,COLUMNS 2, SECURITY 3|ABCDEFGHIJKL|}"; lp.Write(testBarcode); lp.Write("{LP}"); //switch from ez print mode back to line printer mode lp.NewLine(); lp.Write("Test"); //verify line printer mode is working There is a technical document on Intermec's support site called the "Technical Manual" that describes the code for directly controlling the printer. The section about Easy Print describes how to print a variety of barcodes.
[ "c#", "windows-mobile" ]
4
1
4,611
5
0
2008-08-25T16:34:25.150000
2008-08-26T14:21:16.973000
26,355
26,423
Compact Framework - Is there an MVC framework/library available?
I've found an article on this subject by a Microsoft employee, but has anyone implemented a more robust framework for this? Is there a lightweight framework for WinForms that could be ported easily? I'd like to get up to speed fairly quickly and avoid producing a framework/library of my own to handle this when someone smarter has already done this. I haven't looked at the Mobile Software Factory from the P&P group, but I suspect it's kind of heavy. Is it worth a look? Edit: I'm not looking for information on the ASP.NET MVC project. I'm asking about the compact framework 'WinForms' implementation, and how to implement MVC with that.
I personally think that the Mobile Software Factory doesn't hold much joy for CF. We still use one part of it (EventBroker) at work and I'd like to even remove that part if possible (as it doesn't support generic events and you have to cast the arguments into their strong types from EventArgs). A sister project at work used it for part of their UI but had to rip it out due to performance issues (another big project, although that has additional performance issues of it's own as well). The issue I find with the MVP framework that the P&P lib offers is that Forms and Controls OWN presenters instead of Presenters/Controllers owning Forms (who didn't read "It's just a view": Pragmatic Programmer?). This fits beautifully with MS's "Form First" rapid application development mantra but it sucks when you consider how expensive windows handles can be in CE (if you have a lot of them). We run a very large CF application at work and we've rolled our own MVC framework. It's not hard to roll your own, just make sure you separate everything out into Controllers, Views, Business Objects and Services and have a UIController that controls the interactions between the controllers. We actually go one step further and re-use forms/controls by using a Controller->View->Layout pattern. The controller is the same as usual, the view is the object that customises a layout into a particular view and the layout is the actual UserControl. We then swap these in and out of a single Form. This reduces the amount of Windows Controls we use dramatically. This + initialising all of the forms on start-up means that we eradicate the noticable pause that you get when creating new Windows Controls "on-demand". Obviously it only really pays to do this kind of thing if you are rolling a large application. We have roughly 20 + different types of View which use in total about 7 different layouts. This hurts our initialisation routine (as we load the forms at start up) by a magnitude of about 10 seconds but psychologically most users are willing to accept such a hit at start up as opposed to noticeable pauses during run-time. The main issue with the P&P library in my books is that it is a FF -> CF port and due to certain incompatability and performance differences between the two platforms you lose a lot of useful functionality. Btw, this is by far and away the most comprehensive article i've ever read on MVC/MVP. For Windows application (desktop or CE) I'd recommend using the Taligent Model-View-Presenter version without the interactions, commands and selections (e.g the controller/presenter performs all the work).
Compact Framework - Is there an MVC framework/library available? I've found an article on this subject by a Microsoft employee, but has anyone implemented a more robust framework for this? Is there a lightweight framework for WinForms that could be ported easily? I'd like to get up to speed fairly quickly and avoid producing a framework/library of my own to handle this when someone smarter has already done this. I haven't looked at the Mobile Software Factory from the P&P group, but I suspect it's kind of heavy. Is it worth a look? Edit: I'm not looking for information on the ASP.NET MVC project. I'm asking about the compact framework 'WinForms' implementation, and how to implement MVC with that.
TITLE: Compact Framework - Is there an MVC framework/library available? QUESTION: I've found an article on this subject by a Microsoft employee, but has anyone implemented a more robust framework for this? Is there a lightweight framework for WinForms that could be ported easily? I'd like to get up to speed fairly quickly and avoid producing a framework/library of my own to handle this when someone smarter has already done this. I haven't looked at the Mobile Software Factory from the P&P group, but I suspect it's kind of heavy. Is it worth a look? Edit: I'm not looking for information on the ASP.NET MVC project. I'm asking about the compact framework 'WinForms' implementation, and how to implement MVC with that. ANSWER: I personally think that the Mobile Software Factory doesn't hold much joy for CF. We still use one part of it (EventBroker) at work and I'd like to even remove that part if possible (as it doesn't support generic events and you have to cast the arguments into their strong types from EventArgs). A sister project at work used it for part of their UI but had to rip it out due to performance issues (another big project, although that has additional performance issues of it's own as well). The issue I find with the MVP framework that the P&P lib offers is that Forms and Controls OWN presenters instead of Presenters/Controllers owning Forms (who didn't read "It's just a view": Pragmatic Programmer?). This fits beautifully with MS's "Form First" rapid application development mantra but it sucks when you consider how expensive windows handles can be in CE (if you have a lot of them). We run a very large CF application at work and we've rolled our own MVC framework. It's not hard to roll your own, just make sure you separate everything out into Controllers, Views, Business Objects and Services and have a UIController that controls the interactions between the controllers. We actually go one step further and re-use forms/controls by using a Controller->View->Layout pattern. The controller is the same as usual, the view is the object that customises a layout into a particular view and the layout is the actual UserControl. We then swap these in and out of a single Form. This reduces the amount of Windows Controls we use dramatically. This + initialising all of the forms on start-up means that we eradicate the noticable pause that you get when creating new Windows Controls "on-demand". Obviously it only really pays to do this kind of thing if you are rolling a large application. We have roughly 20 + different types of View which use in total about 7 different layouts. This hurts our initialisation routine (as we load the forms at start up) by a magnitude of about 10 seconds but psychologically most users are willing to accept such a hit at start up as opposed to noticeable pauses during run-time. The main issue with the P&P library in my books is that it is a FF -> CF port and due to certain incompatability and performance differences between the two platforms you lose a lot of useful functionality. Btw, this is by far and away the most comprehensive article i've ever read on MVC/MVP. For Windows application (desktop or CE) I'd recommend using the Taligent Model-View-Presenter version without the interactions, commands and selections (e.g the controller/presenter performs all the work).
[ "c#", "model-view-controller", "windows-mobile", "compact-framework", "design-patterns" ]
9
5
2,750
7
0
2008-08-25T16:36:31.340000
2008-08-25T17:11:13.143000
26,362
46,766
Using ItemizedOverlay and OverlayItem In Android Beta 0.9
Has anyone managed to use ItemizedOverlays in Android Beta 0.9? I can't get it to work, but I'm not sure if I've done something wrong or if this functionality isn't yet available. I've been trying to use the ItemizedOverlay and OverlayItem classes. Their intended purpose is to simulate map markers (as seen in Google Maps Mashups) but I've had problems getting them to appear on the map. I can add my own custom overlays using a similar technique, it's just the ItemizedOverlays that don't work. Once I've implemented my own ItemizedOverlay (and overridden createItem ), creating a new instance of my class seems to work (I can extract OverlayItems from it) but adding it to a map's Overlay list doesn't make it appear as it should. This is the code I use to add the ItemizedOverlay class as an Overlay on to my MapView. // Add the ItemizedOverlay to the Map private void addItemizedOverlay() { Resources r = getResources(); MapView mapView = (MapView)findViewById(R.id.mymapview); List overlays = mapView.getOverlays(); MyItemizedOverlay markers = new MyItemizedOverlay(r.getDrawable(R.drawable.icon)); overlays.add(markers); OverlayItem oi = markers.getItem(0); markers.setFocus(oi); mapView.postInvalidate(); } Where MyItemizedOverlay is defined as: public class MyItemizedOverlay extends ItemizedOverlay { public MyItemizedOverlay(Drawable defaultMarker) { super(defaultMarker); populate(); } @Override protected OverlayItem createItem(int index) { Double lat = (index+37.422006)*1E6; Double lng = -122.084095*1E6; GeoPoint point = new GeoPoint(lat.intValue(), lng.intValue()); OverlayItem oi = new OverlayItem(point, "Marker", "Marker Text"); return oi; } @Override public int size() { return 5; } }
For the sake of completeness I'll repeat the discussion on Reto's post over at the Android Groups here. It seems that if you set the bounds on your drawable it does the trick: Drawable defaultMarker = r.getDrawable(R.drawable.icon); // You HAVE to specify the bounds! It seems like the markers are drawn // through Drawable.draw(Canvas) and therefore must have its bounds set // before drawing. defaultMarker.setBounds(0, 0, defaultMarker.getIntrinsicWidth(), defaultMarker.getIntrinsicHeight()); MyItemizedOverlay markers = new MyItemizedOverlay(defaultMarker); overlays.add(markers); By the way, the above is shamelessly ripped from the demo at MarcelP.info. Also, here is a good howto.
Using ItemizedOverlay and OverlayItem In Android Beta 0.9 Has anyone managed to use ItemizedOverlays in Android Beta 0.9? I can't get it to work, but I'm not sure if I've done something wrong or if this functionality isn't yet available. I've been trying to use the ItemizedOverlay and OverlayItem classes. Their intended purpose is to simulate map markers (as seen in Google Maps Mashups) but I've had problems getting them to appear on the map. I can add my own custom overlays using a similar technique, it's just the ItemizedOverlays that don't work. Once I've implemented my own ItemizedOverlay (and overridden createItem ), creating a new instance of my class seems to work (I can extract OverlayItems from it) but adding it to a map's Overlay list doesn't make it appear as it should. This is the code I use to add the ItemizedOverlay class as an Overlay on to my MapView. // Add the ItemizedOverlay to the Map private void addItemizedOverlay() { Resources r = getResources(); MapView mapView = (MapView)findViewById(R.id.mymapview); List overlays = mapView.getOverlays(); MyItemizedOverlay markers = new MyItemizedOverlay(r.getDrawable(R.drawable.icon)); overlays.add(markers); OverlayItem oi = markers.getItem(0); markers.setFocus(oi); mapView.postInvalidate(); } Where MyItemizedOverlay is defined as: public class MyItemizedOverlay extends ItemizedOverlay { public MyItemizedOverlay(Drawable defaultMarker) { super(defaultMarker); populate(); } @Override protected OverlayItem createItem(int index) { Double lat = (index+37.422006)*1E6; Double lng = -122.084095*1E6; GeoPoint point = new GeoPoint(lat.intValue(), lng.intValue()); OverlayItem oi = new OverlayItem(point, "Marker", "Marker Text"); return oi; } @Override public int size() { return 5; } }
TITLE: Using ItemizedOverlay and OverlayItem In Android Beta 0.9 QUESTION: Has anyone managed to use ItemizedOverlays in Android Beta 0.9? I can't get it to work, but I'm not sure if I've done something wrong or if this functionality isn't yet available. I've been trying to use the ItemizedOverlay and OverlayItem classes. Their intended purpose is to simulate map markers (as seen in Google Maps Mashups) but I've had problems getting them to appear on the map. I can add my own custom overlays using a similar technique, it's just the ItemizedOverlays that don't work. Once I've implemented my own ItemizedOverlay (and overridden createItem ), creating a new instance of my class seems to work (I can extract OverlayItems from it) but adding it to a map's Overlay list doesn't make it appear as it should. This is the code I use to add the ItemizedOverlay class as an Overlay on to my MapView. // Add the ItemizedOverlay to the Map private void addItemizedOverlay() { Resources r = getResources(); MapView mapView = (MapView)findViewById(R.id.mymapview); List overlays = mapView.getOverlays(); MyItemizedOverlay markers = new MyItemizedOverlay(r.getDrawable(R.drawable.icon)); overlays.add(markers); OverlayItem oi = markers.getItem(0); markers.setFocus(oi); mapView.postInvalidate(); } Where MyItemizedOverlay is defined as: public class MyItemizedOverlay extends ItemizedOverlay { public MyItemizedOverlay(Drawable defaultMarker) { super(defaultMarker); populate(); } @Override protected OverlayItem createItem(int index) { Double lat = (index+37.422006)*1E6; Double lng = -122.084095*1E6; GeoPoint point = new GeoPoint(lat.intValue(), lng.intValue()); OverlayItem oi = new OverlayItem(point, "Marker", "Marker Text"); return oi; } @Override public int size() { return 5; } } ANSWER: For the sake of completeness I'll repeat the discussion on Reto's post over at the Android Groups here. It seems that if you set the bounds on your drawable it does the trick: Drawable defaultMarker = r.getDrawable(R.drawable.icon); // You HAVE to specify the bounds! It seems like the markers are drawn // through Drawable.draw(Canvas) and therefore must have its bounds set // before drawing. defaultMarker.setBounds(0, 0, defaultMarker.getIntrinsicWidth(), defaultMarker.getIntrinsicHeight()); MyItemizedOverlay markers = new MyItemizedOverlay(defaultMarker); overlays.add(markers); By the way, the above is shamelessly ripped from the demo at MarcelP.info. Also, here is a good howto.
[ "java", "android", "overlay", "android-mapview" ]
58
46
24,690
2
0
2008-08-25T16:39:42.440000
2008-09-05T19:58:48.483000
26,369
26,394
What is the best way to store user settings for a .NET application?
I have a.NET 2.0 Windows Forms application. Where is the best place the store user settings (considering Windows guidelines)? Some people pointed to Application.LocalUserAppDataPath. However, that creates a folder structure like: C:\Documents and Settings\user_name\Local Settings\Application Data\company_name\product_name\product_version\ If I release version 1 of my application and store an XML file there, then release version 2, that would change to a different folder, right? I'd prefer to have a single folder, per user, to store settings, regardless of the application version. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
I love using the built-in Application Settings. Then you have built in support for using the settings designer if you want at design-time, or at runtime to use: // read setting string setting1 = (string)Settings.Default["MySetting1"]; // save setting Settings.Default["MySetting2"] = "My Setting Value"; // you can force a save with Properties.Settings.Default.Save(); It does store the settings in a similar folder structure as you describe (with the version in the path). However, with a simple call to: Properties.Settings.Default.Upgrade(); The app will pull all previous versions settings in to save in.
What is the best way to store user settings for a .NET application? I have a.NET 2.0 Windows Forms application. Where is the best place the store user settings (considering Windows guidelines)? Some people pointed to Application.LocalUserAppDataPath. However, that creates a folder structure like: C:\Documents and Settings\user_name\Local Settings\Application Data\company_name\product_name\product_version\ If I release version 1 of my application and store an XML file there, then release version 2, that would change to a different folder, right? I'd prefer to have a single folder, per user, to store settings, regardless of the application version. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
TITLE: What is the best way to store user settings for a .NET application? QUESTION: I have a.NET 2.0 Windows Forms application. Where is the best place the store user settings (considering Windows guidelines)? Some people pointed to Application.LocalUserAppDataPath. However, that creates a folder structure like: C:\Documents and Settings\user_name\Local Settings\Application Data\company_name\product_name\product_version\ If I release version 1 of my application and store an XML file there, then release version 2, that would change to a different folder, right? I'd prefer to have a single folder, per user, to store settings, regardless of the application version. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­ ANSWER: I love using the built-in Application Settings. Then you have built in support for using the settings designer if you want at design-time, or at runtime to use: // read setting string setting1 = (string)Settings.Default["MySetting1"]; // save setting Settings.Default["MySetting2"] = "My Setting Value"; // you can force a save with Properties.Settings.Default.Save(); It does store the settings in a similar folder structure as you describe (with the version in the path). However, with a simple call to: Properties.Settings.Default.Upgrade(); The app will pull all previous versions settings in to save in.
[ "c#", ".net" ]
66
90
50,690
8
0
2008-08-25T16:43:06.707000
2008-08-25T16:59:15.527000
26,383
26,403
Exception handling: Contract vs Exceptional approach
I know two approaches to Exception handling, lets have a look at them. Contract approach. When a method does not do what it says it will do in the method header, it will throw an exception. Thus the method "promises" that it will do the operation, and if it fails for some reason, it will throw an exception. Exceptional approach. Only throw exceptions when something truly weird happens. You should not use exceptions when you can resolve the situation with normal control flow (If statements). You don't use Exceptions for control flow, as you might in the contract approach. Lets use both approaches in different cases: We have a Customer class that has a method called OrderProduct. contract approach: class Customer { public void OrderProduct(Product product) { if((m_credit - product.Price) < 0) throw new NoCreditException("Not enough credit!"); // do stuff } } exceptional approach: class Customer { public bool OrderProduct(Product product) { if((m_credit - product.Price) < 0) return false; // do stuff return true; } } if!(customer.OrderProduct(product)) Console.WriteLine("Not enough credit!"); else // go on with your life Here I prefer the exceptional approach, as it is not truly Exceptional that a customer has no money assuming he did not win the lottery. But here is a situation I err on the contract style. Exceptional: class CarController { // returns null if car creation failed. public Car CreateCar(string model) { // something went wrong, wrong model return null; } } When I call a method called CreateCar, I damn wel expect a Car instance instead of some lousy null pointer, which can ravage my running code a dozen lines later. Thus I prefer contract to this one: class CarController { public Car CreateCar(string model) { // something went wrong, wrong model throw new CarModelNotKnownException("Model unkown"); return new Car(); } } Which do style do you use? What do you think is best general approach to Exceptions?
I favor what you call the "contract" approach. Returning nulls or other special values to indicate errors isn't necessary in a language that supports exceptions. I find it much easier to understand code when it doesn't have a bunch of "if (result == NULL)" or "if (result == -1)" clauses mixed in with what could be very simple, straightforward logic.
Exception handling: Contract vs Exceptional approach I know two approaches to Exception handling, lets have a look at them. Contract approach. When a method does not do what it says it will do in the method header, it will throw an exception. Thus the method "promises" that it will do the operation, and if it fails for some reason, it will throw an exception. Exceptional approach. Only throw exceptions when something truly weird happens. You should not use exceptions when you can resolve the situation with normal control flow (If statements). You don't use Exceptions for control flow, as you might in the contract approach. Lets use both approaches in different cases: We have a Customer class that has a method called OrderProduct. contract approach: class Customer { public void OrderProduct(Product product) { if((m_credit - product.Price) < 0) throw new NoCreditException("Not enough credit!"); // do stuff } } exceptional approach: class Customer { public bool OrderProduct(Product product) { if((m_credit - product.Price) < 0) return false; // do stuff return true; } } if!(customer.OrderProduct(product)) Console.WriteLine("Not enough credit!"); else // go on with your life Here I prefer the exceptional approach, as it is not truly Exceptional that a customer has no money assuming he did not win the lottery. But here is a situation I err on the contract style. Exceptional: class CarController { // returns null if car creation failed. public Car CreateCar(string model) { // something went wrong, wrong model return null; } } When I call a method called CreateCar, I damn wel expect a Car instance instead of some lousy null pointer, which can ravage my running code a dozen lines later. Thus I prefer contract to this one: class CarController { public Car CreateCar(string model) { // something went wrong, wrong model throw new CarModelNotKnownException("Model unkown"); return new Car(); } } Which do style do you use? What do you think is best general approach to Exceptions?
TITLE: Exception handling: Contract vs Exceptional approach QUESTION: I know two approaches to Exception handling, lets have a look at them. Contract approach. When a method does not do what it says it will do in the method header, it will throw an exception. Thus the method "promises" that it will do the operation, and if it fails for some reason, it will throw an exception. Exceptional approach. Only throw exceptions when something truly weird happens. You should not use exceptions when you can resolve the situation with normal control flow (If statements). You don't use Exceptions for control flow, as you might in the contract approach. Lets use both approaches in different cases: We have a Customer class that has a method called OrderProduct. contract approach: class Customer { public void OrderProduct(Product product) { if((m_credit - product.Price) < 0) throw new NoCreditException("Not enough credit!"); // do stuff } } exceptional approach: class Customer { public bool OrderProduct(Product product) { if((m_credit - product.Price) < 0) return false; // do stuff return true; } } if!(customer.OrderProduct(product)) Console.WriteLine("Not enough credit!"); else // go on with your life Here I prefer the exceptional approach, as it is not truly Exceptional that a customer has no money assuming he did not win the lottery. But here is a situation I err on the contract style. Exceptional: class CarController { // returns null if car creation failed. public Car CreateCar(string model) { // something went wrong, wrong model return null; } } When I call a method called CreateCar, I damn wel expect a Car instance instead of some lousy null pointer, which can ravage my running code a dozen lines later. Thus I prefer contract to this one: class CarController { public Car CreateCar(string model) { // something went wrong, wrong model throw new CarModelNotKnownException("Model unkown"); return new Car(); } } Which do style do you use? What do you think is best general approach to Exceptions? ANSWER: I favor what you call the "contract" approach. Returning nulls or other special values to indicate errors isn't necessary in a language that supports exceptions. I find it much easier to understand code when it doesn't have a bunch of "if (result == NULL)" or "if (result == -1)" clauses mixed in with what could be very simple, straightforward logic.
[ "exception" ]
12
6
905
5
0
2008-08-25T16:52:23.110000
2008-08-25T17:01:07.287000
26,393
26,411
What is a selector engine?
I've seen news of John Resig's fast new selector engine named Sizzle pop up in quite a few places, but I don't know what a selector engine is, nor have any of the articles given an explanation of what it is. I know Resig is the creator of jQuery, and that Sizzle is something in Javascript, but beyond that I don't know what it is. So, what is a selector engine? Thanks!
A selector engine is used to query a page's DOM for particular elements, based on some sort of query (usually CSS syntax or similar). For example, this jQuery: $('div') Would search for and return all of the elements on the page. It uses jQuery's selector engine to do that. Optimizing the selector engine is a big deal because almost every operation you perform with these frameworks is based on some sort of DOM query.
What is a selector engine? I've seen news of John Resig's fast new selector engine named Sizzle pop up in quite a few places, but I don't know what a selector engine is, nor have any of the articles given an explanation of what it is. I know Resig is the creator of jQuery, and that Sizzle is something in Javascript, but beyond that I don't know what it is. So, what is a selector engine? Thanks!
TITLE: What is a selector engine? QUESTION: I've seen news of John Resig's fast new selector engine named Sizzle pop up in quite a few places, but I don't know what a selector engine is, nor have any of the articles given an explanation of what it is. I know Resig is the creator of jQuery, and that Sizzle is something in Javascript, but beyond that I don't know what it is. So, what is a selector engine? Thanks! ANSWER: A selector engine is used to query a page's DOM for particular elements, based on some sort of query (usually CSS syntax or similar). For example, this jQuery: $('div') Would search for and return all of the elements on the page. It uses jQuery's selector engine to do that. Optimizing the selector engine is a big deal because almost every operation you perform with these frameworks is based on some sort of DOM query.
[ "javascript", "jquery", "glossary", "resig" ]
32
52
11,433
5
0
2008-08-25T16:59:09.957000
2008-08-25T17:03:51.897000
26,422
26,426
Third party Visual Studio snippets
Do you know where I could find some useful third party (free) code snippets for VS 2008?
http://gotcodesnippets.com/ http://www.codekeep.net/ has a VS add-in for their snippets, too
Third party Visual Studio snippets Do you know where I could find some useful third party (free) code snippets for VS 2008?
TITLE: Third party Visual Studio snippets QUESTION: Do you know where I could find some useful third party (free) code snippets for VS 2008? ANSWER: http://gotcodesnippets.com/ http://www.codekeep.net/ has a VS add-in for their snippets, too
[ "visual-studio", "visual-studio-2008", "code-snippets" ]
5
6
445
2
0
2008-08-25T17:11:07.153000
2008-08-25T17:11:55.497000
26,452
26,462
Visual Studio 2005 Shortcuts
I'm trying to bind the following shortcut: Ctrl + W to close tabs How can you customize VS to add/change shortcuts? Also, what are the most useful shortcuts you guys have found?
Tools > Options > (Show all settings), then Environment > Keyboard. Here, rebind the key “File.Close” to Ctrl + W.
Visual Studio 2005 Shortcuts I'm trying to bind the following shortcut: Ctrl + W to close tabs How can you customize VS to add/change shortcuts? Also, what are the most useful shortcuts you guys have found?
TITLE: Visual Studio 2005 Shortcuts QUESTION: I'm trying to bind the following shortcut: Ctrl + W to close tabs How can you customize VS to add/change shortcuts? Also, what are the most useful shortcuts you guys have found? ANSWER: Tools > Options > (Show all settings), then Environment > Keyboard. Here, rebind the key “File.Close” to Ctrl + W.
[ "visual-studio", "visual-studio-2005", "shortcut" ]
6
6
4,131
5
0
2008-08-25T17:25:33.857000
2008-08-25T17:28:26.377000
26,455
26,484
Does Design By Contract Work For You?
Do you use Design by Contract professionally? Is it something you have to do from the beginning of a project, or can you change gears and start to incorporate it into your software development lifecycle? What have you found to be the pros/cons of the design approach? I came across the Design by Contract approach in a grad school course. In the academic setting, it seemed to be a pretty useful technique. But I don't currently use Design by Contract professionally, and I don't know any other developers that are using it. It would be good to hear about its actual usage from the SO crowd.
I can't recommend it highly enough. It's particularly nice if you have a suite that takes inline documentation contract specifications, like so: // @returns null iff x = 0 public foo(int x) {... } and turns them into generated unit tests, like so: public test_foo_returns_null_iff_x_equals_0() { assertNull foo(0); } That way, you can actually see the tests you're running, but they're auto-generated. Generated tests shouldn't be checked into source control, by the way.
Does Design By Contract Work For You? Do you use Design by Contract professionally? Is it something you have to do from the beginning of a project, or can you change gears and start to incorporate it into your software development lifecycle? What have you found to be the pros/cons of the design approach? I came across the Design by Contract approach in a grad school course. In the academic setting, it seemed to be a pretty useful technique. But I don't currently use Design by Contract professionally, and I don't know any other developers that are using it. It would be good to hear about its actual usage from the SO crowd.
TITLE: Does Design By Contract Work For You? QUESTION: Do you use Design by Contract professionally? Is it something you have to do from the beginning of a project, or can you change gears and start to incorporate it into your software development lifecycle? What have you found to be the pros/cons of the design approach? I came across the Design by Contract approach in a grad school course. In the academic setting, it seemed to be a pretty useful technique. But I don't currently use Design by Contract professionally, and I don't know any other developers that are using it. It would be good to hear about its actual usage from the SO crowd. ANSWER: I can't recommend it highly enough. It's particularly nice if you have a suite that takes inline documentation contract specifications, like so: // @returns null iff x = 0 public foo(int x) {... } and turns them into generated unit tests, like so: public test_foo_returns_null_iff_x_equals_0() { assertNull foo(0); } That way, you can actually see the tests you're running, but they're auto-generated. Generated tests shouldn't be checked into source control, by the way.
[ "design-by-contract" ]
26
16
4,405
10
0
2008-08-25T17:26:47.163000
2008-08-25T17:41:29.530000
26,478
49,638
Incosistency between MS Sql 2k and 2k5 with columns as function arguments
I'm having trouble getting the following to work in SQL Server 2k, but it works in 2k5: --works in 2k5, not in 2k create view foo as SELECT usertable.legacyCSVVarcharCol as testvar FROM usertable WHERE rsrcID in ( select val from dbo.fnSplitStringToInt(usertable.legacyCSVVarcharCol, default) ) --error message: Msg 170, Level 15, State 1, Procedure foo, Line 4 Line 25: Incorrect syntax near '.'. So, legacyCSVVarcharCol is a column containing comma-separated lists of INTs. I realize that this is a huge WTF, but this is legacy code, and there's nothing that can be done about the schema right now. Passing "testvar" as the argument to the function doesn't work in 2k either. In fact, it results in a slightly different (and even weirder error): Msg 155, Level 15, State 1, Line 8 'testvar' is not a recognized OPTIMIZER LOCK HINTS option. Passing a hard-coded string as the argument to fnSplitStringToInt works in both 2k and 2k5. Does anyone know why this doesn't work in 2k? Is this perhaps a known bug in the query planner? Any suggestions for how to make it work? Again, I realize that the real answer is "don't store CSV lists in your DB!", but alas, that's beyond my control. Some sample data, if it helps: INSERT INTO usertable (legacyCSVVarcharCol) values ('1,2,3'); INSERT INTO usertable (legacyCSVVarcharCol) values ('11,13,42'); Note that the data in the table does not seem to matter since this is a syntax error, and it occurs even if usertable is completely empty. EDIT: Realizing that perhaps the initial example was unclear, here are two examples, one of which works and one of which does not, which should highlight the problem that's occurring: --fails in sql2000, works in 2005 SELECT t1.* FROM usertable t1 WHERE 1 in (Select val from fnSplitStringToInt(t1.legacyCSVVarcharCol, ',') ) --works everywhere: SELECT t1.* FROM usertable t1 WHERE 1 in ( Select val from fnSplitStringToInt('1,4,543,56578', ',') ) Note that the only difference is the first argument to fnSplitStringToInt is a column in the case that fails in 2k and a literal string in the case that succeeds in both.
Passing column-values to a table-valued user-defined function is not supported in SQL Server 2000, you can only use constants, so the following (simpler version) would also fail: SELECT *, (SELECT TOP 1 val FROM dbo.fnSplitStringToInt(usertable.legacyCSVVarcharCol, ',')) FROM usertable It will work on SQL Server 2005, though, as you have found out.
Incosistency between MS Sql 2k and 2k5 with columns as function arguments I'm having trouble getting the following to work in SQL Server 2k, but it works in 2k5: --works in 2k5, not in 2k create view foo as SELECT usertable.legacyCSVVarcharCol as testvar FROM usertable WHERE rsrcID in ( select val from dbo.fnSplitStringToInt(usertable.legacyCSVVarcharCol, default) ) --error message: Msg 170, Level 15, State 1, Procedure foo, Line 4 Line 25: Incorrect syntax near '.'. So, legacyCSVVarcharCol is a column containing comma-separated lists of INTs. I realize that this is a huge WTF, but this is legacy code, and there's nothing that can be done about the schema right now. Passing "testvar" as the argument to the function doesn't work in 2k either. In fact, it results in a slightly different (and even weirder error): Msg 155, Level 15, State 1, Line 8 'testvar' is not a recognized OPTIMIZER LOCK HINTS option. Passing a hard-coded string as the argument to fnSplitStringToInt works in both 2k and 2k5. Does anyone know why this doesn't work in 2k? Is this perhaps a known bug in the query planner? Any suggestions for how to make it work? Again, I realize that the real answer is "don't store CSV lists in your DB!", but alas, that's beyond my control. Some sample data, if it helps: INSERT INTO usertable (legacyCSVVarcharCol) values ('1,2,3'); INSERT INTO usertable (legacyCSVVarcharCol) values ('11,13,42'); Note that the data in the table does not seem to matter since this is a syntax error, and it occurs even if usertable is completely empty. EDIT: Realizing that perhaps the initial example was unclear, here are two examples, one of which works and one of which does not, which should highlight the problem that's occurring: --fails in sql2000, works in 2005 SELECT t1.* FROM usertable t1 WHERE 1 in (Select val from fnSplitStringToInt(t1.legacyCSVVarcharCol, ',') ) --works everywhere: SELECT t1.* FROM usertable t1 WHERE 1 in ( Select val from fnSplitStringToInt('1,4,543,56578', ',') ) Note that the only difference is the first argument to fnSplitStringToInt is a column in the case that fails in 2k and a literal string in the case that succeeds in both.
TITLE: Incosistency between MS Sql 2k and 2k5 with columns as function arguments QUESTION: I'm having trouble getting the following to work in SQL Server 2k, but it works in 2k5: --works in 2k5, not in 2k create view foo as SELECT usertable.legacyCSVVarcharCol as testvar FROM usertable WHERE rsrcID in ( select val from dbo.fnSplitStringToInt(usertable.legacyCSVVarcharCol, default) ) --error message: Msg 170, Level 15, State 1, Procedure foo, Line 4 Line 25: Incorrect syntax near '.'. So, legacyCSVVarcharCol is a column containing comma-separated lists of INTs. I realize that this is a huge WTF, but this is legacy code, and there's nothing that can be done about the schema right now. Passing "testvar" as the argument to the function doesn't work in 2k either. In fact, it results in a slightly different (and even weirder error): Msg 155, Level 15, State 1, Line 8 'testvar' is not a recognized OPTIMIZER LOCK HINTS option. Passing a hard-coded string as the argument to fnSplitStringToInt works in both 2k and 2k5. Does anyone know why this doesn't work in 2k? Is this perhaps a known bug in the query planner? Any suggestions for how to make it work? Again, I realize that the real answer is "don't store CSV lists in your DB!", but alas, that's beyond my control. Some sample data, if it helps: INSERT INTO usertable (legacyCSVVarcharCol) values ('1,2,3'); INSERT INTO usertable (legacyCSVVarcharCol) values ('11,13,42'); Note that the data in the table does not seem to matter since this is a syntax error, and it occurs even if usertable is completely empty. EDIT: Realizing that perhaps the initial example was unclear, here are two examples, one of which works and one of which does not, which should highlight the problem that's occurring: --fails in sql2000, works in 2005 SELECT t1.* FROM usertable t1 WHERE 1 in (Select val from fnSplitStringToInt(t1.legacyCSVVarcharCol, ',') ) --works everywhere: SELECT t1.* FROM usertable t1 WHERE 1 in ( Select val from fnSplitStringToInt('1,4,543,56578', ',') ) Note that the only difference is the first argument to fnSplitStringToInt is a column in the case that fails in 2k and a literal string in the case that succeeds in both. ANSWER: Passing column-values to a table-valued user-defined function is not supported in SQL Server 2000, you can only use constants, so the following (simpler version) would also fail: SELECT *, (SELECT TOP 1 val FROM dbo.fnSplitStringToInt(usertable.legacyCSVVarcharCol, ',')) FROM usertable It will work on SQL Server 2005, though, as you have found out.
[ "sql-server" ]
1
1
473
2
0
2008-08-25T17:38:50.470000
2008-09-08T12:56:51.047000
26,515
26,537
Using MySQLi - which is better for closing queries
I have a habit of keeping my variable usage to a bare minimum. So I'm wondering if there is any advantage to be gained by the following: $query = $mysqli->query('SELECT * FROM `people` ORDER BY `name` ASC LIMIT 0,30'); // Example 1 $query = $query->fetch_assoc(); // Example 2 $query_r = $query->fetch_assoc(); $query->free(); Now if I'm right Example 1 should be more efficient as $query is unset when I reassign it which should free any memory associated with it. However there is a method ( MySQLi_Result::free() ) which frees associated memory - is this the same thing? If I don't call::free() to free any memory associated with the result but unset it by reassigning the variable am I doing the same thing? I don't know how to log this sort of thing - does anyone have some ideas?
The manual seems to suggest that you should still be using free() to release the memory. I believe the reasoning is that free() is freeing the memory in MySQL, not in PHP. Since PHP can't garbage-collect for MySQL, you need to call free().
Using MySQLi - which is better for closing queries I have a habit of keeping my variable usage to a bare minimum. So I'm wondering if there is any advantage to be gained by the following: $query = $mysqli->query('SELECT * FROM `people` ORDER BY `name` ASC LIMIT 0,30'); // Example 1 $query = $query->fetch_assoc(); // Example 2 $query_r = $query->fetch_assoc(); $query->free(); Now if I'm right Example 1 should be more efficient as $query is unset when I reassign it which should free any memory associated with it. However there is a method ( MySQLi_Result::free() ) which frees associated memory - is this the same thing? If I don't call::free() to free any memory associated with the result but unset it by reassigning the variable am I doing the same thing? I don't know how to log this sort of thing - does anyone have some ideas?
TITLE: Using MySQLi - which is better for closing queries QUESTION: I have a habit of keeping my variable usage to a bare minimum. So I'm wondering if there is any advantage to be gained by the following: $query = $mysqli->query('SELECT * FROM `people` ORDER BY `name` ASC LIMIT 0,30'); // Example 1 $query = $query->fetch_assoc(); // Example 2 $query_r = $query->fetch_assoc(); $query->free(); Now if I'm right Example 1 should be more efficient as $query is unset when I reassign it which should free any memory associated with it. However there is a method ( MySQLi_Result::free() ) which frees associated memory - is this the same thing? If I don't call::free() to free any memory associated with the result but unset it by reassigning the variable am I doing the same thing? I don't know how to log this sort of thing - does anyone have some ideas? ANSWER: The manual seems to suggest that you should still be using free() to release the memory. I believe the reasoning is that free() is freeing the memory in MySQL, not in PHP. Since PHP can't garbage-collect for MySQL, you need to call free().
[ "php", "mysql", "memory", "mysqli" ]
2
5
869
2
0
2008-08-25T17:59:28.847000
2008-08-25T18:08:38.373000
26,522
26,582
.NET Multi Dimensional Array Printing
Let's say I have a.NET Array of n number of dimensions. I would like to foreach through the elements and print out something like: [0, 0, 0] = 2 [0, 0, 1] = 32 And so on. I could write a loop using some the Rank and dimension functions to come up with the indices. Is there a built in function instead?
Thanks for the answer, here is what I wrote while I waited: public static string Format(Array array) { var builder = new StringBuilder(); builder.AppendLine("Count: " + array.Length); var counter = 0; var dimensions = new List (); for (int i = 0; i < array.Rank; i++) { dimensions.Add(array.GetUpperBound(i) + 1); } foreach (var current in array) { var index = ""; var remainder = counter; foreach (var bound in dimensions) { index = remainder % bound + ", " + index; remainder = remainder / bound; } index = index.Substring(0, index.Length - 2); builder.AppendLine(" [" + index + "] " + current); counter++; } return builder.ToString(); }
.NET Multi Dimensional Array Printing Let's say I have a.NET Array of n number of dimensions. I would like to foreach through the elements and print out something like: [0, 0, 0] = 2 [0, 0, 1] = 32 And so on. I could write a loop using some the Rank and dimension functions to come up with the indices. Is there a built in function instead?
TITLE: .NET Multi Dimensional Array Printing QUESTION: Let's say I have a.NET Array of n number of dimensions. I would like to foreach through the elements and print out something like: [0, 0, 0] = 2 [0, 0, 1] = 32 And so on. I could write a loop using some the Rank and dimension functions to come up with the indices. Is there a built in function instead? ANSWER: Thanks for the answer, here is what I wrote while I waited: public static string Format(Array array) { var builder = new StringBuilder(); builder.AppendLine("Count: " + array.Length); var counter = 0; var dimensions = new List (); for (int i = 0; i < array.Rank; i++) { dimensions.Add(array.GetUpperBound(i) + 1); } foreach (var current in array) { var index = ""; var remainder = counter; foreach (var bound in dimensions) { index = remainder % bound + ", " + index; remainder = remainder / bound; } index = index.Substring(0, index.Length - 2); builder.AppendLine(" [" + index + "] " + current); counter++; } return builder.ToString(); }
[ "c#", ".net", "arrays" ]
3
2
2,115
2
0
2008-08-25T18:02:48.713000
2008-08-25T18:23:38.977000
26,536
26,684
Active X Control JavaScript
My coworker and I have encountered a nasty situation where we have to use an active X control to manipulate a web camera on a page. Is it possible to assign a javascript event handler to a button in the active x control so that it would fire an action on the page when clicked, or do we have to create a button on the html page itself that manipulates the Active X Control and then can fire any necessary actions on the page?
Please just use an existing ActiveX control. Like Flash or Silverlight. Flash has built-in webcam support and is controllable via JavaScript. Silverlight doesn't have built-in camera support, but it's JavaScript integration is fantastic. If you must write your own then fret not, it is trivial to get it to interact with JavaScript. You just have to expose the IDispatch interface. For events, you need to learn about Connection Points.
Active X Control JavaScript My coworker and I have encountered a nasty situation where we have to use an active X control to manipulate a web camera on a page. Is it possible to assign a javascript event handler to a button in the active x control so that it would fire an action on the page when clicked, or do we have to create a button on the html page itself that manipulates the Active X Control and then can fire any necessary actions on the page?
TITLE: Active X Control JavaScript QUESTION: My coworker and I have encountered a nasty situation where we have to use an active X control to manipulate a web camera on a page. Is it possible to assign a javascript event handler to a button in the active x control so that it would fire an action on the page when clicked, or do we have to create a button on the html page itself that manipulates the Active X Control and then can fire any necessary actions on the page? ANSWER: Please just use an existing ActiveX control. Like Flash or Silverlight. Flash has built-in webcam support and is controllable via JavaScript. Silverlight doesn't have built-in camera support, but it's JavaScript integration is fantastic. If you must write your own then fret not, it is trivial to get it to interact with JavaScript. You just have to expose the IDispatch interface. For events, you need to learn about Connection Points.
[ "javascript", "activex" ]
9
7
6,360
2
0
2008-08-25T18:07:57.110000
2008-08-25T19:25:24.740000
26,547
26,589
How to detect which blog API
Let's say that you want to create a dead simple BlogEditor and, one of your ideas, is to do what Live Writer does and ask only the URL of the persons Blog. How can you detect what type of blog is it? Basic detection can be done with the URL itself, such as “ http://myblog.blogger.com ” etc. But what if it's self hosted? I'm mostly interested on how to do this in Java, but this question could be also used as a reference for any other language.
Many (most?) blogs will have a meta tag for "generator" which will list the blog engine. For example a blogger blog will contain the following meta tag: My Subtext blog shows the following generator meta tag: This meta tag would be the first place to look. For blogs that don't set this meta tag in the source, you'd have to resort to looking for patterns to determine the blog type.
How to detect which blog API Let's say that you want to create a dead simple BlogEditor and, one of your ideas, is to do what Live Writer does and ask only the URL of the persons Blog. How can you detect what type of blog is it? Basic detection can be done with the URL itself, such as “ http://myblog.blogger.com ” etc. But what if it's self hosted? I'm mostly interested on how to do this in Java, but this question could be also used as a reference for any other language.
TITLE: How to detect which blog API QUESTION: Let's say that you want to create a dead simple BlogEditor and, one of your ideas, is to do what Live Writer does and ask only the URL of the persons Blog. How can you detect what type of blog is it? Basic detection can be done with the URL itself, such as “ http://myblog.blogger.com ” etc. But what if it's self hosted? I'm mostly interested on how to do this in Java, but this question could be also used as a reference for any other language. ANSWER: Many (most?) blogs will have a meta tag for "generator" which will list the blog engine. For example a blogger blog will contain the following meta tag: My Subtext blog shows the following generator meta tag: This meta tag would be the first place to look. For blogs that don't set this meta tag in the source, you'd have to resort to looking for patterns to determine the blog type.
[ "java", "api", "blogs" ]
2
3
549
3
0
2008-08-25T18:13:40.420000
2008-08-25T18:25:51.920000
26,551
92,057
How can I pass arguments to a batch file?
I need to pass an ID and a password to a batch file at the time of running rather than hardcoding them into the file. Here's what the command line looks like: test.cmd admin P@55w0rd > test-log.txt
Here's how I did it: @fake-command /u %1 /p %2 Here's what the command looks like: test.cmd admin P@55w0rd > test-log.txt The %1 applies to the first parameter the %2 (and here's the tricky part) applies to the second. You can have up to 9 parameters passed in this way.
How can I pass arguments to a batch file? I need to pass an ID and a password to a batch file at the time of running rather than hardcoding them into the file. Here's what the command line looks like: test.cmd admin P@55w0rd > test-log.txt
TITLE: How can I pass arguments to a batch file? QUESTION: I need to pass an ID and a password to a batch file at the time of running rather than hardcoding them into the file. Here's what the command line looks like: test.cmd admin P@55w0rd > test-log.txt ANSWER: Here's how I did it: @fake-command /u %1 /p %2 Here's what the command looks like: test.cmd admin P@55w0rd > test-log.txt The %1 applies to the first parameter the %2 (and here's the tricky part) applies to the second. You can have up to 9 parameters passed in this way.
[ "batch-file", "arguments" ]
1,435
358
2,491,352
20
0
2008-08-25T18:14:18.437000
2008-09-18T12:26:52.253000
26,552
26,555
What are the advantages and disadvantages of turning NOCOUNT off in SQL server queries?
What are the advantages and disadvantages of turning NOCOUNT off in SQL server queries? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
From SQL BOL: SET NOCOUNT ON prevents the sending of DONE_IN_PROC messages to the client for each statement in a stored procedure. For stored procedures that contain several statements that do not return much actual data, setting SET NOCOUNT to ON can provide a significant performance boost, because network traffic is greatly reduced. See http://msdn.microsoft.com/en-us/library/ms189837.aspx for more details. Also, this article on SQLServerCentral is great on this subject: Performance Effects of NOCOUNT
What are the advantages and disadvantages of turning NOCOUNT off in SQL server queries? What are the advantages and disadvantages of turning NOCOUNT off in SQL server queries? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
TITLE: What are the advantages and disadvantages of turning NOCOUNT off in SQL server queries? QUESTION: What are the advantages and disadvantages of turning NOCOUNT off in SQL server queries? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­ ANSWER: From SQL BOL: SET NOCOUNT ON prevents the sending of DONE_IN_PROC messages to the client for each statement in a stored procedure. For stored procedures that contain several statements that do not return much actual data, setting SET NOCOUNT to ON can provide a significant performance boost, because network traffic is greatly reduced. See http://msdn.microsoft.com/en-us/library/ms189837.aspx for more details. Also, this article on SQLServerCentral is great on this subject: Performance Effects of NOCOUNT
[ "sql-server", "nocount" ]
15
19
14,518
7
0
2008-08-25T18:14:21.197000
2008-08-25T18:15:57.747000
26,559
26,597
Any negative impacts when using Mod-Rewrite?
I know there are a lot of positive things mod-rewrite accomplishes. But are there any negative? Obviously if you have poorly written rules your going to have problems. But what if you have a high volume site and your constantly using mod-rewrite, is it going to have a significant impact on performance? I did a quick search for some benchmarks on Google and didn't find much.
I've used mod_rewrite on sites that get millions/hits/month without any significant performance issues. You do have to know which rewrites get applied first depending on your rules. Using mod_rewrite is most likely faster than parsing the URL with your current language. If you are really worried about performance, don't use.htaccess files, those are slow. Put all your rewrite rules in your Apache config, which is only read once on startup..htaccess files get re-parsed on every request, along with every.htaccess file in parent folders.
Any negative impacts when using Mod-Rewrite? I know there are a lot of positive things mod-rewrite accomplishes. But are there any negative? Obviously if you have poorly written rules your going to have problems. But what if you have a high volume site and your constantly using mod-rewrite, is it going to have a significant impact on performance? I did a quick search for some benchmarks on Google and didn't find much.
TITLE: Any negative impacts when using Mod-Rewrite? QUESTION: I know there are a lot of positive things mod-rewrite accomplishes. But are there any negative? Obviously if you have poorly written rules your going to have problems. But what if you have a high volume site and your constantly using mod-rewrite, is it going to have a significant impact on performance? I did a quick search for some benchmarks on Google and didn't find much. ANSWER: I've used mod_rewrite on sites that get millions/hits/month without any significant performance issues. You do have to know which rewrites get applied first depending on your rules. Using mod_rewrite is most likely faster than parsing the URL with your current language. If you are really worried about performance, don't use.htaccess files, those are slow. Put all your rewrite rules in your Apache config, which is only read once on startup..htaccess files get re-parsed on every request, along with every.htaccess file in parent folders.
[ "performance", "mod-rewrite" ]
25
41
11,103
3
0
2008-08-25T18:17:11.377000
2008-08-25T18:28:35.470000
26,567
30,409
How do I set a textbox to multi-line in SSRS?
I have a report with many fields that I'm trying to get down to 1 page horizontally (I don't care whether it's 2 or 200 pages vertically... just don't want to have to deal with 2 pages wide by x pages long train-wreck). That said, it deals with contact information. My idea was to do: Name: Address: City: State:... Jon Doe Addr1 ThisTown XX... Addr2 Addr3 ----------------------------------------------- Jane Doe Addr1 ThisTown XX... Addr2 Addr3 ----------------------------------------------- Is there some way to set a textbox to be multi-line (or the SQL result)? Have I missed something bloody obvious? The CanGrow Property is on by default, and I've double checked that this is true. My problem is that I don't know how to force a line-break. I get the 3 address fields that just fills a line, then wraps to another. I've tried /n, \n (since I can never remember which is the correct slash to put),, (since the report will be viewed in a ReportViewer control in an ASP.NET website). I can't think of any other ways to wrap the text. Is there some way to get the results from the database as 3 lines of text/characters? ­­­­­­­­­­­­­­­­­­­­­­­­­­­
Alter the report's text box to: = Fields!Addr1.Value + VbCrLf + Fields!Addr2.Value + VbCrLf + Fields!Addr3.Value
How do I set a textbox to multi-line in SSRS? I have a report with many fields that I'm trying to get down to 1 page horizontally (I don't care whether it's 2 or 200 pages vertically... just don't want to have to deal with 2 pages wide by x pages long train-wreck). That said, it deals with contact information. My idea was to do: Name: Address: City: State:... Jon Doe Addr1 ThisTown XX... Addr2 Addr3 ----------------------------------------------- Jane Doe Addr1 ThisTown XX... Addr2 Addr3 ----------------------------------------------- Is there some way to set a textbox to be multi-line (or the SQL result)? Have I missed something bloody obvious? The CanGrow Property is on by default, and I've double checked that this is true. My problem is that I don't know how to force a line-break. I get the 3 address fields that just fills a line, then wraps to another. I've tried /n, \n (since I can never remember which is the correct slash to put),, (since the report will be viewed in a ReportViewer control in an ASP.NET website). I can't think of any other ways to wrap the text. Is there some way to get the results from the database as 3 lines of text/characters? ­­­­­­­­­­­­­­­­­­­­­­­­­­­
TITLE: How do I set a textbox to multi-line in SSRS? QUESTION: I have a report with many fields that I'm trying to get down to 1 page horizontally (I don't care whether it's 2 or 200 pages vertically... just don't want to have to deal with 2 pages wide by x pages long train-wreck). That said, it deals with contact information. My idea was to do: Name: Address: City: State:... Jon Doe Addr1 ThisTown XX... Addr2 Addr3 ----------------------------------------------- Jane Doe Addr1 ThisTown XX... Addr2 Addr3 ----------------------------------------------- Is there some way to set a textbox to be multi-line (or the SQL result)? Have I missed something bloody obvious? The CanGrow Property is on by default, and I've double checked that this is true. My problem is that I don't know how to force a line-break. I get the 3 address fields that just fills a line, then wraps to another. I've tried /n, \n (since I can never remember which is the correct slash to put),, (since the report will be viewed in a ReportViewer control in an ASP.NET website). I can't think of any other ways to wrap the text. Is there some way to get the results from the database as 3 lines of text/characters? ­­­­­­­­­­­­­­­­­­­­­­­­­­­ ANSWER: Alter the report's text box to: = Fields!Addr1.Value + VbCrLf + Fields!Addr2.Value + VbCrLf + Fields!Addr3.Value
[ "reporting-services", "textbox", "multiline" ]
18
25
66,852
8
0
2008-08-25T18:19:18.627000
2008-08-27T15:15:01.563000
26,570
26,600
sizeof() equivalent for reference types?
I'm looking for a way to get the size of an instance of a reference type. sizeof is only for value types. Is this possible?
If you don't mind it being a little less accurate than perfect, and for comparative purposes, you could serialize the object/s and measure that (in bytes for example) EDIT (I kept thinking after posting): Because it's a little more complicated than sizeof for valuetypes, for example: reference types can have references to other objects and so on... there's not an exact and easy way to do it that I know of...
sizeof() equivalent for reference types? I'm looking for a way to get the size of an instance of a reference type. sizeof is only for value types. Is this possible?
TITLE: sizeof() equivalent for reference types? QUESTION: I'm looking for a way to get the size of an instance of a reference type. sizeof is only for value types. Is this possible? ANSWER: If you don't mind it being a little less accurate than perfect, and for comparative purposes, you could serialize the object/s and measure that (in bytes for example) EDIT (I kept thinking after posting): Because it's a little more complicated than sizeof for valuetypes, for example: reference types can have references to other objects and so on... there's not an exact and easy way to do it that I know of...
[ "c#", ".net" ]
21
10
11,662
6
0
2008-08-25T18:19:57.563000
2008-08-25T18:31:00.813000
26,594
26,710
Previewing HTML in Java
What libraries/methods do you know of that can do some basic HTML representation in Swing? Can you comment on your experience?
Many of the Swing controls (like JLabel) can render basic HTML content. JEditorPane can be used to display HTML pages. However, these controls are limited to HTML 3.2 support. For a richer experience, I would use the JDesktop Integration Components. JDIC provides Java applications with access to functionalities and facilities provided by the native desktop. It consists of a collection of Java packages and tools. JDIC supports a variety of features such as embedding the native browser, launching the desktop applications, creating tray icons on the desktop, registering file type associations, creating JNLP installer packages, etc.
Previewing HTML in Java What libraries/methods do you know of that can do some basic HTML representation in Swing? Can you comment on your experience?
TITLE: Previewing HTML in Java QUESTION: What libraries/methods do you know of that can do some basic HTML representation in Swing? Can you comment on your experience? ANSWER: Many of the Swing controls (like JLabel) can render basic HTML content. JEditorPane can be used to display HTML pages. However, these controls are limited to HTML 3.2 support. For a richer experience, I would use the JDesktop Integration Components. JDIC provides Java applications with access to functionalities and facilities provided by the native desktop. It consists of a collection of Java packages and tools. JDIC supports a variety of features such as embedding the native browser, launching the desktop applications, creating tray icons on the desktop, registering file type associations, creating JNLP installer packages, etc.
[ "java", "html" ]
4
1
731
7
0
2008-08-25T18:27:09.950000
2008-08-25T19:47:13.237000
26,595
26,611
Is there any difference between "foo is None" and "foo == None"?
Is there any difference between: if foo is None: pass and if foo == None: pass The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right? Are there any circumstances in which it might?
is always returns True if it compares the same object instance, whereas == is ultimately determined by the __eq__() method. i.e. >>> class Foo: def __eq__(self, other): return True >>> f = Foo() >>> f == None True >>> f is None False
Is there any difference between "foo is None" and "foo == None"? Is there any difference between: if foo is None: pass and if foo == None: pass The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right? Are there any circumstances in which it might?
TITLE: Is there any difference between "foo is None" and "foo == None"? QUESTION: Is there any difference between: if foo is None: pass and if foo == None: pass The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right? Are there any circumstances in which it might? ANSWER: is always returns True if it compares the same object instance, whereas == is ultimately determined by the __eq__() method. i.e. >>> class Foo: def __eq__(self, other): return True >>> f = Foo() >>> f == None True >>> f is None False
[ "python" ]
231
274
34,885
12
0
2008-08-25T18:27:16.330000
2008-08-25T18:38:10.267000
26,620
26,681
How to set encoding in .getJSON jQuery
In my web app, I submit some form fields with jQuery's $.getJSON() method. I am having some problems with the encoding. The character-set of my app is charset=ISO-8859-1, but I think these fields are submitted with UTF-8. How I can set encoding used in $.getJSON calls?
I think that you'll probably have to use $.ajax() if you want to change the encoding, see the contentType param below (the success and error callbacks assume you have and in the html): $.ajax({ type: "POST", url: "SomePage.aspx/GetSomeObjects", contentType: "application/json; charset=utf-8", dataType: "json", data: "{id: '" + someId + "'}", success: function(json) { $("#success").html("json.length=" + json.length); itemAddCallback(json); }, error: function (xhr, textStatus, errorThrown) { $("#error").html(xhr.responseText); } }); I actually just had to do this about an hour ago, what a coincidence!
How to set encoding in .getJSON jQuery In my web app, I submit some form fields with jQuery's $.getJSON() method. I am having some problems with the encoding. The character-set of my app is charset=ISO-8859-1, but I think these fields are submitted with UTF-8. How I can set encoding used in $.getJSON calls?
TITLE: How to set encoding in .getJSON jQuery QUESTION: In my web app, I submit some form fields with jQuery's $.getJSON() method. I am having some problems with the encoding. The character-set of my app is charset=ISO-8859-1, but I think these fields are submitted with UTF-8. How I can set encoding used in $.getJSON calls? ANSWER: I think that you'll probably have to use $.ajax() if you want to change the encoding, see the contentType param below (the success and error callbacks assume you have and in the html): $.ajax({ type: "POST", url: "SomePage.aspx/GetSomeObjects", contentType: "application/json; charset=utf-8", dataType: "json", data: "{id: '" + someId + "'}", success: function(json) { $("#success").html("json.length=" + json.length); itemAddCallback(json); }, error: function (xhr, textStatus, errorThrown) { $("#error").html(xhr.responseText); } }); I actually just had to do this about an hour ago, what a coincidence!
[ "jquery", "ajax", "json", "character-encoding" ]
45
36
127,671
6
0
2008-08-25T18:45:27.660000
2008-08-25T19:23:06.447000
26,638
26,680
What HTML parsing libraries do you recommend in Java
I want to parse some HTML in order to find the values of some attributes/tags etc. What HTML parsers do you recommend? Any pros and cons?
NekoHTML, TagSoup, and JTidy will allow you to parse HTML and then process with XML tools, like XPath.
What HTML parsing libraries do you recommend in Java I want to parse some HTML in order to find the values of some attributes/tags etc. What HTML parsers do you recommend? Any pros and cons?
TITLE: What HTML parsing libraries do you recommend in Java QUESTION: I want to parse some HTML in order to find the values of some attributes/tags etc. What HTML parsers do you recommend? Any pros and cons? ANSWER: NekoHTML, TagSoup, and JTidy will allow you to parse HTML and then process with XML tools, like XPath.
[ "java", "html", "parsing", "html-content-extraction" ]
13
12
3,989
3
0
2008-08-25T18:54:27.107000
2008-08-25T19:22:20.160000
26,652
26,656
Is there a way to make a TSQL variable constant?
Is there a way to make a TSQL variable constant?
No, but you can create a function and hardcode it in there and use that. Here is an example: CREATE FUNCTION fnConstant() RETURNS INT AS BEGIN RETURN 2 END GO SELECT dbo.fnConstant()
Is there a way to make a TSQL variable constant? Is there a way to make a TSQL variable constant?
TITLE: Is there a way to make a TSQL variable constant? QUESTION: Is there a way to make a TSQL variable constant? ANSWER: No, but you can create a function and hardcode it in there and use that. Here is an example: CREATE FUNCTION fnConstant() RETURNS INT AS BEGIN RETURN 2 END GO SELECT dbo.fnConstant()
[ "sql-server", "t-sql" ]
105
64
107,741
14
0
2008-08-25T19:03:30.160000
2008-08-25T19:05:30.060000
26,670
30,688
Why is my PDF footer text invisible?
I'm creating PDFs on-demand with ColdFusion's CFDocument tag, like so: My Client's Corporation Street address City, ST 55555 Phone: 555.555.5555 Fax: 555.555.5555 Email: info@domain.com The problem I'm having is that sometimes (actually, most of the time, but not always) some of the footer text is there, but invisible. I can highlight it and copy/paste it into notepad, where I can see it all -- but in the generated PDF only the first line of the left column of the footer is visible, the rest is invisible. Hence why I added the font color of black in the code. Any ideas on how to correct this?
A PDF is what I'm after, so I'm not sure how outputting another format would help. As it turns out, the footer space just wasn't enough to fit all of this text; verified by the fact that changing the font size to 4pt would fit it all in without a problem. I spent some time attempting to rewrite the footer code using DDX as outlined here and the CFPDF tag to implement it; but even after several hours of hacking away and finally getting a valid DDX as reported by the new isDDX function, the CFPDF tag reported that it was invalid DDX for some reason. At this point I decided I had wasted enough of the client's time/money and just reformatted the footer to be 2 lines of centered text, which was good enough.
Why is my PDF footer text invisible? I'm creating PDFs on-demand with ColdFusion's CFDocument tag, like so: My Client's Corporation Street address City, ST 55555 Phone: 555.555.5555 Fax: 555.555.5555 Email: info@domain.com The problem I'm having is that sometimes (actually, most of the time, but not always) some of the footer text is there, but invisible. I can highlight it and copy/paste it into notepad, where I can see it all -- but in the generated PDF only the first line of the left column of the footer is visible, the rest is invisible. Hence why I added the font color of black in the code. Any ideas on how to correct this?
TITLE: Why is my PDF footer text invisible? QUESTION: I'm creating PDFs on-demand with ColdFusion's CFDocument tag, like so: My Client's Corporation Street address City, ST 55555 Phone: 555.555.5555 Fax: 555.555.5555 Email: info@domain.com The problem I'm having is that sometimes (actually, most of the time, but not always) some of the footer text is there, but invisible. I can highlight it and copy/paste it into notepad, where I can see it all -- but in the generated PDF only the first line of the left column of the footer is visible, the rest is invisible. Hence why I added the font color of black in the code. Any ideas on how to correct this? ANSWER: A PDF is what I'm after, so I'm not sure how outputting another format would help. As it turns out, the footer space just wasn't enough to fit all of this text; verified by the fact that changing the font size to 4pt would fit it all in without a problem. I spent some time attempting to rewrite the footer code using DDX as outlined here and the CFPDF tag to implement it; but even after several hours of hacking away and finally getting a valid DDX as reported by the new isDDX function, the CFPDF tag reported that it was invalid DDX for some reason. At this point I decided I had wasted enough of the client's time/money and just reformatted the footer to be 2 lines of centered text, which was good enough.
[ "pdf", "coldfusion" ]
1
2
1,131
2
0
2008-08-25T19:14:07.280000
2008-08-27T17:30:21.787000
26,685
26,693
What is MVC and what are the advantages of it?
I found What are mvp and mvc and what is the difference but it didn't really answer this question. I've recently started using MVC because it's part of the framework that myself and my work-partner are going to use. We chose it because it looked easy and separated process from display, are there advantages besides this that we don't know about and could be missing out on? Pros Display and Processing are seperated Cons None so far
MVC is the separation of m odel, v iew and c ontroller — nothing more, nothing less. It's simply a paradigm; an ideal that you should have in the back of your mind when designing classes. Avoid mixing code from the three categories into one class. For example, while a table grid view should obviously present data once shown, it should not have code on where to retrieve the data from, or what its native structure (the model ) is like. Likewise, while it may have a function to sum up a column, the actual summing is supposed to happen in the controller. A 'save file' dialog ( view ) ultimately passes the path, once picked by the user, on to the controller, which then asks the model for the data, and does the actual saving. This separation of responsibilities allows flexibility down the road. For example, because the view doesn't care about the underlying model, supporting multiple file formats is easier: just add a model subclass for each.
What is MVC and what are the advantages of it? I found What are mvp and mvc and what is the difference but it didn't really answer this question. I've recently started using MVC because it's part of the framework that myself and my work-partner are going to use. We chose it because it looked easy and separated process from display, are there advantages besides this that we don't know about and could be missing out on? Pros Display and Processing are seperated Cons None so far
TITLE: What is MVC and what are the advantages of it? QUESTION: I found What are mvp and mvc and what is the difference but it didn't really answer this question. I've recently started using MVC because it's part of the framework that myself and my work-partner are going to use. We chose it because it looked easy and separated process from display, are there advantages besides this that we don't know about and could be missing out on? Pros Display and Processing are seperated Cons None so far ANSWER: MVC is the separation of m odel, v iew and c ontroller — nothing more, nothing less. It's simply a paradigm; an ideal that you should have in the back of your mind when designing classes. Avoid mixing code from the three categories into one class. For example, while a table grid view should obviously present data once shown, it should not have code on where to retrieve the data from, or what its native structure (the model ) is like. Likewise, while it may have a function to sum up a column, the actual summing is supposed to happen in the controller. A 'save file' dialog ( view ) ultimately passes the path, once picked by the user, on to the controller, which then asks the model for the data, and does the actual saving. This separation of responsibilities allows flexibility down the road. For example, because the view doesn't care about the underlying model, supporting multiple file formats is easier: just add a model subclass for each.
[ "model-view-controller", "design-patterns" ]
47
46
109,240
11
0
2008-08-25T19:26:39.823000
2008-08-25T19:31:57.250000
26,706
26,707
wxpython: How do I examine dragged data in OnDragOver?
I'm a bit perplexed by drag and drop in wxPython (but perhaps this questions pertains to drag and drop in other GUI frameworks as well). The frameworks provides a couple of callbacks (OnEnter and OnDragOver) that purportedly allow me to inform the system whether the current mouse position is a valid place to drop whatever it is that is being dragged. From these methods I can return wx.DragNone, wx.DragCopy, etc. What baffles me is that from within these methods I am not allowed to call GetData, which means I am not allowed to examine the data that the user is dragging. If I cannot see the data, how am I supposed to know whether it is OK for the user to drop here?
One solution, which is a hack of limited usefulness, is when a drag is initiated, store the dragged data in a global or static reference somewhere. This way, in the OnEnter and OnDragOver handlers, it is possible to get a reference to the data being dragged. This is of course only useful for drags within the same application (the same instance of the application, actually).
wxpython: How do I examine dragged data in OnDragOver? I'm a bit perplexed by drag and drop in wxPython (but perhaps this questions pertains to drag and drop in other GUI frameworks as well). The frameworks provides a couple of callbacks (OnEnter and OnDragOver) that purportedly allow me to inform the system whether the current mouse position is a valid place to drop whatever it is that is being dragged. From these methods I can return wx.DragNone, wx.DragCopy, etc. What baffles me is that from within these methods I am not allowed to call GetData, which means I am not allowed to examine the data that the user is dragging. If I cannot see the data, how am I supposed to know whether it is OK for the user to drop here?
TITLE: wxpython: How do I examine dragged data in OnDragOver? QUESTION: I'm a bit perplexed by drag and drop in wxPython (but perhaps this questions pertains to drag and drop in other GUI frameworks as well). The frameworks provides a couple of callbacks (OnEnter and OnDragOver) that purportedly allow me to inform the system whether the current mouse position is a valid place to drop whatever it is that is being dragged. From these methods I can return wx.DragNone, wx.DragCopy, etc. What baffles me is that from within these methods I am not allowed to call GetData, which means I am not allowed to examine the data that the user is dragging. If I cannot see the data, how am I supposed to know whether it is OK for the user to drop here? ANSWER: One solution, which is a hack of limited usefulness, is when a drag is initiated, store the dragged data in a global or static reference somewhere. This way, in the OnEnter and OnDragOver handlers, it is possible to get a reference to the data being dragged. This is of course only useful for drags within the same application (the same instance of the application, actually).
[ "python", "user-interface", "drag-and-drop", "wxpython", "wxwidgets" ]
6
1
617
2
0
2008-08-25T19:43:15.960000
2008-08-25T19:45:40.977000
26,711
26,720
Asp.net Reinstalling a DLL into the GAC
I'm trying to re-install a DLL in the GAC, everything seems to work fine but the web application accessing it still seems to be using the old one. The old DLL is the same version as the new one with only a minor edit, it will be used by 50 different sites so changing the version then changing the reference in the web.config is not a good solution. Restarting the IIS server or the worker process isn't an option as there are already 50 sites running that must continue to do so. does anyone know what i'm doing wrong or what i can do to remedy this situation?
AFAIK, you need to restart IIS for it to get a fresh reference to the updated DLL. Your best bet is to perform the reset at a low traffic time. If you are running multiple servers with load balancing, you can prevent new connections from hitting one server until all connections have been closed. Afterwards, update the DLL, restart IIS, and bring the server back into the connection pool. Repeat for each server with no visible downtime to the end users.
Asp.net Reinstalling a DLL into the GAC I'm trying to re-install a DLL in the GAC, everything seems to work fine but the web application accessing it still seems to be using the old one. The old DLL is the same version as the new one with only a minor edit, it will be used by 50 different sites so changing the version then changing the reference in the web.config is not a good solution. Restarting the IIS server or the worker process isn't an option as there are already 50 sites running that must continue to do so. does anyone know what i'm doing wrong or what i can do to remedy this situation?
TITLE: Asp.net Reinstalling a DLL into the GAC QUESTION: I'm trying to re-install a DLL in the GAC, everything seems to work fine but the web application accessing it still seems to be using the old one. The old DLL is the same version as the new one with only a minor edit, it will be used by 50 different sites so changing the version then changing the reference in the web.config is not a good solution. Restarting the IIS server or the worker process isn't an option as there are already 50 sites running that must continue to do so. does anyone know what i'm doing wrong or what i can do to remedy this situation? ANSWER: AFAIK, you need to restart IIS for it to get a fresh reference to the updated DLL. Your best bet is to perform the reset at a low traffic time. If you are running multiple servers with load balancing, you can prevent new connections from hitting one server until all connections have been closed. Afterwards, update the DLL, restart IIS, and bring the server back into the connection pool. Repeat for each server with no visible downtime to the end users.
[ "iis", "dll", "gac" ]
3
3
3,624
2
0
2008-08-25T19:47:42.830000
2008-08-25T19:51:47.033000
26,715
26,741
asp.net mvc - subfolders
How does the new Microsoft asp.net mvc implementation handle partitioning your application - for example: --index.aspx --about.aspx --contact.aspx --/feature1 --/feature1/subfeature/action --/feature2/subfeature/action I guess what I am trying to say is that it seems everything has to go into the root of the views/controllers folders which could get unwieldy when working on a project that if built with web forms might have lots and lots of folders and sub-folders to partition the application. I think I get the MVC model and I like the look of it compared to web forms but still getting my head round how you would build a large project in practice.
There isn't any issues with organizing your controllers. You just need to setup the routes to take the organization into consideration. The problem you will run into is finding the view for the controller, since you changed the convention. There isn't any built in functionality for it yet, but it is easy to create a work around yourself with a ActionFilterAttribute and a custom view locator that inherits off ViewLocator. Then when creating your controller, you just specify what ViewLocator to use, so the controller knows how to find the view. I can post some code if needed. This method kind of goes along with some advice I gave another person for separating their views out for a portal using ASP.NET MVC. Here is the link to the question as a reference.
asp.net mvc - subfolders How does the new Microsoft asp.net mvc implementation handle partitioning your application - for example: --index.aspx --about.aspx --contact.aspx --/feature1 --/feature1/subfeature/action --/feature2/subfeature/action I guess what I am trying to say is that it seems everything has to go into the root of the views/controllers folders which could get unwieldy when working on a project that if built with web forms might have lots and lots of folders and sub-folders to partition the application. I think I get the MVC model and I like the look of it compared to web forms but still getting my head round how you would build a large project in practice.
TITLE: asp.net mvc - subfolders QUESTION: How does the new Microsoft asp.net mvc implementation handle partitioning your application - for example: --index.aspx --about.aspx --contact.aspx --/feature1 --/feature1/subfeature/action --/feature2/subfeature/action I guess what I am trying to say is that it seems everything has to go into the root of the views/controllers folders which could get unwieldy when working on a project that if built with web forms might have lots and lots of folders and sub-folders to partition the application. I think I get the MVC model and I like the look of it compared to web forms but still getting my head round how you would build a large project in practice. ANSWER: There isn't any issues with organizing your controllers. You just need to setup the routes to take the organization into consideration. The problem you will run into is finding the view for the controller, since you changed the convention. There isn't any built in functionality for it yet, but it is easy to create a work around yourself with a ActionFilterAttribute and a custom view locator that inherits off ViewLocator. Then when creating your controller, you just specify what ViewLocator to use, so the controller knows how to find the view. I can post some code if needed. This method kind of goes along with some advice I gave another person for separating their views out for a portal using ASP.NET MVC. Here is the link to the question as a reference.
[ "asp.net-mvc", "directory-structure" ]
12
11
11,728
3
0
2008-08-25T19:50:21.827000
2008-08-25T20:02:29.113000
26,719
28,915
Internalize Class and Methods in .NET Assembly
I have a set of multiple assemblies (one assembly is to be used as an API and it depends on other assemblies). I would like to merge all assemblies into one single assembly but prevent all assemblies except the API one to be visible from the outside. I will then obfuscate this assembly with Xenocode. From what I have seen, it is impossible to internalize assembly with Xenocode. I have seen ILMerge from Microsoft, but was unable to figure if it can do what I want. http://research.microsoft.com/~mbarnett/ILMerge.aspx
I know Xenocode can merge assemblies into one but I am not sure if it will internalize other non-primary assemblies. I have found the /internalize switch in ILMerge that "internalize" all assemblies except the primary one. Pretty useful!
Internalize Class and Methods in .NET Assembly I have a set of multiple assemblies (one assembly is to be used as an API and it depends on other assemblies). I would like to merge all assemblies into one single assembly but prevent all assemblies except the API one to be visible from the outside. I will then obfuscate this assembly with Xenocode. From what I have seen, it is impossible to internalize assembly with Xenocode. I have seen ILMerge from Microsoft, but was unable to figure if it can do what I want. http://research.microsoft.com/~mbarnett/ILMerge.aspx
TITLE: Internalize Class and Methods in .NET Assembly QUESTION: I have a set of multiple assemblies (one assembly is to be used as an API and it depends on other assemblies). I would like to merge all assemblies into one single assembly but prevent all assemblies except the API one to be visible from the outside. I will then obfuscate this assembly with Xenocode. From what I have seen, it is impossible to internalize assembly with Xenocode. I have seen ILMerge from Microsoft, but was unable to figure if it can do what I want. http://research.microsoft.com/~mbarnett/ILMerge.aspx ANSWER: I know Xenocode can merge assemblies into one but I am not sure if it will internalize other non-primary assemblies. I have found the /internalize switch in ILMerge that "internalize" all assemblies except the primary one. Pretty useful!
[ "c#", ".net", "vb.net", "assemblies" ]
1
1
1,373
4
0
2008-08-25T19:51:31.260000
2008-08-26T19:27:04.167000
26,721
27,032
How can I make sure scrollbars don't overlap content?
When creating scrollable user controls with.NET and WinForms I have repeatedly encountered situations where, for example, a vertical scrollbar pops up, overlapping the control's content, causing a horizontal scrollbar to also be needed. Ideally the content would shrink just a bit to make room for the vertical scrollbar. My current solution has been to just keep my controls out of the far right 40 pixels or so that the vertical scroll-bar will be taking up. Since this is still effectively client space for the control, the horizontal scroll-bar still comes up when it gets covered by the vertical scroll-bar, even though no controls are being hidden at all. But then at least the user doesn't actually need to use the horizontal scrollbar that comes up. Is there a better way to make this all work? Some way to keep the unneeded and unwanted scrollbars from showing up at all?
You will need your controls to resize slightly to accommodate the width of the vertical scroll bar. One way to achieve this achieved through docking. Rather than just dropping controls on the form, you'll have to play a bit with panels, padding, min/max sizing and docking. Here is example code you can place behind a blank new Form1. Resize the form, in designer or runtime and you'll see that the horizontal scrollbar is not shown and the fields are not overlapped. I've also given the fields a max width for good measure: #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.textBox1 = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.panel1 = new System.Windows.Forms.Panel(); this.panel2 = new System.Windows.Forms.Panel(); this.textBox2 = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.panel1.SuspendLayout(); this.panel2.SuspendLayout(); this.SuspendLayout(); // // textBox1 // this.textBox1.Dock = System.Windows.Forms.DockStyle.Top; this.textBox1.Location = new System.Drawing.Point(32, 0); this.textBox1.MaximumSize = new System.Drawing.Size(250, 0); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(250, 20); this.textBox1.TabIndex = 0; // // label1 // this.label1.AutoSize = true; this.label1.Dock = System.Windows.Forms.DockStyle.Left; this.label1.Location = new System.Drawing.Point(0, 0); this.label1.Name = "label1"; this.label1.Padding = new System.Windows.Forms.Padding(0, 3, 0, 0); this.label1.Size = new System.Drawing.Size(32, 16); this.label1.TabIndex = 0; this.label1.Text = "Field:"; // // panel1 // this.panel1.Controls.Add(this.textBox1); this.panel1.Controls.Add(this.label1); this.panel1.Dock = System.Windows.Forms.DockStyle.Top; this.panel1.Location = new System.Drawing.Point(0, 0); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(392, 37); this.panel1.TabIndex = 2; // // panel2 // this.panel2.Controls.Add(this.textBox2); this.panel2.Controls.Add(this.label2); this.panel2.Dock = System.Windows.Forms.DockStyle.Top; this.panel2.Location = new System.Drawing.Point(0, 37); this.panel2.Name = "panel2"; this.panel2.Size = new System.Drawing.Size(392, 37); this.panel2.TabIndex = 3; // // textBox2 // this.textBox2.Dock = System.Windows.Forms.DockStyle.Top; this.textBox2.Location = new System.Drawing.Point(32, 0); this.textBox2.MaximumSize = new System.Drawing.Size(250, 0); this.textBox2.Name = "textBox2"; this.textBox2.Size = new System.Drawing.Size(250, 20); this.textBox2.TabIndex = 0; // // label2 // this.label2.AutoSize = true; this.label2.Dock = System.Windows.Forms.DockStyle.Left; this.label2.Location = new System.Drawing.Point(0, 0); this.label2.Name = "label2"; this.label2.Padding = new System.Windows.Forms.Padding(0, 3, 0, 0); this.label2.Size = new System.Drawing.Size(32, 16); this.label2.TabIndex = 0; this.label2.Text = "Field:"; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScroll = true; this.ClientSize = new System.Drawing.Size(392, 116); this.Controls.Add(this.panel2); this.Controls.Add(this.panel1); this.Name = "Form1"; this.Text = "Form1"; this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.panel2.ResumeLayout(false); this.panel2.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Label label1; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.TextBox textBox2; private System.Windows.Forms.Label label2;
How can I make sure scrollbars don't overlap content? When creating scrollable user controls with.NET and WinForms I have repeatedly encountered situations where, for example, a vertical scrollbar pops up, overlapping the control's content, causing a horizontal scrollbar to also be needed. Ideally the content would shrink just a bit to make room for the vertical scrollbar. My current solution has been to just keep my controls out of the far right 40 pixels or so that the vertical scroll-bar will be taking up. Since this is still effectively client space for the control, the horizontal scroll-bar still comes up when it gets covered by the vertical scroll-bar, even though no controls are being hidden at all. But then at least the user doesn't actually need to use the horizontal scrollbar that comes up. Is there a better way to make this all work? Some way to keep the unneeded and unwanted scrollbars from showing up at all?
TITLE: How can I make sure scrollbars don't overlap content? QUESTION: When creating scrollable user controls with.NET and WinForms I have repeatedly encountered situations where, for example, a vertical scrollbar pops up, overlapping the control's content, causing a horizontal scrollbar to also be needed. Ideally the content would shrink just a bit to make room for the vertical scrollbar. My current solution has been to just keep my controls out of the far right 40 pixels or so that the vertical scroll-bar will be taking up. Since this is still effectively client space for the control, the horizontal scroll-bar still comes up when it gets covered by the vertical scroll-bar, even though no controls are being hidden at all. But then at least the user doesn't actually need to use the horizontal scrollbar that comes up. Is there a better way to make this all work? Some way to keep the unneeded and unwanted scrollbars from showing up at all? ANSWER: You will need your controls to resize slightly to accommodate the width of the vertical scroll bar. One way to achieve this achieved through docking. Rather than just dropping controls on the form, you'll have to play a bit with panels, padding, min/max sizing and docking. Here is example code you can place behind a blank new Form1. Resize the form, in designer or runtime and you'll see that the horizontal scrollbar is not shown and the fields are not overlapped. I've also given the fields a max width for good measure: #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.textBox1 = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.panel1 = new System.Windows.Forms.Panel(); this.panel2 = new System.Windows.Forms.Panel(); this.textBox2 = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.panel1.SuspendLayout(); this.panel2.SuspendLayout(); this.SuspendLayout(); // // textBox1 // this.textBox1.Dock = System.Windows.Forms.DockStyle.Top; this.textBox1.Location = new System.Drawing.Point(32, 0); this.textBox1.MaximumSize = new System.Drawing.Size(250, 0); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(250, 20); this.textBox1.TabIndex = 0; // // label1 // this.label1.AutoSize = true; this.label1.Dock = System.Windows.Forms.DockStyle.Left; this.label1.Location = new System.Drawing.Point(0, 0); this.label1.Name = "label1"; this.label1.Padding = new System.Windows.Forms.Padding(0, 3, 0, 0); this.label1.Size = new System.Drawing.Size(32, 16); this.label1.TabIndex = 0; this.label1.Text = "Field:"; // // panel1 // this.panel1.Controls.Add(this.textBox1); this.panel1.Controls.Add(this.label1); this.panel1.Dock = System.Windows.Forms.DockStyle.Top; this.panel1.Location = new System.Drawing.Point(0, 0); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(392, 37); this.panel1.TabIndex = 2; // // panel2 // this.panel2.Controls.Add(this.textBox2); this.panel2.Controls.Add(this.label2); this.panel2.Dock = System.Windows.Forms.DockStyle.Top; this.panel2.Location = new System.Drawing.Point(0, 37); this.panel2.Name = "panel2"; this.panel2.Size = new System.Drawing.Size(392, 37); this.panel2.TabIndex = 3; // // textBox2 // this.textBox2.Dock = System.Windows.Forms.DockStyle.Top; this.textBox2.Location = new System.Drawing.Point(32, 0); this.textBox2.MaximumSize = new System.Drawing.Size(250, 0); this.textBox2.Name = "textBox2"; this.textBox2.Size = new System.Drawing.Size(250, 20); this.textBox2.TabIndex = 0; // // label2 // this.label2.AutoSize = true; this.label2.Dock = System.Windows.Forms.DockStyle.Left; this.label2.Location = new System.Drawing.Point(0, 0); this.label2.Name = "label2"; this.label2.Padding = new System.Windows.Forms.Padding(0, 3, 0, 0); this.label2.Size = new System.Drawing.Size(32, 16); this.label2.TabIndex = 0; this.label2.Text = "Field:"; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScroll = true; this.ClientSize = new System.Drawing.Size(392, 116); this.Controls.Add(this.panel2); this.Controls.Add(this.panel1); this.Name = "Form1"; this.Text = "Form1"; this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.panel2.ResumeLayout(false); this.panel2.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Label label1; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.TextBox textBox2; private System.Windows.Forms.Label label2;
[ ".net", "winforms" ]
2
1
3,348
2
0
2008-08-25T19:52:07.173000
2008-08-25T22:15:50.930000
26,732
26,744
java.lang.IllegalArgumentException: Invalid <url-pattern> in servlet mapping
myservlet workflow.WDispatcher 2 myservlet *NEXTEVENT* Above is the snippet from Tomcat's web.xml. The URL pattern *NEXTEVENT* on start up throws java.lang.IllegalArgumentException: Invalid in servlet mapping It will be greatly appreciated if someone can hint at the error. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
*NEXTEVENT* The URL pattern is not valid. It can either end in an asterisk or start with one (to denote a file extension mapping). The url-pattern specification: A string beginning with a ‘/’ character and ending with a ‘/*’ suffix is used for path mapping. A string beginning with a ‘*.’ prefix is used as an extension mapping. A string containing only the ’/’ character indicates the "default" servlet of the application. In this case the servlet path is the request URI minus the context path and the path info is null. All other strings are used for exact matches only. See section 12.2 of the Java Servlet Specification Version 3.1 for more details.
java.lang.IllegalArgumentException: Invalid <url-pattern> in servlet mapping myservlet workflow.WDispatcher 2 myservlet *NEXTEVENT* Above is the snippet from Tomcat's web.xml. The URL pattern *NEXTEVENT* on start up throws java.lang.IllegalArgumentException: Invalid in servlet mapping It will be greatly appreciated if someone can hint at the error. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
TITLE: java.lang.IllegalArgumentException: Invalid <url-pattern> in servlet mapping QUESTION: myservlet workflow.WDispatcher 2 myservlet *NEXTEVENT* Above is the snippet from Tomcat's web.xml. The URL pattern *NEXTEVENT* on start up throws java.lang.IllegalArgumentException: Invalid in servlet mapping It will be greatly appreciated if someone can hint at the error. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­ ANSWER: *NEXTEVENT* The URL pattern is not valid. It can either end in an asterisk or start with one (to denote a file extension mapping). The url-pattern specification: A string beginning with a ‘/’ character and ending with a ‘/*’ suffix is used for path mapping. A string beginning with a ‘*.’ prefix is used as an extension mapping. A string containing only the ’/’ character indicates the "default" servlet of the application. In this case the servlet path is the request URI minus the context path and the path info is null. All other strings are used for exact matches only. See section 12.2 of the Java Servlet Specification Version 3.1 for more details.
[ "tomcat", "servlets", "web.xml", "illegalargumentexception", "servlet-mapping" ]
45
103
92,273
2
0
2008-08-25T19:56:38.470000
2008-08-25T20:04:47.157000
26,733
26,750
Getting all types that implement an interface
Using reflection, how can I get all types that implement an interface with C# 3.0/.NET 3.5 with the least code, and minimizing iterations? This is what I want to re-write: foreach (Type t in this.GetType().Assembly.GetTypes()) if (t is IMyInterface); //do stuff
Mine would be this in c# 3.0:) var type = typeof(IMyInterface); var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(s => s.GetTypes()).Where(p => type.IsAssignableFrom(p)); Basically, the least amount of iterations will always be: loop assemblies loop types see if implemented.
Getting all types that implement an interface Using reflection, how can I get all types that implement an interface with C# 3.0/.NET 3.5 with the least code, and minimizing iterations? This is what I want to re-write: foreach (Type t in this.GetType().Assembly.GetTypes()) if (t is IMyInterface); //do stuff
TITLE: Getting all types that implement an interface QUESTION: Using reflection, how can I get all types that implement an interface with C# 3.0/.NET 3.5 with the least code, and minimizing iterations? This is what I want to re-write: foreach (Type t in this.GetType().Assembly.GetTypes()) if (t is IMyInterface); //do stuff ANSWER: Mine would be this in c# 3.0:) var type = typeof(IMyInterface); var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(s => s.GetTypes()).Where(p => type.IsAssignableFrom(p)); Basically, the least amount of iterations will always be: loop assemblies loop types see if implemented.
[ "c#", "optimization", "reflection", "lambda", "c#-3.0" ]
663
946
393,294
19
0
2008-08-25T19:57:21.903000
2008-08-25T20:11:21.243000
26,760
26,769
Parse string to TimeSpan
I have some strings of xxh:yym format where xx is hours and yy is minutes like "05h:30m". What is an elegant way to convert a string of this type to TimeSpan?
This seems to work, though it is a bit hackish: TimeSpan span; if (TimeSpan.TryParse("05h:30m".Replace("m","").Replace("h",""), out span)) MessageBox.Show(span.ToString());
Parse string to TimeSpan I have some strings of xxh:yym format where xx is hours and yy is minutes like "05h:30m". What is an elegant way to convert a string of this type to TimeSpan?
TITLE: Parse string to TimeSpan QUESTION: I have some strings of xxh:yym format where xx is hours and yy is minutes like "05h:30m". What is an elegant way to convert a string of this type to TimeSpan? ANSWER: This seems to work, though it is a bit hackish: TimeSpan span; if (TimeSpan.TryParse("05h:30m".Replace("m","").Replace("h",""), out span)) MessageBox.Show(span.ToString());
[ "c#", "timespan" ]
30
27
60,924
5
0
2008-08-25T20:16:26.990000
2008-08-25T20:20:22.953000
26,762
26,785
Perforce in a Microsoft Shop
Our dev shop currently uses Visual SourceSafe. We all know how that could end up (badly), so we're investigating other systems. First up is Perforce. Does anyone have experience with using it and its integration into Visual Studio (2003/2005/2008)? Is it as good as any other, or is it pretty solid with good features, comparatively?
I used Perforce at my last 3 jobs (my current job I'm using Subversion, which I don't like nearly as much.) I'm a big fan of Perforce, and moving from SourceSafe it will seem like Nirvana. Just getting atomic checkin will be a big boost for your company. Otherwise, Perforce is fast, it has good tools, and the workflow is simple for doing things like merges and integrations. I wholeheartedly recommend it. It may not be all new and flashy like the latest distributed VCS's, but honestly, I prefer the client/server model for its speed, especially if you're working with people in other countries that may have slow connections to you. The Visual Studio integration is pretty good, but it has a few irritating issues. If you run another Perforce client at the same time (like P4V), it's very poor at keeping changes from the other client in sync in terms of showing what files are currently checked in/out. You generally have to shut down Visual Studio and load the project again if you want it to sync correctly. But, the sync status doesn't actually affect checkins/checkouts/updates from working correctly, it just means you can be fooled in to thinking something is in a different state than it actually is while you're in Visual Studio. The Perforce clients will always show the correct status as they sync continually with the database. Also, on occasion you'll find you need to work "offline" (not connected to the Perforce database for some reason) and when you load the project again the next time, your Perforce bindings may be lost and you'll have to rebind each project individually. If you work with a solution that contains many projects this can be a big pain in the patoot. Same goes for when you first check out a solution, binding to Perforce is needed before the integration occurs.
Perforce in a Microsoft Shop Our dev shop currently uses Visual SourceSafe. We all know how that could end up (badly), so we're investigating other systems. First up is Perforce. Does anyone have experience with using it and its integration into Visual Studio (2003/2005/2008)? Is it as good as any other, or is it pretty solid with good features, comparatively?
TITLE: Perforce in a Microsoft Shop QUESTION: Our dev shop currently uses Visual SourceSafe. We all know how that could end up (badly), so we're investigating other systems. First up is Perforce. Does anyone have experience with using it and its integration into Visual Studio (2003/2005/2008)? Is it as good as any other, or is it pretty solid with good features, comparatively? ANSWER: I used Perforce at my last 3 jobs (my current job I'm using Subversion, which I don't like nearly as much.) I'm a big fan of Perforce, and moving from SourceSafe it will seem like Nirvana. Just getting atomic checkin will be a big boost for your company. Otherwise, Perforce is fast, it has good tools, and the workflow is simple for doing things like merges and integrations. I wholeheartedly recommend it. It may not be all new and flashy like the latest distributed VCS's, but honestly, I prefer the client/server model for its speed, especially if you're working with people in other countries that may have slow connections to you. The Visual Studio integration is pretty good, but it has a few irritating issues. If you run another Perforce client at the same time (like P4V), it's very poor at keeping changes from the other client in sync in terms of showing what files are currently checked in/out. You generally have to shut down Visual Studio and load the project again if you want it to sync correctly. But, the sync status doesn't actually affect checkins/checkouts/updates from working correctly, it just means you can be fooled in to thinking something is in a different state than it actually is while you're in Visual Studio. The Perforce clients will always show the correct status as they sync continually with the database. Also, on occasion you'll find you need to work "offline" (not connected to the Perforce database for some reason) and when you load the project again the next time, your Perforce bindings may be lost and you'll have to rebind each project individually. If you work with a solution that contains many projects this can be a big pain in the patoot. Same goes for when you first check out a solution, binding to Perforce is needed before the integration occurs.
[ "version-control", "visual-sourcesafe", "perforce" ]
6
12
1,620
9
0
2008-08-25T20:17:10.293000
2008-08-25T20:26:40.023000
26,771
26,852
Rewarding code projects for *complete* beginners
Courses for people who are being introduced to programming very often include a code project, which I think is a nice way to learn. However, such projects often feel too artificial, and are thus not very rewarding to work on. What are your ideas of rewarding code projects? (Preferably easy to begin, and extendable at will for the more advanced!). Edit: @Mark: thanks for the link, though I'm more interested in projects for people who are completely new to programming (the link seems to refer more to people who are already proficient in at least one language, and trying to learn a new one -the typical SO audience I'd say:) -). @Kevin, Vaibhav, gary: I was thinking of people who are learning programming through one language, so at the beginning of the course some don't know anything about control structures (and even less about any kind of syntax). However, I was thinking in quite a large project (typically in the 1k-10k lines of code range, possibly in groups of 2 or 3 students). This is what was done at my school for the complete beginners, and it sure seemed to work for them... except that most of them found their projects quite boring to work on!
As has been stated a few times, what you are trying to teach the beginner is very important to the project. My advice to you for planning something like this: 1) Avoid making a computer game A computer game, while fun to build, doesn't reward the programmer with results early on (it's very complex). You want to concentrate on small but useful application programs, such as a Port Scanner. The example there is a little complex, but it's one of the best learning projects I've seen on the web. 2) Teach graphics early It's rewarding to see the fruits of your labors early on, and it motivates you to go further. Whether you're using WinForms, MFC or the Win32 API, OpenGL or DirectX, teach it early. 3) Many small lessons with in depth information This principle is followed by the above linked Port Scanner project, and it works well. Teach each part thoroughly, and give time for the beginner to absorb the lesson. I think that ZophusX had a good format for giving the information. It's too bad he's mostly abandoned his site. 4) It takes time Don't rush things. Nobody becomes a stellar programmer in a few weeks. Try and make the lessons simple, but engaging, and keep building from your previous lessons. 5) Get feedback early and often You might think a project is incredibly interesting, or a particular lesson or such, but you aren't the one learning. Your student(s) will greatly appreciate it when you ask them early on how things are going, and what they'd like to know more about. Be flexible enough that you can accomodate some of those requests. 6) Have fun teaching Have fun. Passion is contagious, and if your student(s) see how much you enjoy the subject matter, some of that enthusiasm will rub off on them as well. I hope that helps!
Rewarding code projects for *complete* beginners Courses for people who are being introduced to programming very often include a code project, which I think is a nice way to learn. However, such projects often feel too artificial, and are thus not very rewarding to work on. What are your ideas of rewarding code projects? (Preferably easy to begin, and extendable at will for the more advanced!). Edit: @Mark: thanks for the link, though I'm more interested in projects for people who are completely new to programming (the link seems to refer more to people who are already proficient in at least one language, and trying to learn a new one -the typical SO audience I'd say:) -). @Kevin, Vaibhav, gary: I was thinking of people who are learning programming through one language, so at the beginning of the course some don't know anything about control structures (and even less about any kind of syntax). However, I was thinking in quite a large project (typically in the 1k-10k lines of code range, possibly in groups of 2 or 3 students). This is what was done at my school for the complete beginners, and it sure seemed to work for them... except that most of them found their projects quite boring to work on!
TITLE: Rewarding code projects for *complete* beginners QUESTION: Courses for people who are being introduced to programming very often include a code project, which I think is a nice way to learn. However, such projects often feel too artificial, and are thus not very rewarding to work on. What are your ideas of rewarding code projects? (Preferably easy to begin, and extendable at will for the more advanced!). Edit: @Mark: thanks for the link, though I'm more interested in projects for people who are completely new to programming (the link seems to refer more to people who are already proficient in at least one language, and trying to learn a new one -the typical SO audience I'd say:) -). @Kevin, Vaibhav, gary: I was thinking of people who are learning programming through one language, so at the beginning of the course some don't know anything about control structures (and even less about any kind of syntax). However, I was thinking in quite a large project (typically in the 1k-10k lines of code range, possibly in groups of 2 or 3 students). This is what was done at my school for the complete beginners, and it sure seemed to work for them... except that most of them found their projects quite boring to work on! ANSWER: As has been stated a few times, what you are trying to teach the beginner is very important to the project. My advice to you for planning something like this: 1) Avoid making a computer game A computer game, while fun to build, doesn't reward the programmer with results early on (it's very complex). You want to concentrate on small but useful application programs, such as a Port Scanner. The example there is a little complex, but it's one of the best learning projects I've seen on the web. 2) Teach graphics early It's rewarding to see the fruits of your labors early on, and it motivates you to go further. Whether you're using WinForms, MFC or the Win32 API, OpenGL or DirectX, teach it early. 3) Many small lessons with in depth information This principle is followed by the above linked Port Scanner project, and it works well. Teach each part thoroughly, and give time for the beginner to absorb the lesson. I think that ZophusX had a good format for giving the information. It's too bad he's mostly abandoned his site. 4) It takes time Don't rush things. Nobody becomes a stellar programmer in a few weeks. Try and make the lessons simple, but engaging, and keep building from your previous lessons. 5) Get feedback early and often You might think a project is incredibly interesting, or a particular lesson or such, but you aren't the one learning. Your student(s) will greatly appreciate it when you ask them early on how things are going, and what they'd like to know more about. Be flexible enough that you can accomodate some of those requests. 6) Have fun teaching Have fun. Passion is contagious, and if your student(s) see how much you enjoy the subject matter, some of that enthusiasm will rub off on them as well. I hope that helps!
[ "language-agnostic" ]
9
4
4,914
7
0
2008-08-25T20:21:18.257000
2008-08-25T20:47:34.450000
26,799
26,858
How do you back up your development machine?
How do you back up your development machine so that in the event of a catastrophic hardware malfunction, you are up and running in the least amount of time possible?
There's an important distinction between backing up your development machine and backing up your work. For a development machine your best bet is an imaging solution that offers as near a "one-click-restore" process as possible. TimeMachine (Mac) and Windows Home Server (Windows) are both excellent for this purpose. Not only can you have your entire machine restored in 1-2 hours (depending on HDD size), but both run automatically and store deltas so you can have months of backups in relatively little space. There are also numerous "ghosting" packages, though they usually do not offer incremental/delta backups so take more time/space to backup your machine. Less good are products such as Carbonite/Mozy/JungleDisk/RSync. These products WILL allow you to retrieve your data, but you will still have to reinstall the OS and programs. Some have limited/no histories either. In terms of backing up your code and data then I would recommend a sourcecode control product like SVN. While a general backup solution will protect your data, it does not offer the labeling/branching/history functionality that SCC packages do. These functions are invaluable for any type of project with a shelf-life. You can easily run a SVN server on your local machine. If your machine is backed up then your SVN database will be also. This IMO is the best solution for a home developer and is how I keep things.
How do you back up your development machine? How do you back up your development machine so that in the event of a catastrophic hardware malfunction, you are up and running in the least amount of time possible?
TITLE: How do you back up your development machine? QUESTION: How do you back up your development machine so that in the event of a catastrophic hardware malfunction, you are up and running in the least amount of time possible? ANSWER: There's an important distinction between backing up your development machine and backing up your work. For a development machine your best bet is an imaging solution that offers as near a "one-click-restore" process as possible. TimeMachine (Mac) and Windows Home Server (Windows) are both excellent for this purpose. Not only can you have your entire machine restored in 1-2 hours (depending on HDD size), but both run automatically and store deltas so you can have months of backups in relatively little space. There are also numerous "ghosting" packages, though they usually do not offer incremental/delta backups so take more time/space to backup your machine. Less good are products such as Carbonite/Mozy/JungleDisk/RSync. These products WILL allow you to retrieve your data, but you will still have to reinstall the OS and programs. Some have limited/no histories either. In terms of backing up your code and data then I would recommend a sourcecode control product like SVN. While a general backup solution will protect your data, it does not offer the labeling/branching/history functionality that SCC packages do. These functions are invaluable for any type of project with a shelf-life. You can easily run a SVN server on your local machine. If your machine is backed up then your SVN database will be also. This IMO is the best solution for a home developer and is how I keep things.
[ "backup", "hardware", "installation" ]
40
45
7,140
26
0
2008-08-25T20:32:33.767000
2008-08-25T20:49:56.253000
26,800
26,805
XPath and Selecting a single node
I'm using XPath in.NET to parse an XML document, along the lines of: XmlNodeList lotsOStuff = doc.SelectNodes("//stuff"); foreach (XmlNode stuff in lotsOStuff) { XmlNode stuffChild = stuff.SelectSingleNode("//stuffChild"); //... etc } The issue is that the XPath Query for stuffChild is always returning the child of the first stuff element, never the rest. Can XPath not be used to query against an individual XMLElement?
// at the beginning of an XPath expression starts from the document root. Try ".//stuffChild".. is shorthand for self::node(), which will set the context for the search, and // is shorthand for the descendant axis. So you have: XmlNode stuffChild = stuff.SelectSingleNode(".//stuffChild"); which translates to: xmlNode stuffChild = stuff.SelectSingleNode("self::node()/descendant::stuffChild"); xmlNode stuffChild = stuff.SelectSingleNode("self::node()/descendant-or-self::stuffChild"); In the case where the child node could have the same name as the parent, you would want to use the slightly more verbose syntax that follows, to ensure that you don't re-select the parent: xmlNode stuffChild = stuff.SelectSingleNode("self::node()/descendant::stuffChild"); Also note that if "stuffChild" is a direct descendant of "stuff", you can completely omit the prefixes, and just select "stuffChild". XmlNode stuffChild = stuff.SelectSingleNode("stuffChild"); The W3Schools tutorial has helpful info in an easy to digest format.
XPath and Selecting a single node I'm using XPath in.NET to parse an XML document, along the lines of: XmlNodeList lotsOStuff = doc.SelectNodes("//stuff"); foreach (XmlNode stuff in lotsOStuff) { XmlNode stuffChild = stuff.SelectSingleNode("//stuffChild"); //... etc } The issue is that the XPath Query for stuffChild is always returning the child of the first stuff element, never the rest. Can XPath not be used to query against an individual XMLElement?
TITLE: XPath and Selecting a single node QUESTION: I'm using XPath in.NET to parse an XML document, along the lines of: XmlNodeList lotsOStuff = doc.SelectNodes("//stuff"); foreach (XmlNode stuff in lotsOStuff) { XmlNode stuffChild = stuff.SelectSingleNode("//stuffChild"); //... etc } The issue is that the XPath Query for stuffChild is always returning the child of the first stuff element, never the rest. Can XPath not be used to query against an individual XMLElement? ANSWER: // at the beginning of an XPath expression starts from the document root. Try ".//stuffChild".. is shorthand for self::node(), which will set the context for the search, and // is shorthand for the descendant axis. So you have: XmlNode stuffChild = stuff.SelectSingleNode(".//stuffChild"); which translates to: xmlNode stuffChild = stuff.SelectSingleNode("self::node()/descendant::stuffChild"); xmlNode stuffChild = stuff.SelectSingleNode("self::node()/descendant-or-self::stuffChild"); In the case where the child node could have the same name as the parent, you would want to use the slightly more verbose syntax that follows, to ensure that you don't re-select the parent: xmlNode stuffChild = stuff.SelectSingleNode("self::node()/descendant::stuffChild"); Also note that if "stuffChild" is a direct descendant of "stuff", you can completely omit the prefixes, and just select "stuffChild". XmlNode stuffChild = stuff.SelectSingleNode("stuffChild"); The W3Schools tutorial has helpful info in an easy to digest format.
[ ".net", "xpath" ]
12
10
10,218
4
0
2008-08-25T20:32:36.170000
2008-08-25T20:35:29.003000
26,809
26,832
What is the best way to deal with DBNull's
I frequently have problems dealing with DataRows returned from SqlDataAdapters. When I try to fill in an object using code like this: DataRow row = ds.Tables[0].Rows[0]; string value = (string)row; What is the best way to deal with DBNull's in this type of situation.
Nullable types are good, but only for types that are not nullable to begin with. To make a type "nullable" append a question mark to the type, for example: int? value = 5; I would also recommend using the " as " keyword instead of casting. You can only use the "as" keyword on nullable types, so make sure you're casting things that are already nullable (like strings) or you use nullable types as mentioned above. The reasoning for this is If a type is nullable, the " as " keyword returns null if a value is DBNull. It's ever-so-slightly faster than casting though only in certain cases. This on its own is never a good enough reason to use as, but coupled with the reason above it's useful. I'd recommend doing something like this DataRow row = ds.Tables[0].Rows[0]; string value = row as string; In the case above, if row comes back as DBNull, then value will become null instead of throwing an exception. Be aware that if your DB query changes the columns/types being returned, using as will cause your code to silently fail and make values simple null instead of throwing the appropriate exception when incorrect data is returned so it is recommended that you have tests in place to validate your queries in other ways to ensure data integrity as your codebase evolves.
What is the best way to deal with DBNull's I frequently have problems dealing with DataRows returned from SqlDataAdapters. When I try to fill in an object using code like this: DataRow row = ds.Tables[0].Rows[0]; string value = (string)row; What is the best way to deal with DBNull's in this type of situation.
TITLE: What is the best way to deal with DBNull's QUESTION: I frequently have problems dealing with DataRows returned from SqlDataAdapters. When I try to fill in an object using code like this: DataRow row = ds.Tables[0].Rows[0]; string value = (string)row; What is the best way to deal with DBNull's in this type of situation. ANSWER: Nullable types are good, but only for types that are not nullable to begin with. To make a type "nullable" append a question mark to the type, for example: int? value = 5; I would also recommend using the " as " keyword instead of casting. You can only use the "as" keyword on nullable types, so make sure you're casting things that are already nullable (like strings) or you use nullable types as mentioned above. The reasoning for this is If a type is nullable, the " as " keyword returns null if a value is DBNull. It's ever-so-slightly faster than casting though only in certain cases. This on its own is never a good enough reason to use as, but coupled with the reason above it's useful. I'd recommend doing something like this DataRow row = ds.Tables[0].Rows[0]; string value = row as string; In the case above, if row comes back as DBNull, then value will become null instead of throwing an exception. Be aware that if your DB query changes the columns/types being returned, using as will cause your code to silently fail and make values simple null instead of throwing the appropriate exception when incorrect data is returned so it is recommended that you have tests in place to validate your queries in other ways to ensure data integrity as your codebase evolves.
[ "c#", ".net", "sql-server" ]
47
37
62,164
14
0
2008-08-25T20:36:30.840000
2008-08-25T20:41:24.323000
26,816
26,830
How to abort threads created with ThreadPool.QueueUserWorkItem
is there a way to abort threads created with QueueUserWorkItem? Or maybe I don't need to? What happens if the main application exits? Are all thread created from it aborted automatically?
You don't need to abort them. When your application exits,.NET will kill any threads with IsBackground = true. The.NET threadpool has all its threads set to IsBackground = true, so you don't have to worry about it. Now if you're creating threads by newing up the Thread class, then you'll either need to abort them or set their IsBackground property to true.
How to abort threads created with ThreadPool.QueueUserWorkItem is there a way to abort threads created with QueueUserWorkItem? Or maybe I don't need to? What happens if the main application exits? Are all thread created from it aborted automatically?
TITLE: How to abort threads created with ThreadPool.QueueUserWorkItem QUESTION: is there a way to abort threads created with QueueUserWorkItem? Or maybe I don't need to? What happens if the main application exits? Are all thread created from it aborted automatically? ANSWER: You don't need to abort them. When your application exits,.NET will kill any threads with IsBackground = true. The.NET threadpool has all its threads set to IsBackground = true, so you don't have to worry about it. Now if you're creating threads by newing up the Thread class, then you'll either need to abort them or set their IsBackground property to true.
[ "c#", "multithreading" ]
19
15
21,988
6
0
2008-08-25T20:38:09.370000
2008-08-25T20:41:02.233000
26,825
26,912
Uncollapsible CollapsiblePanelExtender
I have a CollapsiblePanelExtender that will not collapse. I have "collapsed" set to true and all the ControlID set correctly. I try to collapse and it goes through the animation but then expands almost instantly. This is in an User Control with the following structure....Stuff...
I am sorry I do not have time to trouble-shoot your code, so this is from the hip. There is a good chance that this a client-side action that is failing. Make certain that your page has the correct doctype tag if you took it out of your page or masterPage. Furthermore, attempt to set the ClientState as well: DDE.ClientState = true; The issue is you have that thing wrapped inside of your TemplateField. I have ran into issues using the AjaxControlToolkit on repeated fields and usually side with using a lighter weight client-side option, up to and including rolling your own show/hide method that can be reused just by passing in an DOM understood id.
Uncollapsible CollapsiblePanelExtender I have a CollapsiblePanelExtender that will not collapse. I have "collapsed" set to true and all the ControlID set correctly. I try to collapse and it goes through the animation but then expands almost instantly. This is in an User Control with the following structure....Stuff...
TITLE: Uncollapsible CollapsiblePanelExtender QUESTION: I have a CollapsiblePanelExtender that will not collapse. I have "collapsed" set to true and all the ControlID set correctly. I try to collapse and it goes through the animation but then expands almost instantly. This is in an User Control with the following structure....Stuff... ANSWER: I am sorry I do not have time to trouble-shoot your code, so this is from the hip. There is a good chance that this a client-side action that is failing. Make certain that your page has the correct doctype tag if you took it out of your page or masterPage. Furthermore, attempt to set the ClientState as well: DDE.ClientState = true; The issue is you have that thing wrapped inside of your TemplateField. I have ran into issues using the AjaxControlToolkit on repeated fields and usually side with using a lighter weight client-side option, up to and including rolling your own show/hide method that can be reused just by passing in an DOM understood id.
[ "asp.net" ]
2
3
4,634
4
0
2008-08-25T20:39:24.593000
2008-08-25T21:12:24.797000
26,826
26,838
Modifying SharePoint System Files
What is the general feeling amongst developers regarding the changing of files in the 12 hive. For example if you were asked to remove the sign is a different user menu item, you would need to modify the relevent user control on the filesystem. Now if you just go and modify it via notepad or copy over and then if you go and bring a new server into the farm you will need to remember to do the same on the new server. Obvouisly you could deploy the changed file as a solution and have that done automatically, but I'm just wondering if people are hesitant to make changes to the default installed files?
I have done a bit of SharePoint development, and I must tell you that messing with the 12-hive is a ticket to a world of pain if you ever want to move the app. I'd rather hack up some javascript to hide it, at least that can be bound to the master page, which is much more portable. And remember, you never know when the next service pack comes around and nukes your changes:)
Modifying SharePoint System Files What is the general feeling amongst developers regarding the changing of files in the 12 hive. For example if you were asked to remove the sign is a different user menu item, you would need to modify the relevent user control on the filesystem. Now if you just go and modify it via notepad or copy over and then if you go and bring a new server into the farm you will need to remember to do the same on the new server. Obvouisly you could deploy the changed file as a solution and have that done automatically, but I'm just wondering if people are hesitant to make changes to the default installed files?
TITLE: Modifying SharePoint System Files QUESTION: What is the general feeling amongst developers regarding the changing of files in the 12 hive. For example if you were asked to remove the sign is a different user menu item, you would need to modify the relevent user control on the filesystem. Now if you just go and modify it via notepad or copy over and then if you go and bring a new server into the farm you will need to remember to do the same on the new server. Obvouisly you could deploy the changed file as a solution and have that done automatically, but I'm just wondering if people are hesitant to make changes to the default installed files? ANSWER: I have done a bit of SharePoint development, and I must tell you that messing with the 12-hive is a ticket to a world of pain if you ever want to move the app. I'd rather hack up some javascript to hide it, at least that can be bound to the master page, which is much more portable. And remember, you never know when the next service pack comes around and nukes your changes:)
[ "sharepoint" ]
3
2
627
7
0
2008-08-25T20:40:46.120000
2008-08-25T20:44:09.480000
26,834
26,996
How to represent cross-model information in MVC?
I have an application, built using MVC, that produces a view which delivers summary information across a number of models. Further to that, some calculations are performed across the different sets of data. There's no clear single model (that maps to a table at least) that seems to make sense as the starting point for this, so the various summaries are pulled from the contributing models in the controller, passed into the view and the calculations are performed there. But that seems, well, dirty. But controllers are supposed to be lightweight, aren't they? And business logic shouldn't be in views, as I have it as present. So where should this information be assembled? A new model, that doesn't map to a table? A library function/module? Or something else? (Although I see this as mostly of an architectural/pattern question, I'm working in Rails, FWIW.) Edit: Good answers all round, and a lot of consensus, which is reassuring. I "accepted" the answer I did to keep the link to Railscasts at the top. I'm behind in my Railscast viewing - something I shall make strenuous attempts to rectify!
As Brian said, you can create another model that marshals out the work that needs doing. There is a great Railscast on how to do this type of thing. HTH
How to represent cross-model information in MVC? I have an application, built using MVC, that produces a view which delivers summary information across a number of models. Further to that, some calculations are performed across the different sets of data. There's no clear single model (that maps to a table at least) that seems to make sense as the starting point for this, so the various summaries are pulled from the contributing models in the controller, passed into the view and the calculations are performed there. But that seems, well, dirty. But controllers are supposed to be lightweight, aren't they? And business logic shouldn't be in views, as I have it as present. So where should this information be assembled? A new model, that doesn't map to a table? A library function/module? Or something else? (Although I see this as mostly of an architectural/pattern question, I'm working in Rails, FWIW.) Edit: Good answers all round, and a lot of consensus, which is reassuring. I "accepted" the answer I did to keep the link to Railscasts at the top. I'm behind in my Railscast viewing - something I shall make strenuous attempts to rectify!
TITLE: How to represent cross-model information in MVC? QUESTION: I have an application, built using MVC, that produces a view which delivers summary information across a number of models. Further to that, some calculations are performed across the different sets of data. There's no clear single model (that maps to a table at least) that seems to make sense as the starting point for this, so the various summaries are pulled from the contributing models in the controller, passed into the view and the calculations are performed there. But that seems, well, dirty. But controllers are supposed to be lightweight, aren't they? And business logic shouldn't be in views, as I have it as present. So where should this information be assembled? A new model, that doesn't map to a table? A library function/module? Or something else? (Although I see this as mostly of an architectural/pattern question, I'm working in Rails, FWIW.) Edit: Good answers all round, and a lot of consensus, which is reassuring. I "accepted" the answer I did to keep the link to Railscasts at the top. I'm behind in my Railscast viewing - something I shall make strenuous attempts to rectify! ANSWER: As Brian said, you can create another model that marshals out the work that needs doing. There is a great Railscast on how to do this type of thing. HTH
[ "ruby-on-rails", "model-view-controller", "design-patterns" ]
3
3
992
5
0
2008-08-25T20:42:40.077000
2008-08-25T21:53:18.987000
26,842
30,538
Why can't I connect to my CAS server with Perl's AuthCAS?
I'm attempting to use an existing CAS server to authenticate login for a Perl CGI web script and am using the AuthCAS Perl module (v 1.3.1). I can connect to the CAS server to get the service ticket but when I try to connect to validate the ticket my script returns with the following error from the IO::Socket::SSL module: 500 Can't connect to [CAS Server]:443 (Bad hostname '[CAS Server]') ([CAS Server] substituted for real server name) Symptoms/Tests: If I type the generated URL for the authentication into the web browser's location bar it returns just fine with the expected XML snippet. So it is not a bad host name. If I generate a script without using the AuthCAS module but using the IO::Socket::SSL module directly to query the CAS server for validation on the generated service ticket the Perl script will run fine from the command line but not in the browser. If I add the AuthCAS module into the script in item 2, the script no longer works on the command line and still doesn't work in the browser. Here is the bare-bones script that produces the error: #!/usr/bin/perl use strict; use warnings; use CGI; use AuthCAS; use CGI::Carp qw( fatalsToBrowser ); my $id = $ENV{QUERY_STRING}; my $q = new CGI; my $target = "http://localhost/cgi-bin/testCAS.cgi"; my $cas = new AuthCAS(casUrl => 'https://cas_server/cas'); if ($id eq ""){ my $login_url = $cas->getServerLoginURL($target); printf "Location: $login_url\n\n"; exit 0; } else { print $q->header(); print "CAS TEST \n"; ## When coming back from the CAS server a ticket is provided in the QUERY_STRING print "QUERY_STRING = ". $id. "\n"; ## $ST should contain the received Service Ticket my $ST = $q->param('ticket'); my $user = $cas->validateST($target, $ST); #### This is what fails printf "Error: %s\n", &AuthCAS::get_errors() unless (defined $user); } Any ideas on where the conflict might be? The error is coming from the line directly above the snippet Cebjyre quoted namely $ssl_socket = new IO::Socket::SSL(%ssl_options); namely the socket creation. All of the input parameters are correct. I had edited the module to put in debug statements and print out all the parameters just before that call and they are all fine. Looks like I'm going to have to dive deeper into the IO::Socket::SSL module.
As usually happens when I post questions like this, I found the problem. It turns out the Crypt::SSLeay module was not installed or at least not up to date. Of course the error messages didn't give me any clues. Updating it and all the problems go away and things are working fine now.
Why can't I connect to my CAS server with Perl's AuthCAS? I'm attempting to use an existing CAS server to authenticate login for a Perl CGI web script and am using the AuthCAS Perl module (v 1.3.1). I can connect to the CAS server to get the service ticket but when I try to connect to validate the ticket my script returns with the following error from the IO::Socket::SSL module: 500 Can't connect to [CAS Server]:443 (Bad hostname '[CAS Server]') ([CAS Server] substituted for real server name) Symptoms/Tests: If I type the generated URL for the authentication into the web browser's location bar it returns just fine with the expected XML snippet. So it is not a bad host name. If I generate a script without using the AuthCAS module but using the IO::Socket::SSL module directly to query the CAS server for validation on the generated service ticket the Perl script will run fine from the command line but not in the browser. If I add the AuthCAS module into the script in item 2, the script no longer works on the command line and still doesn't work in the browser. Here is the bare-bones script that produces the error: #!/usr/bin/perl use strict; use warnings; use CGI; use AuthCAS; use CGI::Carp qw( fatalsToBrowser ); my $id = $ENV{QUERY_STRING}; my $q = new CGI; my $target = "http://localhost/cgi-bin/testCAS.cgi"; my $cas = new AuthCAS(casUrl => 'https://cas_server/cas'); if ($id eq ""){ my $login_url = $cas->getServerLoginURL($target); printf "Location: $login_url\n\n"; exit 0; } else { print $q->header(); print "CAS TEST \n"; ## When coming back from the CAS server a ticket is provided in the QUERY_STRING print "QUERY_STRING = ". $id. "\n"; ## $ST should contain the received Service Ticket my $ST = $q->param('ticket'); my $user = $cas->validateST($target, $ST); #### This is what fails printf "Error: %s\n", &AuthCAS::get_errors() unless (defined $user); } Any ideas on where the conflict might be? The error is coming from the line directly above the snippet Cebjyre quoted namely $ssl_socket = new IO::Socket::SSL(%ssl_options); namely the socket creation. All of the input parameters are correct. I had edited the module to put in debug statements and print out all the parameters just before that call and they are all fine. Looks like I'm going to have to dive deeper into the IO::Socket::SSL module.
TITLE: Why can't I connect to my CAS server with Perl's AuthCAS? QUESTION: I'm attempting to use an existing CAS server to authenticate login for a Perl CGI web script and am using the AuthCAS Perl module (v 1.3.1). I can connect to the CAS server to get the service ticket but when I try to connect to validate the ticket my script returns with the following error from the IO::Socket::SSL module: 500 Can't connect to [CAS Server]:443 (Bad hostname '[CAS Server]') ([CAS Server] substituted for real server name) Symptoms/Tests: If I type the generated URL for the authentication into the web browser's location bar it returns just fine with the expected XML snippet. So it is not a bad host name. If I generate a script without using the AuthCAS module but using the IO::Socket::SSL module directly to query the CAS server for validation on the generated service ticket the Perl script will run fine from the command line but not in the browser. If I add the AuthCAS module into the script in item 2, the script no longer works on the command line and still doesn't work in the browser. Here is the bare-bones script that produces the error: #!/usr/bin/perl use strict; use warnings; use CGI; use AuthCAS; use CGI::Carp qw( fatalsToBrowser ); my $id = $ENV{QUERY_STRING}; my $q = new CGI; my $target = "http://localhost/cgi-bin/testCAS.cgi"; my $cas = new AuthCAS(casUrl => 'https://cas_server/cas'); if ($id eq ""){ my $login_url = $cas->getServerLoginURL($target); printf "Location: $login_url\n\n"; exit 0; } else { print $q->header(); print "CAS TEST \n"; ## When coming back from the CAS server a ticket is provided in the QUERY_STRING print "QUERY_STRING = ". $id. "\n"; ## $ST should contain the received Service Ticket my $ST = $q->param('ticket'); my $user = $cas->validateST($target, $ST); #### This is what fails printf "Error: %s\n", &AuthCAS::get_errors() unless (defined $user); } Any ideas on where the conflict might be? The error is coming from the line directly above the snippet Cebjyre quoted namely $ssl_socket = new IO::Socket::SSL(%ssl_options); namely the socket creation. All of the input parameters are correct. I had edited the module to put in debug statements and print out all the parameters just before that call and they are all fine. Looks like I'm going to have to dive deeper into the IO::Socket::SSL module. ANSWER: As usually happens when I post questions like this, I found the problem. It turns out the Crypt::SSLeay module was not installed or at least not up to date. Of course the error messages didn't give me any clues. Updating it and all the problems go away and things are working fine now.
[ "perl", "apache", "authentication", "ssl", "cgi" ]
2
3
2,049
2
0
2008-08-25T20:45:32.927000
2008-08-27T16:01:30.737000