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
19,011
62,837
Best practice for storing large amounts of data with J2ME
I am developing a J2ME application that has a large amount of data to store on the device (in the region of 1MB but variable). I can't rely on the file system so I'm stuck the Record Management System (RMS), which allows multiple record stores but each have a limited size. My initial target platform, Blackberry, limits each to 64KB. I'm wondering if anyone else has had to tackle the problem of storing a large amount of data in the RMS and how they managed it? I'm thinking of having to calculate record sizes and split one data set accross multiple stores if its too large, but that adds a lot of complexity to keep it intact. There is lots of different types of data being stored but only one set in particular will exceed the 64KB limit.
For anything past a few kilobytes you need to use either JSR 75 or a remote server. RMS records are extremely limited in size and speed, even in some higher end handsets. If you need to juggle 1MB of data in J2ME the only reliable, portable way is to store it on the network. The HttpConnection class and the GET and POST methods are always supported. On the handsets that support JSR 75 FileConnection it may be valid alternative but without code signing it is an user experience nightmare. Almost every single API call will invoke a security prompt with no blanket permission choice. Companies that deploy apps with JSR 75 usually need half a dozen binaries for every port just to cover a small part of the possible certificates. And this is just for the manufacturer certificates; some handsets only have carrier-locked certificates.
Best practice for storing large amounts of data with J2ME I am developing a J2ME application that has a large amount of data to store on the device (in the region of 1MB but variable). I can't rely on the file system so I'm stuck the Record Management System (RMS), which allows multiple record stores but each have a limited size. My initial target platform, Blackberry, limits each to 64KB. I'm wondering if anyone else has had to tackle the problem of storing a large amount of data in the RMS and how they managed it? I'm thinking of having to calculate record sizes and split one data set accross multiple stores if its too large, but that adds a lot of complexity to keep it intact. There is lots of different types of data being stored but only one set in particular will exceed the 64KB limit.
TITLE: Best practice for storing large amounts of data with J2ME QUESTION: I am developing a J2ME application that has a large amount of data to store on the device (in the region of 1MB but variable). I can't rely on the file system so I'm stuck the Record Management System (RMS), which allows multiple record stores but each have a limited size. My initial target platform, Blackberry, limits each to 64KB. I'm wondering if anyone else has had to tackle the problem of storing a large amount of data in the RMS and how they managed it? I'm thinking of having to calculate record sizes and split one data set accross multiple stores if its too large, but that adds a lot of complexity to keep it intact. There is lots of different types of data being stored but only one set in particular will exceed the 64KB limit. ANSWER: For anything past a few kilobytes you need to use either JSR 75 or a remote server. RMS records are extremely limited in size and speed, even in some higher end handsets. If you need to juggle 1MB of data in J2ME the only reliable, portable way is to store it on the network. The HttpConnection class and the GET and POST methods are always supported. On the handsets that support JSR 75 FileConnection it may be valid alternative but without code signing it is an user experience nightmare. Almost every single API call will invoke a security prompt with no blanket permission choice. Companies that deploy apps with JSR 75 usually need half a dozen binaries for every port just to cover a small part of the possible certificates. And this is just for the manufacturer certificates; some handsets only have carrier-locked certificates.
[ "java", "java-me", "rms" ]
9
9
7,365
8
0
2008-08-20T22:42:04.200000
2008-09-15T13:25:10.517000
19,014
20,468
Using Lucene to search for email addresses
I want to use Lucene (in particular, Lucene.NET) to search for email address domains. E.g. I want to search for "@gmail.com" to find all emails sent to a gmail address. Running a Lucene query for "*@gmail.com" results in an error, asterisks cannot be at the start of queries. Running a query for "@gmail.com" doesn't return any matches, because "foo@gmail.com" is seen as a whole word, and you cannot search for just parts of a word. How can I do this?
No one gave a satisfactory answer, so we started poking around Lucene documentation and discovered we can accomplish this using custom Analyzers and Tokenizers. The answer is this: create a WhitespaceAndAtSymbolTokenizer and a WhitespaceAndAtSymbolAnalyzer, then recreate your index using this analyzer. Once you do this, a search for "@gmail.com" will return all gmail addresses, because it's seen as a separate word thanks to the Tokenizer we just created. Here's the source code, it's actually very simple: class WhitespaceAndAtSymbolTokenizer: CharTokenizer { public WhitespaceAndAtSymbolTokenizer(TextReader input): base(input) { } protected override bool IsTokenChar(char c) { // Make whitespace characters and the @ symbol be indicators of new words. return!(char.IsWhiteSpace(c) || c == '@'); } } internal class WhitespaceAndAtSymbolAnalyzer: Analyzer { public override TokenStream TokenStream(string fieldName, TextReader reader) { return new WhitespaceAndAtSymbolTokenizer(reader); } } That's it! Now you just need to rebuild your index and do all searches using this new Analyzer. For example, to write documents to your index: IndexWriter index = new IndexWriter(indexDirectory, new WhitespaceAndAtSymbolAnalyzer()); index.AddDocument(myDocument); Performing searches should use the analyzer as well: IndexSearcher searcher = new IndexSearcher(indexDirectory); Query query = new QueryParser("TheFieldNameToSearch", new WhitespaceAndAtSymbolAnalyzer()).Parse("@gmail.com"); Hits hits = query.Search(query);
Using Lucene to search for email addresses I want to use Lucene (in particular, Lucene.NET) to search for email address domains. E.g. I want to search for "@gmail.com" to find all emails sent to a gmail address. Running a Lucene query for "*@gmail.com" results in an error, asterisks cannot be at the start of queries. Running a query for "@gmail.com" doesn't return any matches, because "foo@gmail.com" is seen as a whole word, and you cannot search for just parts of a word. How can I do this?
TITLE: Using Lucene to search for email addresses QUESTION: I want to use Lucene (in particular, Lucene.NET) to search for email address domains. E.g. I want to search for "@gmail.com" to find all emails sent to a gmail address. Running a Lucene query for "*@gmail.com" results in an error, asterisks cannot be at the start of queries. Running a query for "@gmail.com" doesn't return any matches, because "foo@gmail.com" is seen as a whole word, and you cannot search for just parts of a word. How can I do this? ANSWER: No one gave a satisfactory answer, so we started poking around Lucene documentation and discovered we can accomplish this using custom Analyzers and Tokenizers. The answer is this: create a WhitespaceAndAtSymbolTokenizer and a WhitespaceAndAtSymbolAnalyzer, then recreate your index using this analyzer. Once you do this, a search for "@gmail.com" will return all gmail addresses, because it's seen as a separate word thanks to the Tokenizer we just created. Here's the source code, it's actually very simple: class WhitespaceAndAtSymbolTokenizer: CharTokenizer { public WhitespaceAndAtSymbolTokenizer(TextReader input): base(input) { } protected override bool IsTokenChar(char c) { // Make whitespace characters and the @ symbol be indicators of new words. return!(char.IsWhiteSpace(c) || c == '@'); } } internal class WhitespaceAndAtSymbolAnalyzer: Analyzer { public override TokenStream TokenStream(string fieldName, TextReader reader) { return new WhitespaceAndAtSymbolTokenizer(reader); } } That's it! Now you just need to rebuild your index and do all searches using this new Analyzer. For example, to write documents to your index: IndexWriter index = new IndexWriter(indexDirectory, new WhitespaceAndAtSymbolAnalyzer()); index.AddDocument(myDocument); Performing searches should use the analyzer as well: IndexSearcher searcher = new IndexSearcher(indexDirectory); Query query = new QueryParser("TheFieldNameToSearch", new WhitespaceAndAtSymbolAnalyzer()).Parse("@gmail.com"); Hits hits = query.Search(query);
[ ".net", "search", "lucene" ]
7
13
7,557
4
0
2008-08-20T22:44:17.610000
2008-08-21T16:38:40.307000
19,030
21,302
How to check set of files conform to a naming scheme
I have a bunch of files (TV episodes, although that is fairly arbitrary) that I want to check match a specific naming/organisation scheme.. Currently: I have three arrays of regex, one for valid filenames, one for files missing an episode name, and one for valid paths. Then, I loop though each valid-filename regex, if it matches, append it to a "valid" dict, if not, do the same with the missing-ep-name regexs, if it matches this I append it to an "invalid" dict with an error code (2:'missing epsiode name'), if it matches neither, it gets added to invalid with the 'malformed name' error code. The current code can be found here I want to add a rule that checks for the presence of a folder.jpg file in each directory, but to add this would make the code substantially more messy in it's current state.. How could I write this system in a more expandable way? The rules it needs to check would be.. File is in the format Show Name - [01x23] - Episode Name.avi or Show Name - [01xSpecial02] - Special Name.avi or Show Name - [01xExtra01] - Extra Name.avi If filename is in the format Show Name - [01x23].avi display it a 'missing episode name' section of the output The path should be in the format Show Name/season 2/the_file.avi (where season 2 should be the correct season number in the filename) each Show Name/season 1/ folder should contain "folder.jpg".any ideas? While I'm trying to check TV episodes, this concept/code should be able to apply to many things.. The only thought I had was a list of dicts in the format: checker = [ { 'name':'valid files', 'type':'file', 'function':check_valid(), # runs check_valid() on all files 'status':0 # if it returns True, this is the status the file gets }
I want to add a rule that checks for the presence of a folder.jpg file in each directory, but to add this would make the code substantially more messy in it's current state.. This doesn't look bad. In fact your current code does it very nicely, and Sven mentioned a good way to do it as well: Get a list of all the files Check for "required" files You would just have have add to your dictionary a list of required files: checker = {... 'required': ['file', 'list', 'for_required'] } As far as there being a better/extensible way to do this? I am not exactly sure. I could only really think of a way to possibly drop the "multiple" regular expressions and build off of Sven's idea for using a delimiter. So my strategy would be defining a dictionary as follows (and I'm sorry I don't know Python syntax and I'm a tad to lazy to look it up but it should make sense. The /regex/ is shorthand for a regex): check_dict = { 'delim': /\-/, 'parts': [ 'Show Name', 'Episode Name', 'Episode Number' ], 'patterns': [/valid name/, /valid episode name/, /valid number/ ], 'required': ['list', 'of', 'files'], 'ignored': ['.*', 'hidden.txt'], 'start_dir': '/path/to/dir/to/test/' } Split the filename based on the delimiter. Check each of the parts. Because its an ordered list you can determine what parts are missing and if a section doesn't match any pattern it is malformed. Here the parts and patterns have a 1 to 1 ratio. Two arrays instead of a dictionary enforces the order. Ignored and required files can be listed. The. and.. files should probably be ignored automatically. The user should be allowed to input "globs" which can be shell expanded. I'm thinking here of svn:ignore properties, but globbing is natural for listing files. Here start_dir would be default to the current directory but if you wanted a single file to run automated testing of a bunch of directories this would be useful. The real loose end here is the path template and along the same lines what path is required for "valid files". I really couldn't come up with a solid idea without writing one large regular expression and taking groups from it... to build a template. It felt a lot like writing a TextMate language grammar. But that starts to stray on the ease of use. The real problem was that the path template was not composed of parts, which makes sense but adds complexity. Is this strategy in tune with what you were thinking of?
How to check set of files conform to a naming scheme I have a bunch of files (TV episodes, although that is fairly arbitrary) that I want to check match a specific naming/organisation scheme.. Currently: I have three arrays of regex, one for valid filenames, one for files missing an episode name, and one for valid paths. Then, I loop though each valid-filename regex, if it matches, append it to a "valid" dict, if not, do the same with the missing-ep-name regexs, if it matches this I append it to an "invalid" dict with an error code (2:'missing epsiode name'), if it matches neither, it gets added to invalid with the 'malformed name' error code. The current code can be found here I want to add a rule that checks for the presence of a folder.jpg file in each directory, but to add this would make the code substantially more messy in it's current state.. How could I write this system in a more expandable way? The rules it needs to check would be.. File is in the format Show Name - [01x23] - Episode Name.avi or Show Name - [01xSpecial02] - Special Name.avi or Show Name - [01xExtra01] - Extra Name.avi If filename is in the format Show Name - [01x23].avi display it a 'missing episode name' section of the output The path should be in the format Show Name/season 2/the_file.avi (where season 2 should be the correct season number in the filename) each Show Name/season 1/ folder should contain "folder.jpg".any ideas? While I'm trying to check TV episodes, this concept/code should be able to apply to many things.. The only thought I had was a list of dicts in the format: checker = [ { 'name':'valid files', 'type':'file', 'function':check_valid(), # runs check_valid() on all files 'status':0 # if it returns True, this is the status the file gets }
TITLE: How to check set of files conform to a naming scheme QUESTION: I have a bunch of files (TV episodes, although that is fairly arbitrary) that I want to check match a specific naming/organisation scheme.. Currently: I have three arrays of regex, one for valid filenames, one for files missing an episode name, and one for valid paths. Then, I loop though each valid-filename regex, if it matches, append it to a "valid" dict, if not, do the same with the missing-ep-name regexs, if it matches this I append it to an "invalid" dict with an error code (2:'missing epsiode name'), if it matches neither, it gets added to invalid with the 'malformed name' error code. The current code can be found here I want to add a rule that checks for the presence of a folder.jpg file in each directory, but to add this would make the code substantially more messy in it's current state.. How could I write this system in a more expandable way? The rules it needs to check would be.. File is in the format Show Name - [01x23] - Episode Name.avi or Show Name - [01xSpecial02] - Special Name.avi or Show Name - [01xExtra01] - Extra Name.avi If filename is in the format Show Name - [01x23].avi display it a 'missing episode name' section of the output The path should be in the format Show Name/season 2/the_file.avi (where season 2 should be the correct season number in the filename) each Show Name/season 1/ folder should contain "folder.jpg".any ideas? While I'm trying to check TV episodes, this concept/code should be able to apply to many things.. The only thought I had was a list of dicts in the format: checker = [ { 'name':'valid files', 'type':'file', 'function':check_valid(), # runs check_valid() on all files 'status':0 # if it returns True, this is the status the file gets } ANSWER: I want to add a rule that checks for the presence of a folder.jpg file in each directory, but to add this would make the code substantially more messy in it's current state.. This doesn't look bad. In fact your current code does it very nicely, and Sven mentioned a good way to do it as well: Get a list of all the files Check for "required" files You would just have have add to your dictionary a list of required files: checker = {... 'required': ['file', 'list', 'for_required'] } As far as there being a better/extensible way to do this? I am not exactly sure. I could only really think of a way to possibly drop the "multiple" regular expressions and build off of Sven's idea for using a delimiter. So my strategy would be defining a dictionary as follows (and I'm sorry I don't know Python syntax and I'm a tad to lazy to look it up but it should make sense. The /regex/ is shorthand for a regex): check_dict = { 'delim': /\-/, 'parts': [ 'Show Name', 'Episode Name', 'Episode Number' ], 'patterns': [/valid name/, /valid episode name/, /valid number/ ], 'required': ['list', 'of', 'files'], 'ignored': ['.*', 'hidden.txt'], 'start_dir': '/path/to/dir/to/test/' } Split the filename based on the delimiter. Check each of the parts. Because its an ordered list you can determine what parts are missing and if a section doesn't match any pattern it is malformed. Here the parts and patterns have a 1 to 1 ratio. Two arrays instead of a dictionary enforces the order. Ignored and required files can be listed. The. and.. files should probably be ignored automatically. The user should be allowed to input "globs" which can be shell expanded. I'm thinking here of svn:ignore properties, but globbing is natural for listing files. Here start_dir would be default to the current directory but if you wanted a single file to run automated testing of a bunch of directories this would be useful. The real loose end here is the path template and along the same lines what path is required for "valid files". I really couldn't come up with a solid idea without writing one large regular expression and taking groups from it... to build a template. It felt a lot like writing a TextMate language grammar. But that starts to stray on the ease of use. The real problem was that the path template was not composed of parts, which makes sense but adds complexity. Is this strategy in tune with what you were thinking of?
[ "python", "validation", "naming" ]
4
2
837
2
0
2008-08-20T22:50:55.643000
2008-08-21T22:02:01.853000
19,035
19,348
JavaScript Load Order
I am working with both amq.js (ActiveMQ) and Google Maps. I load my scripts in this order AMQ & Maps Demo However in my application.js it loads Maps fine but I get an error when trying to subscribe to a Topic with AMQ. AMQ depends on prototype which the error console in Firefox says object is not defined. I think I have a problem with using the amq object before the script is finished loading. Is there a way to make sure both scripts load before I use them in my application.js? Google has this nice function call google.setOnLoadCallback(initialize); which works great. I'm not sure amq.js has something like this.
Is there a way to make sure both scripts load before I use them in my application.js? JavaScript files should load sequentially and block so unless the scripts you are depending on are doing something unusual all you should need to do is load application.js after the other files. Non-blocking JavaScript Downloads has some information about how scripts load (and discusses some techniques to subvert the blocking).
JavaScript Load Order I am working with both amq.js (ActiveMQ) and Google Maps. I load my scripts in this order AMQ & Maps Demo However in my application.js it loads Maps fine but I get an error when trying to subscribe to a Topic with AMQ. AMQ depends on prototype which the error console in Firefox says object is not defined. I think I have a problem with using the amq object before the script is finished loading. Is there a way to make sure both scripts load before I use them in my application.js? Google has this nice function call google.setOnLoadCallback(initialize); which works great. I'm not sure amq.js has something like this.
TITLE: JavaScript Load Order QUESTION: I am working with both amq.js (ActiveMQ) and Google Maps. I load my scripts in this order AMQ & Maps Demo However in my application.js it loads Maps fine but I get an error when trying to subscribe to a Topic with AMQ. AMQ depends on prototype which the error console in Firefox says object is not defined. I think I have a problem with using the amq object before the script is finished loading. Is there a way to make sure both scripts load before I use them in my application.js? Google has this nice function call google.setOnLoadCallback(initialize); which works great. I'm not sure amq.js has something like this. ANSWER: Is there a way to make sure both scripts load before I use them in my application.js? JavaScript files should load sequentially and block so unless the scripts you are depending on are doing something unusual all you should need to do is load application.js after the other files. Non-blocking JavaScript Downloads has some information about how scripts load (and discusses some techniques to subvert the blocking).
[ "javascript", "google-maps" ]
30
27
38,837
8
0
2008-08-20T22:53:25.373000
2008-08-21T04:46:39.690000
19,047
19,053
TortoiseSVN side-by-side configuration is incorrect
After upgrading to the latest version of TortoiseSVN (1.5.2.13595), it's context menu is no longer available. When attempting to run it manually, I get this error: The application has failed to start because its side-by-side configuration is incorrect. Please see the application event log for more detail The application log shows this Activation context generation failed for "C:\Program Files\TortoiseSVN\bin\TortoiseSVN.dll". Dependent Assembly Microsoft.VC90.CRT,processorArchitecture="x86",publicKeyToken="1fc8b3b9a1e18e3b",type="win32",version="9.0.30411.0" could not be found. Please use sxstrace.exe for detailed diagnosis.
I remembered I'd seen this thing before just after posting to SO It seems that later versions of TortoiseSVN are built with Visual Studio 2008 SP1 (hence the 9.0.30411.0 build number) Installing the VC2008 SP1 Redistributable fixes it
TortoiseSVN side-by-side configuration is incorrect After upgrading to the latest version of TortoiseSVN (1.5.2.13595), it's context menu is no longer available. When attempting to run it manually, I get this error: The application has failed to start because its side-by-side configuration is incorrect. Please see the application event log for more detail The application log shows this Activation context generation failed for "C:\Program Files\TortoiseSVN\bin\TortoiseSVN.dll". Dependent Assembly Microsoft.VC90.CRT,processorArchitecture="x86",publicKeyToken="1fc8b3b9a1e18e3b",type="win32",version="9.0.30411.0" could not be found. Please use sxstrace.exe for detailed diagnosis.
TITLE: TortoiseSVN side-by-side configuration is incorrect QUESTION: After upgrading to the latest version of TortoiseSVN (1.5.2.13595), it's context menu is no longer available. When attempting to run it manually, I get this error: The application has failed to start because its side-by-side configuration is incorrect. Please see the application event log for more detail The application log shows this Activation context generation failed for "C:\Program Files\TortoiseSVN\bin\TortoiseSVN.dll". Dependent Assembly Microsoft.VC90.CRT,processorArchitecture="x86",publicKeyToken="1fc8b3b9a1e18e3b",type="win32",version="9.0.30411.0" could not be found. Please use sxstrace.exe for detailed diagnosis. ANSWER: I remembered I'd seen this thing before just after posting to SO It seems that later versions of TortoiseSVN are built with Visual Studio 2008 SP1 (hence the 9.0.30411.0 build number) Installing the VC2008 SP1 Redistributable fixes it
[ "tortoisesvn", "winsxs" ]
8
9
5,291
2
0
2008-08-20T23:02:18.083000
2008-08-20T23:03:53.960000
19,058
19,061
What is the difference between oracle's 'yy' and 'rr' date mask?
Example: select ename from emp where hiredate = todate('01/05/81','dd/mm/yy') and select ename from emp where hiredate = todate('01/05/81','dd/mm/rr') return different results
http://oracle.ittoolbox.com/groups/technical-functional/oracle-dev-l/difference-between-yyyy-and-rrrr-format-519525 YY allows you to retrieve just two digits of a year, for example, the 99 in 1999. The other digits (19) are automatically assigned to the current century. RR converts two-digit years into four-digit years by rounding. 50-99 are stored as 1950-1999, and dates ending in 00-49 are stored as 2000-2049. RRRR accepts a four-digit input (although not required), and converts two-digit dates as RR does. YYYY accepts 4-digit inputs butdoesn't do any date converting Essentially, your first example will assume that 81 is 2081 whereas the RR one assumes 1981. So the first example should not return any rows as you most likely did not hire any guys after May 1 2081 yet:-)
What is the difference between oracle's 'yy' and 'rr' date mask? Example: select ename from emp where hiredate = todate('01/05/81','dd/mm/yy') and select ename from emp where hiredate = todate('01/05/81','dd/mm/rr') return different results
TITLE: What is the difference between oracle's 'yy' and 'rr' date mask? QUESTION: Example: select ename from emp where hiredate = todate('01/05/81','dd/mm/yy') and select ename from emp where hiredate = todate('01/05/81','dd/mm/rr') return different results ANSWER: http://oracle.ittoolbox.com/groups/technical-functional/oracle-dev-l/difference-between-yyyy-and-rrrr-format-519525 YY allows you to retrieve just two digits of a year, for example, the 99 in 1999. The other digits (19) are automatically assigned to the current century. RR converts two-digit years into four-digit years by rounding. 50-99 are stored as 1950-1999, and dates ending in 00-49 are stored as 2000-2049. RRRR accepts a four-digit input (although not required), and converts two-digit dates as RR does. YYYY accepts 4-digit inputs butdoesn't do any date converting Essentially, your first example will assume that 81 is 2081 whereas the RR one assumes 1981. So the first example should not return any rows as you most likely did not hire any guys after May 1 2081 yet:-)
[ "sql", "oracle" ]
30
50
86,597
6
0
2008-08-20T23:07:51.250000
2008-08-20T23:11:32.710000
19,089
19,109
How do I do an Upsert Into Table?
I have a view that has a list of jobs in it, with data like who they're assigned to and the stage they are in. I need to write a stored procedure that returns how many jobs each person has at each stage. So far I have this (simplified): DECLARE @ResultTable table ( StaffName nvarchar(100), Stage1Count int, Stage2Count int ) INSERT INTO @ResultTable (StaffName, Stage1Count) SELECT StaffName, COUNT(*) FROM ViewJob WHERE InStage1 = 1 GROUP BY StaffName INSERT INTO @ResultTable (StaffName, Stage2Count) SELECT StaffName, COUNT(*) FROM ViewJob WHERE InStage2 = 1 GROUP BY StaffName The problem with that is that the rows don't combine. So if a staff member has jobs in stage1 and stage2 there's two rows in @ResultTable. What I would really like to do is to update the row if one exists for the staff member and insert a new row if one doesn't exist. Does anyone know how to do this, or can suggest a different approach? I would really like to avoid using cursors to iterate on the list of users (but that's my fall back option). I'm using SQL Server 2005. Edit: @Lee: Unfortunately the InStage1 = 1 was a simplification. It's really more like WHERE DateStarted IS NOT NULL and DateFinished IS NULL. Edit: @BCS: I like the idea of doing an insert of all the staff first so I just have to do an update every time. But I'm struggling to get those UPDATE statements correct.
IIRC there is some sort of "On Duplicate" (name might be wrong) syntax that lets you update if a row exists (MySQL) Alternately some form of: INSERT INTO @ResultTable (StaffName, Stage1Count, Stage2Count) SELECT StaffName,0,0 FROM ViewJob GROUP BY StaffName UPDATE @ResultTable Stage1Count= ( SELECT COUNT(*) AS count FROM ViewJob WHERE InStage1 = 1 @ResultTable.StaffName = StaffName) UPDATE @ResultTable Stage2Count= ( SELECT COUNT(*) AS count FROM ViewJob WHERE InStage2 = 1 @ResultTable.StaffName = StaffName)
How do I do an Upsert Into Table? I have a view that has a list of jobs in it, with data like who they're assigned to and the stage they are in. I need to write a stored procedure that returns how many jobs each person has at each stage. So far I have this (simplified): DECLARE @ResultTable table ( StaffName nvarchar(100), Stage1Count int, Stage2Count int ) INSERT INTO @ResultTable (StaffName, Stage1Count) SELECT StaffName, COUNT(*) FROM ViewJob WHERE InStage1 = 1 GROUP BY StaffName INSERT INTO @ResultTable (StaffName, Stage2Count) SELECT StaffName, COUNT(*) FROM ViewJob WHERE InStage2 = 1 GROUP BY StaffName The problem with that is that the rows don't combine. So if a staff member has jobs in stage1 and stage2 there's two rows in @ResultTable. What I would really like to do is to update the row if one exists for the staff member and insert a new row if one doesn't exist. Does anyone know how to do this, or can suggest a different approach? I would really like to avoid using cursors to iterate on the list of users (but that's my fall back option). I'm using SQL Server 2005. Edit: @Lee: Unfortunately the InStage1 = 1 was a simplification. It's really more like WHERE DateStarted IS NOT NULL and DateFinished IS NULL. Edit: @BCS: I like the idea of doing an insert of all the staff first so I just have to do an update every time. But I'm struggling to get those UPDATE statements correct.
TITLE: How do I do an Upsert Into Table? QUESTION: I have a view that has a list of jobs in it, with data like who they're assigned to and the stage they are in. I need to write a stored procedure that returns how many jobs each person has at each stage. So far I have this (simplified): DECLARE @ResultTable table ( StaffName nvarchar(100), Stage1Count int, Stage2Count int ) INSERT INTO @ResultTable (StaffName, Stage1Count) SELECT StaffName, COUNT(*) FROM ViewJob WHERE InStage1 = 1 GROUP BY StaffName INSERT INTO @ResultTable (StaffName, Stage2Count) SELECT StaffName, COUNT(*) FROM ViewJob WHERE InStage2 = 1 GROUP BY StaffName The problem with that is that the rows don't combine. So if a staff member has jobs in stage1 and stage2 there's two rows in @ResultTable. What I would really like to do is to update the row if one exists for the staff member and insert a new row if one doesn't exist. Does anyone know how to do this, or can suggest a different approach? I would really like to avoid using cursors to iterate on the list of users (but that's my fall back option). I'm using SQL Server 2005. Edit: @Lee: Unfortunately the InStage1 = 1 was a simplification. It's really more like WHERE DateStarted IS NOT NULL and DateFinished IS NULL. Edit: @BCS: I like the idea of doing an insert of all the staff first so I just have to do an update every time. But I'm struggling to get those UPDATE statements correct. ANSWER: IIRC there is some sort of "On Duplicate" (name might be wrong) syntax that lets you update if a row exists (MySQL) Alternately some form of: INSERT INTO @ResultTable (StaffName, Stage1Count, Stage2Count) SELECT StaffName,0,0 FROM ViewJob GROUP BY StaffName UPDATE @ResultTable Stage1Count= ( SELECT COUNT(*) AS count FROM ViewJob WHERE InStage1 = 1 @ResultTable.StaffName = StaffName) UPDATE @ResultTable Stage2Count= ( SELECT COUNT(*) AS count FROM ViewJob WHERE InStage2 = 1 @ResultTable.StaffName = StaffName)
[ "sql", "sql-server", "t-sql" ]
3
1
3,975
6
0
2008-08-20T23:46:13.360000
2008-08-21T00:09:16.580000
19,113
19,128
Should menu items always be enabled? And how do you tell the user?
One of the things that has been talked about a few times on the podcast is whether menu items should always be enabled to prevent "WHY ISN'T THIS AVAILABLE!" frustration for the end user. This strikes me as a good idea, but then there's the issue of communicating the lack of availability (and the reason why) to the user. Is there anything better than just popping up a message box with a blurb of text? As I'm about to start on a fairly sizeable cross-platform Windows / Mac app I thought I'd throw this out to hear the wisdom of the SO crowd.
One thing I've seen a printer manufacturer do with their printer properties dialog is to have a little help baloon icon beside disabled items that display a tooltip when hovered over. Another thing you can do with disabled items is to add in parenthesis why it's disabled or what the user would have to do to enable it. E.g., "Save (already saved)" or "Copy (select something to copy)". I don't like keeping it enabled because then it will instill hesitation in users to select any menu item in fear that they'll just get an error message making them feel stupid for not realizing that they couldn't possibly perform that operation at the time. Menu items that spring dialogs have elipsis (...) after them to let users know it's not just click and carry on. Required form fields have an asterisk or bold label to spare the user from being scolded with a validation error message.
Should menu items always be enabled? And how do you tell the user? One of the things that has been talked about a few times on the podcast is whether menu items should always be enabled to prevent "WHY ISN'T THIS AVAILABLE!" frustration for the end user. This strikes me as a good idea, but then there's the issue of communicating the lack of availability (and the reason why) to the user. Is there anything better than just popping up a message box with a blurb of text? As I'm about to start on a fairly sizeable cross-platform Windows / Mac app I thought I'd throw this out to hear the wisdom of the SO crowd.
TITLE: Should menu items always be enabled? And how do you tell the user? QUESTION: One of the things that has been talked about a few times on the podcast is whether menu items should always be enabled to prevent "WHY ISN'T THIS AVAILABLE!" frustration for the end user. This strikes me as a good idea, but then there's the issue of communicating the lack of availability (and the reason why) to the user. Is there anything better than just popping up a message box with a blurb of text? As I'm about to start on a fairly sizeable cross-platform Windows / Mac app I thought I'd throw this out to hear the wisdom of the SO crowd. ANSWER: One thing I've seen a printer manufacturer do with their printer properties dialog is to have a little help baloon icon beside disabled items that display a tooltip when hovered over. Another thing you can do with disabled items is to add in parenthesis why it's disabled or what the user would have to do to enable it. E.g., "Save (already saved)" or "Copy (select something to copy)". I don't like keeping it enabled because then it will instill hesitation in users to select any menu item in fear that they'll just get an error message making them feel stupid for not realizing that they couldn't possibly perform that operation at the time. Menu items that spring dialogs have elipsis (...) after them to let users know it's not just click and carry on. Required form fields have an asterisk or bold label to spare the user from being scolded with a validation error message.
[ "user-interface", "usability", "menu-items" ]
4
4
283
4
0
2008-08-21T00:14:56.660000
2008-08-21T00:24:47.400000
19,122
19,383
Bash Pipe Handling
Does anyone know how bash handles sending data through pipes? cat file.txt | tail -20 Does this command print all the contents of file.txt into a buffer, which is then read by tail? Or does this command, say, print the contents of file.txt line by line, and then pause at each line for tail to process, and then ask for more data? The reason I ask is that I'm writing a program on an embedded device that basically performs a sequence of operations on some chunk of data, where the output of one operation is send off as the input of the next operation. I would like to know how linux (bash) handles this so please give me a general answer, not specifically what happens when I run "cat file.txt | tail -20". EDIT: Shog9 pointed out a relevant Wikipedia Article, this didn't lead me directly to the article but it helped me find this: http://en.wikipedia.org/wiki/Pipeline_%28Unix%29#Implementation which did have the information I was looking for. I'm sorry for not making myself clear. Of course you're using a pipe and of course you're using stdin and stdout of the respective parts of the command. I had assumed that was too obvious to state. What I'm asking is how this is handled/implemented. Since both programs cannot run at once, how is data sent from stdin to stdout? What happens if the first program generates data significantly faster than the second program? Does the system just run the first command until either it's terminated or it's stdout buffer is full, and then move on to the next program, and so on in a loop until no more data is left to be processed or is there a more complicated mechanism?
I decided to write a slightly more detailed explanation. The "magic" here lies in the operating system. Both programs do start up at roughly the same time, and run at the same time (the operating system assigns them slices of time on the processor to run) as every other simultaneously running process on your computer (including the terminal application and the kernel). So, before any data gets passed, the processes are doing whatever initialization necessary. In your example, tail is parsing the '-20' argument and cat is parsing the 'file.txt' argument and opening the file. At some point tail will get to the point where it needs input and it will tell the operating system that it is waiting for input. At some other point (either before or after, it doesn't matter) cat will start passing data to the operating system using stdout. This goes into a buffer in the operating system. The next time tail gets a time slice on the processor after some data has been put into the buffer by cat, it will retrieve some amount of that data (or all of it) which leaves the buffer on the operating system. When the buffer is empty, at some point tail will have to wait for cat to output more data. If cat is outputting data much faster than tail is handling it, the buffer will expand. cat will eventually be done outputting data, but tail will still be processing, so cat will close and tail will process all remaining data in the buffer. The operating system will signal tail when their is no more incoming data with an EOF. Tail will process the remaining data. In this case, tail is probably just receiving all the data into a circular buffer of 20 lines, and when it is signalled by the operating system that there is no more incoming data, it then dumps the last twenty lines to its own stdout, which just gets displayed in the terminal. Since tail is a much simpler program than cat, it will likely spend most of the time waiting for cat to put data into the buffer. On a system with multiple processors, the two programs will not just be sharing alternating time slices on the same processor core, but likely running at the same time on separate cores. To get into a little more detail, if you open some kind of process monitor (operating system specific) like 'top' in Linux you will see a whole list of running processes, most of which are effectively using 0% of the processor. Most applications, unless they are crunching data, spend most of their time doing nothing. This is good, because it allows other processes to have unfettered access to the processor according to their needs. This is accomplished in basically three ways. A process could get to a sleep(n) style instruction where it basically tells the kernel to wait n milliseconds before giving it another time slice to work with. Most commonly a program needs to wait for something from another program, like 'tail' waiting for more data to enter the buffer. In this case the operating system will wake up the process when more data is available. Lastly, the kernel can preempt a process in the middle of execution, giving some processor time slices to other processes. 'cat' and 'tail' are simple programs. In this example, tail spends most of it's time waiting for more data on the buffer, and cat spends most of it's time waiting for the operating system to retrieve data from the harddrive. The bottleneck is the speed (or slowness) of the physical medium that the file is stored on. That perceptible delay you might detect when you run this command for the first time is the time it takes for the read heads on the disk drive to seek to the position on the harddrive where 'file.txt' is. If you run the command a second time, the operating system will likely have the contents of file.txt cached in memory, and you will not likely see any perceptible delay (unless file.txt is very large, or the file is no longer cached.) Most operations you do on your computer are IO bound, which is to say that you are usually waiting for data to come from your harddrive, or from a network device, etc.
Bash Pipe Handling Does anyone know how bash handles sending data through pipes? cat file.txt | tail -20 Does this command print all the contents of file.txt into a buffer, which is then read by tail? Or does this command, say, print the contents of file.txt line by line, and then pause at each line for tail to process, and then ask for more data? The reason I ask is that I'm writing a program on an embedded device that basically performs a sequence of operations on some chunk of data, where the output of one operation is send off as the input of the next operation. I would like to know how linux (bash) handles this so please give me a general answer, not specifically what happens when I run "cat file.txt | tail -20". EDIT: Shog9 pointed out a relevant Wikipedia Article, this didn't lead me directly to the article but it helped me find this: http://en.wikipedia.org/wiki/Pipeline_%28Unix%29#Implementation which did have the information I was looking for. I'm sorry for not making myself clear. Of course you're using a pipe and of course you're using stdin and stdout of the respective parts of the command. I had assumed that was too obvious to state. What I'm asking is how this is handled/implemented. Since both programs cannot run at once, how is data sent from stdin to stdout? What happens if the first program generates data significantly faster than the second program? Does the system just run the first command until either it's terminated or it's stdout buffer is full, and then move on to the next program, and so on in a loop until no more data is left to be processed or is there a more complicated mechanism?
TITLE: Bash Pipe Handling QUESTION: Does anyone know how bash handles sending data through pipes? cat file.txt | tail -20 Does this command print all the contents of file.txt into a buffer, which is then read by tail? Or does this command, say, print the contents of file.txt line by line, and then pause at each line for tail to process, and then ask for more data? The reason I ask is that I'm writing a program on an embedded device that basically performs a sequence of operations on some chunk of data, where the output of one operation is send off as the input of the next operation. I would like to know how linux (bash) handles this so please give me a general answer, not specifically what happens when I run "cat file.txt | tail -20". EDIT: Shog9 pointed out a relevant Wikipedia Article, this didn't lead me directly to the article but it helped me find this: http://en.wikipedia.org/wiki/Pipeline_%28Unix%29#Implementation which did have the information I was looking for. I'm sorry for not making myself clear. Of course you're using a pipe and of course you're using stdin and stdout of the respective parts of the command. I had assumed that was too obvious to state. What I'm asking is how this is handled/implemented. Since both programs cannot run at once, how is data sent from stdin to stdout? What happens if the first program generates data significantly faster than the second program? Does the system just run the first command until either it's terminated or it's stdout buffer is full, and then move on to the next program, and so on in a loop until no more data is left to be processed or is there a more complicated mechanism? ANSWER: I decided to write a slightly more detailed explanation. The "magic" here lies in the operating system. Both programs do start up at roughly the same time, and run at the same time (the operating system assigns them slices of time on the processor to run) as every other simultaneously running process on your computer (including the terminal application and the kernel). So, before any data gets passed, the processes are doing whatever initialization necessary. In your example, tail is parsing the '-20' argument and cat is parsing the 'file.txt' argument and opening the file. At some point tail will get to the point where it needs input and it will tell the operating system that it is waiting for input. At some other point (either before or after, it doesn't matter) cat will start passing data to the operating system using stdout. This goes into a buffer in the operating system. The next time tail gets a time slice on the processor after some data has been put into the buffer by cat, it will retrieve some amount of that data (or all of it) which leaves the buffer on the operating system. When the buffer is empty, at some point tail will have to wait for cat to output more data. If cat is outputting data much faster than tail is handling it, the buffer will expand. cat will eventually be done outputting data, but tail will still be processing, so cat will close and tail will process all remaining data in the buffer. The operating system will signal tail when their is no more incoming data with an EOF. Tail will process the remaining data. In this case, tail is probably just receiving all the data into a circular buffer of 20 lines, and when it is signalled by the operating system that there is no more incoming data, it then dumps the last twenty lines to its own stdout, which just gets displayed in the terminal. Since tail is a much simpler program than cat, it will likely spend most of the time waiting for cat to put data into the buffer. On a system with multiple processors, the two programs will not just be sharing alternating time slices on the same processor core, but likely running at the same time on separate cores. To get into a little more detail, if you open some kind of process monitor (operating system specific) like 'top' in Linux you will see a whole list of running processes, most of which are effectively using 0% of the processor. Most applications, unless they are crunching data, spend most of their time doing nothing. This is good, because it allows other processes to have unfettered access to the processor according to their needs. This is accomplished in basically three ways. A process could get to a sleep(n) style instruction where it basically tells the kernel to wait n milliseconds before giving it another time slice to work with. Most commonly a program needs to wait for something from another program, like 'tail' waiting for more data to enter the buffer. In this case the operating system will wake up the process when more data is available. Lastly, the kernel can preempt a process in the middle of execution, giving some processor time slices to other processes. 'cat' and 'tail' are simple programs. In this example, tail spends most of it's time waiting for more data on the buffer, and cat spends most of it's time waiting for the operating system to retrieve data from the harddrive. The bottleneck is the speed (or slowness) of the physical medium that the file is stored on. That perceptible delay you might detect when you run this command for the first time is the time it takes for the read heads on the disk drive to seek to the position on the harddrive where 'file.txt' is. If you run the command a second time, the operating system will likely have the contents of file.txt cached in memory, and you will not likely see any perceptible delay (unless file.txt is very large, or the file is no longer cached.) Most operations you do on your computer are IO bound, which is to say that you are usually waiting for data to come from your harddrive, or from a network device, etc.
[ "linux", "bash", "pipe" ]
31
55
13,150
3
0
2008-08-21T00:20:34.133000
2008-08-21T05:46:23.337000
19,127
19,199
Best way to fix CSS/JS drop-down in IE7 when page includes Google Map
I have a page using lists for navigation (Javascript changes the styling to display or not on mouseover). This is working fine for me except in IE6 and IE7 when I have a Google Map on the page. In this case the drop-down simply does not work. However, the page continues to work in FireFox 2. I have done a little bit of research and discovered that this may be an example of the IE Select Box Bug, but I am not sure as the Google Map appears to be using a, not an. Has anyone else encountered a problem similar to this, and if so do they have any recommendations on the best way to overcome this problem?
I don't know if this will fix your problem but you may want to try this solution at ccsplay.co.uk which fixes the problem of menus appearing underneath drop-down lists. I don't know if it will work for sure, but it's worth a shot.
Best way to fix CSS/JS drop-down in IE7 when page includes Google Map I have a page using lists for navigation (Javascript changes the styling to display or not on mouseover). This is working fine for me except in IE6 and IE7 when I have a Google Map on the page. In this case the drop-down simply does not work. However, the page continues to work in FireFox 2. I have done a little bit of research and discovered that this may be an example of the IE Select Box Bug, but I am not sure as the Google Map appears to be using a, not an. Has anyone else encountered a problem similar to this, and if so do they have any recommendations on the best way to overcome this problem?
TITLE: Best way to fix CSS/JS drop-down in IE7 when page includes Google Map QUESTION: I have a page using lists for navigation (Javascript changes the styling to display or not on mouseover). This is working fine for me except in IE6 and IE7 when I have a Google Map on the page. In this case the drop-down simply does not work. However, the page continues to work in FireFox 2. I have done a little bit of research and discovered that this may be an example of the IE Select Box Bug, but I am not sure as the Google Map appears to be using a, not an. Has anyone else encountered a problem similar to this, and if so do they have any recommendations on the best way to overcome this problem? ANSWER: I don't know if this will fix your problem but you may want to try this solution at ccsplay.co.uk which fixes the problem of menus appearing underneath drop-down lists. I don't know if it will work for sure, but it's worth a shot.
[ "javascript", "css", "cross-browser", "browser", "client-side" ]
6
2
2,276
5
0
2008-08-21T00:24:15.093000
2008-08-21T01:41:16.547000
19,132
19,224
Expression versus Statement
I'm asking with regards to C#, but I assume it's the same in most other languages. Does anyone have a good definition of expressions and statements and what the differences are?
Expression: Something which evaluates to a value. Example: 1+2/x Statement: A line of code which does something. Example: GOTO 100 In the earliest general-purpose programming languages, like FORTRAN, the distinction was crystal-clear. In FORTRAN, a statement was one unit of execution, a thing that you did. The only reason it wasn't called a "line" was because sometimes it spanned multiple lines. An expression on its own couldn't do anything... you had to assign it to a variable. 1 + 2 / X is an error in FORTRAN, because it doesn't do anything. You had to do something with that expression: X = 1 + 2 / X FORTRAN didn't have a grammar as we know it today—that idea was invented, along with Backus-Naur Form (BNF), as part of the definition of Algol-60. At that point the semantic distinction ("have a value" versus "do something") was enshrined in syntax: one kind of phrase was an expression, and another was a statement, and the parser could tell them apart. Designers of later languages blurred the distinction: they allowed syntactic expressions to do things, and they allowed syntactic statements that had values. The earliest popular language example that still survives is C. The designers of C realized that no harm was done if you were allowed to evaluate an expression and throw away the result. In C, every syntactic expression can be a made into a statement just by tacking a semicolon along the end: 1 + 2 / x; is a totally legit statement even though absolutely nothing will happen. Similarly, in C, an expression can have side-effects —it can change something. 1 + 2 / callfunc(12); because callfunc might just do something useful. Once you allow any expression to be a statement, you might as well allow the assignment operator (=) inside expressions. That's why C lets you do things like callfunc(x = 2); This evaluates the expression x = 2 (assigning the value of 2 to x) and then passes that (the 2) to the function callfunc. This blurring of expressions and statements occurs in all the C-derivatives (C, C++, C#, and Java), which still have some statements (like while ) but which allow almost any expression to be used as a statement (in C# only assignment, call, increment, and decrement expressions may be used as statements; see Scott Wisniewski's answer ). Having two "syntactic categories" (which is the technical name for the sort of thing statements and expressions are) can lead to duplication of effort. For example, C has two forms of conditional, the statement form if (E) S1; else S2; and the expression form E? E1: E2 And sometimes people want duplication that isn't there: in standard C, for example, only a statement can declare a new local variable—but this ability is useful enough that the GNU C compiler provides a GNU extension that enables an expression to declare a local variable as well. Designers of other languages didn't like this kind of duplication, and they saw early on that if expressions can have side effects as well as values, then the syntactic distinction between statements and expressions is not all that useful—so they got rid of it. Haskell, Icon, Lisp, and ML are all languages that don't have syntactic statements—they only have expressions. Even the class structured looping and conditional forms are considered expressions, and they have values—but not very interesting ones.
Expression versus Statement I'm asking with regards to C#, but I assume it's the same in most other languages. Does anyone have a good definition of expressions and statements and what the differences are?
TITLE: Expression versus Statement QUESTION: I'm asking with regards to C#, but I assume it's the same in most other languages. Does anyone have a good definition of expressions and statements and what the differences are? ANSWER: Expression: Something which evaluates to a value. Example: 1+2/x Statement: A line of code which does something. Example: GOTO 100 In the earliest general-purpose programming languages, like FORTRAN, the distinction was crystal-clear. In FORTRAN, a statement was one unit of execution, a thing that you did. The only reason it wasn't called a "line" was because sometimes it spanned multiple lines. An expression on its own couldn't do anything... you had to assign it to a variable. 1 + 2 / X is an error in FORTRAN, because it doesn't do anything. You had to do something with that expression: X = 1 + 2 / X FORTRAN didn't have a grammar as we know it today—that idea was invented, along with Backus-Naur Form (BNF), as part of the definition of Algol-60. At that point the semantic distinction ("have a value" versus "do something") was enshrined in syntax: one kind of phrase was an expression, and another was a statement, and the parser could tell them apart. Designers of later languages blurred the distinction: they allowed syntactic expressions to do things, and they allowed syntactic statements that had values. The earliest popular language example that still survives is C. The designers of C realized that no harm was done if you were allowed to evaluate an expression and throw away the result. In C, every syntactic expression can be a made into a statement just by tacking a semicolon along the end: 1 + 2 / x; is a totally legit statement even though absolutely nothing will happen. Similarly, in C, an expression can have side-effects —it can change something. 1 + 2 / callfunc(12); because callfunc might just do something useful. Once you allow any expression to be a statement, you might as well allow the assignment operator (=) inside expressions. That's why C lets you do things like callfunc(x = 2); This evaluates the expression x = 2 (assigning the value of 2 to x) and then passes that (the 2) to the function callfunc. This blurring of expressions and statements occurs in all the C-derivatives (C, C++, C#, and Java), which still have some statements (like while ) but which allow almost any expression to be used as a statement (in C# only assignment, call, increment, and decrement expressions may be used as statements; see Scott Wisniewski's answer ). Having two "syntactic categories" (which is the technical name for the sort of thing statements and expressions are) can lead to duplication of effort. For example, C has two forms of conditional, the statement form if (E) S1; else S2; and the expression form E? E1: E2 And sometimes people want duplication that isn't there: in standard C, for example, only a statement can declare a new local variable—but this ability is useful enough that the GNU C compiler provides a GNU extension that enables an expression to declare a local variable as well. Designers of other languages didn't like this kind of duplication, and they saw early on that if expressions can have side effects as well as values, then the syntactic distinction between statements and expressions is not all that useful—so they got rid of it. Haskell, Icon, Lisp, and ML are all languages that don't have syntactic statements—they only have expressions. Even the class structured looping and conditional forms are considered expressions, and they have values—but not very interesting ones.
[ "language-agnostic", "expression", "language-features" ]
480
585
82,563
21
0
2008-08-21T00:28:00.263000
2008-08-21T02:17:21
19,147
522,874
What is the correct way to create a single-instance WPF application?
Using C# and WPF under.NET (rather than Windows Forms or console), what is the correct way to create an application that can only be run as a single instance? I know it has something to do with some mythical thing called a mutex, rarely can I find someone that bothers to stop and explain what one of these are. The code needs to also inform the already-running instance that the user tried to start a second one, and maybe also pass any command-line arguments if any existed.
Here is a very good article regarding the Mutex solution. The approach described by the article is advantageous for two reasons. First, it does not require a dependency on the Microsoft.VisualBasic assembly. If my project already had a dependency on that assembly, I would probably advocate using the approach shown in another answer. But as it is, I do not use the Microsoft.VisualBasic assembly, and I'd rather not add an unnecessary dependency to my project. Second, the article shows how to bring the existing instance of the application to the foreground when the user tries to start another instance. That's a very nice touch that the other Mutex solutions described here do not address. UPDATE As of 8/1/2014, the article I linked to above is still active, but the blog hasn't been updated in a while. That makes me worry that eventually it might disappear, and with it, the advocated solution. I'm reproducing the content of the article here for posterity. The words belong solely to the blog owner at Sanity Free Coding. Today I wanted to refactor some code that prohibited my application from running multiple instances of itself. Previously I had use System.Diagnostics.Process to search for an instance of my myapp.exe in the process list. While this works, it brings on a lot of overhead, and I wanted something cleaner. Knowing that I could use a mutex for this (but never having done it before) I set out to cut down my code and simplify my life. In the class of my application main I created a static named Mutex: static class Program { static Mutex mutex = new Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}"); [STAThread]... } Having a named mutex allows us to stack synchronization across multiple threads and processes which is just the magic I'm looking for. Mutex.WaitOne has an overload that specifies an amount of time for us to wait. Since we're not actually wanting to synchronizing our code (more just check if it is currently in use) we use the overload with two parameters: Mutex.WaitOne(Timespan timeout, bool exitContext). Wait one returns true if it is able to enter, and false if it wasn't. In this case, we don't want to wait at all; If our mutex is being used, skip it, and move on, so we pass in TimeSpan.Zero (wait 0 milliseconds), and set the exitContext to true so we can exit the synchronization context before we try to aquire a lock on it. Using this, we wrap our Application.Run code inside something like this: static class Program { static Mutex mutex = new Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}"); [STAThread] static void Main() { if(mutex.WaitOne(TimeSpan.Zero, true)) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); mutex.ReleaseMutex(); } else { MessageBox.Show("only one instance at a time"); } } } So, if our app is running, WaitOne will return false, and we'll get a message box. Instead of showing a message box, I opted to utilize a little Win32 to notify my running instance that someone forgot that it was already running (by bringing itself to the top of all the other windows). To achieve this I used PostMessage to broadcast a custom message to every window (the custom message was registered with RegisterWindowMessage by my running application, which means only my application knows what it is) then my second instance exits. The running application instance would receive that notification and process it. In order to do that, I overrode WndProc in my main form and listened for my custom notification. When I received that notification I set the form's TopMost property to true to bring it up on top. Here is what I ended up with: Program.cs static class Program { static Mutex mutex = new Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}"); [STAThread] static void Main() { if(mutex.WaitOne(TimeSpan.Zero, true)) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); mutex.ReleaseMutex(); } else { // send our Win32 message to make the currently running instance // jump on top of all the other windows NativeMethods.PostMessage( (IntPtr)NativeMethods.HWND_BROADCAST, NativeMethods.WM_SHOWME, IntPtr.Zero, IntPtr.Zero); } } } NativeMethods.cs // this class just wraps some Win32 stuff that we're going to use internal class NativeMethods { public const int HWND_BROADCAST = 0xffff; public static readonly int WM_SHOWME = RegisterWindowMessage("WM_SHOWME"); [DllImport("user32")] public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam); [DllImport("user32")] public static extern int RegisterWindowMessage(string message); } Form1.cs (front side partial) public partial class Form1: Form { public Form1() { InitializeComponent(); } protected override void WndProc(ref Message m) { if(m.Msg == NativeMethods.WM_SHOWME) { ShowMe(); } base.WndProc(ref m); } private void ShowMe() { if(WindowState == FormWindowState.Minimized) { WindowState = FormWindowState.Normal; } // get our current "TopMost" value (ours will always be false though) bool top = TopMost; // make our form jump to the top of everything TopMost = true; // set it back to whatever it was TopMost = top; } }
What is the correct way to create a single-instance WPF application? Using C# and WPF under.NET (rather than Windows Forms or console), what is the correct way to create an application that can only be run as a single instance? I know it has something to do with some mythical thing called a mutex, rarely can I find someone that bothers to stop and explain what one of these are. The code needs to also inform the already-running instance that the user tried to start a second one, and maybe also pass any command-line arguments if any existed.
TITLE: What is the correct way to create a single-instance WPF application? QUESTION: Using C# and WPF under.NET (rather than Windows Forms or console), what is the correct way to create an application that can only be run as a single instance? I know it has something to do with some mythical thing called a mutex, rarely can I find someone that bothers to stop and explain what one of these are. The code needs to also inform the already-running instance that the user tried to start a second one, and maybe also pass any command-line arguments if any existed. ANSWER: Here is a very good article regarding the Mutex solution. The approach described by the article is advantageous for two reasons. First, it does not require a dependency on the Microsoft.VisualBasic assembly. If my project already had a dependency on that assembly, I would probably advocate using the approach shown in another answer. But as it is, I do not use the Microsoft.VisualBasic assembly, and I'd rather not add an unnecessary dependency to my project. Second, the article shows how to bring the existing instance of the application to the foreground when the user tries to start another instance. That's a very nice touch that the other Mutex solutions described here do not address. UPDATE As of 8/1/2014, the article I linked to above is still active, but the blog hasn't been updated in a while. That makes me worry that eventually it might disappear, and with it, the advocated solution. I'm reproducing the content of the article here for posterity. The words belong solely to the blog owner at Sanity Free Coding. Today I wanted to refactor some code that prohibited my application from running multiple instances of itself. Previously I had use System.Diagnostics.Process to search for an instance of my myapp.exe in the process list. While this works, it brings on a lot of overhead, and I wanted something cleaner. Knowing that I could use a mutex for this (but never having done it before) I set out to cut down my code and simplify my life. In the class of my application main I created a static named Mutex: static class Program { static Mutex mutex = new Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}"); [STAThread]... } Having a named mutex allows us to stack synchronization across multiple threads and processes which is just the magic I'm looking for. Mutex.WaitOne has an overload that specifies an amount of time for us to wait. Since we're not actually wanting to synchronizing our code (more just check if it is currently in use) we use the overload with two parameters: Mutex.WaitOne(Timespan timeout, bool exitContext). Wait one returns true if it is able to enter, and false if it wasn't. In this case, we don't want to wait at all; If our mutex is being used, skip it, and move on, so we pass in TimeSpan.Zero (wait 0 milliseconds), and set the exitContext to true so we can exit the synchronization context before we try to aquire a lock on it. Using this, we wrap our Application.Run code inside something like this: static class Program { static Mutex mutex = new Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}"); [STAThread] static void Main() { if(mutex.WaitOne(TimeSpan.Zero, true)) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); mutex.ReleaseMutex(); } else { MessageBox.Show("only one instance at a time"); } } } So, if our app is running, WaitOne will return false, and we'll get a message box. Instead of showing a message box, I opted to utilize a little Win32 to notify my running instance that someone forgot that it was already running (by bringing itself to the top of all the other windows). To achieve this I used PostMessage to broadcast a custom message to every window (the custom message was registered with RegisterWindowMessage by my running application, which means only my application knows what it is) then my second instance exits. The running application instance would receive that notification and process it. In order to do that, I overrode WndProc in my main form and listened for my custom notification. When I received that notification I set the form's TopMost property to true to bring it up on top. Here is what I ended up with: Program.cs static class Program { static Mutex mutex = new Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}"); [STAThread] static void Main() { if(mutex.WaitOne(TimeSpan.Zero, true)) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); mutex.ReleaseMutex(); } else { // send our Win32 message to make the currently running instance // jump on top of all the other windows NativeMethods.PostMessage( (IntPtr)NativeMethods.HWND_BROADCAST, NativeMethods.WM_SHOWME, IntPtr.Zero, IntPtr.Zero); } } } NativeMethods.cs // this class just wraps some Win32 stuff that we're going to use internal class NativeMethods { public const int HWND_BROADCAST = 0xffff; public static readonly int WM_SHOWME = RegisterWindowMessage("WM_SHOWME"); [DllImport("user32")] public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam); [DllImport("user32")] public static extern int RegisterWindowMessage(string message); } Form1.cs (front side partial) public partial class Form1: Form { public Form1() { InitializeComponent(); } protected override void WndProc(ref Message m) { if(m.Msg == NativeMethods.WM_SHOWME) { ShowMe(); } base.WndProc(ref m); } private void ShowMe() { if(WindowState == FormWindowState.Minimized) { WindowState = FormWindowState.Normal; } // get our current "TopMost" value (ours will always be false though) bool top = TopMost; // make our form jump to the top of everything TopMost = true; // set it back to whatever it was TopMost = top; } }
[ "c#", ".net", "wpf", "mutex" ]
742
612
260,583
39
0
2008-08-21T00:33:59.453000
2009-02-07T01:18:20.277000
19,151
24,377
How to build a basic iterator?
How can I create an iterator in Python? For example, suppose I have a class whose instances logically "contain" some values: class Example: def __init__(self, values): self.values = values I want to be able to write code like: e = Example([1, 2, 3]) # Each time through the loop, expose one of the values from e.values for value in e: print("The example object contains", value) More generally, the iterator should be able to control where the values come from, or even compute them on the fly (rather than considering any particular attribute of the instance).
Iterator objects in python conform to the iterator protocol, which basically means they provide two methods: __iter__() and __next__(). The __iter__ returns the iterator object and is implicitly called at the start of loops. The __next__() method returns the next value and is implicitly called at each loop increment. This method raises a StopIteration exception when there are no more value to return, which is implicitly captured by looping constructs to stop iterating. Here's a simple example of a counter: class Counter: def __init__(self, low, high): self.current = low - 1 self.high = high def __iter__(self): return self def __next__(self): # Python 2: def next(self) self.current += 1 if self.current < self.high: return self.current raise StopIteration for c in Counter(3, 9): print(c) This will print: 3 4 5 6 7 8 This is easier to write using a generator, as covered in a previous answer: def counter(low, high): current = low while current < high: yield current current += 1 for c in counter(3, 9): print(c) The printed output will be the same. Under the hood, the generator object supports the iterator protocol and does something roughly similar to the class Counter. David Mertz's article, Iterators and Simple Generators, is a pretty good introduction.
How to build a basic iterator? How can I create an iterator in Python? For example, suppose I have a class whose instances logically "contain" some values: class Example: def __init__(self, values): self.values = values I want to be able to write code like: e = Example([1, 2, 3]) # Each time through the loop, expose one of the values from e.values for value in e: print("The example object contains", value) More generally, the iterator should be able to control where the values come from, or even compute them on the fly (rather than considering any particular attribute of the instance).
TITLE: How to build a basic iterator? QUESTION: How can I create an iterator in Python? For example, suppose I have a class whose instances logically "contain" some values: class Example: def __init__(self, values): self.values = values I want to be able to write code like: e = Example([1, 2, 3]) # Each time through the loop, expose one of the values from e.values for value in e: print("The example object contains", value) More generally, the iterator should be able to control where the values come from, or even compute them on the fly (rather than considering any particular attribute of the instance). ANSWER: Iterator objects in python conform to the iterator protocol, which basically means they provide two methods: __iter__() and __next__(). The __iter__ returns the iterator object and is implicitly called at the start of loops. The __next__() method returns the next value and is implicitly called at each loop increment. This method raises a StopIteration exception when there are no more value to return, which is implicitly captured by looping constructs to stop iterating. Here's a simple example of a counter: class Counter: def __init__(self, low, high): self.current = low - 1 self.high = high def __iter__(self): return self def __next__(self): # Python 2: def next(self) self.current += 1 if self.current < self.high: return self.current raise StopIteration for c in Counter(3, 9): print(c) This will print: 3 4 5 6 7 8 This is easier to write using a generator, as covered in a previous answer: def counter(low, high): current = low while current < high: yield current current += 1 for c in counter(3, 9): print(c) The printed output will be the same. Under the hood, the generator object supports the iterator protocol and does something roughly similar to the class Counter. David Mertz's article, Iterators and Simple Generators, is a pretty good introduction.
[ "python", "object", "iterator" ]
695
761
484,428
10
0
2008-08-21T00:36:11.773000
2008-08-23T16:57:28.637000
19,162
19,171
PHP Script to populate MySQL tables
Is anyone aware of a script/class (preferably in PHP) that would parse a given MySQL table's structure and then fill it with x number of rows of random test data based on the field types? I have never seen or heard of something like this and thought I would check before writing one myself.
What you are after would be a data generator. There is one available here which i had bookmarked but i haven't got around to trying it yet.
PHP Script to populate MySQL tables Is anyone aware of a script/class (preferably in PHP) that would parse a given MySQL table's structure and then fill it with x number of rows of random test data based on the field types? I have never seen or heard of something like this and thought I would check before writing one myself.
TITLE: PHP Script to populate MySQL tables QUESTION: Is anyone aware of a script/class (preferably in PHP) that would parse a given MySQL table's structure and then fill it with x number of rows of random test data based on the field types? I have never seen or heard of something like this and thought I would check before writing one myself. ANSWER: What you are after would be a data generator. There is one available here which i had bookmarked but i haven't got around to trying it yet.
[ "php", "mysql", "testing", "dataset", "test-data" ]
14
21
5,196
1
0
2008-08-21T00:46:52.293000
2008-08-21T00:54:24.147000
19,173
23,208
Are there reasons not to use JSONP for AJA~X requests?
If you're building an AJA~Xy app, are there any downsides to using JSONP requests/responses even if you're not planning on any cross-domain requests? The only thing I can think of is that there are a couple extra bytes for the callback wrapper... Edit: I found this which also suggests security and error handling as potential problems... There's no error handling. The script injection either works, or it doesn't. If there's an error from the injection, it'll hit the page, and short of a window wide error handler (bad, bad, very bad), you need to be sure the return value is valid on the server side. I don't think error handling is much of a problem... most of us would use a library to generate the JSON... the well-formedness of my response isn't a concern for this question. and security: There are documents out on the web that can help, but as a cursory check, I would check the referrer in the server side script. it seems like this is a potential problem with any type of response... certainly, there's nothing unique to JSONP in the security arena...?
Downside? It's fairly limited - you trigger a "GET" request and get back some script that's executed. You don't get error handling if your server throws an error, so you need to wrap all errors in JSON as well. You can't really cancel or retry the request. You're at the mercy of the various browser author opinions of "correct" behavior for dynamically-generated
Are there reasons not to use JSONP for AJA~X requests? If you're building an AJA~Xy app, are there any downsides to using JSONP requests/responses even if you're not planning on any cross-domain requests? The only thing I can think of is that there are a couple extra bytes for the callback wrapper... Edit: I found this which also suggests security and error handling as potential problems... There's no error handling. The script injection either works, or it doesn't. If there's an error from the injection, it'll hit the page, and short of a window wide error handler (bad, bad, very bad), you need to be sure the return value is valid on the server side. I don't think error handling is much of a problem... most of us would use a library to generate the JSON... the well-formedness of my response isn't a concern for this question. and security: There are documents out on the web that can help, but as a cursory check, I would check the referrer in the server side script. it seems like this is a potential problem with any type of response... certainly, there's nothing unique to JSONP in the security arena...?
TITLE: Are there reasons not to use JSONP for AJA~X requests? QUESTION: If you're building an AJA~Xy app, are there any downsides to using JSONP requests/responses even if you're not planning on any cross-domain requests? The only thing I can think of is that there are a couple extra bytes for the callback wrapper... Edit: I found this which also suggests security and error handling as potential problems... There's no error handling. The script injection either works, or it doesn't. If there's an error from the injection, it'll hit the page, and short of a window wide error handler (bad, bad, very bad), you need to be sure the return value is valid on the server side. I don't think error handling is much of a problem... most of us would use a library to generate the JSON... the well-formedness of my response isn't a concern for this question. and security: There are documents out on the web that can help, but as a cursory check, I would check the referrer in the server side script. it seems like this is a potential problem with any type of response... certainly, there's nothing unique to JSONP in the security arena...? ANSWER: Downside? It's fairly limited - you trigger a "GET" request and get back some script that's executed. You don't get error handling if your server throws an error, so you need to wrap all errors in JSON as well. You can't really cancel or retry the request. You're at the mercy of the various browser author opinions of "correct" behavior for dynamically-generated
[ "javascript", "ajax", "json", "jsonp" ]
9
10
3,427
4
0
2008-08-21T00:56:45.217000
2008-08-22T19:03:51.183000
19,185
19,188
Is there a way to check to see if the user is currently idle?
There is some documentation on the internet that shows that Windows changes the behavior of the NotifyIcon.BalloonTipShown command if the user is currently idle and this is detected by checking for keyboard and mouse events. I am currently working on an application that spends most of its time in the system tray, but pop-ups up multiple balloon tips from time to time and I would like to prevent the user from missing any of them if they are currently away from the system. Since any currently displayed balloon tips are destroyed if a new one is displayed, I want to hold off on displaying them if the user is away. As such, is there any way to check to see if the user is currently idle if the application is minimized to the system tray?
How about the Win32 LASTINPUTINFO function? using System.Runtime.InteropServices; [DllImport("User32.dll")] static extern bool GetLastInputInfo(ref LASTINPUTINFO plii); struct LASTINPUTINFO { public uint cbSize; public uint dwTime; }
Is there a way to check to see if the user is currently idle? There is some documentation on the internet that shows that Windows changes the behavior of the NotifyIcon.BalloonTipShown command if the user is currently idle and this is detected by checking for keyboard and mouse events. I am currently working on an application that spends most of its time in the system tray, but pop-ups up multiple balloon tips from time to time and I would like to prevent the user from missing any of them if they are currently away from the system. Since any currently displayed balloon tips are destroyed if a new one is displayed, I want to hold off on displaying them if the user is away. As such, is there any way to check to see if the user is currently idle if the application is minimized to the system tray?
TITLE: Is there a way to check to see if the user is currently idle? QUESTION: There is some documentation on the internet that shows that Windows changes the behavior of the NotifyIcon.BalloonTipShown command if the user is currently idle and this is detected by checking for keyboard and mouse events. I am currently working on an application that spends most of its time in the system tray, but pop-ups up multiple balloon tips from time to time and I would like to prevent the user from missing any of them if they are currently away from the system. Since any currently displayed balloon tips are destroyed if a new one is displayed, I want to hold off on displaying them if the user is away. As such, is there any way to check to see if the user is currently idle if the application is minimized to the system tray? ANSWER: How about the Win32 LASTINPUTINFO function? using System.Runtime.InteropServices; [DllImport("User32.dll")] static extern bool GetLastInputInfo(ref LASTINPUTINFO plii); struct LASTINPUTINFO { public uint cbSize; public uint dwTime; }
[ ".net", "windows", "user-interface", "tray" ]
3
4
578
3
0
2008-08-21T01:15:00.213000
2008-08-21T01:19:35.600000
19,193
19,255
How to make a tree in C++?
How do I make a tree data structure in C++ that uses iterators instead of pointers? I couldn't find anything in the STL that can do this. What I would like to do is to be able to create and manipulate trees like this: #include #include using namespace std; int main() { tree myTree; tree::iterator i = myTree.root(); *i = 42; tree::iterator j = i.add_child(); *j = 777; j = j.parent(); if (i == myTree.root() && i == j) cout << "i and j are both pointing to the root\n"; return 0; } Thank you, tree.hh seems to be just what I was looking for. If this is for gaining the benefit of a data-structure holding arbitrary index types, optimized for searching and good at insertion then consider using a map. A map is an associative container that has performance guarantees identical to those of a tree: logarithmic searching, logarithmic insertion, logarithmic deletion, linear space. Internally they are often implemented as red-black trees, although that is not a guarantee. Still, as an STL user all you should care about is the performance guarantees of the STL algorithms and data-structures. Whether they're implemented as trees or little green men shouldn't matter to you. I'm not sure if a map is what I need, but thanks for the info. I will remember to use maps whenever possible instead of implementing trees.
Here is tree.hh which is a bit close to what you want to do, though a bit different. Here is a piece of code extracted from its website. int main(int, char **) { tree tr; tree::iterator top, one, two, loc, banana; top=tr.begin(); one=tr.insert(top, "one"); two=tr.append_child(one, "two"); tr.append_child(two, "apple"); banana=tr.append_child(two, "banana"); tr.append_child(banana,"cherry"); tr.append_child(two, "peach"); tr.append_child(one,"three"); loc=find(tr.begin(), tr.end(), "two"); if(loc!=tr.end()) { tree::sibling_iterator sib=tr.begin(loc); while(sib!=tr.end(loc)) { cout << (*sib) << endl; ++sib; } cout << endl; tree::iterator sib2=tr.begin(loc); tree::iterator end2=tr.end(loc); while(sib2!=end2) { for(int i=0; i Now what's different? Your implementation is simpler when it comes to append a node to the tree. Though your version is indiscutably simpler, the dev of this lib probably wanted to have some info accessible without browsing the tree, such as the size of the tree for instance. I also assume he didn't want to store the root on all nodes for performance reason. So if you want to implement it your way, I suggest you keep most of the logic and add the link to the parent tree in the iterator and rewrite append a bit.
How to make a tree in C++? How do I make a tree data structure in C++ that uses iterators instead of pointers? I couldn't find anything in the STL that can do this. What I would like to do is to be able to create and manipulate trees like this: #include #include using namespace std; int main() { tree myTree; tree::iterator i = myTree.root(); *i = 42; tree::iterator j = i.add_child(); *j = 777; j = j.parent(); if (i == myTree.root() && i == j) cout << "i and j are both pointing to the root\n"; return 0; } Thank you, tree.hh seems to be just what I was looking for. If this is for gaining the benefit of a data-structure holding arbitrary index types, optimized for searching and good at insertion then consider using a map. A map is an associative container that has performance guarantees identical to those of a tree: logarithmic searching, logarithmic insertion, logarithmic deletion, linear space. Internally they are often implemented as red-black trees, although that is not a guarantee. Still, as an STL user all you should care about is the performance guarantees of the STL algorithms and data-structures. Whether they're implemented as trees or little green men shouldn't matter to you. I'm not sure if a map is what I need, but thanks for the info. I will remember to use maps whenever possible instead of implementing trees.
TITLE: How to make a tree in C++? QUESTION: How do I make a tree data structure in C++ that uses iterators instead of pointers? I couldn't find anything in the STL that can do this. What I would like to do is to be able to create and manipulate trees like this: #include #include using namespace std; int main() { tree myTree; tree::iterator i = myTree.root(); *i = 42; tree::iterator j = i.add_child(); *j = 777; j = j.parent(); if (i == myTree.root() && i == j) cout << "i and j are both pointing to the root\n"; return 0; } Thank you, tree.hh seems to be just what I was looking for. If this is for gaining the benefit of a data-structure holding arbitrary index types, optimized for searching and good at insertion then consider using a map. A map is an associative container that has performance guarantees identical to those of a tree: logarithmic searching, logarithmic insertion, logarithmic deletion, linear space. Internally they are often implemented as red-black trees, although that is not a guarantee. Still, as an STL user all you should care about is the performance guarantees of the STL algorithms and data-structures. Whether they're implemented as trees or little green men shouldn't matter to you. I'm not sure if a map is what I need, but thanks for the info. I will remember to use maps whenever possible instead of implementing trees. ANSWER: Here is tree.hh which is a bit close to what you want to do, though a bit different. Here is a piece of code extracted from its website. int main(int, char **) { tree tr; tree::iterator top, one, two, loc, banana; top=tr.begin(); one=tr.insert(top, "one"); two=tr.append_child(one, "two"); tr.append_child(two, "apple"); banana=tr.append_child(two, "banana"); tr.append_child(banana,"cherry"); tr.append_child(two, "peach"); tr.append_child(one,"three"); loc=find(tr.begin(), tr.end(), "two"); if(loc!=tr.end()) { tree::sibling_iterator sib=tr.begin(loc); while(sib!=tr.end(loc)) { cout << (*sib) << endl; ++sib; } cout << endl; tree::iterator sib2=tr.begin(loc); tree::iterator end2=tr.end(loc); while(sib2!=end2) { for(int i=0; i Now what's different? Your implementation is simpler when it comes to append a node to the tree. Though your version is indiscutably simpler, the dev of this lib probably wanted to have some info accessible without browsing the tree, such as the size of the tree for instance. I also assume he didn't want to store the root on all nodes for performance reason. So if you want to implement it your way, I suggest you keep most of the logic and add the link to the parent tree in the iterator and rewrite append a bit.
[ "c++", "tree", "iterator" ]
6
5
19,642
2
0
2008-08-21T01:28:06.470000
2008-08-21T02:57:14.663000
19,245
19,396
IIS 6/COM+ hangs
I have a web application that sometimes just hangs over heavy load. To make it come back I have to kill the "dllhost.exe" process. Does someone know what to do? This is an Classic ASP (VBScript) app with lots of COM+ objects. The server has the following configuration: Intel Core 2 Duo 2.2 GHz / 4 GB RAM Windows Server 2003 Web Edition SP2 IIS 6.0 There is some errors in the event log related to the COM objects. But why errors in the COM objects would crash the whole server? The COM objects are PowerBuilder objects deployed as COM objects. Is IIS 7.0 (much) more stable than IIS 6.0?
Sounds like dodgy COM objects causing the problem.. do you load them into the "Application", if you do then are they threadsafe; or are they used and discarded on each request? Yes, recycling every few hours would help 'hide' the problem, but they ought to be debugged and fixed properly... have you tried divide/conquer to discover which COM object is the problem... I can imagine this is tricky on a production environment so you need to set up some heavy automated tests to reproduce the problem locally then you can do something about it.
IIS 6/COM+ hangs I have a web application that sometimes just hangs over heavy load. To make it come back I have to kill the "dllhost.exe" process. Does someone know what to do? This is an Classic ASP (VBScript) app with lots of COM+ objects. The server has the following configuration: Intel Core 2 Duo 2.2 GHz / 4 GB RAM Windows Server 2003 Web Edition SP2 IIS 6.0 There is some errors in the event log related to the COM objects. But why errors in the COM objects would crash the whole server? The COM objects are PowerBuilder objects deployed as COM objects. Is IIS 7.0 (much) more stable than IIS 6.0?
TITLE: IIS 6/COM+ hangs QUESTION: I have a web application that sometimes just hangs over heavy load. To make it come back I have to kill the "dllhost.exe" process. Does someone know what to do? This is an Classic ASP (VBScript) app with lots of COM+ objects. The server has the following configuration: Intel Core 2 Duo 2.2 GHz / 4 GB RAM Windows Server 2003 Web Edition SP2 IIS 6.0 There is some errors in the event log related to the COM objects. But why errors in the COM objects would crash the whole server? The COM objects are PowerBuilder objects deployed as COM objects. Is IIS 7.0 (much) more stable than IIS 6.0? ANSWER: Sounds like dodgy COM objects causing the problem.. do you load them into the "Application", if you do then are they threadsafe; or are they used and discarded on each request? Yes, recycling every few hours would help 'hide' the problem, but they ought to be debugged and fixed properly... have you tried divide/conquer to discover which COM object is the problem... I can imagine this is tricky on a production environment so you need to set up some heavy automated tests to reproduce the problem locally then you can do something about it.
[ "iis", "dll", "asp-classic", "crash" ]
4
2
1,801
3
0
2008-08-21T02:43:23.153000
2008-08-21T06:08:34.830000
19,280
19,290
Code to ask yes/no question in javascript
I could only find the function confirm() that gives OK/Cancel buttons. Is there any way to give Yes/No buttons?
Javascript offers 3 modal boxes. prompt, confirm and alert. None of those satisfy your request. There are a plethora of js modal popup solutions. Here's an example. ModalBox
Code to ask yes/no question in javascript I could only find the function confirm() that gives OK/Cancel buttons. Is there any way to give Yes/No buttons?
TITLE: Code to ask yes/no question in javascript QUESTION: I could only find the function confirm() that gives OK/Cancel buttons. Is there any way to give Yes/No buttons? ANSWER: Javascript offers 3 modal boxes. prompt, confirm and alert. None of those satisfy your request. There are a plethora of js modal popup solutions. Here's an example. ModalBox
[ "javascript" ]
22
7
19,679
7
0
2008-08-21T03:20:05.780000
2008-08-21T03:31:16.097000
19,294
19,306
Calling base Methods When Overriding Page Level Events
In my code behind I wire up my events like so: protected override void OnInit(EventArgs e) { base.OnInit(e); btnUpdateUser.Click += btnUpateUserClick; } I've done it this way because that's what I've seen in examples. Does the base.OnInit() method need to be called? Will it be implicitly be called? Is it better to call it at the beginning of the method or at the end? What would be an example where confusion over the base method can get you in trouble?
I should clarify: The guidelines recommend that firing an event should involve calling a virtual "On EventName " method, but they also say that if a derived class overrides that method and forgets to call the base method, the event should still fire. See the "Important Note" about halfway down this page: Derived classes that override the protected virtual method are not required to call the base class implementation. The base class must continue to work correctly even if its implementation is not called.
Calling base Methods When Overriding Page Level Events In my code behind I wire up my events like so: protected override void OnInit(EventArgs e) { base.OnInit(e); btnUpdateUser.Click += btnUpateUserClick; } I've done it this way because that's what I've seen in examples. Does the base.OnInit() method need to be called? Will it be implicitly be called? Is it better to call it at the beginning of the method or at the end? What would be an example where confusion over the base method can get you in trouble?
TITLE: Calling base Methods When Overriding Page Level Events QUESTION: In my code behind I wire up my events like so: protected override void OnInit(EventArgs e) { base.OnInit(e); btnUpdateUser.Click += btnUpateUserClick; } I've done it this way because that's what I've seen in examples. Does the base.OnInit() method need to be called? Will it be implicitly be called? Is it better to call it at the beginning of the method or at the end? What would be an example where confusion over the base method can get you in trouble? ANSWER: I should clarify: The guidelines recommend that firing an event should involve calling a virtual "On EventName " method, but they also say that if a derived class overrides that method and forgets to call the base method, the event should still fire. See the "Important Note" about halfway down this page: Derived classes that override the protected virtual method are not required to call the base class implementation. The base class must continue to work correctly even if its implementation is not called.
[ "asp.net", "events", "webforms" ]
3
3
5,440
6
0
2008-08-21T03:33:25.920000
2008-08-21T03:46:51.800000
19,295
19,308
Database backed i18n for java web-app
I'd like to use a database to store i18n key/value pairs so we can modify / reload the i18n data at runtime. Has anyone done this? Or does anyone have an idea of how to implement this? I've read several threads on this, but I haven't seen a workable solution. I'm specifically refering to something that would work with the jstl tags such as I think this will involve extending ResourceBundle, but when I tried this I ran into problems that had to do with the way the jstl tags get the resource bundle.
Are you just asking how to store UTF-8/16 characters in a DB? in mysql it's just a matter of making sure you build with UTF8 support and setting that as the default, or specifying it at the column or table level. I've done this in oracle and mysql before. Create a table and cut and paste some i18n data into it and see what happens... you might be set already.. or am I completely missing your point? edit: to be more explicit... I usually implement a three column table... language, key, value... where "value" contains potentially foreign language words or phrases... "language" contains some language key and "key" is an english key (i.e. login.error.password.dup)... language and key are indexed... I've then built interfaces on a structure like this that shows each key with all its translations (values)... it can get fancy and include audit trails and "dirty" markers and all the other stuff you need to enable translators and data entry folk to make use of it.. Edit 2: Now that you added the info about the JSTL tags, I understand a bit more... I've never done that myself.. but I found this old info on theserverside... HttpSession session =.. [get hold of the session] ResourceBundle bundle = new PropertyResourceBundle(toInputStream(myOwnProperties)) [toInputStream just stores the properties into an inputstream] Locale locale =.. [get hold of the locale] javax.servlet.jsp.jstl.core.Config.set(session, Config.FMT_LOCALIZATION_CONTEXT, new LocalizationContext(bundle,locale));
Database backed i18n for java web-app I'd like to use a database to store i18n key/value pairs so we can modify / reload the i18n data at runtime. Has anyone done this? Or does anyone have an idea of how to implement this? I've read several threads on this, but I haven't seen a workable solution. I'm specifically refering to something that would work with the jstl tags such as I think this will involve extending ResourceBundle, but when I tried this I ran into problems that had to do with the way the jstl tags get the resource bundle.
TITLE: Database backed i18n for java web-app QUESTION: I'd like to use a database to store i18n key/value pairs so we can modify / reload the i18n data at runtime. Has anyone done this? Or does anyone have an idea of how to implement this? I've read several threads on this, but I haven't seen a workable solution. I'm specifically refering to something that would work with the jstl tags such as I think this will involve extending ResourceBundle, but when I tried this I ran into problems that had to do with the way the jstl tags get the resource bundle. ANSWER: Are you just asking how to store UTF-8/16 characters in a DB? in mysql it's just a matter of making sure you build with UTF8 support and setting that as the default, or specifying it at the column or table level. I've done this in oracle and mysql before. Create a table and cut and paste some i18n data into it and see what happens... you might be set already.. or am I completely missing your point? edit: to be more explicit... I usually implement a three column table... language, key, value... where "value" contains potentially foreign language words or phrases... "language" contains some language key and "key" is an english key (i.e. login.error.password.dup)... language and key are indexed... I've then built interfaces on a structure like this that shows each key with all its translations (values)... it can get fancy and include audit trails and "dirty" markers and all the other stuff you need to enable translators and data entry folk to make use of it.. Edit 2: Now that you added the info about the JSTL tags, I understand a bit more... I've never done that myself.. but I found this old info on theserverside... HttpSession session =.. [get hold of the session] ResourceBundle bundle = new PropertyResourceBundle(toInputStream(myOwnProperties)) [toInputStream just stores the properties into an inputstream] Locale locale =.. [get hold of the locale] javax.servlet.jsp.jstl.core.Config.set(session, Config.FMT_LOCALIZATION_CONTEXT, new LocalizationContext(bundle,locale));
[ "java", "internationalization" ]
6
2
12,931
4
0
2008-08-21T03:36:38.110000
2008-08-21T03:48:51.590000
19,314
19,344
Alternatives to Windows Workflow Foundation?
I've been using WWF for a while as part of an internal call center application (ASP.NET), and while learning it was a good practice in understanding how a state machine based workflow system should work, I am definitely not in love with WWF itself. In my opinion it is: Overly complex, especially for use within web apps (all that threaded runtime stuff) Immature (ever worked with that horrible designer?) Anemic in its current feature set Does anyone have a suggestion for a better.NET based workflow framework? Specifically, I am looking for the following features: State machine based (mapping states to available actions) A focus on user permissions (controlling who has access to what actions) The ability to run workflows as timed background tasks (for example, to send out reminders for items that have been sitting in a certain state for x days) That's really all I need. I don't need to be able to "drag and drop" any activities or visually design the flow. I am perfectly comfortable writing actual code once a particular action is triggered.
You could try Simple State Machine. You would have to implement access control and background timers yourself, but that shouldn't be a big deal. SSM was also built out of frustration with WF. There are some other state machine implementations on Codeplex as well. If one of them doesn't fit he bill out of the box, they are open source and should get you close enough. I wholeheartedly agree with you about state machines in WF - they aren't testable, are too complicated, the threading model is peculiar and hard to follow, and I'm not sure a visual designer could have been more poorly conceived for designing state machines graphically. I think this may be because the state machine concept feels tacked onto the WF runtime, which was designed for sequential state machines, something WF does a much better job with, in my opinion. The problem is that state machines are really not the same animal as a sequential work flow, and should have been given a first class implementation of their own, because the warping of WF to make it seem to support them turned out to be more or less unsupportable, if not actually unusable.
Alternatives to Windows Workflow Foundation? I've been using WWF for a while as part of an internal call center application (ASP.NET), and while learning it was a good practice in understanding how a state machine based workflow system should work, I am definitely not in love with WWF itself. In my opinion it is: Overly complex, especially for use within web apps (all that threaded runtime stuff) Immature (ever worked with that horrible designer?) Anemic in its current feature set Does anyone have a suggestion for a better.NET based workflow framework? Specifically, I am looking for the following features: State machine based (mapping states to available actions) A focus on user permissions (controlling who has access to what actions) The ability to run workflows as timed background tasks (for example, to send out reminders for items that have been sitting in a certain state for x days) That's really all I need. I don't need to be able to "drag and drop" any activities or visually design the flow. I am perfectly comfortable writing actual code once a particular action is triggered.
TITLE: Alternatives to Windows Workflow Foundation? QUESTION: I've been using WWF for a while as part of an internal call center application (ASP.NET), and while learning it was a good practice in understanding how a state machine based workflow system should work, I am definitely not in love with WWF itself. In my opinion it is: Overly complex, especially for use within web apps (all that threaded runtime stuff) Immature (ever worked with that horrible designer?) Anemic in its current feature set Does anyone have a suggestion for a better.NET based workflow framework? Specifically, I am looking for the following features: State machine based (mapping states to available actions) A focus on user permissions (controlling who has access to what actions) The ability to run workflows as timed background tasks (for example, to send out reminders for items that have been sitting in a certain state for x days) That's really all I need. I don't need to be able to "drag and drop" any activities or visually design the flow. I am perfectly comfortable writing actual code once a particular action is triggered. ANSWER: You could try Simple State Machine. You would have to implement access control and background timers yourself, but that shouldn't be a big deal. SSM was also built out of frustration with WF. There are some other state machine implementations on Codeplex as well. If one of them doesn't fit he bill out of the box, they are open source and should get you close enough. I wholeheartedly agree with you about state machines in WF - they aren't testable, are too complicated, the threading model is peculiar and hard to follow, and I'm not sure a visual designer could have been more poorly conceived for designing state machines graphically. I think this may be because the state machine concept feels tacked onto the WF runtime, which was designed for sequential state machines, something WF does a much better job with, in my opinion. The problem is that state machines are really not the same animal as a sequential work flow, and should have been given a first class implementation of their own, because the warping of WF to make it seem to support them turned out to be more or less unsupportable, if not actually unusable.
[ "asp.net", "workflow" ]
15
14
10,295
9
0
2008-08-21T03:58:11.507000
2008-08-21T04:38:42.127000
19,318
19,328
Calling ASP.NET web service from ASP using SOAPClient
I have an ASP.NET webservice with along the lines of: [WebService(Namespace = "http://internalservice.net/messageprocessing")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ToolboxItem(false)] public class ProvisioningService: WebService { [WebMethod] public XmlDocument ProcessMessage(XmlDocument message) { //... do stuff } } I am calling the web service from ASP using something like: provWSDL = "http://servername:12011/MessageProcessor.asmx?wsdl" Set service = CreateObject("MSSOAP.SoapClient30") service.ClientProperty("ServerHTTPRequest") = True Call service.MSSoapInit(provWSDL) xmlMessage = "....various xml " result = service.ProcessMessage(xmlMessage) The problem I am encountering is that when the XML reaches the ProcessMessage method, the web service plumbing has added a default namespace along the way. i.e. if I set a breakpoint inside ProcessMessage(XmlDocument message) I see:....various xml When I capture packets on the wire I can see that the XML sent by the SOAP toolkit is slightly different from that sent by the.NET WS client. The SOAP toolkit sends:...stuff to do Whilst the.NET client sends:...stuff to do It's been so long since I used the ASP/SOAP toolkit to call into.NET webservices, I can't remember all the clever tricks/SOAP-fu I used to pull to get around stuff like this. Any ideas? One solution is to knock up a COM callable.NET proxy that takes the XML as a string param and calls the WS on my behalf, but it's an extra layer of complexity/work I hoped not to do.
I solved this: The SOAP client request node was picking up the default namespace from: Adding an empty default namespace to the XML sent by the ASP client overrides this behaviour: xmlMessage = "....various xml "
Calling ASP.NET web service from ASP using SOAPClient I have an ASP.NET webservice with along the lines of: [WebService(Namespace = "http://internalservice.net/messageprocessing")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ToolboxItem(false)] public class ProvisioningService: WebService { [WebMethod] public XmlDocument ProcessMessage(XmlDocument message) { //... do stuff } } I am calling the web service from ASP using something like: provWSDL = "http://servername:12011/MessageProcessor.asmx?wsdl" Set service = CreateObject("MSSOAP.SoapClient30") service.ClientProperty("ServerHTTPRequest") = True Call service.MSSoapInit(provWSDL) xmlMessage = "....various xml " result = service.ProcessMessage(xmlMessage) The problem I am encountering is that when the XML reaches the ProcessMessage method, the web service plumbing has added a default namespace along the way. i.e. if I set a breakpoint inside ProcessMessage(XmlDocument message) I see:....various xml When I capture packets on the wire I can see that the XML sent by the SOAP toolkit is slightly different from that sent by the.NET WS client. The SOAP toolkit sends:...stuff to do Whilst the.NET client sends:...stuff to do It's been so long since I used the ASP/SOAP toolkit to call into.NET webservices, I can't remember all the clever tricks/SOAP-fu I used to pull to get around stuff like this. Any ideas? One solution is to knock up a COM callable.NET proxy that takes the XML as a string param and calls the WS on my behalf, but it's an extra layer of complexity/work I hoped not to do.
TITLE: Calling ASP.NET web service from ASP using SOAPClient QUESTION: I have an ASP.NET webservice with along the lines of: [WebService(Namespace = "http://internalservice.net/messageprocessing")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ToolboxItem(false)] public class ProvisioningService: WebService { [WebMethod] public XmlDocument ProcessMessage(XmlDocument message) { //... do stuff } } I am calling the web service from ASP using something like: provWSDL = "http://servername:12011/MessageProcessor.asmx?wsdl" Set service = CreateObject("MSSOAP.SoapClient30") service.ClientProperty("ServerHTTPRequest") = True Call service.MSSoapInit(provWSDL) xmlMessage = "....various xml " result = service.ProcessMessage(xmlMessage) The problem I am encountering is that when the XML reaches the ProcessMessage method, the web service plumbing has added a default namespace along the way. i.e. if I set a breakpoint inside ProcessMessage(XmlDocument message) I see:....various xml When I capture packets on the wire I can see that the XML sent by the SOAP toolkit is slightly different from that sent by the.NET WS client. The SOAP toolkit sends:...stuff to do Whilst the.NET client sends:...stuff to do It's been so long since I used the ASP/SOAP toolkit to call into.NET webservices, I can't remember all the clever tricks/SOAP-fu I used to pull to get around stuff like this. Any ideas? One solution is to knock up a COM callable.NET proxy that takes the XML as a string param and calls the WS on my behalf, but it's an extra layer of complexity/work I hoped not to do. ANSWER: I solved this: The SOAP client request node was picking up the default namespace from: Adding an empty default namespace to the XML sent by the ASP client overrides this behaviour: xmlMessage = "....various xml "
[ ".net", "asp.net", "web-services", "soap", "asp-classic" ]
3
0
13,802
3
0
2008-08-21T04:07:59.253000
2008-08-21T04:18:45.200000
19,339
19,343
Transpose/Unzip Function (inverse of zip)?
I have a list of 2-item tuples and I'd like to convert them to 2 lists where the first contains the first item in each tuple and the second list holds the second item. For example: original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)] # and I want to become... result = (['a', 'b', 'c', 'd'], [1, 2, 3, 4]) Is there a builtin function that does that?
In 2.x, zip is its own inverse! Provided you use the special * operator. >>> zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)]) [('a', 'b', 'c', 'd'), (1, 2, 3, 4)] This is equivalent to calling zip with each element of the list as a separate argument: zip(('a', 1), ('b', 2), ('c', 3), ('d', 4)) except the arguments are passed to zip directly (after being converted to a tuple), so there's no need to worry about the number of arguments getting too big. In 3.x, zip returns a lazy iterator, but this is trivially converted: >>> list(zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)])) [('a', 'b', 'c', 'd'), (1, 2, 3, 4)]
Transpose/Unzip Function (inverse of zip)? I have a list of 2-item tuples and I'd like to convert them to 2 lists where the first contains the first item in each tuple and the second list holds the second item. For example: original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)] # and I want to become... result = (['a', 'b', 'c', 'd'], [1, 2, 3, 4]) Is there a builtin function that does that?
TITLE: Transpose/Unzip Function (inverse of zip)? QUESTION: I have a list of 2-item tuples and I'd like to convert them to 2 lists where the first contains the first item in each tuple and the second list holds the second item. For example: original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)] # and I want to become... result = (['a', 'b', 'c', 'd'], [1, 2, 3, 4]) Is there a builtin function that does that? ANSWER: In 2.x, zip is its own inverse! Provided you use the special * operator. >>> zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)]) [('a', 'b', 'c', 'd'), (1, 2, 3, 4)] This is equivalent to calling zip with each element of the list as a separate argument: zip(('a', 1), ('b', 2), ('c', 3), ('d', 4)) except the arguments are passed to zip directly (after being converted to a tuple), so there's no need to worry about the number of arguments getting too big. In 3.x, zip returns a lazy iterator, but this is trivially converted: >>> list(zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)])) [('a', 'b', 'c', 'd'), (1, 2, 3, 4)]
[ "python", "list", "matrix", "transpose" ]
606
910
208,550
14
0
2008-08-21T04:29:07.580000
2008-08-21T04:36:29.590000
19,347
19,372
What is the best way to go from Java/C# to C++?
At my university most of my classes have been in Java. I have also recently learned C# (and the Visual Studio environment) at a summer internship. Now I'm taking an Intro to Computer Graphics class and the grad student teaching the class prefers us to use C++ to access the OpenGL bindings via GLUT. Does anyone have any good resources on how to make a good transition from Java/C# to C++? Obviously pointers are going to be a big issue, but any other things I should be looking out for? Any tutorials, guides, etc. would be very helpful! Thanks!
Yeah, I got bit by the same bug. The university tended to lean on Java, and then allowed you to choose the language you wanted to work with during projects. The best way is to just jump in. Start small, take baby steps, and just Google things that confuse you when you get there. Also find projects that have released their source code. See how they structure their programs. Basically, just tinker with concepts. There is plenty of information around the web. Make it fun and grab a C++ game development book so it doesn't become mind numbing too quickly. Here's some places that I found useful while learning http://www.cprogramming.com/ http://www.wikipedia.com http://www.cplusplus.com/
What is the best way to go from Java/C# to C++? At my university most of my classes have been in Java. I have also recently learned C# (and the Visual Studio environment) at a summer internship. Now I'm taking an Intro to Computer Graphics class and the grad student teaching the class prefers us to use C++ to access the OpenGL bindings via GLUT. Does anyone have any good resources on how to make a good transition from Java/C# to C++? Obviously pointers are going to be a big issue, but any other things I should be looking out for? Any tutorials, guides, etc. would be very helpful! Thanks!
TITLE: What is the best way to go from Java/C# to C++? QUESTION: At my university most of my classes have been in Java. I have also recently learned C# (and the Visual Studio environment) at a summer internship. Now I'm taking an Intro to Computer Graphics class and the grad student teaching the class prefers us to use C++ to access the OpenGL bindings via GLUT. Does anyone have any good resources on how to make a good transition from Java/C# to C++? Obviously pointers are going to be a big issue, but any other things I should be looking out for? Any tutorials, guides, etc. would be very helpful! Thanks! ANSWER: Yeah, I got bit by the same bug. The university tended to lean on Java, and then allowed you to choose the language you wanted to work with during projects. The best way is to just jump in. Start small, take baby steps, and just Google things that confuse you when you get there. Also find projects that have released their source code. See how they structure their programs. Basically, just tinker with concepts. There is plenty of information around the web. Make it fun and grab a C++ game development book so it doesn't become mind numbing too quickly. Here's some places that I found useful while learning http://www.cprogramming.com/ http://www.wikipedia.com http://www.cplusplus.com/
[ "c#", "java", "c++", "visual-studio" ]
10
8
946
10
0
2008-08-21T04:46:02.313000
2008-08-21T05:25:22.373000
19,349
19,367
"Data Execution Prevention" kills (VS2008) local ASP.Net Development Server (aka Cassini) on Vista 64
Occasionally, I find that while debugging an ASP.Net application (written in visual studio 2008, running on Vista 64-bit) the local ASP.Net development server (i.e. 'Cassini') stops responding. A message often comes up telling me that "Data Execution Prevention (DEP)" has killed WebDev.WebServer.exe The event logs simply tell me that "WebDev.WebServer.exe has stopped working" I've heard that this 'problem' presents itself more often on Vista 64-bit because DEP is on by default. Hence, turning DEP off may 'solve' the problem. But i'm wondering: Is there a known bug/situation with Cassini that causes DEP to kill the process? Alternatively, what is the practical danger of disabling Data Execution Prevention?
The only way to know for sure would be to dig through the Cassini source and see if there are any areas where it generates code on the heap and then executes it without clearing the NX flag. However, instead of doing that, why not use IIS? EDIT: The danger of disabling DEP is that you open up security holes. DEP works by not allowing arbitrary generated code on the heap to be executed. This helps prevent malware programs from inserting code into the data segments of legit programs.
"Data Execution Prevention" kills (VS2008) local ASP.Net Development Server (aka Cassini) on Vista 64 Occasionally, I find that while debugging an ASP.Net application (written in visual studio 2008, running on Vista 64-bit) the local ASP.Net development server (i.e. 'Cassini') stops responding. A message often comes up telling me that "Data Execution Prevention (DEP)" has killed WebDev.WebServer.exe The event logs simply tell me that "WebDev.WebServer.exe has stopped working" I've heard that this 'problem' presents itself more often on Vista 64-bit because DEP is on by default. Hence, turning DEP off may 'solve' the problem. But i'm wondering: Is there a known bug/situation with Cassini that causes DEP to kill the process? Alternatively, what is the practical danger of disabling Data Execution Prevention?
TITLE: "Data Execution Prevention" kills (VS2008) local ASP.Net Development Server (aka Cassini) on Vista 64 QUESTION: Occasionally, I find that while debugging an ASP.Net application (written in visual studio 2008, running on Vista 64-bit) the local ASP.Net development server (i.e. 'Cassini') stops responding. A message often comes up telling me that "Data Execution Prevention (DEP)" has killed WebDev.WebServer.exe The event logs simply tell me that "WebDev.WebServer.exe has stopped working" I've heard that this 'problem' presents itself more often on Vista 64-bit because DEP is on by default. Hence, turning DEP off may 'solve' the problem. But i'm wondering: Is there a known bug/situation with Cassini that causes DEP to kill the process? Alternatively, what is the practical danger of disabling Data Execution Prevention? ANSWER: The only way to know for sure would be to dig through the Cassini source and see if there are any areas where it generates code on the heap and then executes it without clearing the NX flag. However, instead of doing that, why not use IIS? EDIT: The danger of disabling DEP is that you open up security holes. DEP works by not allowing arbitrary generated code on the heap to be executed. This helps prevent malware programs from inserting code into the data segments of legit programs.
[ "asp.net", "cassini", "dep" ]
3
3
1,298
5
0
2008-08-21T04:50:13.720000
2008-08-21T05:15:01.073000
19,353
19,373
Detecting audio silence in WAV files using C#
I'm tasked with building a.NET client app to detect silence in a WAV files. Is this possible with the built-in Windows APIs? Or alternately, any good libraries out there to help with this?
Audio analysis is a difficult thing requiring a lot of complex math (think Fourier Transforms). The question you have to ask is "what is silence". If the audio that you are trying to edit is captured from an analog source, the chances are that there isn't any silence... they will only be areas of soft noise (line hum, ambient background noise, etc). All that said, an algorithm that should work would be to determine a minimum volume (amplitude) threshold and duration (say, <10dbA for more than 2 seconds) and then simply do a volume analysis of the waveform looking for areas that meet this criteria (with perhaps some filters for millisecond spikes). I've never written this in C#, but this CodeProject article looks interesting; it describes C# code to draw a waveform... that is the same kind of code which could be used to do other amplitude analysis.
Detecting audio silence in WAV files using C# I'm tasked with building a.NET client app to detect silence in a WAV files. Is this possible with the built-in Windows APIs? Or alternately, any good libraries out there to help with this?
TITLE: Detecting audio silence in WAV files using C# QUESTION: I'm tasked with building a.NET client app to detect silence in a WAV files. Is this possible with the built-in Windows APIs? Or alternately, any good libraries out there to help with this? ANSWER: Audio analysis is a difficult thing requiring a lot of complex math (think Fourier Transforms). The question you have to ask is "what is silence". If the audio that you are trying to edit is captured from an analog source, the chances are that there isn't any silence... they will only be areas of soft noise (line hum, ambient background noise, etc). All that said, an algorithm that should work would be to determine a minimum volume (amplitude) threshold and duration (say, <10dbA for more than 2 seconds) and then simply do a volume analysis of the waveform looking for areas that meet this criteria (with perhaps some filters for millisecond spikes). I've never written this in C#, but this CodeProject article looks interesting; it describes C# code to draw a waveform... that is the same kind of code which could be used to do other amplitude analysis.
[ "c#", ".net", "audio" ]
33
14
34,153
8
0
2008-08-21T04:56:33.380000
2008-08-21T05:30:09.740000
19,355
19,361
How to manage Configuration Settings for each Developer
In a.NET project, say you have a configuration setting - like a connection string - stored in a app.config file, which is different for each developer on your team (they may be using a local SQL Server, or a specific server instance, or using a remote server, etc). How can you structure your solution so that each developer can have their own development "preferences" (i.e. not checked into source control), but provide a default connection string that is checked into source control (thereby supplying the correct defaults for a build process or new developers). Edit: Can the " file " method suggested by @Jonathon be somehow used with the connectionStrings section?
AppSettings can be overridden with a local file: This allows for each developer to keep their own local settings. As far as the connection string, in a perfect world all developers should connect to a test DB, not run SQL Server each. However, I've found it best to keep a file named Web.Config.Prd in source control, and use that for build deployments. If someone modifies web.config, they must also add the change to the.PRD file...There is no good automation there:(
How to manage Configuration Settings for each Developer In a.NET project, say you have a configuration setting - like a connection string - stored in a app.config file, which is different for each developer on your team (they may be using a local SQL Server, or a specific server instance, or using a remote server, etc). How can you structure your solution so that each developer can have their own development "preferences" (i.e. not checked into source control), but provide a default connection string that is checked into source control (thereby supplying the correct defaults for a build process or new developers). Edit: Can the " file " method suggested by @Jonathon be somehow used with the connectionStrings section?
TITLE: How to manage Configuration Settings for each Developer QUESTION: In a.NET project, say you have a configuration setting - like a connection string - stored in a app.config file, which is different for each developer on your team (they may be using a local SQL Server, or a specific server instance, or using a remote server, etc). How can you structure your solution so that each developer can have their own development "preferences" (i.e. not checked into source control), but provide a default connection string that is checked into source control (thereby supplying the correct defaults for a build process or new developers). Edit: Can the " file " method suggested by @Jonathon be somehow used with the connectionStrings section? ANSWER: AppSettings can be overridden with a local file: This allows for each developer to keep their own local settings. As far as the connection string, in a perfect world all developers should connect to a test DB, not run SQL Server each. However, I've found it best to keep a file named Web.Config.Prd in source control, and use that for build deployments. If someone modifies web.config, they must also add the change to the.PRD file...There is no good automation there:(
[ ".net", "configuration-files" ]
3
4
764
5
0
2008-08-21T04:59:53.700000
2008-08-21T05:05:24.370000
19,358
34,213
Experience documentation about Shared Nothing Architecture
Do you have any experience of designing a Real Shared-Nothing Architecture? Would you have some readings to recommend me?
Building Scalable Web Sites by Flickr architect Cal Henderson is pretty much the holy book for scalable web architectures. The presentations by Brad Fitzpatrick of Danga Interactive, creators of LiveJournal, are also excellent case studies. Check out this one first.
Experience documentation about Shared Nothing Architecture Do you have any experience of designing a Real Shared-Nothing Architecture? Would you have some readings to recommend me?
TITLE: Experience documentation about Shared Nothing Architecture QUESTION: Do you have any experience of designing a Real Shared-Nothing Architecture? Would you have some readings to recommend me? ANSWER: Building Scalable Web Sites by Flickr architect Cal Henderson is pretty much the holy book for scalable web architectures. The presentations by Brad Fitzpatrick of Danga Interactive, creators of LiveJournal, are also excellent case studies. Check out this one first.
[ "architecture", "shared-nothing" ]
1
4
1,012
3
0
2008-08-21T05:02:08.310000
2008-08-29T09:06:21.607000
19,387
19,392
Rich GUI OS X Frameworks?
What would you recommend for OS X development of a graphical application like those possible in WPF? My specific background is in Smalltalk & Java, but I currently work mostly in DHTML/.NET (ASP.NET/C#).
Cocoa. Considered by many to be the best application framework ever. The language is Objective-C, SmallTalk-like language that inspired the creators of Java. Really, there is no reasonable alternative to Cocoa for OS X development, unless you have specific needs like wanting to be cross-platform.
Rich GUI OS X Frameworks? What would you recommend for OS X development of a graphical application like those possible in WPF? My specific background is in Smalltalk & Java, but I currently work mostly in DHTML/.NET (ASP.NET/C#).
TITLE: Rich GUI OS X Frameworks? QUESTION: What would you recommend for OS X development of a graphical application like those possible in WPF? My specific background is in Smalltalk & Java, but I currently work mostly in DHTML/.NET (ASP.NET/C#). ANSWER: Cocoa. Considered by many to be the best application framework ever. The language is Objective-C, SmallTalk-like language that inspired the creators of Java. Really, there is no reasonable alternative to Cocoa for OS X development, unless you have specific needs like wanting to be cross-platform.
[ "wpf", "user-interface", "macos", "frameworks" ]
6
15
2,236
8
0
2008-08-21T05:57:14.857000
2008-08-21T06:01:20.353000
19,388
19,403
GOTO command in PHP?
I've heard rumors that PHP is planning on introducing a "goto" command. What is it supposed to be doing? I've tried searching a bit, but haven't found anything awfully descriptive. I understand that it won't be a " GOTO 10 "-like command...
They are not adding a real GOTO, but extending the BREAK keyword to use static labels. Basically, it will be enhancing the ability to break out of switch nested if statements. Here's the concept example I found: Of course, once the GOTO "rumor" was out, there was nothing to stop some evil guys to propagate an additional COMEFROM joke. Be on your toes. See also: http://www.php.net/~derick/meeting-notes.html#adding-goto
GOTO command in PHP? I've heard rumors that PHP is planning on introducing a "goto" command. What is it supposed to be doing? I've tried searching a bit, but haven't found anything awfully descriptive. I understand that it won't be a " GOTO 10 "-like command...
TITLE: GOTO command in PHP? QUESTION: I've heard rumors that PHP is planning on introducing a "goto" command. What is it supposed to be doing? I've tried searching a bit, but haven't found anything awfully descriptive. I understand that it won't be a " GOTO 10 "-like command... ANSWER: They are not adding a real GOTO, but extending the BREAK keyword to use static labels. Basically, it will be enhancing the ability to break out of switch nested if statements. Here's the concept example I found: Of course, once the GOTO "rumor" was out, there was nothing to stop some evil guys to propagate an additional COMEFROM joke. Be on your toes. See also: http://www.php.net/~derick/meeting-notes.html#adding-goto
[ "php", "language-features", "goto" ]
5
9
3,503
7
0
2008-08-21T05:57:59.673000
2008-08-21T06:14:47.763000
19,409
19,453
Incrementing from 0 to 100 in assembly language
This is kinda oddball, but I was poking around with the GNU assembler today (I want to be able to at least read the syntax), and was trying to get this little contrived example of mine to work. Namely I just want to go from 0 to 100, printing out numbers all the while. So a few minutes later I come up with this: # count.s: print the numbers from 0 to 100..text string:.asciz "%d\n".globl _main _main: movl $0, %eax # The starting point/current value. movl $100, %ebx # The ending point. _loop: # Display the current value. pushl %eax pushl $string call _printf addl $8, %esp # Check against the ending value. cmpl %eax, %ebx je _end # Increment the current value. incl %eax jmp _loop _end: All I get from this is 3 printed over and over again. Like I said, just a little contrived example, so don't worry too much about it, it's not a life or death problem. (The formatting's a little messed up, but nothing major).
You can't trust what any called procedure does to any of the registers. Either push the registers onto the stack and pop them back off after calling printf or have the increment and end point values held in memory and read/written into registers as you need them. I hope the following works. I'm assuming that pushl has an equivalant popl and you can push an extra couple of numbers onto the stack. # count.s: print the numbers from 0 to 100..text string:.asciz "%d\n".globl _main _main: movl $0, %eax # The starting point/current value. movl $100, %ebx # The ending point. _loop: # Remember your registers. pushl %eax pushl %ebx # Display the current value. pushl %eax pushl $string call _printf addl $8, %esp # reinstate registers. popl %ebx popl %eax # Check against the ending value. cmpl %eax, %ebx je _end # Increment the current value. incl %eax jmp _loop _end:
Incrementing from 0 to 100 in assembly language This is kinda oddball, but I was poking around with the GNU assembler today (I want to be able to at least read the syntax), and was trying to get this little contrived example of mine to work. Namely I just want to go from 0 to 100, printing out numbers all the while. So a few minutes later I come up with this: # count.s: print the numbers from 0 to 100..text string:.asciz "%d\n".globl _main _main: movl $0, %eax # The starting point/current value. movl $100, %ebx # The ending point. _loop: # Display the current value. pushl %eax pushl $string call _printf addl $8, %esp # Check against the ending value. cmpl %eax, %ebx je _end # Increment the current value. incl %eax jmp _loop _end: All I get from this is 3 printed over and over again. Like I said, just a little contrived example, so don't worry too much about it, it's not a life or death problem. (The formatting's a little messed up, but nothing major).
TITLE: Incrementing from 0 to 100 in assembly language QUESTION: This is kinda oddball, but I was poking around with the GNU assembler today (I want to be able to at least read the syntax), and was trying to get this little contrived example of mine to work. Namely I just want to go from 0 to 100, printing out numbers all the while. So a few minutes later I come up with this: # count.s: print the numbers from 0 to 100..text string:.asciz "%d\n".globl _main _main: movl $0, %eax # The starting point/current value. movl $100, %ebx # The ending point. _loop: # Display the current value. pushl %eax pushl $string call _printf addl $8, %esp # Check against the ending value. cmpl %eax, %ebx je _end # Increment the current value. incl %eax jmp _loop _end: All I get from this is 3 printed over and over again. Like I said, just a little contrived example, so don't worry too much about it, it's not a life or death problem. (The formatting's a little messed up, but nothing major). ANSWER: You can't trust what any called procedure does to any of the registers. Either push the registers onto the stack and pop them back off after calling printf or have the increment and end point values held in memory and read/written into registers as you need them. I hope the following works. I'm assuming that pushl has an equivalant popl and you can push an extra couple of numbers onto the stack. # count.s: print the numbers from 0 to 100..text string:.asciz "%d\n".globl _main _main: movl $0, %eax # The starting point/current value. movl $100, %ebx # The ending point. _loop: # Remember your registers. pushl %eax pushl %ebx # Display the current value. pushl %eax pushl $string call _printf addl $8, %esp # reinstate registers. popl %ebx popl %eax # Check against the ending value. cmpl %eax, %ebx je _end # Increment the current value. incl %eax jmp _loop _end:
[ "gnu-assembler", "assembly" ]
8
12
9,310
6
0
2008-08-21T06:20:08.233000
2008-08-21T07:47:00.007000
19,412
19,419
How to request a random row in SQL?
How can I request a random row (or as close to truly random as possible) in pure SQL?
See this post: SQL to Select a random row from a database table. It goes through methods for doing this in MySQL, PostgreSQL, Microsoft SQL Server, IBM DB2 and Oracle (the following is copied from that link): Select a random row with MySQL: SELECT column FROM table ORDER BY RAND() LIMIT 1 Select a random row with PostgreSQL: SELECT column FROM table ORDER BY RANDOM() LIMIT 1 Select a random row with Microsoft SQL Server: SELECT TOP 1 column FROM table ORDER BY NEWID() Select a random row with IBM DB2 SELECT column, RAND() as IDX FROM table ORDER BY IDX FETCH FIRST 1 ROWS ONLY Select a random record with Oracle: SELECT column FROM ( SELECT column FROM table ORDER BY dbms_random.value ) WHERE rownum = 1
How to request a random row in SQL? How can I request a random row (or as close to truly random as possible) in pure SQL?
TITLE: How to request a random row in SQL? QUESTION: How can I request a random row (or as close to truly random as possible) in pure SQL? ANSWER: See this post: SQL to Select a random row from a database table. It goes through methods for doing this in MySQL, PostgreSQL, Microsoft SQL Server, IBM DB2 and Oracle (the following is copied from that link): Select a random row with MySQL: SELECT column FROM table ORDER BY RAND() LIMIT 1 Select a random row with PostgreSQL: SELECT column FROM table ORDER BY RANDOM() LIMIT 1 Select a random row with Microsoft SQL Server: SELECT TOP 1 column FROM table ORDER BY NEWID() Select a random row with IBM DB2 SELECT column, RAND() as IDX FROM table ORDER BY IDX FETCH FIRST 1 ROWS ONLY Select a random record with Oracle: SELECT column FROM ( SELECT column FROM table ORDER BY dbms_random.value ) WHERE rownum = 1
[ "sql", "random" ]
609
877
587,341
32
0
2008-08-21T06:28:49.927000
2008-08-21T06:32:32.853000
19,433
19,467
What is a good free library for editing MP3s/FLACs?
What is a good free library for editing MP3s/FLACs. By editing I mean: Cutting audio file into multiple parts Joining multiple audio files together Increase playback speed of file without affecting the pitch (eg. podcasts up to 1.3x) Re-encoding audio file from Flac -> MP3 or vice versa I don't mean software, I mean a library that I can use within another application. Programming language agnostic.
Just about every language has bindings to C, so you'll probably want to get the applicable C libraries for encoding/decoding mp3's and FLAC files. This list might include libFLAC http://flac.sourceforge.net/api/index.html FLAC encoding/decoding LAME http://lame.sourceforge.net/index.php MP3 encoding MAD http://www.underbit.com/products/mad/ MP3 decoding The rest of your signal processing needs could be gathered around a single popular API such as LADSPA http://www.ladspa.org/. Here's a stretching / pitch shifting library: http://www.breakfastquay.com/rubberband/ Most audio processing programs have a certain internal format they use. That keeps things simple. Everything coming in gets converted to the same format. Once you've standardized the internal format, cutting and splicing audio data is about as difficult as cutting and splicing strings. You don't really need a library for that.
What is a good free library for editing MP3s/FLACs? What is a good free library for editing MP3s/FLACs. By editing I mean: Cutting audio file into multiple parts Joining multiple audio files together Increase playback speed of file without affecting the pitch (eg. podcasts up to 1.3x) Re-encoding audio file from Flac -> MP3 or vice versa I don't mean software, I mean a library that I can use within another application. Programming language agnostic.
TITLE: What is a good free library for editing MP3s/FLACs? QUESTION: What is a good free library for editing MP3s/FLACs. By editing I mean: Cutting audio file into multiple parts Joining multiple audio files together Increase playback speed of file without affecting the pitch (eg. podcasts up to 1.3x) Re-encoding audio file from Flac -> MP3 or vice versa I don't mean software, I mean a library that I can use within another application. Programming language agnostic. ANSWER: Just about every language has bindings to C, so you'll probably want to get the applicable C libraries for encoding/decoding mp3's and FLAC files. This list might include libFLAC http://flac.sourceforge.net/api/index.html FLAC encoding/decoding LAME http://lame.sourceforge.net/index.php MP3 encoding MAD http://www.underbit.com/products/mad/ MP3 decoding The rest of your signal processing needs could be gathered around a single popular API such as LADSPA http://www.ladspa.org/. Here's a stretching / pitch shifting library: http://www.breakfastquay.com/rubberband/ Most audio processing programs have a certain internal format they use. That keeps things simple. Everything coming in gets converted to the same format. Once you've standardized the internal format, cutting and splicing audio data is about as difficult as cutting and splicing strings. You don't really need a library for that.
[ "audio" ]
4
5
697
3
0
2008-08-21T07:06:38.153000
2008-08-21T08:08:21.763000
19,436
19,447
Delete Datalist row with multiple primary keys
I have a datalist with a OnDeleteCommand="Delete_Command". I want the delete a record with multiple primary Keys but I do not know how to access it from the Delete_Command event. If I use DataKeyField I'm limited to only one key. Any workarounds for this?
You can access all of the keys: gridView.DataKeys[rowNum][dataKeyName] where rowNum is e.RowIndex from the gridView_RowDeleting event handler, and dataKeyName is the key you want to get: protected void gridView_RowDeleting(object sender, GridViewDeleteEventArgs e) { gridView.DataKeys[e.RowIndex]["userid"]... gridView.DataKeys[e.RowIndex]["id1"]... gridView.DataKeys[e.RowIndex]["id2"]... gridView.DataKeys[e.RowIndex]["id3"]... }
Delete Datalist row with multiple primary keys I have a datalist with a OnDeleteCommand="Delete_Command". I want the delete a record with multiple primary Keys but I do not know how to access it from the Delete_Command event. If I use DataKeyField I'm limited to only one key. Any workarounds for this?
TITLE: Delete Datalist row with multiple primary keys QUESTION: I have a datalist with a OnDeleteCommand="Delete_Command". I want the delete a record with multiple primary Keys but I do not know how to access it from the Delete_Command event. If I use DataKeyField I'm limited to only one key. Any workarounds for this? ANSWER: You can access all of the keys: gridView.DataKeys[rowNum][dataKeyName] where rowNum is e.RowIndex from the gridView_RowDeleting event handler, and dataKeyName is the key you want to get: protected void gridView_RowDeleting(object sender, GridViewDeleteEventArgs e) { gridView.DataKeys[e.RowIndex]["userid"]... gridView.DataKeys[e.RowIndex]["id1"]... gridView.DataKeys[e.RowIndex]["id2"]... gridView.DataKeys[e.RowIndex]["id3"]... }
[ "asp.net" ]
4
1
2,360
2
0
2008-08-21T07:13:24.487000
2008-08-21T07:31:42.600000
19,437
19,444
Custom font in SQL Server 2005 Reporting Services
I'm having issues with my SQL Reporting Services reports. I'm using a custom font for report headers, and when deployed to the server it does not render correctly when I print or export to PDF/TIFF. I have installed the font on the server. Is there anything else I need to do in order to use custom fonts? When viewing the font in the browser it looks correct - since all client computers have the font installed... Thanks Ryan, your post to the FAQ solved the problem. Installing the fonts on the server fixes the print problem, as well as problems with charts (which are also rendered on the server). Like you point out (as well as being mentioned in the FAQ) Reporting Services 2005 does not do font embedding in PDF files. I guess that is okay for now - the most important part was being able to hit print and get the correct fonts. The reason the fonts didn't show up straight away is answered in the FAQ: Q: I've installed the font on my client/server but I still see?'s or black boxes. Why? A: For the client machine, closing all instances of the PDF viewer then reopening them should fix the issue. For the server, restarting the services should allow the PDF renderer to pick up the new font information. Unfortunately, I have also seen times where I needed a full machine reboot to get the client/server to recognize the newly installed font.
The PDF files served up from SSRS, like many PDF files, have embedded postscript fonts. So, the local fonts used in the report are converted to a best matching postscript font when the conversion takes place so the PDF is totally portable without relying on locally installed fonts. You can see the official MS guidelines and font requirements for SSRS PDF exports here: SQL Server 2005 Books Online (September 2007) Designing for PDF Output. Also, this post should provide some help as well: Reporting Services: PDF Renderer FAQ Aspose apparently also has a component that claims to be able to add custom embedded fonts in SQL Report PDFs. See Aspose.Pdf for Reporting Services Aspose.Pdf for Reporting Services makes it possible generating PDF reports in Microsoft SQL Server 2000 and 2005 Reporting Services. Some advanced features like XMP metadata, custom embedded font and rendering watermark for pages are now supported. All RDL report features including sections, images, charts, tables, matrices, headers and footers are converted with the highest degree of precision to PDF. I've not tried this component, so I can only share what it claims to be able to do.
Custom font in SQL Server 2005 Reporting Services I'm having issues with my SQL Reporting Services reports. I'm using a custom font for report headers, and when deployed to the server it does not render correctly when I print or export to PDF/TIFF. I have installed the font on the server. Is there anything else I need to do in order to use custom fonts? When viewing the font in the browser it looks correct - since all client computers have the font installed... Thanks Ryan, your post to the FAQ solved the problem. Installing the fonts on the server fixes the print problem, as well as problems with charts (which are also rendered on the server). Like you point out (as well as being mentioned in the FAQ) Reporting Services 2005 does not do font embedding in PDF files. I guess that is okay for now - the most important part was being able to hit print and get the correct fonts. The reason the fonts didn't show up straight away is answered in the FAQ: Q: I've installed the font on my client/server but I still see?'s or black boxes. Why? A: For the client machine, closing all instances of the PDF viewer then reopening them should fix the issue. For the server, restarting the services should allow the PDF renderer to pick up the new font information. Unfortunately, I have also seen times where I needed a full machine reboot to get the client/server to recognize the newly installed font.
TITLE: Custom font in SQL Server 2005 Reporting Services QUESTION: I'm having issues with my SQL Reporting Services reports. I'm using a custom font for report headers, and when deployed to the server it does not render correctly when I print or export to PDF/TIFF. I have installed the font on the server. Is there anything else I need to do in order to use custom fonts? When viewing the font in the browser it looks correct - since all client computers have the font installed... Thanks Ryan, your post to the FAQ solved the problem. Installing the fonts on the server fixes the print problem, as well as problems with charts (which are also rendered on the server). Like you point out (as well as being mentioned in the FAQ) Reporting Services 2005 does not do font embedding in PDF files. I guess that is okay for now - the most important part was being able to hit print and get the correct fonts. The reason the fonts didn't show up straight away is answered in the FAQ: Q: I've installed the font on my client/server but I still see?'s or black boxes. Why? A: For the client machine, closing all instances of the PDF viewer then reopening them should fix the issue. For the server, restarting the services should allow the PDF renderer to pick up the new font information. Unfortunately, I have also seen times where I needed a full machine reboot to get the client/server to recognize the newly installed font. ANSWER: The PDF files served up from SSRS, like many PDF files, have embedded postscript fonts. So, the local fonts used in the report are converted to a best matching postscript font when the conversion takes place so the PDF is totally portable without relying on locally installed fonts. You can see the official MS guidelines and font requirements for SSRS PDF exports here: SQL Server 2005 Books Online (September 2007) Designing for PDF Output. Also, this post should provide some help as well: Reporting Services: PDF Renderer FAQ Aspose apparently also has a component that claims to be able to add custom embedded fonts in SQL Report PDFs. See Aspose.Pdf for Reporting Services Aspose.Pdf for Reporting Services makes it possible generating PDF reports in Microsoft SQL Server 2000 and 2005 Reporting Services. Some advanced features like XMP metadata, custom embedded font and rendering watermark for pages are now supported. All RDL report features including sections, images, charts, tables, matrices, headers and footers are converted with the highest degree of precision to PDF. I've not tried this component, so I can only share what it claims to be able to do.
[ "sql", "reporting-services" ]
11
4
18,882
5
0
2008-08-21T07:16:16.087000
2008-08-21T07:29:10.390000
19,442
19,443
how to allow files starting with period and no extension in windows 2003 server?
How can I create this file in a directory in windows 2003 SP2:.hgignore I get error: You must type a file name.
That's a "feature" of Windows Explorer. Try to create your files from a command line (or from a batch/program you wrote) and it should work fine. Try this from a dos prompt: echo Hello there! >.hgignore
how to allow files starting with period and no extension in windows 2003 server? How can I create this file in a directory in windows 2003 SP2:.hgignore I get error: You must type a file name.
TITLE: how to allow files starting with period and no extension in windows 2003 server? QUESTION: How can I create this file in a directory in windows 2003 SP2:.hgignore I get error: You must type a file name. ANSWER: That's a "feature" of Windows Explorer. Try to create your files from a command line (or from a batch/program you wrote) and it should work fine. Try this from a dos prompt: echo Hello there! >.hgignore
[ "mercurial", "windows-server-2003", "hgignore" ]
23
27
5,451
2
0
2008-08-21T07:26:27.030000
2008-08-21T07:28:37.320000
19,445
26,105
Content Management system recommendations
Management is thinking of changing out Content Management Systems. What do you use/recommend? What UCM solution is your company using? How big is your company? Are you happy with the implementation? Current setup: The company I work for uses Oracle ECM (formerly Stellent UCM). We have somewhere over 10,000 employees across Australia, New Zealand and Indonesia. It works! Having worked with the system for a while now. I can see where the initial implementation went wrong. Its 3 years later and it is Rewrite Time! (Three year itch?)
1) CMS: Oracle's BEA Aqualogic 2) Size: 10,000+ 3) Experience: As an end user with full community and content admin privileges, I find the tool to be outdated and stifling in terms of knowledge sharing and trying to get the benefits that exist in social networks. Perhaps this is due to the implementation, and not an inherent weakness in the product. Not sure of the future direction of the product either, since Oracle recently acquired it.
Content Management system recommendations Management is thinking of changing out Content Management Systems. What do you use/recommend? What UCM solution is your company using? How big is your company? Are you happy with the implementation? Current setup: The company I work for uses Oracle ECM (formerly Stellent UCM). We have somewhere over 10,000 employees across Australia, New Zealand and Indonesia. It works! Having worked with the system for a while now. I can see where the initial implementation went wrong. Its 3 years later and it is Rewrite Time! (Three year itch?)
TITLE: Content Management system recommendations QUESTION: Management is thinking of changing out Content Management Systems. What do you use/recommend? What UCM solution is your company using? How big is your company? Are you happy with the implementation? Current setup: The company I work for uses Oracle ECM (formerly Stellent UCM). We have somewhere over 10,000 employees across Australia, New Zealand and Indonesia. It works! Having worked with the system for a while now. I can see where the initial implementation went wrong. Its 3 years later and it is Rewrite Time! (Three year itch?) ANSWER: 1) CMS: Oracle's BEA Aqualogic 2) Size: 10,000+ 3) Experience: As an end user with full community and content admin privileges, I find the tool to be outdated and stifling in terms of knowledge sharing and trying to get the benefits that exist in social networks. Perhaps this is due to the implementation, and not an inherent weakness in the product. Not sure of the future direction of the product either, since Oracle recently acquired it.
[ "content-management-system", "content-management", "ecm" ]
0
1
1,175
13
0
2008-08-21T07:29:46.990000
2008-08-25T14:25:58.500000
19,448
19,495
In a DDS file can you detect textures with 0/1 alpha bits?
In my engine I have a need to be able to detect DXT1 textures that have texels with 0 alpha (e.g. a cutout for a window frame). This is easy for textures I compress myself, but I'm not sure about textures that are already compressed. Is there an easy way to tell from the header whether a DDS image contains alpha?
As far as I know, there's no way to tell from the header. There's a DDPF_ALPHAPIXELS flag, but I don't think that will get set based on what's in the pixel data. You'd need to parse the DXT1 blocks, and look for colours that have 0 alpha in them (making sure to check that the colour is actually used in the block, too, I suppose).
In a DDS file can you detect textures with 0/1 alpha bits? In my engine I have a need to be able to detect DXT1 textures that have texels with 0 alpha (e.g. a cutout for a window frame). This is easy for textures I compress myself, but I'm not sure about textures that are already compressed. Is there an easy way to tell from the header whether a DDS image contains alpha?
TITLE: In a DDS file can you detect textures with 0/1 alpha bits? QUESTION: In my engine I have a need to be able to detect DXT1 textures that have texels with 0 alpha (e.g. a cutout for a window frame). This is easy for textures I compress myself, but I'm not sure about textures that are already compressed. Is there an easy way to tell from the header whether a DDS image contains alpha? ANSWER: As far as I know, there's no way to tell from the header. There's a DDPF_ALPHAPIXELS flag, but I don't think that will get set based on what's in the pixel data. You'd need to parse the DXT1 blocks, and look for colours that have 0 alpha in them (making sure to check that the colour is actually used in the block, too, I suppose).
[ "graphics", "directx", "directdraw", "dds-format" ]
1
2
1,223
4
0
2008-08-21T07:33:10.867000
2008-08-21T08:46:47.303000
19,454
19,455
Enforce Attribute Decoration of Classes/Methods
Following on from my recent question on Large, Complex Objects as a Web Service Result. I have been thinking about how I can ensure all future child classes are serializable to XML. Now, obviously I could implement the IXmlSerializable interface and then chuck a reader/writer to it but I would like to avoid that since it then means I need to instantiate a reader/writer whenever I want to do it, and 99.99% of the time I am going to be working with a string so I may just write my own. However, to serialize to XML, I am simply decorating the class and its members with the Xml??? attributes ( XmlRoot, XmlElement etc.) and then passing it to the XmlSerializer and a StringWriter to get the string. Which is all good. I intend to put the method to return the string into a generic utility method so I don't need to worry about type etc. The this that concerns me is this: If I do not decorate the class(es) with the required attributes an error is not thrown until run time. Is there any way to enforce attribute decoration? Can this be done with FxCop? (I have not used FxCop yet) UPDATE: Sorry for the delay in getting this close off guys, lots to do! Definitely like the idea of using reflection to do it in a test case rather than resorting to FxCop (like to keep everything together).. Fredrik Kalseth's answer was fantastic, thanks for including the code as it probably would have taken me a bit of digging to figure out how to do it myself! +1 to the other guys for similar suggestions:)
I'd write a unit/integration test that verifies that any class matching some given criteria (ie subclassing X) is decorated appropriately. If you set up your build to run with tests, you can have the build fail when this test fails. UPDATE: You said, "Looks like I will just have to roll my sleeves up and make sure that the unit tests are collectively maintained" - you don't have to. Just write a general test class that uses reflection to find all classes that needs to be asserted. Something like this: [TestClass] public class When_type_inherits_MyObject { private readonly List _types = new List (); public When_type_inherits_MyObject() { // lets find all types that inherit from MyObject, directly or indirectly foreach(Type type in typeof(MyObject).Assembly.GetTypes()) { if(type.IsClass && typeof(MyObject).IsAssignableFrom(type)) { _types.Add(type); } } } [TestMethod] public void Properties_have_XmlElement_attribute { foreach(Type type in _types) { foreach(PropertyInfo property in type.GetProperties()) { object[] attribs = property.GetCustomAttributes(typeof(XmlElementAttribute), false); Assert.IsTrue(attribs.Count > 0, "Missing XmlElementAttribute on property " + property.Name + " in type " + type.FullName); } } } }
Enforce Attribute Decoration of Classes/Methods Following on from my recent question on Large, Complex Objects as a Web Service Result. I have been thinking about how I can ensure all future child classes are serializable to XML. Now, obviously I could implement the IXmlSerializable interface and then chuck a reader/writer to it but I would like to avoid that since it then means I need to instantiate a reader/writer whenever I want to do it, and 99.99% of the time I am going to be working with a string so I may just write my own. However, to serialize to XML, I am simply decorating the class and its members with the Xml??? attributes ( XmlRoot, XmlElement etc.) and then passing it to the XmlSerializer and a StringWriter to get the string. Which is all good. I intend to put the method to return the string into a generic utility method so I don't need to worry about type etc. The this that concerns me is this: If I do not decorate the class(es) with the required attributes an error is not thrown until run time. Is there any way to enforce attribute decoration? Can this be done with FxCop? (I have not used FxCop yet) UPDATE: Sorry for the delay in getting this close off guys, lots to do! Definitely like the idea of using reflection to do it in a test case rather than resorting to FxCop (like to keep everything together).. Fredrik Kalseth's answer was fantastic, thanks for including the code as it probably would have taken me a bit of digging to figure out how to do it myself! +1 to the other guys for similar suggestions:)
TITLE: Enforce Attribute Decoration of Classes/Methods QUESTION: Following on from my recent question on Large, Complex Objects as a Web Service Result. I have been thinking about how I can ensure all future child classes are serializable to XML. Now, obviously I could implement the IXmlSerializable interface and then chuck a reader/writer to it but I would like to avoid that since it then means I need to instantiate a reader/writer whenever I want to do it, and 99.99% of the time I am going to be working with a string so I may just write my own. However, to serialize to XML, I am simply decorating the class and its members with the Xml??? attributes ( XmlRoot, XmlElement etc.) and then passing it to the XmlSerializer and a StringWriter to get the string. Which is all good. I intend to put the method to return the string into a generic utility method so I don't need to worry about type etc. The this that concerns me is this: If I do not decorate the class(es) with the required attributes an error is not thrown until run time. Is there any way to enforce attribute decoration? Can this be done with FxCop? (I have not used FxCop yet) UPDATE: Sorry for the delay in getting this close off guys, lots to do! Definitely like the idea of using reflection to do it in a test case rather than resorting to FxCop (like to keep everything together).. Fredrik Kalseth's answer was fantastic, thanks for including the code as it probably would have taken me a bit of digging to figure out how to do it myself! +1 to the other guys for similar suggestions:) ANSWER: I'd write a unit/integration test that verifies that any class matching some given criteria (ie subclassing X) is decorated appropriately. If you set up your build to run with tests, you can have the build fail when this test fails. UPDATE: You said, "Looks like I will just have to roll my sleeves up and make sure that the unit tests are collectively maintained" - you don't have to. Just write a general test class that uses reflection to find all classes that needs to be asserted. Something like this: [TestClass] public class When_type_inherits_MyObject { private readonly List _types = new List (); public When_type_inherits_MyObject() { // lets find all types that inherit from MyObject, directly or indirectly foreach(Type type in typeof(MyObject).Assembly.GetTypes()) { if(type.IsClass && typeof(MyObject).IsAssignableFrom(type)) { _types.Add(type); } } } [TestMethod] public void Properties_have_XmlElement_attribute { foreach(Type type in _types) { foreach(PropertyInfo property in type.GetProperties()) { object[] attribs = property.GetCustomAttributes(typeof(XmlElementAttribute), false); Assert.IsTrue(attribs.Count > 0, "Missing XmlElementAttribute on property " + property.Name + " in type " + type.FullName); } } } }
[ "c#", "xml", "serialization", "coding-style", ".net-attributes" ]
18
19
4,966
5
0
2008-08-21T07:49:56.083000
2008-08-21T07:54:12.670000
19,466
19,472
Check file permissions
How can I check file permissions, without having to run operating system specific command via passthru() or exec()?
Use fileperms() function clearstatcache(); echo substr(sprintf('%o', fileperms('/etc/passwd')), -4);
Check file permissions How can I check file permissions, without having to run operating system specific command via passthru() or exec()?
TITLE: Check file permissions QUESTION: How can I check file permissions, without having to run operating system specific command via passthru() or exec()? ANSWER: Use fileperms() function clearstatcache(); echo substr(sprintf('%o', fileperms('/etc/passwd')), -4);
[ "php", "file-permissions" ]
18
23
23,123
6
0
2008-08-21T08:06:06.933000
2008-08-21T08:10:44.817000
19,471
19,480
Weird yellow bar pops-up: 'Microsoft Data Access - Remote Data Services
When I access my site from any computer, I see this warning popping up: "This web site wants to run the following add-on: 'Microsoft Data Access - Remote Data Services Dat...' from 'Microsoft Corporation'. If you trust the web site and the add-on and want to allow it to run, click here..." I am guessing this is some kind of virus or something. I would like to know how to remove this from my site.
Id be very concerned if this is on your own server. I found the following blog post that warns on the issue: http://msmvps.com/blogs/hostsnews/archive/2007/09/13/can-you-spot-the-fake.aspx but doesn't provide any way of removing it. I'd recommend making sure both the server and the client are up to date on Windows Updates, and then installing a good virus scanner.
Weird yellow bar pops-up: 'Microsoft Data Access - Remote Data Services When I access my site from any computer, I see this warning popping up: "This web site wants to run the following add-on: 'Microsoft Data Access - Remote Data Services Dat...' from 'Microsoft Corporation'. If you trust the web site and the add-on and want to allow it to run, click here..." I am guessing this is some kind of virus or something. I would like to know how to remove this from my site.
TITLE: Weird yellow bar pops-up: 'Microsoft Data Access - Remote Data Services QUESTION: When I access my site from any computer, I see this warning popping up: "This web site wants to run the following add-on: 'Microsoft Data Access - Remote Data Services Dat...' from 'Microsoft Corporation'. If you trust the web site and the add-on and want to allow it to run, click here..." I am guessing this is some kind of virus or something. I would like to know how to remove this from my site. ANSWER: Id be very concerned if this is on your own server. I found the following blog post that warns on the issue: http://msmvps.com/blogs/hostsnews/archive/2007/09/13/can-you-spot-the-fake.aspx but doesn't provide any way of removing it. I'd recommend making sure both the server and the client are up to date on Windows Updates, and then installing a good virus scanner.
[ "security", "internet-explorer-7" ]
1
3
594
1
0
2008-08-21T08:10:14.910000
2008-08-21T08:22:28.190000
19,487
22,087
What's the best way to go from a Photoshop mockup to semantic HTML and CSS?
I generally use a manual process: Look at the page, figure out the semantic elements, and build the HTML Slice up the images I think I'll need Start writing CSS Tweak and repeat different steps as necessary Got a better approach, or a tool?
I have a fairly natural way of coding. The key is to treat the page like a document or an article. If you think of it like this the following becomes logically clear: The page title is a top level heading Whether you make the site title or actual page title the h1 is up to you - personally I'd make About Us the h1 rather than Stack Overflow. The navigation is a table of contents, and thus an ordered list - you may as well use an ol over a ul. Section headers are h2, sections within those sections are h3s etc. Stack them up. Use blockquotes and quotes where possible. Don't just surround it with ". Don't use b and i. Use strong and em. This is because HTML is structural rather than presentational markup. Strong and em phasis tags should be used where you'd put emphasis on the word. your form elements. Use s and s where possible, but only in the first instance. The easiest: always, always give your images some alternate text. There's lots of HTML tags you could use that you probably haven't - address for postal addresses, screen code output. Have a look at HTML Dog for some, it's my favourite reference. That's just a few pointers, I'm sure I could think of more. Oh, and if you want a challenge write your XHTML first, then write the CSS. When CSS-ing you aren't allowed to touch the HTML. It's actually harder than you think (but I've found it's made me quicker).
What's the best way to go from a Photoshop mockup to semantic HTML and CSS? I generally use a manual process: Look at the page, figure out the semantic elements, and build the HTML Slice up the images I think I'll need Start writing CSS Tweak and repeat different steps as necessary Got a better approach, or a tool?
TITLE: What's the best way to go from a Photoshop mockup to semantic HTML and CSS? QUESTION: I generally use a manual process: Look at the page, figure out the semantic elements, and build the HTML Slice up the images I think I'll need Start writing CSS Tweak and repeat different steps as necessary Got a better approach, or a tool? ANSWER: I have a fairly natural way of coding. The key is to treat the page like a document or an article. If you think of it like this the following becomes logically clear: The page title is a top level heading Whether you make the site title or actual page title the h1 is up to you - personally I'd make About Us the h1 rather than Stack Overflow. The navigation is a table of contents, and thus an ordered list - you may as well use an ol over a ul. Section headers are h2, sections within those sections are h3s etc. Stack them up. Use blockquotes and quotes where possible. Don't just surround it with ". Don't use b and i. Use strong and em. This is because HTML is structural rather than presentational markup. Strong and em phasis tags should be used where you'd put emphasis on the word. your form elements. Use s and s where possible, but only in the first instance. The easiest: always, always give your images some alternate text. There's lots of HTML tags you could use that you probably haven't - address for postal addresses, screen code output. Have a look at HTML Dog for some, it's my favourite reference. That's just a few pointers, I'm sure I could think of more. Oh, and if you want a challenge write your XHTML first, then write the CSS. When CSS-ing you aren't allowed to touch the HTML. It's actually harder than you think (but I've found it's made me quicker).
[ "html", "css" ]
23
10
1,221
8
0
2008-08-21T08:32:34.873000
2008-08-22T11:21:22.697000
19,493
19,597
mod_rewrite rule to redirect all requests except for one specific path
I'm trying to redirect all requests to my domain to another domain using mod_rewrite in an Apache 2.2 VirtualHost declaration. There is one exception to this -- I'd like all requests to the /audio path not to be redirected. I've written a RewriteCond and RewriteRule to do this but it's not quite right and I can't figure out why. The regular expression contains a negative lookahead for the string "/audio", but for some reason this isn't matching. Here's the definition: RewriteEngine on RewriteCond %{HTTP_HOST} ^(.*\.)?mydomain\.net(?!/audio) [NC] RewriteRule ^(.*)$ http://www.newdomain.example [L,R=301] If I change the RewriteCond to: RewriteCond %{HTTP_HOST} ^(.*\.)?mydomain\.example/(?!audio) [NC] (i.e. put the forward slash outside of the negative lookahead part) then it works, but the downside of this is that requests to mydomain.example without a trailing slash will not be redirected. Can anyone point out what I'm doing wrong? Here are the rules: ServerAdmin me@mydomain.example DocumentRoot "/var/www/mydomain.example/htdocs" ServerName www.mydomain.example ServerAlias mydomain.example RewriteEngine on RewriteCond {REQUEST_URI}!^/audio RewriteRule ^(.*)$ http://www.newdomain.example [L,R=301] RewriteLog logs/mod_rewrite_log RewriteLogLevel 3 ErrorLog logs/error_log CustomLog logs/access_log common Thanks @mercutio -- that makes perfect sense but it still doesn't seem to work. Here's what the mod_rewrite log says when I make a request to http://mydomain.example/audio/something.mp3: (2) init rewrite engine with requested uri /audio/something.mp3 (3) applying pattern '^(.*)$' to uri '/audio' (2) rewrite '/audio' -> 'http://www.newdomain.example/' (2) explicitly forcing redirect with http://www.newdomain.example (1) escaping http://www.newdomain.example for redirect (1) redirect to http://www.newdomain.example [REDIRECT/301] Since the REQUEST_URI does start with /audio I would expect the RewriteRule to be ignored.
The HTTP_HOST only contains the host name, not the path of the URL requested. RewriteCond %{REQUEST_URI}!^/audio Should be all you need. Further, you can get debug info from the rewrite engine with the following, which is really useful to see how your conditions and rules are being matched: RewriteLog /path/to/log/file RewriteLogLevel 3
mod_rewrite rule to redirect all requests except for one specific path I'm trying to redirect all requests to my domain to another domain using mod_rewrite in an Apache 2.2 VirtualHost declaration. There is one exception to this -- I'd like all requests to the /audio path not to be redirected. I've written a RewriteCond and RewriteRule to do this but it's not quite right and I can't figure out why. The regular expression contains a negative lookahead for the string "/audio", but for some reason this isn't matching. Here's the definition: RewriteEngine on RewriteCond %{HTTP_HOST} ^(.*\.)?mydomain\.net(?!/audio) [NC] RewriteRule ^(.*)$ http://www.newdomain.example [L,R=301] If I change the RewriteCond to: RewriteCond %{HTTP_HOST} ^(.*\.)?mydomain\.example/(?!audio) [NC] (i.e. put the forward slash outside of the negative lookahead part) then it works, but the downside of this is that requests to mydomain.example without a trailing slash will not be redirected. Can anyone point out what I'm doing wrong? Here are the rules: ServerAdmin me@mydomain.example DocumentRoot "/var/www/mydomain.example/htdocs" ServerName www.mydomain.example ServerAlias mydomain.example RewriteEngine on RewriteCond {REQUEST_URI}!^/audio RewriteRule ^(.*)$ http://www.newdomain.example [L,R=301] RewriteLog logs/mod_rewrite_log RewriteLogLevel 3 ErrorLog logs/error_log CustomLog logs/access_log common Thanks @mercutio -- that makes perfect sense but it still doesn't seem to work. Here's what the mod_rewrite log says when I make a request to http://mydomain.example/audio/something.mp3: (2) init rewrite engine with requested uri /audio/something.mp3 (3) applying pattern '^(.*)$' to uri '/audio' (2) rewrite '/audio' -> 'http://www.newdomain.example/' (2) explicitly forcing redirect with http://www.newdomain.example (1) escaping http://www.newdomain.example for redirect (1) redirect to http://www.newdomain.example [REDIRECT/301] Since the REQUEST_URI does start with /audio I would expect the RewriteRule to be ignored.
TITLE: mod_rewrite rule to redirect all requests except for one specific path QUESTION: I'm trying to redirect all requests to my domain to another domain using mod_rewrite in an Apache 2.2 VirtualHost declaration. There is one exception to this -- I'd like all requests to the /audio path not to be redirected. I've written a RewriteCond and RewriteRule to do this but it's not quite right and I can't figure out why. The regular expression contains a negative lookahead for the string "/audio", but for some reason this isn't matching. Here's the definition: RewriteEngine on RewriteCond %{HTTP_HOST} ^(.*\.)?mydomain\.net(?!/audio) [NC] RewriteRule ^(.*)$ http://www.newdomain.example [L,R=301] If I change the RewriteCond to: RewriteCond %{HTTP_HOST} ^(.*\.)?mydomain\.example/(?!audio) [NC] (i.e. put the forward slash outside of the negative lookahead part) then it works, but the downside of this is that requests to mydomain.example without a trailing slash will not be redirected. Can anyone point out what I'm doing wrong? Here are the rules: ServerAdmin me@mydomain.example DocumentRoot "/var/www/mydomain.example/htdocs" ServerName www.mydomain.example ServerAlias mydomain.example RewriteEngine on RewriteCond {REQUEST_URI}!^/audio RewriteRule ^(.*)$ http://www.newdomain.example [L,R=301] RewriteLog logs/mod_rewrite_log RewriteLogLevel 3 ErrorLog logs/error_log CustomLog logs/access_log common Thanks @mercutio -- that makes perfect sense but it still doesn't seem to work. Here's what the mod_rewrite log says when I make a request to http://mydomain.example/audio/something.mp3: (2) init rewrite engine with requested uri /audio/something.mp3 (3) applying pattern '^(.*)$' to uri '/audio' (2) rewrite '/audio' -> 'http://www.newdomain.example/' (2) explicitly forcing redirect with http://www.newdomain.example (1) escaping http://www.newdomain.example for redirect (1) redirect to http://www.newdomain.example [REDIRECT/301] Since the REQUEST_URI does start with /audio I would expect the RewriteRule to be ignored. ANSWER: The HTTP_HOST only contains the host name, not the path of the URL requested. RewriteCond %{REQUEST_URI}!^/audio Should be all you need. Further, you can get debug info from the rewrite engine with the following, which is really useful to see how your conditions and rules are being matched: RewriteLog /path/to/log/file RewriteLogLevel 3
[ "apache", "mod-rewrite" ]
40
49
56,008
1
0
2008-08-21T08:42:17.407000
2008-08-21T10:41:08.590000
19,516
19,521
SQL2005: Linking a table to multiple tables and retaining Ref Integrity?
Here is a simplification of my database: Table: Property Fields: ID, Address Table: Quote Fields: ID, PropertyID, BespokeQuoteFields... Table: Job Fields: ID, PropertyID, BespokeJobFields... Then we have other tables that relate to the Quote and Job tables individually. I now need to add a Message table where users can record telephone messages left by customers regarding Jobs and Quotes. I could create two identical tables ( QuoteMessage and JobMessage ), but this violates the DRY principal and seems messy. I could create one Message table: Table: Message Fields: ID, RelationID, RelationType, OtherFields... But this stops me from using constraints to enforce my referential integrity. I can also forsee it creating problems with the devlopment side using Linq to SQL later on. Is there an elegant solution to this problem, or am I ultimately going to have to hack something together? Burns
Create one Message table, containing a unique MessageId and the various properties you need to store for a message. Table: Message Fields: Id, TimeReceived, MessageDetails, WhateverElse... Create two link tables - QuoteMessage and JobMessage. These will just contain two fields each, foreign keys to the Quote/Job and the Message. Table: QuoteMessage Fields: QuoteId, MessageId Table: JobMessage Fields: JobId, MessageId In this way you have defined the data properties of a Message in one place only (making it easy to extend, and to query across all messages), but you also have the referential integrity linking Quotes and Jobs to any number of messages. Indeed, both a Quote and Job could be linked to the same message (I'm not sure if that is appropriate to your business model, but at least the data model gives you the option).
SQL2005: Linking a table to multiple tables and retaining Ref Integrity? Here is a simplification of my database: Table: Property Fields: ID, Address Table: Quote Fields: ID, PropertyID, BespokeQuoteFields... Table: Job Fields: ID, PropertyID, BespokeJobFields... Then we have other tables that relate to the Quote and Job tables individually. I now need to add a Message table where users can record telephone messages left by customers regarding Jobs and Quotes. I could create two identical tables ( QuoteMessage and JobMessage ), but this violates the DRY principal and seems messy. I could create one Message table: Table: Message Fields: ID, RelationID, RelationType, OtherFields... But this stops me from using constraints to enforce my referential integrity. I can also forsee it creating problems with the devlopment side using Linq to SQL later on. Is there an elegant solution to this problem, or am I ultimately going to have to hack something together? Burns
TITLE: SQL2005: Linking a table to multiple tables and retaining Ref Integrity? QUESTION: Here is a simplification of my database: Table: Property Fields: ID, Address Table: Quote Fields: ID, PropertyID, BespokeQuoteFields... Table: Job Fields: ID, PropertyID, BespokeJobFields... Then we have other tables that relate to the Quote and Job tables individually. I now need to add a Message table where users can record telephone messages left by customers regarding Jobs and Quotes. I could create two identical tables ( QuoteMessage and JobMessage ), but this violates the DRY principal and seems messy. I could create one Message table: Table: Message Fields: ID, RelationID, RelationType, OtherFields... But this stops me from using constraints to enforce my referential integrity. I can also forsee it creating problems with the devlopment side using Linq to SQL later on. Is there an elegant solution to this problem, or am I ultimately going to have to hack something together? Burns ANSWER: Create one Message table, containing a unique MessageId and the various properties you need to store for a message. Table: Message Fields: Id, TimeReceived, MessageDetails, WhateverElse... Create two link tables - QuoteMessage and JobMessage. These will just contain two fields each, foreign keys to the Quote/Job and the Message. Table: QuoteMessage Fields: QuoteId, MessageId Table: JobMessage Fields: JobId, MessageId In this way you have defined the data properties of a Message in one place only (making it easy to extend, and to query across all messages), but you also have the referential integrity linking Quotes and Jobs to any number of messages. Indeed, both a Quote and Job could be linked to the same message (I'm not sure if that is appropriate to your business model, but at least the data model gives you the option).
[ "database", "sql-server-2005", "referential-integrity" ]
3
4
1,200
4
0
2008-08-21T09:12:00.083000
2008-08-21T09:26:24.103000
19,517
21,841
Is anybody using the Specter BDD Framework?
I was reading the example chapter from the book by Ayende and on the website of the Boo language I saw a reference to the Specter BDD Framework. I am wondering if anybody is using it in their project, how that works out and if there are more examples and/or suggested readings. Just in case you are wondering, I'm a C# developer and so I plan to use it in a C#/.NET environment. A few year later visiting this question. I think we can safely assume Specflow and some others like NSpec became the tools we are using.
I'm not using it, but I've seen demos of it. It's very nice. Boo has a lot of interesting extensibility points in parsing and interpreting the language itself that make it ideal for writing frameworks like Specter. The end result is much nicer looking than you'd be able to get with languages like C#. Unfortunately, the fact that Boo isn't "in the box" and can't simply be something you check into your source tree and use really holds it back here. It's a much heavier adoption cost than just picking a framework like NSpec.
Is anybody using the Specter BDD Framework? I was reading the example chapter from the book by Ayende and on the website of the Boo language I saw a reference to the Specter BDD Framework. I am wondering if anybody is using it in their project, how that works out and if there are more examples and/or suggested readings. Just in case you are wondering, I'm a C# developer and so I plan to use it in a C#/.NET environment. A few year later visiting this question. I think we can safely assume Specflow and some others like NSpec became the tools we are using.
TITLE: Is anybody using the Specter BDD Framework? QUESTION: I was reading the example chapter from the book by Ayende and on the website of the Boo language I saw a reference to the Specter BDD Framework. I am wondering if anybody is using it in their project, how that works out and if there are more examples and/or suggested readings. Just in case you are wondering, I'm a C# developer and so I plan to use it in a C#/.NET environment. A few year later visiting this question. I think we can safely assume Specflow and some others like NSpec became the tools we are using. ANSWER: I'm not using it, but I've seen demos of it. It's very nice. Boo has a lot of interesting extensibility points in parsing and interpreting the language itself that make it ideal for writing frameworks like Specter. The end result is much nicer looking than you'd be able to get with languages like C#. Unfortunately, the fact that Boo isn't "in the box" and can't simply be something you check into your source tree and use really holds it back here. It's a much heavier adoption cost than just picking a framework like NSpec.
[ "c#", ".net", "bdd", "boo" ]
7
1
1,385
2
0
2008-08-21T09:23:56.137000
2008-08-22T05:28:38.987000
19,553
19,835
Enforcing required function call
I have a "Status" class in C#, used like this: Status MyFunction() { if(...) // something bad return new Status(false, "Something went wrong") else return new Status(true, "OK"); } You get the idea. All callers of MyFunction should check the returned Status: Status myStatus = MyFunction(); if (! myStatus.IsOK() ) // handle it, show a message,... Lazy callers however can ignore the Status. MyFunction(); // call function and ignore returned Status or { Status myStatus = MyFunction(); } // lose all references to myStatus, without calling IsOK() on it Is it possible to make this impossible? e.g. an throw exception In general: is it possible to write a C# class on which you have to call a certain function? In the C++ version of the Status class, I can write a test on some private bool bIsChecked in the destructor and ring some bells when someone doesn't check this instance. What is the equivalent option in C#? I read somewhere that "You don't want a destructor in your C# class" Is the Dispose method of the IDisposable interface an option? In this case there are no unmanaged resources to free. Additionally, it is not determined when the GC will dispose the object. When it eventually gets disposed, is it still possible to know where and when you ignored that specific Status instance? The "using" keyword does help, but again, it is not required for lazy callers.
I am fairly certain you can't get the effect you want as a return value from a method. C# just can't do some of the things C++ can. However, a somewhat ugly way to get a similar effect is the following: using System; public class Example { public class Toy { private bool inCupboard = false; public void Play() { Console.WriteLine("Playing."); } public void PutAway() { inCupboard = true; } public bool IsInCupboard { get { return inCupboard; } } } public delegate void ToyUseCallback(Toy toy); public class Parent { public static void RequestToy(ToyUseCallback callback) { Toy toy = new Toy(); callback(toy); if (!toy.IsInCupboard) { throw new Exception("You didn't put your toy in the cupboard!"); } } } public class Child { public static void Play() { Parent.RequestToy(delegate(Toy toy) { toy.Play(); // Oops! Forgot to put the toy away! }); } } public static void Main() { Child.Play(); Console.ReadLine(); } } In the very simple example, you get an instance of Toy by calling Parent.RequestToy, and passing it a delegate. Instead of returning the toy, the method immediately calls the delegate with the toy, which must call PutAway before it returns, or the RequestToy method will throw an exception. I make no claims as to the wisdom of using this technique -- indeed in all "something went wrong" examples an exception is almost certainly a better bet -- but I think it comes about as close as you can get to your original request.
Enforcing required function call I have a "Status" class in C#, used like this: Status MyFunction() { if(...) // something bad return new Status(false, "Something went wrong") else return new Status(true, "OK"); } You get the idea. All callers of MyFunction should check the returned Status: Status myStatus = MyFunction(); if (! myStatus.IsOK() ) // handle it, show a message,... Lazy callers however can ignore the Status. MyFunction(); // call function and ignore returned Status or { Status myStatus = MyFunction(); } // lose all references to myStatus, without calling IsOK() on it Is it possible to make this impossible? e.g. an throw exception In general: is it possible to write a C# class on which you have to call a certain function? In the C++ version of the Status class, I can write a test on some private bool bIsChecked in the destructor and ring some bells when someone doesn't check this instance. What is the equivalent option in C#? I read somewhere that "You don't want a destructor in your C# class" Is the Dispose method of the IDisposable interface an option? In this case there are no unmanaged resources to free. Additionally, it is not determined when the GC will dispose the object. When it eventually gets disposed, is it still possible to know where and when you ignored that specific Status instance? The "using" keyword does help, but again, it is not required for lazy callers.
TITLE: Enforcing required function call QUESTION: I have a "Status" class in C#, used like this: Status MyFunction() { if(...) // something bad return new Status(false, "Something went wrong") else return new Status(true, "OK"); } You get the idea. All callers of MyFunction should check the returned Status: Status myStatus = MyFunction(); if (! myStatus.IsOK() ) // handle it, show a message,... Lazy callers however can ignore the Status. MyFunction(); // call function and ignore returned Status or { Status myStatus = MyFunction(); } // lose all references to myStatus, without calling IsOK() on it Is it possible to make this impossible? e.g. an throw exception In general: is it possible to write a C# class on which you have to call a certain function? In the C++ version of the Status class, I can write a test on some private bool bIsChecked in the destructor and ring some bells when someone doesn't check this instance. What is the equivalent option in C#? I read somewhere that "You don't want a destructor in your C# class" Is the Dispose method of the IDisposable interface an option? In this case there are no unmanaged resources to free. Additionally, it is not determined when the GC will dispose the object. When it eventually gets disposed, is it still possible to know where and when you ignored that specific Status instance? The "using" keyword does help, but again, it is not required for lazy callers. ANSWER: I am fairly certain you can't get the effect you want as a return value from a method. C# just can't do some of the things C++ can. However, a somewhat ugly way to get a similar effect is the following: using System; public class Example { public class Toy { private bool inCupboard = false; public void Play() { Console.WriteLine("Playing."); } public void PutAway() { inCupboard = true; } public bool IsInCupboard { get { return inCupboard; } } } public delegate void ToyUseCallback(Toy toy); public class Parent { public static void RequestToy(ToyUseCallback callback) { Toy toy = new Toy(); callback(toy); if (!toy.IsInCupboard) { throw new Exception("You didn't put your toy in the cupboard!"); } } } public class Child { public static void Play() { Parent.RequestToy(delegate(Toy toy) { toy.Play(); // Oops! Forgot to put the toy away! }); } } public static void Main() { Child.Play(); Console.ReadLine(); } } In the very simple example, you get an instance of Toy by calling Parent.RequestToy, and passing it a delegate. Instead of returning the toy, the method immediately calls the delegate with the toy, which must call PutAway before it returns, or the RequestToy method will throw an exception. I make no claims as to the wisdom of using this technique -- indeed in all "something went wrong" examples an exception is almost certainly a better bet -- but I think it comes about as close as you can get to your original request.
[ "c#", "garbage-collection", "dispose", "destructor" ]
10
2
785
11
0
2008-08-21T09:57:26.463000
2008-08-21T13:17:05.203000
19,589
19,596
Loading System.ServiceModel configuration section using ConfigurationManager
Using C#.NET 3.5 and WCF, I'm trying to write out some of the WCF configuration in a client application (the name of the server the client is connecting to). The obvious way is to use ConfigurationManager to load the configuration section and write out the data I need. var serviceModelSection = ConfigurationManager.GetSection("system.serviceModel"); Appears to always return null. var serviceModelSection = ConfigurationManager.GetSection("appSettings"); Works perfectly. The configuration section is present in the App.config but for some reason ConfigurationManager refuses to load the system.ServiceModel section. I want to avoid manually loading the xxx.exe.config file and using XPath but if I have to resort to that I will. Just seems like a bit of a hack. Any suggestions?
The element is for a configuration section group, not a section. You'll need to use System.ServiceModel.Configuration.ServiceModelSectionGroup.GetSectionGroup() to get the whole group.
Loading System.ServiceModel configuration section using ConfigurationManager Using C#.NET 3.5 and WCF, I'm trying to write out some of the WCF configuration in a client application (the name of the server the client is connecting to). The obvious way is to use ConfigurationManager to load the configuration section and write out the data I need. var serviceModelSection = ConfigurationManager.GetSection("system.serviceModel"); Appears to always return null. var serviceModelSection = ConfigurationManager.GetSection("appSettings"); Works perfectly. The configuration section is present in the App.config but for some reason ConfigurationManager refuses to load the system.ServiceModel section. I want to avoid manually loading the xxx.exe.config file and using XPath but if I have to resort to that I will. Just seems like a bit of a hack. Any suggestions?
TITLE: Loading System.ServiceModel configuration section using ConfigurationManager QUESTION: Using C#.NET 3.5 and WCF, I'm trying to write out some of the WCF configuration in a client application (the name of the server the client is connecting to). The obvious way is to use ConfigurationManager to load the configuration section and write out the data I need. var serviceModelSection = ConfigurationManager.GetSection("system.serviceModel"); Appears to always return null. var serviceModelSection = ConfigurationManager.GetSection("appSettings"); Works perfectly. The configuration section is present in the App.config but for some reason ConfigurationManager refuses to load the system.ServiceModel section. I want to avoid manually loading the xxx.exe.config file and using XPath but if I have to resort to that I will. Just seems like a bit of a hack. Any suggestions? ANSWER: The element is for a configuration section group, not a section. You'll need to use System.ServiceModel.Configuration.ServiceModelSectionGroup.GetSectionGroup() to get the whole group.
[ "c#", ".net", "xml", "wcf", "configurationmanager" ]
67
51
61,451
5
0
2008-08-21T10:27:59.137000
2008-08-21T10:38:07.083000
19,604
23,556
Best TinyMce editor Image Manager / File upload for Asp.net Mvc
What is the best Image Manager to integrate in TinyMce editor apart the official Moxiecode commercial ones? I'm looking to integrate a light texteditor in an asp.net mvc application and I choosed the Tinymce solution (and not the classic FCKEditor as this seems more lightweight and more jquery friendly). Sadly TinyMce doesn't come with the Image Manager or Document Manager integrated like FCKeditor but you must buy them as plugins form Moxiecode. I've looked other plugins but till now I've not find any decend and light solution that works with asp.net mvc framework. Any suggestions?
There are a couple of open source plugins on SourceForge, http://sourceforge.net/tracker/?group_id=103281&atid=738747 (search for image) The plugin architecture is easy to understand if you know Javascript. If you have the time you could roll out your own.
Best TinyMce editor Image Manager / File upload for Asp.net Mvc What is the best Image Manager to integrate in TinyMce editor apart the official Moxiecode commercial ones? I'm looking to integrate a light texteditor in an asp.net mvc application and I choosed the Tinymce solution (and not the classic FCKEditor as this seems more lightweight and more jquery friendly). Sadly TinyMce doesn't come with the Image Manager or Document Manager integrated like FCKeditor but you must buy them as plugins form Moxiecode. I've looked other plugins but till now I've not find any decend and light solution that works with asp.net mvc framework. Any suggestions?
TITLE: Best TinyMce editor Image Manager / File upload for Asp.net Mvc QUESTION: What is the best Image Manager to integrate in TinyMce editor apart the official Moxiecode commercial ones? I'm looking to integrate a light texteditor in an asp.net mvc application and I choosed the Tinymce solution (and not the classic FCKEditor as this seems more lightweight and more jquery friendly). Sadly TinyMce doesn't come with the Image Manager or Document Manager integrated like FCKeditor but you must buy them as plugins form Moxiecode. I've looked other plugins but till now I've not find any decend and light solution that works with asp.net mvc framework. Any suggestions? ANSWER: There are a couple of open source plugins on SourceForge, http://sourceforge.net/tracker/?group_id=103281&atid=738747 (search for image) The plugin architecture is easy to understand if you know Javascript. If you have the time you could roll out your own.
[ "asp.net", "asp.net-mvc", ".net-2.0" ]
28
5
60,501
10
0
2008-08-21T10:53:54.283000
2008-08-22T21:33:39.183000
19,653
19,678
Is Visual C++ memory managed by the Dot Net framework
Recently, I've been dealing with an error with accessing MAPI via the.NET framework (as described in this article ). I am now left with a series of memory access violation errors. To get past the issues, I have been trying to use this 3rd party component, which has a Visual C++ core. Unfortunately - we are still having the same errors. I've personally never used Visual C++, but my question is: if the C++ library is compiled using Visual Studio 2005, using Visual C++ - does the memory of the project become managed by the.NET framework, as well, which would therefore make it subject to the same issues as the.NET libraries we're using? Or am I barking up the wrong tree?
I'm not entirely sure what you're asking, but i'll give it a shot. Visual C++ is a pure C/C++ compiler so has none of.NET's memory management, nor any of its runtime -- You have to manually call new and delete..NET also provides C++/CLI, which is a slightly modified version of C++ that targets the.NET runtime, and is GC aware -- eg. its memory is managed by the.NET runtime. Without more details about your bug I can't really make any suggestions, beyond suggesting that you make sure you use the appropriate GC guards, and the provide finalizers in any place they are needed.
Is Visual C++ memory managed by the Dot Net framework Recently, I've been dealing with an error with accessing MAPI via the.NET framework (as described in this article ). I am now left with a series of memory access violation errors. To get past the issues, I have been trying to use this 3rd party component, which has a Visual C++ core. Unfortunately - we are still having the same errors. I've personally never used Visual C++, but my question is: if the C++ library is compiled using Visual Studio 2005, using Visual C++ - does the memory of the project become managed by the.NET framework, as well, which would therefore make it subject to the same issues as the.NET libraries we're using? Or am I barking up the wrong tree?
TITLE: Is Visual C++ memory managed by the Dot Net framework QUESTION: Recently, I've been dealing with an error with accessing MAPI via the.NET framework (as described in this article ). I am now left with a series of memory access violation errors. To get past the issues, I have been trying to use this 3rd party component, which has a Visual C++ core. Unfortunately - we are still having the same errors. I've personally never used Visual C++, but my question is: if the C++ library is compiled using Visual Studio 2005, using Visual C++ - does the memory of the project become managed by the.NET framework, as well, which would therefore make it subject to the same issues as the.NET libraries we're using? Or am I barking up the wrong tree? ANSWER: I'm not entirely sure what you're asking, but i'll give it a shot. Visual C++ is a pure C/C++ compiler so has none of.NET's memory management, nor any of its runtime -- You have to manually call new and delete..NET also provides C++/CLI, which is a slightly modified version of C++ that targets the.NET runtime, and is GC aware -- eg. its memory is managed by the.NET runtime. Without more details about your bug I can't really make any suggestions, beyond suggesting that you make sure you use the appropriate GC guards, and the provide finalizers in any place they are needed.
[ ".net", "visual-c++", "memory" ]
1
0
1,357
3
0
2008-08-21T11:47:11.630000
2008-08-21T12:00:51.690000
19,654
19,715
Introducing Python
The company I used to work with has two developers working fulltime, and a handful of freelancers. They're in the process of hiring a new lead developer to try to bring order and management to the development. But, currently, one of the developers has seen the light of Django (the company has only developed in PHP to date) while the other developer is concerned that introducing a new language (Python) is a bad idea right now. How should they approach introducing this new technology? Obviously with only one of the developers actually knowing Python, there will be no redundancy when that dev is away or leaves the company. Should they bother to introduce Python, or should they look for PHP-only solutions until such a time when the team actually have more than one Pythonion? Without a team leader, the decisions are having to fall to them.
I recently introduced Python to my company, which does consulting work for the Post Office. I did this by waiting until there was a project for which I would be the only programmer, then getting permission to do this new project in Python. I then did another small project in Python with similarly impressive results. In addition, I used Python for all of my small throwaway assignments ("can you parse the stats in these files into a CSV file organized by date and site?", etc) and had a quick turnaround time on all of them. I also evangelized Python a bit; I went out of my way to NOT be obnoxious about it, but I'd occasionally describe why I liked it so much, talked about the personal projects I use it for in my free time and why it's awesome for me, etc. Eventually we started another project and I convinced everyone to use Python for it. I took care to point everyone to a lot of documentation, including the specific webpages relating to what they were working on, and every time they had a question, I'd explain how to do things properly by explaining the Pythonic approach to things, etc. This has worked really well. However, this might be somewhat different than what you're describing. In my case I started with moderately small projects and Python is only being used for new projects. Also, none of my co-workers were really Perl or PHP gurus; they all knew those languages and had been using them for awhile, but it didn't take much effort for them to become more productive in Python than they'd been before. So if you're talking about new projects with people who currently use PHP but aren't super-experts and don't love that language, then I think switching to Python is a no-brainer. However, if you're talking about working with a large existing PHP code base with a lot of very experienced PHP programmers who are happy with their current setup, then switching languages is probably not a good idea. You're probably somewhere in between, so you'll have to weigh the tradeoffs; hopefully my answer will help you do that.
Introducing Python The company I used to work with has two developers working fulltime, and a handful of freelancers. They're in the process of hiring a new lead developer to try to bring order and management to the development. But, currently, one of the developers has seen the light of Django (the company has only developed in PHP to date) while the other developer is concerned that introducing a new language (Python) is a bad idea right now. How should they approach introducing this new technology? Obviously with only one of the developers actually knowing Python, there will be no redundancy when that dev is away or leaves the company. Should they bother to introduce Python, or should they look for PHP-only solutions until such a time when the team actually have more than one Pythonion? Without a team leader, the decisions are having to fall to them.
TITLE: Introducing Python QUESTION: The company I used to work with has two developers working fulltime, and a handful of freelancers. They're in the process of hiring a new lead developer to try to bring order and management to the development. But, currently, one of the developers has seen the light of Django (the company has only developed in PHP to date) while the other developer is concerned that introducing a new language (Python) is a bad idea right now. How should they approach introducing this new technology? Obviously with only one of the developers actually knowing Python, there will be no redundancy when that dev is away or leaves the company. Should they bother to introduce Python, or should they look for PHP-only solutions until such a time when the team actually have more than one Pythonion? Without a team leader, the decisions are having to fall to them. ANSWER: I recently introduced Python to my company, which does consulting work for the Post Office. I did this by waiting until there was a project for which I would be the only programmer, then getting permission to do this new project in Python. I then did another small project in Python with similarly impressive results. In addition, I used Python for all of my small throwaway assignments ("can you parse the stats in these files into a CSV file organized by date and site?", etc) and had a quick turnaround time on all of them. I also evangelized Python a bit; I went out of my way to NOT be obnoxious about it, but I'd occasionally describe why I liked it so much, talked about the personal projects I use it for in my free time and why it's awesome for me, etc. Eventually we started another project and I convinced everyone to use Python for it. I took care to point everyone to a lot of documentation, including the specific webpages relating to what they were working on, and every time they had a question, I'd explain how to do things properly by explaining the Pythonic approach to things, etc. This has worked really well. However, this might be somewhat different than what you're describing. In my case I started with moderately small projects and Python is only being used for new projects. Also, none of my co-workers were really Perl or PHP gurus; they all knew those languages and had been using them for awhile, but it didn't take much effort for them to become more productive in Python than they'd been before. So if you're talking about new projects with people who currently use PHP but aren't super-experts and don't love that language, then I think switching to Python is a no-brainer. However, if you're talking about working with a large existing PHP code base with a lot of very experienced PHP programmers who are happy with their current setup, then switching languages is probably not a good idea. You're probably somewhere in between, so you'll have to weigh the tradeoffs; hopefully my answer will help you do that.
[ "php", "python" ]
6
15
667
8
0
2008-08-21T11:48:03
2008-08-21T12:25:21.210000
19,656
19,663
How to find an implementation of a C# interface in the current assembly with a specific name?
I have an Interface called IStep that can do some computation (See " Execution in the Kingdom of Nouns "). At runtime, I want to select the appropriate implementation by class name. // use like this: IStep step = GetStep(sName);
Your question is very confusing... If you want to find types that implement IStep, then do this: foreach (Type t in Assembly.GetCallingAssembly().GetTypes()) { if (!typeof(IStep).IsAssignableFrom(t)) continue; Console.WriteLine(t.FullName + " implements " + typeof(IStep).FullName); } If you know already the name of the required type, just do this IStep step = (IStep)Activator.CreateInstance(Type.GetType("MyNamespace.MyType"));
How to find an implementation of a C# interface in the current assembly with a specific name? I have an Interface called IStep that can do some computation (See " Execution in the Kingdom of Nouns "). At runtime, I want to select the appropriate implementation by class name. // use like this: IStep step = GetStep(sName);
TITLE: How to find an implementation of a C# interface in the current assembly with a specific name? QUESTION: I have an Interface called IStep that can do some computation (See " Execution in the Kingdom of Nouns "). At runtime, I want to select the appropriate implementation by class name. // use like this: IStep step = GetStep(sName); ANSWER: Your question is very confusing... If you want to find types that implement IStep, then do this: foreach (Type t in Assembly.GetCallingAssembly().GetTypes()) { if (!typeof(IStep).IsAssignableFrom(t)) continue; Console.WriteLine(t.FullName + " implements " + typeof(IStep).FullName); } If you know already the name of the required type, just do this IStep step = (IStep)Activator.CreateInstance(Type.GetType("MyNamespace.MyType"));
[ "c#", "linq", "reflection", "linq-to-objects" ]
7
8
5,648
4
0
2008-08-21T11:49:08.020000
2008-08-21T11:53:00.647000
19,708
19,716
Fast(er) way to get file inode using PHP
To grab the inode of a file in PHP, you can use this: $fs = stat($file); echo $fs['ino']; The problem with this is EVERYWHERE says it's slow and you should avoid it. So the question becomes what's the fast(er) way to do it?
You could use fileinode() but you should run benchmarks if you think it is slow.
Fast(er) way to get file inode using PHP To grab the inode of a file in PHP, you can use this: $fs = stat($file); echo $fs['ino']; The problem with this is EVERYWHERE says it's slow and you should avoid it. So the question becomes what's the fast(er) way to do it?
TITLE: Fast(er) way to get file inode using PHP QUESTION: To grab the inode of a file in PHP, you can use this: $fs = stat($file); echo $fs['ino']; The problem with this is EVERYWHERE says it's slow and you should avoid it. So the question becomes what's the fast(er) way to do it? ANSWER: You could use fileinode() but you should run benchmarks if you think it is slow.
[ "php", "inode" ]
0
1
1,260
2
0
2008-08-21T12:22:44.570000
2008-08-21T12:25:25.080000
19,713
19,732
Interlocked.Exchange, but not for booleans?
Is there an equivalent for Interlocked.Exchange for boolean? Such as an atomic exchange of values that returns the previous value and doesn't require locks?
No; use integers instead of booleans. In principle such a thing could be written (cmpxchg, the underlying processor instruction, can operate on 8, 16, 32, and 64-bit operands on x86, 8, 16, 32, 64, and 128-bit operands on x64), but in practice most APIs stick to pointer and double pointer (32 and 64-bit on x86, 64 and 128-bit on x64) operands, because they're all you really need.
Interlocked.Exchange, but not for booleans? Is there an equivalent for Interlocked.Exchange for boolean? Such as an atomic exchange of values that returns the previous value and doesn't require locks?
TITLE: Interlocked.Exchange, but not for booleans? QUESTION: Is there an equivalent for Interlocked.Exchange for boolean? Such as an atomic exchange of values that returns the previous value and doesn't require locks? ANSWER: No; use integers instead of booleans. In principle such a thing could be written (cmpxchg, the underlying processor instruction, can operate on 8, 16, 32, and 64-bit operands on x86, 8, 16, 32, 64, and 128-bit operands on x64), but in practice most APIs stick to pointer and double pointer (32 and 64-bit on x86, 64 and 128-bit on x64) operands, because they're all you really need.
[ ".net", "multithreading" ]
11
8
2,107
1
0
2008-08-21T12:24:23.333000
2008-08-21T12:33:13.907000
19,721
19,736
How do I secure my new web server (Server 2008)?
I've just put my new server up on an IP address with a domain pointing to it. I need to be able to remote admin it. I've opened the firewall for Remote Desktop and HTTP traffic. Is this going to be secure enough? I guess I should probably rename the administrator user...
The absolute minimum you should do is change the Remote Desktop port, change the Admin username, and have a very strong admin password.
How do I secure my new web server (Server 2008)? I've just put my new server up on an IP address with a domain pointing to it. I need to be able to remote admin it. I've opened the firewall for Remote Desktop and HTTP traffic. Is this going to be secure enough? I guess I should probably rename the administrator user...
TITLE: How do I secure my new web server (Server 2008)? QUESTION: I've just put my new server up on an IP address with a domain pointing to it. I need to be able to remote admin it. I've opened the firewall for Remote Desktop and HTTP traffic. Is this going to be secure enough? I guess I should probably rename the administrator user... ANSWER: The absolute minimum you should do is change the Remote Desktop port, change the Admin username, and have a very strong admin password.
[ "security" ]
3
4
652
4
0
2008-08-21T12:28:47.193000
2008-08-21T12:33:33.577000
19,725
19,740
How do I unregister COM dlls initially added with RegSvr32 when the /u arg doesn't work?
Right, initially ran: c:\regsvr32 Amazing.dll then, (accidentally - I might add) I must have run it again, and (indeed) again when new versions of 'Amazing.dll' were released. Yes - I know now I should've run: c:\regsvr32 /u Amazing.dll beforehand - but hey! I forgot. To cut to the chase, when add the COM reference in VS, I can see 3 instances of 'Amazing' all pointing to the same location (c:\Amazing.dll), running regsvr32 /u removes one of the references, the second time - does nothing... How do I get rid of these references? Am I looking at a regedit scenario? - If so - what exactly happens if I delete one of the keys??? Cheers
Your object's GUID's should not be changing. In other words, once you register the COM object, re-registering shouldn't be adding anything additional to the registry. Unless you added additional COM interfaces or objects to the project. In any case, if this is a one time deal (and it sounds like it is), open regedit and delete the unneeded keys manually.
How do I unregister COM dlls initially added with RegSvr32 when the /u arg doesn't work? Right, initially ran: c:\regsvr32 Amazing.dll then, (accidentally - I might add) I must have run it again, and (indeed) again when new versions of 'Amazing.dll' were released. Yes - I know now I should've run: c:\regsvr32 /u Amazing.dll beforehand - but hey! I forgot. To cut to the chase, when add the COM reference in VS, I can see 3 instances of 'Amazing' all pointing to the same location (c:\Amazing.dll), running regsvr32 /u removes one of the references, the second time - does nothing... How do I get rid of these references? Am I looking at a regedit scenario? - If so - what exactly happens if I delete one of the keys??? Cheers
TITLE: How do I unregister COM dlls initially added with RegSvr32 when the /u arg doesn't work? QUESTION: Right, initially ran: c:\regsvr32 Amazing.dll then, (accidentally - I might add) I must have run it again, and (indeed) again when new versions of 'Amazing.dll' were released. Yes - I know now I should've run: c:\regsvr32 /u Amazing.dll beforehand - but hey! I forgot. To cut to the chase, when add the COM reference in VS, I can see 3 instances of 'Amazing' all pointing to the same location (c:\Amazing.dll), running regsvr32 /u removes one of the references, the second time - does nothing... How do I get rid of these references? Am I looking at a regedit scenario? - If so - what exactly happens if I delete one of the keys??? Cheers ANSWER: Your object's GUID's should not be changing. In other words, once you register the COM object, re-registering shouldn't be adding anything additional to the registry. Unless you added additional COM interfaces or objects to the project. In any case, if this is a one time deal (and it sounds like it is), open regedit and delete the unneeded keys manually.
[ "visual-studio", "com", "regsvr32", "dllregistration" ]
14
14
16,222
3
0
2008-08-21T12:30:49.107000
2008-08-21T12:35:41.543000
19,728
19,774
What is the best strategy for retainment of large data sets?
I'm leading a project where we'll be recording metrics data. I'd like to retain the data for years. However, I'd also like to keep the primary table from becoming bloated with data that, while necessary for long term trending, isn't required for short term reporting. What is the best strategy for handling this situation? Simply archive the old data to another table? Or "roll it up" via some consolidation of the data itself (and then store it off to a different table)? Or something else entirely? Additional info: we are using SQL Server 2005.
We use both methods at my work, but slightly different, we keep all sales data in the primary table for 30 days, then at night (part of the nightly jobs) the days sales are rolled up into summaries (n qty of x product sold today ect) in a separate table for reporting reasons, and sales over 30 days are archived into a different database, then once a year (we go on tax years) a new archive database is started. not exactly perfect but.. this way we get the summaries data fast, keep all current sales data at hand and have an unlimited space for the detailed archive data. we did try keeping it all in one database (in different tables) but the file size of the database (interbase) would grow so large that it would drag the system down. the only real problem we have is accessing detailed data that spans several database, as connecting and disconnecting is slow, and analysis has to be done in code rather than sql
What is the best strategy for retainment of large data sets? I'm leading a project where we'll be recording metrics data. I'd like to retain the data for years. However, I'd also like to keep the primary table from becoming bloated with data that, while necessary for long term trending, isn't required for short term reporting. What is the best strategy for handling this situation? Simply archive the old data to another table? Or "roll it up" via some consolidation of the data itself (and then store it off to a different table)? Or something else entirely? Additional info: we are using SQL Server 2005.
TITLE: What is the best strategy for retainment of large data sets? QUESTION: I'm leading a project where we'll be recording metrics data. I'd like to retain the data for years. However, I'd also like to keep the primary table from becoming bloated with data that, while necessary for long term trending, isn't required for short term reporting. What is the best strategy for handling this situation? Simply archive the old data to another table? Or "roll it up" via some consolidation of the data itself (and then store it off to a different table)? Or something else entirely? Additional info: we are using SQL Server 2005. ANSWER: We use both methods at my work, but slightly different, we keep all sales data in the primary table for 30 days, then at night (part of the nightly jobs) the days sales are rolled up into summaries (n qty of x product sold today ect) in a separate table for reporting reasons, and sales over 30 days are archived into a different database, then once a year (we go on tax years) a new archive database is started. not exactly perfect but.. this way we get the summaries data fast, keep all current sales data at hand and have an unlimited space for the detailed archive data. we did try keeping it all in one database (in different tables) but the file size of the database (interbase) would grow so large that it would drag the system down. the only real problem we have is accessing detailed data that spans several database, as connecting and disconnecting is slow, and analysis has to be done in code rather than sql
[ "database-design", "dataset" ]
9
4
748
5
0
2008-08-21T12:31:54.783000
2008-08-21T12:54:23.463000
19,744
30,681
Trigger without a transaction?
Is it possible to create a trigger that will not be in a transaction? I want to update data on a linked server with a trigger but due to firewall issues we can't create a distributed transaction between the two servers.
What you probably want is a combination of a queue that contains updates for the linked server and a process that reads data from the queue and updates the remote server. The trigger will then insert a message into the queue as part of the normal transaction. This data will be read by the separate process and used to update the remote server. Logic will needed in the process handle errors (and possibly retries). The queue can be implemented with one or more tables.
Trigger without a transaction? Is it possible to create a trigger that will not be in a transaction? I want to update data on a linked server with a trigger but due to firewall issues we can't create a distributed transaction between the two servers.
TITLE: Trigger without a transaction? QUESTION: Is it possible to create a trigger that will not be in a transaction? I want to update data on a linked server with a trigger but due to firewall issues we can't create a distributed transaction between the two servers. ANSWER: What you probably want is a combination of a queue that contains updates for the linked server and a process that reads data from the queue and updates the remote server. The trigger will then insert a message into the queue as part of the normal transaction. This data will be read by the separate process and used to update the remote server. Logic will needed in the process handle errors (and possibly retries). The queue can be implemented with one or more tables.
[ "sql-server", "t-sql", "triggers" ]
4
3
2,483
2
0
2008-08-21T12:36:42.540000
2008-08-27T17:24:42.250000
19,746
35,250
Views in separate assemblies in ASP.NET MVC
I'm trying to create a webapplication where I want to be able to plug-in separate assemblies. I'm using MVC preview 4 combined with Unity for dependency injection, which I use to create the controllers from my plugin assemblies. I'm using WebForms (default aspx) as my view engine. If I want to use a view, I'm stuck on the ones that are defined in the core project, because of the dynamic compiling of the ASPX part. I'm looking for a proper way to enclose ASPX files in a different assembly, without having to go through the whole deployment step. Am I missing something obvious? Or should I resort to creating my views programmatically? Update: I changed the accepted answer. Even though Dale's answer is very thorough, I went for the solution with a different virtual path provider. It works like a charm, and takes only about 20 lines in code altogether I think.
Essentially this is the same issue as people had with WebForms and trying to compile their UserControl ASCX files into a DLL. I found this http://www.codeproject.com/KB/aspnet/ASP2UserControlLibrary.aspx that might work for you too.
Views in separate assemblies in ASP.NET MVC I'm trying to create a webapplication where I want to be able to plug-in separate assemblies. I'm using MVC preview 4 combined with Unity for dependency injection, which I use to create the controllers from my plugin assemblies. I'm using WebForms (default aspx) as my view engine. If I want to use a view, I'm stuck on the ones that are defined in the core project, because of the dynamic compiling of the ASPX part. I'm looking for a proper way to enclose ASPX files in a different assembly, without having to go through the whole deployment step. Am I missing something obvious? Or should I resort to creating my views programmatically? Update: I changed the accepted answer. Even though Dale's answer is very thorough, I went for the solution with a different virtual path provider. It works like a charm, and takes only about 20 lines in code altogether I think.
TITLE: Views in separate assemblies in ASP.NET MVC QUESTION: I'm trying to create a webapplication where I want to be able to plug-in separate assemblies. I'm using MVC preview 4 combined with Unity for dependency injection, which I use to create the controllers from my plugin assemblies. I'm using WebForms (default aspx) as my view engine. If I want to use a view, I'm stuck on the ones that are defined in the core project, because of the dynamic compiling of the ASPX part. I'm looking for a proper way to enclose ASPX files in a different assembly, without having to go through the whole deployment step. Am I missing something obvious? Or should I resort to creating my views programmatically? Update: I changed the accepted answer. Even though Dale's answer is very thorough, I went for the solution with a different virtual path provider. It works like a charm, and takes only about 20 lines in code altogether I think. ANSWER: Essentially this is the same issue as people had with WebForms and trying to compile their UserControl ASCX files into a DLL. I found this http://www.codeproject.com/KB/aspnet/ASP2UserControlLibrary.aspx that might work for you too.
[ "c#", "asp.net-mvc", "plugins" ]
54
15
30,670
4
0
2008-08-21T12:37:23.490000
2008-08-29T20:34:48.740000
19,766
19,804
How do I make a list with checkboxes in Java Swing?
What would be the best way to have a list of items with a checkbox each in Java Swing? I.e. a JList with items that have some text and a checkbox each?
Create a custom ListCellRenderer and asign it to the JList. This custom ListCellRenderer must return a JCheckbox in the implementantion of getListCellRendererComponent(...) method. But this JCheckbox will not be editable, is a simple paint in the screen is up to you to choose when this JCheckbox must be 'ticked' or not, For example, show it ticked when the row is selected (parameter isSelected ), but this way the check status will no be mantained if the selection changes. Its better to show it checked consulting the data below the ListModel, but then is up to you to implement the method who changes the check status of the data, and notify the change to the JList to be repainted. I Will post sample code later if you need it ListCellRenderer
How do I make a list with checkboxes in Java Swing? What would be the best way to have a list of items with a checkbox each in Java Swing? I.e. a JList with items that have some text and a checkbox each?
TITLE: How do I make a list with checkboxes in Java Swing? QUESTION: What would be the best way to have a list of items with a checkbox each in Java Swing? I.e. a JList with items that have some text and a checkbox each? ANSWER: Create a custom ListCellRenderer and asign it to the JList. This custom ListCellRenderer must return a JCheckbox in the implementantion of getListCellRendererComponent(...) method. But this JCheckbox will not be editable, is a simple paint in the screen is up to you to choose when this JCheckbox must be 'ticked' or not, For example, show it ticked when the row is selected (parameter isSelected ), but this way the check status will no be mantained if the selection changes. Its better to show it checked consulting the data below the ListModel, but then is up to you to implement the method who changes the check status of the data, and notify the change to the JList to be repainted. I Will post sample code later if you need it ListCellRenderer
[ "java", "swing", "jcheckbox" ]
35
17
90,011
11
0
2008-08-21T12:49:12.400000
2008-08-21T13:05:26.637000
19,772
19,778
CMD.exe replacement
Does anyone know of a good Command Prompt replacement? I've tried bash/Cygwin, but that does not really meet my needs at work because it's too heavy. I'd like a function-for-function identical wrapper on cmd.exe, but with highlighting, intellisense, and (critically) a tabbed interface. Powershell is okay, but the interface is still lacking.
Edited: I've been using ConEmu ( http://conemu.github.io/ ) for quite some time now. This one is a wrapper too, since it is not really possible to replace the Windows console without rewriting the whole command interpreter. Below the line is my original answer for an earlier alternative. Not exactly a replacement (actually, it's a prettifying wrapper) but you might try Console ( http://sourceforge.net/projects/console/ )
CMD.exe replacement Does anyone know of a good Command Prompt replacement? I've tried bash/Cygwin, but that does not really meet my needs at work because it's too heavy. I'd like a function-for-function identical wrapper on cmd.exe, but with highlighting, intellisense, and (critically) a tabbed interface. Powershell is okay, but the interface is still lacking.
TITLE: CMD.exe replacement QUESTION: Does anyone know of a good Command Prompt replacement? I've tried bash/Cygwin, but that does not really meet my needs at work because it's too heavy. I'd like a function-for-function identical wrapper on cmd.exe, but with highlighting, intellisense, and (critically) a tabbed interface. Powershell is okay, but the interface is still lacking. ANSWER: Edited: I've been using ConEmu ( http://conemu.github.io/ ) for quite some time now. This one is a wrapper too, since it is not really possible to replace the Windows console without rewriting the whole command interpreter. Below the line is my original answer for an earlier alternative. Not exactly a replacement (actually, it's a prettifying wrapper) but you might try Console ( http://sourceforge.net/projects/console/ )
[ "command-line", "terminal" ]
90
64
52,720
10
0
2008-08-21T12:53:46.663000
2008-08-21T12:56:01.323000
19,773
19,784
Huge Web App With Memory Leak in IE 6
I have a huge web app that is having issues with memory leak in IE 6. Fixing a memory leak in a 5 line code sample that demonstrates the problem is easy. But if I have a very huge application, where should a start from?
Check out Drip. That usually takes the guesswork out of IE memory leaks. If for some reason Drip doesn't find it, take a close look at any JavaScript code that works with events. That is almost always the source of any significant memory leak in a browser. Destroying a DOM element with handlers attached to it, without removing those handlers first, will prevent the memory associated with those handlers from being recovered.
Huge Web App With Memory Leak in IE 6 I have a huge web app that is having issues with memory leak in IE 6. Fixing a memory leak in a 5 line code sample that demonstrates the problem is easy. But if I have a very huge application, where should a start from?
TITLE: Huge Web App With Memory Leak in IE 6 QUESTION: I have a huge web app that is having issues with memory leak in IE 6. Fixing a memory leak in a 5 line code sample that demonstrates the problem is easy. But if I have a very huge application, where should a start from? ANSWER: Check out Drip. That usually takes the guesswork out of IE memory leaks. If for some reason Drip doesn't find it, take a close look at any JavaScript code that works with events. That is almost always the source of any significant memory leak in a browser. Destroying a DOM element with handlers attached to it, without removing those handlers first, will prevent the memory associated with those handlers from being recovered.
[ "memory-leaks", "internet-explorer-6" ]
3
7
1,589
3
0
2008-08-21T12:54:18.037000
2008-08-21T12:59:03.173000
19,786
19,920
Local Currency String conversion
I am maintaining an app for a client that is used in two locations. One in England and one in Poland. The database is stored in England and uses the format £1000.00 for currency, but the information is being gathered locally in Poland where 1000,00 is the format. My question is, in VB6 is there a function that takes a currency string in a local format and converts to another, or will I just have to parse the string and replace, or.? BTW I have looked at CCur, but not sure if that will do what I want.
The data is not actually stored as the string "£1000.00"; it's stored in some numeric format. Sidebar: Usually databases are set up to store money amounts using either the decimal data type (also called money in some DBs), or as a floating point number (also called double ). The difference is that when it's stored as decimal certain numbers like 0.01 are represented exactly whereas in double those numbers can only be stored approximately, causing rounding errors. The database appears to be storing the number as "£1000.00" because something is formatting it for display. In VB6, there's a function FormatCurrency which would take a number like 1000 and return a string like "£1000.00". You'll notice that the FormatCurrency function does not take an argument specifying what type of currency to use. That's because it, along with all the other locale-specific functions in VB, figures out the currency from the current locale of the system (from the Windows Control Panel). That means that on my system, Debug.Print FormatCurrency(1000) will print $1,000.00, but if I run that same program on a Windows computer set to the UK locale, it will probably print £1,000.00, which, of course, is something completely different. Similarly, you've got some code, somewhere, I can't tell where, in Poland, it seems, that is responsible for parsing the user's string and converting it to a number. And if that code is in Visual Basic, again, it's relying on the control panel to decide whether "." or "," is the thousands separator and whether "," or "." is the decimal point. The function CDbl converts its argument to a number. So for example on my system in the US Debug.Print CDbl("1.200") produces the number one point two, on a system with the Control Panel set to European formatting, it would produce the number one thousand, two hundred. It's possible that the problem is that you have someone sitting a computer with the regional control panel set to use "." as the decimal separator, but they're typing "," as the decimal separator.
Local Currency String conversion I am maintaining an app for a client that is used in two locations. One in England and one in Poland. The database is stored in England and uses the format £1000.00 for currency, but the information is being gathered locally in Poland where 1000,00 is the format. My question is, in VB6 is there a function that takes a currency string in a local format and converts to another, or will I just have to parse the string and replace, or.? BTW I have looked at CCur, but not sure if that will do what I want.
TITLE: Local Currency String conversion QUESTION: I am maintaining an app for a client that is used in two locations. One in England and one in Poland. The database is stored in England and uses the format £1000.00 for currency, but the information is being gathered locally in Poland where 1000,00 is the format. My question is, in VB6 is there a function that takes a currency string in a local format and converts to another, or will I just have to parse the string and replace, or.? BTW I have looked at CCur, but not sure if that will do what I want. ANSWER: The data is not actually stored as the string "£1000.00"; it's stored in some numeric format. Sidebar: Usually databases are set up to store money amounts using either the decimal data type (also called money in some DBs), or as a floating point number (also called double ). The difference is that when it's stored as decimal certain numbers like 0.01 are represented exactly whereas in double those numbers can only be stored approximately, causing rounding errors. The database appears to be storing the number as "£1000.00" because something is formatting it for display. In VB6, there's a function FormatCurrency which would take a number like 1000 and return a string like "£1000.00". You'll notice that the FormatCurrency function does not take an argument specifying what type of currency to use. That's because it, along with all the other locale-specific functions in VB, figures out the currency from the current locale of the system (from the Windows Control Panel). That means that on my system, Debug.Print FormatCurrency(1000) will print $1,000.00, but if I run that same program on a Windows computer set to the UK locale, it will probably print £1,000.00, which, of course, is something completely different. Similarly, you've got some code, somewhere, I can't tell where, in Poland, it seems, that is responsible for parsing the user's string and converting it to a number. And if that code is in Visual Basic, again, it's relying on the control panel to decide whether "." or "," is the thousands separator and whether "," or "." is the decimal point. The function CDbl converts its argument to a number. So for example on my system in the US Debug.Print CDbl("1.200") produces the number one point two, on a system with the Control Panel set to European formatting, it would produce the number one thousand, two hundred. It's possible that the problem is that you have someone sitting a computer with the regional control panel set to use "." as the decimal separator, but they're typing "," as the decimal separator.
[ "vb6", "localization", "internationalization" ]
2
8
4,749
4
0
2008-08-21T12:59:45.340000
2008-08-21T13:40:13.540000
19,787
19,826
How Do I Find a File in a Subversion Repository History?
Is it possible to look back through the history of a Subversion repository for files of a certain name (even better would be for them to have a wildcard search)? I want to see if a.bat file has been committed to the repository at some point in the past but has since been removed in later updates. Even a dump of the file history at each revision would work, as I could just grep the output. I have looked through the manual but could not see a good way to do this. The logs for each commit are descriptive, so I cannot just look through the log messages to see what modifications were done. I presume Subversion does have a way of retrieving this?
TortoiseSVN can search the logs very easily, and on my system I can enter ".plg" in the search box and find all adds, modifies, and deletes for those files. Without Tortoise, the only way I can think of doing that would be to grep the full logs or parse the logs and do your own searching for 'A' and 'D' indicators on the file you are looking for (use svn log --verbose to get file paths). svn log --verbose | grep.bat
How Do I Find a File in a Subversion Repository History? Is it possible to look back through the history of a Subversion repository for files of a certain name (even better would be for them to have a wildcard search)? I want to see if a.bat file has been committed to the repository at some point in the past but has since been removed in later updates. Even a dump of the file history at each revision would work, as I could just grep the output. I have looked through the manual but could not see a good way to do this. The logs for each commit are descriptive, so I cannot just look through the log messages to see what modifications were done. I presume Subversion does have a way of retrieving this?
TITLE: How Do I Find a File in a Subversion Repository History? QUESTION: Is it possible to look back through the history of a Subversion repository for files of a certain name (even better would be for them to have a wildcard search)? I want to see if a.bat file has been committed to the repository at some point in the past but has since been removed in later updates. Even a dump of the file history at each revision would work, as I could just grep the output. I have looked through the manual but could not see a good way to do this. The logs for each commit are descriptive, so I cannot just look through the log messages to see what modifications were done. I presume Subversion does have a way of retrieving this? ANSWER: TortoiseSVN can search the logs very easily, and on my system I can enter ".plg" in the search box and find all adds, modifies, and deletes for those files. Without Tortoise, the only way I can think of doing that would be to grep the full logs or parse the logs and do your own searching for 'A' and 'D' indicators on the file you are looking for (use svn log --verbose to get file paths). svn log --verbose | grep.bat
[ "svn", "repository" ]
26
23
19,015
5
0
2008-08-21T12:59:53.357000
2008-08-21T13:11:29.180000
19,790
19,805
Display rows in multiple columns in Asp.net Gridview
By default each row of a Gridview maps to each row in a datatable or dataset attached to its datasource. But what if I want to display these rows in multiple columns. For example if it has 10 rows, 5 rows each should be displayed in 2 columns side by side. Also can I do this with the Infragistics grid. Is this possible?
You can use a DataList control instead. It has a RepeatColumns property that you can define the number of columns you want to display. In.NET Framework 3.5, there is an even better solution, the ListView control. You can find further information about how to use the ListView control here.
Display rows in multiple columns in Asp.net Gridview By default each row of a Gridview maps to each row in a datatable or dataset attached to its datasource. But what if I want to display these rows in multiple columns. For example if it has 10 rows, 5 rows each should be displayed in 2 columns side by side. Also can I do this with the Infragistics grid. Is this possible?
TITLE: Display rows in multiple columns in Asp.net Gridview QUESTION: By default each row of a Gridview maps to each row in a datatable or dataset attached to its datasource. But what if I want to display these rows in multiple columns. For example if it has 10 rows, 5 rows each should be displayed in 2 columns side by side. Also can I do this with the Infragistics grid. Is this possible? ANSWER: You can use a DataList control instead. It has a RepeatColumns property that you can define the number of columns you want to display. In.NET Framework 3.5, there is an even better solution, the ListView control. You can find further information about how to use the ListView control here.
[ "asp.net", "gridview", "infragistics", "ultrawebgrid" ]
8
14
29,879
3
0
2008-08-21T13:00:56.787000
2008-08-21T13:05:57.243000
19,803
19,874
Profiling/Optimizing (Sharepoint 2007) Web Parts
I just wonder what options there are to properly measure/profile/optimize ASP.net 2.0 Web Parts, especially the ones for Sharepoint 2007? As Web Parts are a layer on another layer of technology, getting resource usage, open handles and stuff only for the web part seems to be a bit difficult. Does anyone know some good tools or practices for profiling and optimizing web parts?
Back when we started with SP2003, we used to worry about not closing connection in apps or web parts. We used the following query to check if the base number of connections (not counting the initial spike) would increase as the app is used on the development server: SELECT hostname, sysdatabases.name, sysprocesses.status, last_batch from sysprocesses, sysdatabases where sysprocesses.dbid = sysdatabases.dbid and nt_username = ' SP Service Account ' and (hostname=' WFE1 ' or hostname=' WFE2 ') and sysprocesses.dbid = 10 order by last_batch desc (replace the bolded values with those appropriate for your environment) We haven't tried this since the upgrade to MOSS though.
Profiling/Optimizing (Sharepoint 2007) Web Parts I just wonder what options there are to properly measure/profile/optimize ASP.net 2.0 Web Parts, especially the ones for Sharepoint 2007? As Web Parts are a layer on another layer of technology, getting resource usage, open handles and stuff only for the web part seems to be a bit difficult. Does anyone know some good tools or practices for profiling and optimizing web parts?
TITLE: Profiling/Optimizing (Sharepoint 2007) Web Parts QUESTION: I just wonder what options there are to properly measure/profile/optimize ASP.net 2.0 Web Parts, especially the ones for Sharepoint 2007? As Web Parts are a layer on another layer of technology, getting resource usage, open handles and stuff only for the web part seems to be a bit difficult. Does anyone know some good tools or practices for profiling and optimizing web parts? ANSWER: Back when we started with SP2003, we used to worry about not closing connection in apps or web parts. We used the following query to check if the base number of connections (not counting the initial spike) would increase as the app is used on the development server: SELECT hostname, sysdatabases.name, sysprocesses.status, last_batch from sysprocesses, sysdatabases where sysprocesses.dbid = sysdatabases.dbid and nt_username = ' SP Service Account ' and (hostname=' WFE1 ' or hostname=' WFE2 ') and sysprocesses.dbid = 10 order by last_batch desc (replace the bolded values with those appropriate for your environment) We haven't tried this since the upgrade to MOSS though.
[ "asp.net", "sharepoint" ]
1
0
388
3
0
2008-08-21T13:05:21.863000
2008-08-21T13:32:06.760000
19,837
20,427
PHP with SQL Server 2005+
Currently we have a hybrid ASP/PHP setup connecting to a SQL Server 2005 database. But all the query work is done on the client side, I'd like to move some of this to PHP. What driver and/or connection string is needed to connect to Sql Svr and what is the syntax to use in PHP? Update: OK so I was definitely trying to avoid using anything to do with copying DLLs etc. I'll look into the SQL2K5PHP driver (thanks Vincent). @jcarrascal for the sake of clarity, by "client side" I mean our application is an internal web app that runs as an HTA, with all queries done via javascript calls to an ASP which actually submits the DB request.
You have two options: 1) php_mssql extension: If you'd like something that has the same API mysql and mysqli has, then use the php_mssql extension. But there is a catch, the bundled ntwdblib.dll file with PHP is not working. You have to find this file from a SQL Server 2000 installation or you can find it on the Internet. This API is supposedly not very reliable but I have been using it without problem for about one year. http://ca.php.net/mssql 2) Microsoft SQL Server 2005 PHP Driver: If you'd like something more modern but which does not have the same API and is missing some important functions (mssql_num_rows). The big plus is that it is supported by Microsoft and is likely to work with a future version. http://msdn.microsoft.com/en-us/data/cc299381.aspx
PHP with SQL Server 2005+ Currently we have a hybrid ASP/PHP setup connecting to a SQL Server 2005 database. But all the query work is done on the client side, I'd like to move some of this to PHP. What driver and/or connection string is needed to connect to Sql Svr and what is the syntax to use in PHP? Update: OK so I was definitely trying to avoid using anything to do with copying DLLs etc. I'll look into the SQL2K5PHP driver (thanks Vincent). @jcarrascal for the sake of clarity, by "client side" I mean our application is an internal web app that runs as an HTA, with all queries done via javascript calls to an ASP which actually submits the DB request.
TITLE: PHP with SQL Server 2005+ QUESTION: Currently we have a hybrid ASP/PHP setup connecting to a SQL Server 2005 database. But all the query work is done on the client side, I'd like to move some of this to PHP. What driver and/or connection string is needed to connect to Sql Svr and what is the syntax to use in PHP? Update: OK so I was definitely trying to avoid using anything to do with copying DLLs etc. I'll look into the SQL2K5PHP driver (thanks Vincent). @jcarrascal for the sake of clarity, by "client side" I mean our application is an internal web app that runs as an HTA, with all queries done via javascript calls to an ASP which actually submits the DB request. ANSWER: You have two options: 1) php_mssql extension: If you'd like something that has the same API mysql and mysqli has, then use the php_mssql extension. But there is a catch, the bundled ntwdblib.dll file with PHP is not working. You have to find this file from a SQL Server 2000 installation or you can find it on the Internet. This API is supposedly not very reliable but I have been using it without problem for about one year. http://ca.php.net/mssql 2) Microsoft SQL Server 2005 PHP Driver: If you'd like something more modern but which does not have the same API and is missing some important functions (mssql_num_rows). The big plus is that it is supported by Microsoft and is likely to work with a future version. http://msdn.microsoft.com/en-us/data/cc299381.aspx
[ "php", "sql-server" ]
3
5
508
3
0
2008-08-21T13:17:44.297000
2008-08-21T16:20:25.700000
19,838
20,154
Ruby blocks/Java closures in C
I've been trying to understand how Ruby blocks work, and to do that I've been trying to implement them in C. One easy way to implement closures is to pass a void* to the enclosing stack to the closure/function but Ruby blocks also seem to handle returns and break statements from the scope that uses the block. loop do break i if (i >= 4000) i *= 2 end I think one of the closures proposals for Java works like this also. So, how would you implement Ruby-blocks/Java-closures in C?
The concept of closures requires the concept of contexts. C's context is based on the stack and the registers of the CPU, so to create a block/closure, you need to be able to manipulate the stack pointer in a correct (and reentrant) way, and store/restore registers as needed. The way this is done by interpreters or virtual machines is to have a context structure or something similar, and not use the stack and registers directly. This structure keeps track of a stack and optionally some registers, if you're designing a register based VM. At least, that's the simplest way to do it (though slightly less performant than actually mapping things correctly).
Ruby blocks/Java closures in C I've been trying to understand how Ruby blocks work, and to do that I've been trying to implement them in C. One easy way to implement closures is to pass a void* to the enclosing stack to the closure/function but Ruby blocks also seem to handle returns and break statements from the scope that uses the block. loop do break i if (i >= 4000) i *= 2 end I think one of the closures proposals for Java works like this also. So, how would you implement Ruby-blocks/Java-closures in C?
TITLE: Ruby blocks/Java closures in C QUESTION: I've been trying to understand how Ruby blocks work, and to do that I've been trying to implement them in C. One easy way to implement closures is to pass a void* to the enclosing stack to the closure/function but Ruby blocks also seem to handle returns and break statements from the scope that uses the block. loop do break i if (i >= 4000) i *= 2 end I think one of the closures proposals for Java works like this also. So, how would you implement Ruby-blocks/Java-closures in C? ANSWER: The concept of closures requires the concept of contexts. C's context is based on the stack and the registers of the CPU, so to create a block/closure, you need to be able to manipulate the stack pointer in a correct (and reentrant) way, and store/restore registers as needed. The way this is done by interpreters or virtual machines is to have a context structure or something similar, and not use the stack and registers directly. This structure keeps track of a stack and optionally some registers, if you're designing a register based VM. At least, that's the simplest way to do it (though slightly less performant than actually mapping things correctly).
[ "java", "c", "ruby" ]
6
10
1,323
3
0
2008-08-21T13:17:50.367000
2008-08-21T14:53:49.933000
19,843
20,139
Generics in c# & accessing the static members of T
My question concerns c# and how to access Static members... Well I don't really know how to explain it (which kind of is bad for a question isn't it?) I will just give you some sample code: Class test { int method1(Obj Parameter1){ //in here I want to do something which I would explain as T.TryParse(Parameter1); //my problem is that it does not work... I get an error. //just to explain: if I declare test (with type Integer) //I want my sample code to call int.TryParse(). If it were String //it should have been String.TryParse() } } So thank you guys for your answers (By the way the question is: how would I solve this problem without getting an error). This probably quite an easy question for you! Edit: Thank you all for your answers! Though I think the try - catch phrase is the most elegant, I know from my experience with vb that it can really be a bummer. I used it once and it took about 30 minutes to run a program, which later on only took 2 minutes to compute just because I avoided try - catch. This is why I chose the switch statement as the best answer. It makes the code more complicated but on the other hand I imagine it to be relatively fast and relatively easy to read. (Though I still think there should be a more elegant way... maybe in the next language I learn) Though if you have some other suggestion I am still waiting (and willing to participate)
One more way to do it, this time some reflection in the mix: static class Parser { public static bool TryParse ( string str, out TType x ) { // Get the type on that TryParse shall be called Type objType = typeof( TType ); // Enumerate the methods of TType foreach( MethodInfo mi in objType.GetMethods() ) { if( mi.Name == "TryParse" ) { // We found a TryParse method, check for the 2-parameter-signature ParameterInfo[] pi = mi.GetParameters(); if( pi.Length == 2 ) // Find TryParse( String, TType ) { // Build a parameter list for the call object[] paramList = new object[2] { str, default( TType ) }; // Invoke the static method object ret = objType.InvokeMember( "TryParse", BindingFlags.InvokeMethod, null, null, paramList ); // Get the output value from the parameter list x = (TType)paramList[1]; return (bool)ret; } } } // Maybe we should throw an exception here, because we were unable to find the TryParse // method; this is not just a unable-to-parse error. x = default( TType ); return false; } } The next step would be trying to implement public static TRet CallStaticMethod ( object obj, string methodName, params object[] args ); With full parameter type matching etc.
Generics in c# & accessing the static members of T My question concerns c# and how to access Static members... Well I don't really know how to explain it (which kind of is bad for a question isn't it?) I will just give you some sample code: Class test { int method1(Obj Parameter1){ //in here I want to do something which I would explain as T.TryParse(Parameter1); //my problem is that it does not work... I get an error. //just to explain: if I declare test (with type Integer) //I want my sample code to call int.TryParse(). If it were String //it should have been String.TryParse() } } So thank you guys for your answers (By the way the question is: how would I solve this problem without getting an error). This probably quite an easy question for you! Edit: Thank you all for your answers! Though I think the try - catch phrase is the most elegant, I know from my experience with vb that it can really be a bummer. I used it once and it took about 30 minutes to run a program, which later on only took 2 minutes to compute just because I avoided try - catch. This is why I chose the switch statement as the best answer. It makes the code more complicated but on the other hand I imagine it to be relatively fast and relatively easy to read. (Though I still think there should be a more elegant way... maybe in the next language I learn) Though if you have some other suggestion I am still waiting (and willing to participate)
TITLE: Generics in c# & accessing the static members of T QUESTION: My question concerns c# and how to access Static members... Well I don't really know how to explain it (which kind of is bad for a question isn't it?) I will just give you some sample code: Class test { int method1(Obj Parameter1){ //in here I want to do something which I would explain as T.TryParse(Parameter1); //my problem is that it does not work... I get an error. //just to explain: if I declare test (with type Integer) //I want my sample code to call int.TryParse(). If it were String //it should have been String.TryParse() } } So thank you guys for your answers (By the way the question is: how would I solve this problem without getting an error). This probably quite an easy question for you! Edit: Thank you all for your answers! Though I think the try - catch phrase is the most elegant, I know from my experience with vb that it can really be a bummer. I used it once and it took about 30 minutes to run a program, which later on only took 2 minutes to compute just because I avoided try - catch. This is why I chose the switch statement as the best answer. It makes the code more complicated but on the other hand I imagine it to be relatively fast and relatively easy to read. (Though I still think there should be a more elegant way... maybe in the next language I learn) Though if you have some other suggestion I am still waiting (and willing to participate) ANSWER: One more way to do it, this time some reflection in the mix: static class Parser { public static bool TryParse ( string str, out TType x ) { // Get the type on that TryParse shall be called Type objType = typeof( TType ); // Enumerate the methods of TType foreach( MethodInfo mi in objType.GetMethods() ) { if( mi.Name == "TryParse" ) { // We found a TryParse method, check for the 2-parameter-signature ParameterInfo[] pi = mi.GetParameters(); if( pi.Length == 2 ) // Find TryParse( String, TType ) { // Build a parameter list for the call object[] paramList = new object[2] { str, default( TType ) }; // Invoke the static method object ret = objType.InvokeMember( "TryParse", BindingFlags.InvokeMethod, null, null, paramList ); // Get the output value from the parameter list x = (TType)paramList[1]; return (bool)ret; } } } // Maybe we should throw an exception here, because we were unable to find the TryParse // method; this is not just a unable-to-parse error. x = default( TType ); return false; } } The next step would be trying to implement public static TRet CallStaticMethod ( object obj, string methodName, params object[] args ); With full parameter type matching etc.
[ "c#", "generics", "static", "methods", "data-access" ]
15
2
9,048
12
0
2008-08-21T13:20:05.710000
2008-08-21T14:46:46.097000
19,852
1,849,792
Maximum length of a MIME Content-Type header field?
I'm just designing the schema for a database table which will hold details of email attachments - their size in bytes, filename and content-type (i.e. "image/jpg", "audio/mp3", etc). Does anybody know the maximum length that I can expect a content-type to be?
I hope I havn't misread, but it looks like the length is max 127/127 or 255 total. RFC 4288 has a reference in 4.2 (page 6): Type and subtype names MUST conform to the following ABNF: type-name = reg-name subtype-name = reg-name reg-name = 1*127reg-name-chars reg-name-chars = ALPHA / DIGIT / "!" / "#" / "$" / "&" / "." / "+" / "-" / "^" / "_" It is not clear to me if the +suffix can add past the 127, but it appears not.
Maximum length of a MIME Content-Type header field? I'm just designing the schema for a database table which will hold details of email attachments - their size in bytes, filename and content-type (i.e. "image/jpg", "audio/mp3", etc). Does anybody know the maximum length that I can expect a content-type to be?
TITLE: Maximum length of a MIME Content-Type header field? QUESTION: I'm just designing the schema for a database table which will hold details of email attachments - their size in bytes, filename and content-type (i.e. "image/jpg", "audio/mp3", etc). Does anybody know the maximum length that I can expect a content-type to be? ANSWER: I hope I havn't misread, but it looks like the length is max 127/127 or 255 total. RFC 4288 has a reference in 4.2 (page 6): Type and subtype names MUST conform to the following ABNF: type-name = reg-name subtype-name = reg-name reg-name = 1*127reg-name-chars reg-name-chars = ALPHA / DIGIT / "!" / "#" / "$" / "&" / "." / "+" / "-" / "^" / "_" It is not clear to me if the +suffix can add past the 127, but it appears not.
[ "email", "mime" ]
41
49
21,097
3
0
2008-08-21T13:23:09.480000
2009-12-04T21:35:52.013000
19,883
19,896
Is there a bug/issue tracking system which integrates with Mercurial?
I've used Trac/Subversion before and really like the integration. My current project is using Mercurial for distributed development and it'd be nice to be able to track issues/bugs and have this be integrated with Mercurial. I realized this could be tricky with the nature of DVCS.
TracMercurial integrates Trac with Mercurial. Assembla provides free Mercurial hosting with Trac integration. The idea is that you have a central repository as your master and upload all the subsidiary changes from local repositories into the main one.
Is there a bug/issue tracking system which integrates with Mercurial? I've used Trac/Subversion before and really like the integration. My current project is using Mercurial for distributed development and it'd be nice to be able to track issues/bugs and have this be integrated with Mercurial. I realized this could be tricky with the nature of DVCS.
TITLE: Is there a bug/issue tracking system which integrates with Mercurial? QUESTION: I've used Trac/Subversion before and really like the integration. My current project is using Mercurial for distributed development and it'd be nice to be able to track issues/bugs and have this be integrated with Mercurial. I realized this could be tricky with the nature of DVCS. ANSWER: TracMercurial integrates Trac with Mercurial. Assembla provides free Mercurial hosting with Trac integration. The idea is that you have a central repository as your master and upload all the subsidiary changes from local repositories into the main one.
[ "mercurial", "integration", "bug-tracking" ]
20
11
12,667
12
0
2008-08-21T13:34:43.150000
2008-08-21T13:37:10.367000
19,893
19,904
How do you embed binary data in XML?
I have two applications written in Java that communicate with each other using XML messages over the network. I'm using a SAX parser at the receiving end to get the data back out of the messages. One of the requirements is to embed binary data in an XML message, but SAX doesn't like this. Does anyone know how to do this? UPDATE: I got this working with the Base64 class from the apache commons codec library, in case anyone else is trying something similar.
You could encode the binary data using base64 and put it into a Base64 element; the below article is a pretty good one on the subject. Handling Binary Data in XML Documents
How do you embed binary data in XML? I have two applications written in Java that communicate with each other using XML messages over the network. I'm using a SAX parser at the receiving end to get the data back out of the messages. One of the requirements is to embed binary data in an XML message, but SAX doesn't like this. Does anyone know how to do this? UPDATE: I got this working with the Base64 class from the apache commons codec library, in case anyone else is trying something similar.
TITLE: How do you embed binary data in XML? QUESTION: I have two applications written in Java that communicate with each other using XML messages over the network. I'm using a SAX parser at the receiving end to get the data back out of the messages. One of the requirements is to embed binary data in an XML message, but SAX doesn't like this. Does anyone know how to do this? UPDATE: I got this working with the Base64 class from the apache commons codec library, in case anyone else is trying something similar. ANSWER: You could encode the binary data using base64 and put it into a Base64 element; the below article is a pretty good one on the subject. Handling Binary Data in XML Documents
[ "java", "xml", "binary", "binary-data" ]
114
231
122,847
12
0
2008-08-21T13:35:46.830000
2008-08-21T13:37:58.600000
19,941
19,949
How do I redirect a user to a custom 404 page in ASP.NET MVC instead of throwing an exception?
I want to be able to capture the exception that is thrown when a user requests a non-existent controller and re-direct it to a 404 page. How can I do this? For example, the user requests http://www.nosite.com/paeges/1 ( should be /pages/ ). How do I make it so they get re-directed to the 404 rather than the exception screen?
Take a look at this page for routing your 404-errors to a specified page.
How do I redirect a user to a custom 404 page in ASP.NET MVC instead of throwing an exception? I want to be able to capture the exception that is thrown when a user requests a non-existent controller and re-direct it to a 404 page. How can I do this? For example, the user requests http://www.nosite.com/paeges/1 ( should be /pages/ ). How do I make it so they get re-directed to the 404 rather than the exception screen?
TITLE: How do I redirect a user to a custom 404 page in ASP.NET MVC instead of throwing an exception? QUESTION: I want to be able to capture the exception that is thrown when a user requests a non-existent controller and re-direct it to a 404 page. How can I do this? For example, the user requests http://www.nosite.com/paeges/1 ( should be /pages/ ). How do I make it so they get re-directed to the 404 rather than the exception screen? ANSWER: Take a look at this page for routing your 404-errors to a specified page.
[ "asp.net-mvc", "exception", "routes" ]
18
6
15,386
3
0
2008-08-21T13:46:58.563000
2008-08-21T13:50:20.303000
19,952
19,983
Algorithm to perform RFC calculation in Java
The RFC for a Java class is set of all methods that can be invoked in response to a message to an object of the class or by some method in the class. RFC = M + R where M = Number of methods in the class. R = Total number of other methods directly invoked from the M. Thinking C is the.class and J is the.java file of which we need to calculate RFC. class J{ a(){} b(){} c(){ e1.e(); e1.f(); e1.g(); } h(){ i.k(); i.j(); } m(){} n(){ i.o(); i.p(); i.p(); i.p(); } } here M=6 and R=9 (Don't worry about call inside a loop. It's considered as a single call) Calculating M is easy. Load C using classloader and use reflection to get the count of methods. Calculating R is not direct. We need to count the number of method calls from the class. First level only. For calculating R I must use regex. Usually format would be (calls without using. are not counted) [variable_name].[method_name]([zero or more parameters]); or [variable_name].[method_name]([zero or more parameters]) with out semicolon when call return is directly becomes parameter to another method. or [variable_name].[method_name]([zero or more parameters]).method2(); this becomes two method calls What other patterns of the method call can you think of? Is there any other way other than using RegEx that can be used to calculate R. UPDATE: @McDowell Looks like using BCEL I can simplify the whole process. Let me try it.
You could use the Byte Code Engineering Library with binaries. You can use a DescendingVisitor to visit a class' members and references. I've used it to find class dependencies. Alternatively, you could reuse some model of the source files. I'm pretty sure the Java editor in the Eclipse JDT is backed by some form of model.
Algorithm to perform RFC calculation in Java The RFC for a Java class is set of all methods that can be invoked in response to a message to an object of the class or by some method in the class. RFC = M + R where M = Number of methods in the class. R = Total number of other methods directly invoked from the M. Thinking C is the.class and J is the.java file of which we need to calculate RFC. class J{ a(){} b(){} c(){ e1.e(); e1.f(); e1.g(); } h(){ i.k(); i.j(); } m(){} n(){ i.o(); i.p(); i.p(); i.p(); } } here M=6 and R=9 (Don't worry about call inside a loop. It's considered as a single call) Calculating M is easy. Load C using classloader and use reflection to get the count of methods. Calculating R is not direct. We need to count the number of method calls from the class. First level only. For calculating R I must use regex. Usually format would be (calls without using. are not counted) [variable_name].[method_name]([zero or more parameters]); or [variable_name].[method_name]([zero or more parameters]) with out semicolon when call return is directly becomes parameter to another method. or [variable_name].[method_name]([zero or more parameters]).method2(); this becomes two method calls What other patterns of the method call can you think of? Is there any other way other than using RegEx that can be used to calculate R. UPDATE: @McDowell Looks like using BCEL I can simplify the whole process. Let me try it.
TITLE: Algorithm to perform RFC calculation in Java QUESTION: The RFC for a Java class is set of all methods that can be invoked in response to a message to an object of the class or by some method in the class. RFC = M + R where M = Number of methods in the class. R = Total number of other methods directly invoked from the M. Thinking C is the.class and J is the.java file of which we need to calculate RFC. class J{ a(){} b(){} c(){ e1.e(); e1.f(); e1.g(); } h(){ i.k(); i.j(); } m(){} n(){ i.o(); i.p(); i.p(); i.p(); } } here M=6 and R=9 (Don't worry about call inside a loop. It's considered as a single call) Calculating M is easy. Load C using classloader and use reflection to get the count of methods. Calculating R is not direct. We need to count the number of method calls from the class. First level only. For calculating R I must use regex. Usually format would be (calls without using. are not counted) [variable_name].[method_name]([zero or more parameters]); or [variable_name].[method_name]([zero or more parameters]) with out semicolon when call return is directly becomes parameter to another method. or [variable_name].[method_name]([zero or more parameters]).method2(); this becomes two method calls What other patterns of the method call can you think of? Is there any other way other than using RegEx that can be used to calculate R. UPDATE: @McDowell Looks like using BCEL I can simplify the whole process. Let me try it. ANSWER: You could use the Byte Code Engineering Library with binaries. You can use a DescendingVisitor to visit a class' members and references. I've used it to find class dependencies. Alternatively, you could reuse some model of the source files. I'm pretty sure the Java editor in the Eclipse JDT is backed by some form of model.
[ "java", "regex", "algorithm", "reflection" ]
4
2
1,194
4
0
2008-08-21T13:50:35.997000
2008-08-21T14:01:58.247000
19,956
23,022
What to use Windows CardSpace for?
I'm doing some funky authentication work (and yes, I know, open-id is awesome, but then again my open-id doesn't work right at this moment!). Stumbling across Windows CardSpace I was wondering if anyone has used this in a real product-system. If you have used it, what were the pros and cons for you? And how can i use it in my open-id?
Umm no you don't; you can accept information cards on a web site using a cheap and cheerful certificate (but not self signed) or no certificate at all. And yes, I've used it as part of a production system which grew out of a proof of concept I did at Microsoft. Cons: If you don't have an EV SSL certificate you get warnings. The code for parsing a card is incomplete at best (you have to hack it around for no-SSL), you have to explain to users what one is. Pros: Well that's more interesting; I was using managed cards and issuing them and then having 3rd parties use those to check claims; but for self issued cards; well, it's stronger than username password and doesn't have the same vulnerabilities OpenID has.
What to use Windows CardSpace for? I'm doing some funky authentication work (and yes, I know, open-id is awesome, but then again my open-id doesn't work right at this moment!). Stumbling across Windows CardSpace I was wondering if anyone has used this in a real product-system. If you have used it, what were the pros and cons for you? And how can i use it in my open-id?
TITLE: What to use Windows CardSpace for? QUESTION: I'm doing some funky authentication work (and yes, I know, open-id is awesome, but then again my open-id doesn't work right at this moment!). Stumbling across Windows CardSpace I was wondering if anyone has used this in a real product-system. If you have used it, what were the pros and cons for you? And how can i use it in my open-id? ANSWER: Umm no you don't; you can accept information cards on a web site using a cheap and cheerful certificate (but not self signed) or no certificate at all. And yes, I've used it as part of a production system which grew out of a proof of concept I did at Microsoft. Cons: If you don't have an EV SSL certificate you get warnings. The code for parsing a card is incomplete at best (you have to hack it around for no-SSL), you have to explain to users what one is. Pros: Well that's more interesting; I was using managed cards and issuing them and then having 3rd parties use those to check claims; but for self issued cards; well, it's stronger than username password and doesn't have the same vulnerabilities OpenID has.
[ "windows", "security", "authentication" ]
2
2
406
1
0
2008-08-21T13:53:35.880000
2008-08-22T17:51:57.890000
19,963
1,729,083
What's the best way of diffing Crystal Reports?
If you have two versions of the same report (.rpt) and you want to establish what the exact differences are, what is the best way to go about this? I've seen some commercial tools to do this, but I'm not too interested in forking out cash for something that should be relatively straight forward. Can I hook into the Crystal API and simply list all of the properties of every field or something? Please someone tell me that there's an Open Source project somewhere that does this... @:-) @Kogus, wouldn't diffing the outputs as text hide any formatting differences? @ladoucep, I don't seem to be able to export the report without data.
Can I hook into the Crystal API and simply list all of the properties of every field or something? Please someone tell me that there's an Open Source project somewhere that does this... @:-) There is in fact, such an API. I wrote a VB6 application to do just what you asked and more. I think I even migrated it to VB.Net. As it was for my own use, I didn't spend much time making it 'polished'. I've been intending to release it, but I haven't had the time... Another approach that I've used in the past is to create an Access application to help manage large, report-development projects. One of it's many features includes the ability to extract the tables that are used by the report, and the SQL statements used by its Commands and SQL Expressions. It's intent is to give one a global perspective of which reports use which tables. I probably still have it somewhere... ** edit 1 ** BusinessObjects Enterprise XI (R?) has a feature named 'Meta Manager'. It will periodically examine the contents of the Repository and save the results to a database. It uses the Report-Application Service (RAS) to generate the meta data. It's an additional, 5-figure license, of course. ** edit 2 ** Consider using PowerShell to do the work: PsCrystal.
What's the best way of diffing Crystal Reports? If you have two versions of the same report (.rpt) and you want to establish what the exact differences are, what is the best way to go about this? I've seen some commercial tools to do this, but I'm not too interested in forking out cash for something that should be relatively straight forward. Can I hook into the Crystal API and simply list all of the properties of every field or something? Please someone tell me that there's an Open Source project somewhere that does this... @:-) @Kogus, wouldn't diffing the outputs as text hide any formatting differences? @ladoucep, I don't seem to be able to export the report without data.
TITLE: What's the best way of diffing Crystal Reports? QUESTION: If you have two versions of the same report (.rpt) and you want to establish what the exact differences are, what is the best way to go about this? I've seen some commercial tools to do this, but I'm not too interested in forking out cash for something that should be relatively straight forward. Can I hook into the Crystal API and simply list all of the properties of every field or something? Please someone tell me that there's an Open Source project somewhere that does this... @:-) @Kogus, wouldn't diffing the outputs as text hide any formatting differences? @ladoucep, I don't seem to be able to export the report without data. ANSWER: Can I hook into the Crystal API and simply list all of the properties of every field or something? Please someone tell me that there's an Open Source project somewhere that does this... @:-) There is in fact, such an API. I wrote a VB6 application to do just what you asked and more. I think I even migrated it to VB.Net. As it was for my own use, I didn't spend much time making it 'polished'. I've been intending to release it, but I haven't had the time... Another approach that I've used in the past is to create an Access application to help manage large, report-development projects. One of it's many features includes the ability to extract the tables that are used by the report, and the SQL statements used by its Commands and SQL Expressions. It's intent is to give one a global perspective of which reports use which tables. I probably still have it somewhere... ** edit 1 ** BusinessObjects Enterprise XI (R?) has a feature named 'Meta Manager'. It will periodically examine the contents of the Repository and save the results to a database. It uses the Report-Application Service (RAS) to generate the meta data. It's an additional, 5-figure license, of course. ** edit 2 ** Consider using PowerShell to do the work: PsCrystal.
[ "crystal-reports", "diff" ]
19
12
8,381
3
0
2008-08-21T13:56:06.903000
2009-11-13T12:59:24.943000
19,970
20,000
Best way to keep an ordered list of windows (from most-recently created to oldest)?
What is the best way to manage a list of windows (keeping them in order) to be able to promote the next window to the top-level when the current top-level window is closed. This is for a web application, so we're using jQuery Javascript. We'd talked through a few simplistic solutions, such as using an array and just treating [0] index as the top-most window. I'm wondering if there's any potentially more efficient or useful alternative to what we had brainstormed.
A stack if you want to just close the window on top. A queue if you also need to open windows at the end.
Best way to keep an ordered list of windows (from most-recently created to oldest)? What is the best way to manage a list of windows (keeping them in order) to be able to promote the next window to the top-level when the current top-level window is closed. This is for a web application, so we're using jQuery Javascript. We'd talked through a few simplistic solutions, such as using an array and just treating [0] index as the top-most window. I'm wondering if there's any potentially more efficient or useful alternative to what we had brainstormed.
TITLE: Best way to keep an ordered list of windows (from most-recently created to oldest)? QUESTION: What is the best way to manage a list of windows (keeping them in order) to be able to promote the next window to the top-level when the current top-level window is closed. This is for a web application, so we're using jQuery Javascript. We'd talked through a few simplistic solutions, such as using an array and just treating [0] index as the top-most window. I'm wondering if there's any potentially more efficient or useful alternative to what we had brainstormed. ANSWER: A stack if you want to just close the window on top. A queue if you also need to open windows at the end.
[ "javascript" ]
4
1
327
3
0
2008-08-21T13:58:25.697000
2008-08-21T14:06:11.747000
19,988
20,029
Being as DRY as possible in a Ruby on Rails App
I'm currently using the awesome attachment-fu plugin for a Rails app, but as a novice developer, I've never encountered a scenario like the one I've found myself in. Essentially, I'm using the attachment-fu plugin on two levels. Is for user avatars in the user class. Is to allow file attachments ( PDFs, etc) in a messaging system. My question is what the best use practice would be in these situations to remain DRY, clear, and consistent. Clearly it would make no sense to define and execute the plugin in both classes, but there's something deeply strange to me (possibly unfounded) about just going ahead and setting it all up in the godly Application class. Is there something in between, or is the parent class the way to go? Thanks!
I would lean towards using a parent class, with subclassing for the different ways you intend to actually use the attachments in your application. It may not be the DRYest solution available, however, it lends itself to a logical pattern rather well.
Being as DRY as possible in a Ruby on Rails App I'm currently using the awesome attachment-fu plugin for a Rails app, but as a novice developer, I've never encountered a scenario like the one I've found myself in. Essentially, I'm using the attachment-fu plugin on two levels. Is for user avatars in the user class. Is to allow file attachments ( PDFs, etc) in a messaging system. My question is what the best use practice would be in these situations to remain DRY, clear, and consistent. Clearly it would make no sense to define and execute the plugin in both classes, but there's something deeply strange to me (possibly unfounded) about just going ahead and setting it all up in the godly Application class. Is there something in between, or is the parent class the way to go? Thanks!
TITLE: Being as DRY as possible in a Ruby on Rails App QUESTION: I'm currently using the awesome attachment-fu plugin for a Rails app, but as a novice developer, I've never encountered a scenario like the one I've found myself in. Essentially, I'm using the attachment-fu plugin on two levels. Is for user avatars in the user class. Is to allow file attachments ( PDFs, etc) in a messaging system. My question is what the best use practice would be in these situations to remain DRY, clear, and consistent. Clearly it would make no sense to define and execute the plugin in both classes, but there's something deeply strange to me (possibly unfounded) about just going ahead and setting it all up in the godly Application class. Is there something in between, or is the parent class the way to go? Thanks! ANSWER: I would lean towards using a parent class, with subclassing for the different ways you intend to actually use the attachments in your application. It may not be the DRYest solution available, however, it lends itself to a logical pattern rather well.
[ "ruby-on-rails", "ruby", "model-view-controller", "attachment-fu" ]
0
1
717
6
0
2008-08-21T14:02:56.467000
2008-08-21T14:12:05.540000
19,995
20,004
Is there some way to PUSH data from web server to browser?
Of course I am aware of Ajax, but the problem with Ajax is that the browser should poll the server frequently to find whether there is new data. This increases server load. Is there any better method (even using Ajax) other than polling the server frequently?
Yes, what you're looking for is COMET http://en.wikipedia.org/wiki/Comet_(programming). Other good Google terms to search for are AJAX-push and reverse-ajax.
Is there some way to PUSH data from web server to browser? Of course I am aware of Ajax, but the problem with Ajax is that the browser should poll the server frequently to find whether there is new data. This increases server load. Is there any better method (even using Ajax) other than polling the server frequently?
TITLE: Is there some way to PUSH data from web server to browser? QUESTION: Of course I am aware of Ajax, but the problem with Ajax is that the browser should poll the server frequently to find whether there is new data. This increases server load. Is there any better method (even using Ajax) other than polling the server frequently? ANSWER: Yes, what you're looking for is COMET http://en.wikipedia.org/wiki/Comet_(programming). Other good Google terms to search for are AJAX-push and reverse-ajax.
[ "ajax", "webserver", "comet" ]
137
70
78,470
18
0
2008-08-21T14:04:55.540000
2008-08-21T14:07:00.340000
20,003
20,682
Repository layout for large Maven projects
I have a large application (~50 modules) using a structure similar to the following: Application Communication modules Color communication module SSN communication module etc. communication module Router module Service modules Voting service module Web interface submodule for voting Vote collector submodule for voting etc. for voting Quiz service module etc. module I would like to import the application to Maven and Subversion. After some research I found that two practical approaches exists for this. One is using a tree structure just as the previous one. The drawback of this structure is that you need a ton of tweaking/hacks to get the multi-module reporting work well with Maven. Another downside is that in Subversion the standard trunk/tags/branches approach add even more complexity to the repository. The other approach uses a flat structure, where there are only one parent project and all the modules, submodules and parts-of-the-submodules are a direct child of the parent project. This approach works well for reporting and is easier in Subversion, however I feel I lose a bit of the structure this way. Which way would you choose in the long term and why?
We have a largish application (160+ OSGi bundles where each bundle is a Maven module) and the lesson we learned, and continue to learn, is that flat is better. The problem with encoding semantics in your hierarchy is that you lose flexibility. A module that is 100% say "communication" today may be partly "service" tomorrow and then you'll need to be moving things around in your repository and that will break all sorts of scripts, documentation, references, etc. So I would recommend a flat structure and to encode the semantics in another place (say for example an IDE workspace or documentation). I've answered a question about version control layout in some detail with examples at another question, it may be relevant to your situation.
Repository layout for large Maven projects I have a large application (~50 modules) using a structure similar to the following: Application Communication modules Color communication module SSN communication module etc. communication module Router module Service modules Voting service module Web interface submodule for voting Vote collector submodule for voting etc. for voting Quiz service module etc. module I would like to import the application to Maven and Subversion. After some research I found that two practical approaches exists for this. One is using a tree structure just as the previous one. The drawback of this structure is that you need a ton of tweaking/hacks to get the multi-module reporting work well with Maven. Another downside is that in Subversion the standard trunk/tags/branches approach add even more complexity to the repository. The other approach uses a flat structure, where there are only one parent project and all the modules, submodules and parts-of-the-submodules are a direct child of the parent project. This approach works well for reporting and is easier in Subversion, however I feel I lose a bit of the structure this way. Which way would you choose in the long term and why?
TITLE: Repository layout for large Maven projects QUESTION: I have a large application (~50 modules) using a structure similar to the following: Application Communication modules Color communication module SSN communication module etc. communication module Router module Service modules Voting service module Web interface submodule for voting Vote collector submodule for voting etc. for voting Quiz service module etc. module I would like to import the application to Maven and Subversion. After some research I found that two practical approaches exists for this. One is using a tree structure just as the previous one. The drawback of this structure is that you need a ton of tweaking/hacks to get the multi-module reporting work well with Maven. Another downside is that in Subversion the standard trunk/tags/branches approach add even more complexity to the repository. The other approach uses a flat structure, where there are only one parent project and all the modules, submodules and parts-of-the-submodules are a direct child of the parent project. This approach works well for reporting and is easier in Subversion, however I feel I lose a bit of the structure this way. Which way would you choose in the long term and why? ANSWER: We have a largish application (160+ OSGi bundles where each bundle is a Maven module) and the lesson we learned, and continue to learn, is that flat is better. The problem with encoding semantics in your hierarchy is that you lose flexibility. A module that is 100% say "communication" today may be partly "service" tomorrow and then you'll need to be moving things around in your repository and that will break all sorts of scripts, documentation, references, etc. So I would recommend a flat structure and to encode the semantics in another place (say for example an IDE workspace or documentation). I've answered a question about version control layout in some detail with examples at another question, it may be relevant to your situation.
[ "java", "svn", "maven-2" ]
15
16
4,133
2
0
2008-08-21T14:06:44.850000
2008-08-21T18:07:00.513000
20,021
20,215
Version track, automate DB schema changes with django
I'm currently looking at the Python framework Django for future db-based web apps as well as for a port of some apps currently written in PHP. One of the nastier issues during my last years was keeping track of database schema changes and deploying these changes to productive systems. I haven't dared asking for being able to undo them too, but of course for testing and debugging that would be a great feature. From other questions here (such as this one or this one ), I can see that I'm not alone and that this is not a trivial problem. Also, I found many inspirations in the answers there. Now, as Django seems to be very powerful, does it have any tools to help with the above? Maybe it's even in their docs and I missed it?
There are at least two third party utilities to handle DB schema migrations, South and Django Evolution. I haven't tried either one, but I have heard some good things about South, though Evolution has been around a little longer. Also, look at SchemaEvolution on the Django wiki. It is just a wiki page about migrating the db.
Version track, automate DB schema changes with django I'm currently looking at the Python framework Django for future db-based web apps as well as for a port of some apps currently written in PHP. One of the nastier issues during my last years was keeping track of database schema changes and deploying these changes to productive systems. I haven't dared asking for being able to undo them too, but of course for testing and debugging that would be a great feature. From other questions here (such as this one or this one ), I can see that I'm not alone and that this is not a trivial problem. Also, I found many inspirations in the answers there. Now, as Django seems to be very powerful, does it have any tools to help with the above? Maybe it's even in their docs and I missed it?
TITLE: Version track, automate DB schema changes with django QUESTION: I'm currently looking at the Python framework Django for future db-based web apps as well as for a port of some apps currently written in PHP. One of the nastier issues during my last years was keeping track of database schema changes and deploying these changes to productive systems. I haven't dared asking for being able to undo them too, but of course for testing and debugging that would be a great feature. From other questions here (such as this one or this one ), I can see that I'm not alone and that this is not a trivial problem. Also, I found many inspirations in the answers there. Now, as Django seems to be very powerful, does it have any tools to help with the above? Maybe it's even in their docs and I missed it? ANSWER: There are at least two third party utilities to handle DB schema migrations, South and Django Evolution. I haven't tried either one, but I have heard some good things about South, though Evolution has been around a little longer. Also, look at SchemaEvolution on the Django wiki. It is just a wiki page about migrating the db.
[ "database", "django", "svn" ]
11
12
1,821
6
0
2008-08-21T14:10:25.123000
2008-08-21T15:20:00.040000
20,034
485,304
Is Project Darkstar Realistic?
Project Darkstar was the topic of the monthly JavaSIG meeting down at the Google offices in NYC last night. For those that don't know (probably everyone), Project Darkstar is a framework for massively multiplayer online games that attempts to take care of all of the "hard stuff." The basic idea is that you write your game server logic in such a way that all operations are broken up into tiny tasks. You pass these tasks to the Project Darkstar framework which handles distributing them to a specific node in the cluster, any concurrency issues, and finally persisting the data. Apparently doing this kind of thing is a much different problem for video games than it is for enterprise applications. Jim Waldo, who gave the lecture, claims that MMO games have a DB read/write ratio of 50/50, whereas enterprise apps are more like 90% read, 10% write. He also claims that most existing MMOs keep everything in memory exlcusively, and only dump to a DB every 6 hours of so. This means if a server goes down, you would lose all of the work since the last DB dump. Now, the project itself sounds really cool, but I don't think the industry will accept it. First, you have to write your server code in Java. The client code can be written in anything (Jim claims ActionScript 3 is the most popular, follow by C++), but the server stuff has to be Java. Sounds good to me, but I really get the impression that everyone in the games industry hates Java. Second, unlike other industries where developers prefer to use existing frameworks and libraries, the guys in the games industry seem to like to write everything themselves. Not only that, they like to rewrite everything for every new game they produce. Things are starting to change where developers are using Havok for physics, Unreal Engine 3 as their platform, etc., but for the most part it looks like everything is still proprietary. So, are the guys at Project Darkstar just wasting their time? Can a general framework like this really work for complex games with the performance that is required? Even if it does work, are game companies willing to use it?
Edit: This was written before Oracle bought Sun and started a rampage to kill everything that does not make them a billion $ per day. See the comments for an OSS Fork. I still stand by my opinion that stuff like that (MMO Middleware) is realistic, you just need a company that doesn't suck behind it. The Market may be dominated by few large games, but that does not mean that there is not a lot of room for more niche games. Lets face it: If you want to reach 100.000+ players, you're ending up building your own technology stack, at least for the critical core. That's what CCP did for EVE Online ( StacklessIO ), that's what Blizzard did for World of Warcraft (although they do use many third-party libraries), that's what Mythic did for Warhammer Online (although they are based on Gamebryo). However, if you aim to be a small, niche MMO (like the dozens of Free-to-Play/Itemshop MMOs), then getting the Network stuff right is just insanely hard, data consistency is even harder and scalability is the biggest b*tch. But game technology is not your only problem - you also need to tackle Billing. Credit Card only? Have fun selling in Germany then, people there want ELV. That's where you need a reliable billing provider, but you still need to wire in the billing application with your accounts to make sure that accounts are blocked/reactivated when the billing fails. There are some companies already offering "MMO Infratructure Services" (i.e. Arvato's EEIS ), but the bottom line is: Stuff like Project Darkstar IS realistic, but assuming that you can build a Multi-Billion-MMO entirely on a Third Party Stack is optimistic, possibly idealistic. But then again, entirely inventing all of the technology is even more stupid - use the Third Party stuff that you need (i.e. Billing, Font Rendering, Audio Output...), but write the stuff that really makes or breaks your business (i.e. Network stack, User interface etc.) on your own. (Note: Jeff's posting may be a bit flawed, but the overall direction is correct IMHO.) Addendum: Also, the game industry does license and reuse engines a lot. The most prominent game Engines are the Unreal Engine, Source Engine and id Tech, which fuel dozens, if not hundreds of games. But there are some lesser-known (outside of the industry) engines. There is Gamebryo, the Middleware behind games like Civilization 4 and Fallout 3, there was RenderWare that is now only EA-in-House, but used in games like Battlefield 2 or The Sims 3. There is the open source Ogre3d, which was used in some commercial titles. If you're just looking for Sound, there's stuff like FMOD or if you want to do font-rendering, why not give FreeType a spin? What I'm saying is: Third-Party Engines/Middleware do exist, and they ARE being successfully used since more than a decade (I know for sure that id's Wolfenstein Engine was licensed to other companies, and that was 1992), even by big companies in multi-million-dollar titles. The important thing is the support, because a good engine with no help in case of an issue is pretty much worthless or at least very expensive if the developer has to spend their game-development-time with unneccessary debugging of the Engine. If the Darkstar folks manage to get the support side right and 2 or 3 higher profile titles out, I do believe it could succeed in opening the MMO market to a lot more smaller developers and indies.
Is Project Darkstar Realistic? Project Darkstar was the topic of the monthly JavaSIG meeting down at the Google offices in NYC last night. For those that don't know (probably everyone), Project Darkstar is a framework for massively multiplayer online games that attempts to take care of all of the "hard stuff." The basic idea is that you write your game server logic in such a way that all operations are broken up into tiny tasks. You pass these tasks to the Project Darkstar framework which handles distributing them to a specific node in the cluster, any concurrency issues, and finally persisting the data. Apparently doing this kind of thing is a much different problem for video games than it is for enterprise applications. Jim Waldo, who gave the lecture, claims that MMO games have a DB read/write ratio of 50/50, whereas enterprise apps are more like 90% read, 10% write. He also claims that most existing MMOs keep everything in memory exlcusively, and only dump to a DB every 6 hours of so. This means if a server goes down, you would lose all of the work since the last DB dump. Now, the project itself sounds really cool, but I don't think the industry will accept it. First, you have to write your server code in Java. The client code can be written in anything (Jim claims ActionScript 3 is the most popular, follow by C++), but the server stuff has to be Java. Sounds good to me, but I really get the impression that everyone in the games industry hates Java. Second, unlike other industries where developers prefer to use existing frameworks and libraries, the guys in the games industry seem to like to write everything themselves. Not only that, they like to rewrite everything for every new game they produce. Things are starting to change where developers are using Havok for physics, Unreal Engine 3 as their platform, etc., but for the most part it looks like everything is still proprietary. So, are the guys at Project Darkstar just wasting their time? Can a general framework like this really work for complex games with the performance that is required? Even if it does work, are game companies willing to use it?
TITLE: Is Project Darkstar Realistic? QUESTION: Project Darkstar was the topic of the monthly JavaSIG meeting down at the Google offices in NYC last night. For those that don't know (probably everyone), Project Darkstar is a framework for massively multiplayer online games that attempts to take care of all of the "hard stuff." The basic idea is that you write your game server logic in such a way that all operations are broken up into tiny tasks. You pass these tasks to the Project Darkstar framework which handles distributing them to a specific node in the cluster, any concurrency issues, and finally persisting the data. Apparently doing this kind of thing is a much different problem for video games than it is for enterprise applications. Jim Waldo, who gave the lecture, claims that MMO games have a DB read/write ratio of 50/50, whereas enterprise apps are more like 90% read, 10% write. He also claims that most existing MMOs keep everything in memory exlcusively, and only dump to a DB every 6 hours of so. This means if a server goes down, you would lose all of the work since the last DB dump. Now, the project itself sounds really cool, but I don't think the industry will accept it. First, you have to write your server code in Java. The client code can be written in anything (Jim claims ActionScript 3 is the most popular, follow by C++), but the server stuff has to be Java. Sounds good to me, but I really get the impression that everyone in the games industry hates Java. Second, unlike other industries where developers prefer to use existing frameworks and libraries, the guys in the games industry seem to like to write everything themselves. Not only that, they like to rewrite everything for every new game they produce. Things are starting to change where developers are using Havok for physics, Unreal Engine 3 as their platform, etc., but for the most part it looks like everything is still proprietary. So, are the guys at Project Darkstar just wasting their time? Can a general framework like this really work for complex games with the performance that is required? Even if it does work, are game companies willing to use it? ANSWER: Edit: This was written before Oracle bought Sun and started a rampage to kill everything that does not make them a billion $ per day. See the comments for an OSS Fork. I still stand by my opinion that stuff like that (MMO Middleware) is realistic, you just need a company that doesn't suck behind it. The Market may be dominated by few large games, but that does not mean that there is not a lot of room for more niche games. Lets face it: If you want to reach 100.000+ players, you're ending up building your own technology stack, at least for the critical core. That's what CCP did for EVE Online ( StacklessIO ), that's what Blizzard did for World of Warcraft (although they do use many third-party libraries), that's what Mythic did for Warhammer Online (although they are based on Gamebryo). However, if you aim to be a small, niche MMO (like the dozens of Free-to-Play/Itemshop MMOs), then getting the Network stuff right is just insanely hard, data consistency is even harder and scalability is the biggest b*tch. But game technology is not your only problem - you also need to tackle Billing. Credit Card only? Have fun selling in Germany then, people there want ELV. That's where you need a reliable billing provider, but you still need to wire in the billing application with your accounts to make sure that accounts are blocked/reactivated when the billing fails. There are some companies already offering "MMO Infratructure Services" (i.e. Arvato's EEIS ), but the bottom line is: Stuff like Project Darkstar IS realistic, but assuming that you can build a Multi-Billion-MMO entirely on a Third Party Stack is optimistic, possibly idealistic. But then again, entirely inventing all of the technology is even more stupid - use the Third Party stuff that you need (i.e. Billing, Font Rendering, Audio Output...), but write the stuff that really makes or breaks your business (i.e. Network stack, User interface etc.) on your own. (Note: Jeff's posting may be a bit flawed, but the overall direction is correct IMHO.) Addendum: Also, the game industry does license and reuse engines a lot. The most prominent game Engines are the Unreal Engine, Source Engine and id Tech, which fuel dozens, if not hundreds of games. But there are some lesser-known (outside of the industry) engines. There is Gamebryo, the Middleware behind games like Civilization 4 and Fallout 3, there was RenderWare that is now only EA-in-House, but used in games like Battlefield 2 or The Sims 3. There is the open source Ogre3d, which was used in some commercial titles. If you're just looking for Sound, there's stuff like FMOD or if you want to do font-rendering, why not give FreeType a spin? What I'm saying is: Third-Party Engines/Middleware do exist, and they ARE being successfully used since more than a decade (I know for sure that id's Wolfenstein Engine was licensed to other companies, and that was 1992), even by big companies in multi-million-dollar titles. The important thing is the support, because a good engine with no help in case of an issue is pretty much worthless or at least very expensive if the developer has to spend their game-development-time with unneccessary debugging of the Engine. If the Darkstar folks manage to get the support side right and 2 or 3 higher profile titles out, I do believe it could succeed in opening the MMO market to a lot more smaller developers and indies.
[ "java", "concurrency", "distributed" ]
26
26
4,975
7
0
2008-08-21T14:13:11.327000
2009-01-27T21:20:26.120000
20,040
20,058
What are the most important things to learn about .net as a Project Manager?
Thinking about getting into.net technology project management I've had plenty of experience with PHP projects: I'm aware of most of the existing frameworks and libraries, and I've written specs and case studies based on this knowledge. What should I know about.net? Which top resources would you recommend me to know so I can rapidly learn and later stay up to date on the technology? Edit (8.24.08): The answers I got so far essentially discuss being a good PM. Thanks, but this is not what I meant. Any.net essentials would be appreciated.
Start with the basics before you get to the higher level stuff like web services (though that is important too). The most important things you need to learn, as a project manager, are the things you're going to be questioning your underlings about later. For example, my PM (also a PHP guy) has absolutely no knowledge of garbage collection and its implications, which makes it incredibly difficult for me to explain to him why our.NET Windows service appears to be taking 80MB of RAM. Remember, you are not the one who needs to know everything. You should be issuing overarching directives, and let the people with the expertise sort out the details. That said, study up on the technicals a bit so that they can communicate effectively with you. Edit (8/24/08):You should know something about the underlying technicals; not necessarily all.NET stuff either (garbage collection,.config files, pipes and services if you're running services adjacent to your project's main focus, stuff like that). Higher-reaching concepts would probably include WPF (maybe Silverlight as well), LINQ (or your ORM of choice), as well as the Vista bridge and related bridging code if your project includes desktop apps at all. Those three things seem to be the focus for this round of.NET. Something else that's very important to have at least a passing knowledge of is the ways that.NET code can/must interoperate with native code: P/Invoke, Runtime Callable Wrapping and COM Callable Wrapping. There are still a lot of native things that don't have a.NET equivalent. As for resources, I'd highly recommend MSDN Magazine. They tend to preview upcoming technologies and tools well before average developers will ever see them.
What are the most important things to learn about .net as a Project Manager? Thinking about getting into.net technology project management I've had plenty of experience with PHP projects: I'm aware of most of the existing frameworks and libraries, and I've written specs and case studies based on this knowledge. What should I know about.net? Which top resources would you recommend me to know so I can rapidly learn and later stay up to date on the technology? Edit (8.24.08): The answers I got so far essentially discuss being a good PM. Thanks, but this is not what I meant. Any.net essentials would be appreciated.
TITLE: What are the most important things to learn about .net as a Project Manager? QUESTION: Thinking about getting into.net technology project management I've had plenty of experience with PHP projects: I'm aware of most of the existing frameworks and libraries, and I've written specs and case studies based on this knowledge. What should I know about.net? Which top resources would you recommend me to know so I can rapidly learn and later stay up to date on the technology? Edit (8.24.08): The answers I got so far essentially discuss being a good PM. Thanks, but this is not what I meant. Any.net essentials would be appreciated. ANSWER: Start with the basics before you get to the higher level stuff like web services (though that is important too). The most important things you need to learn, as a project manager, are the things you're going to be questioning your underlings about later. For example, my PM (also a PHP guy) has absolutely no knowledge of garbage collection and its implications, which makes it incredibly difficult for me to explain to him why our.NET Windows service appears to be taking 80MB of RAM. Remember, you are not the one who needs to know everything. You should be issuing overarching directives, and let the people with the expertise sort out the details. That said, study up on the technicals a bit so that they can communicate effectively with you. Edit (8/24/08):You should know something about the underlying technicals; not necessarily all.NET stuff either (garbage collection,.config files, pipes and services if you're running services adjacent to your project's main focus, stuff like that). Higher-reaching concepts would probably include WPF (maybe Silverlight as well), LINQ (or your ORM of choice), as well as the Vista bridge and related bridging code if your project includes desktop apps at all. Those three things seem to be the focus for this round of.NET. Something else that's very important to have at least a passing knowledge of is the ways that.NET code can/must interoperate with native code: P/Invoke, Runtime Callable Wrapping and COM Callable Wrapping. There are still a lot of native things that don't have a.NET equivalent. As for resources, I'd highly recommend MSDN Magazine. They tend to preview upcoming technologies and tools well before average developers will ever see them.
[ ".net", "project-management" ]
3
2
2,700
5
0
2008-08-21T14:14:53.287000
2008-08-21T14:23:40.753000
20,047
21,158
Diagnosing Deadlocks in SQL Server 2005
We're seeing some pernicious, but rare, deadlock conditions in the Stack Overflow SQL Server 2005 database. I attached the profiler, set up a trace profile using this excellent article on troubleshooting deadlocks, and captured a bunch of examples. The weird thing is that the deadlocking write is always the same: UPDATE [dbo].[Posts] SET [AnswerCount] = @p1, [LastActivityDate] = @p2, [LastActivityUserId] = @p3 WHERE [Id] = @p0 The other deadlocking statement varies, but it's usually some kind of trivial, simple read of the posts table. This one always gets killed in the deadlock. Here's an example SELECT [t0].[Id], [t0].[PostTypeId], [t0].[Score], [t0].[Views], [t0].[AnswerCount], [t0].[AcceptedAnswerId], [t0].[IsLocked], [t0].[IsLockedEdit], [t0].[ParentId], [t0].[CurrentRevisionId], [t0].[FirstRevisionId], [t0].[LockedReason], [t0].[LastActivityDate], [t0].[LastActivityUserId] FROM [dbo].[Posts] AS [t0] WHERE [t0].[ParentId] = @p0 To be perfectly clear, we are not seeing write / write deadlocks, but read / write. We have a mixture of LINQ and parameterized SQL queries at the moment. We have added with (nolock) to all the SQL queries. This may have helped some. We also had a single (very) poorly-written badge query that I fixed yesterday, which was taking upwards of 20 seconds to run every time, and was running every minute on top of that. I was hoping this was the source of some of the locking problems! Unfortunately, I got another deadlock error about 2 hours ago. Same exact symptoms, same exact culprit write. The truly strange thing is that the locking write SQL statement you see above is part of a very specific code path. It's only executed when a new answer is added to a question -- it updates the parent question with the new answer count and last date/user. This is, obviously, not that common relative to the massive number of reads we are doing! As far as I can tell, we're not doing huge numbers of writes anywhere in the app. I realize that NOLOCK is sort of a giant hammer, but most of the queries we run here don't need to be that accurate. Will you care if your user profile is a few seconds out of date? Using NOLOCK with Linq is a bit more difficult as Scott Hanselman discusses here. We are flirting with the idea of using SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED on the base database context so that all our LINQ queries have this set. Without that, we'd have to wrap every LINQ call we make (well, the simple reading ones, which is the vast majority of them) in a 3-4 line transaction code block, which is ugly. I guess I'm a little frustrated that trivial reads in SQL 2005 can deadlock on writes. I could see write/write deadlocks being a huge issue, but reads? We're not running a banking site here, we don't need perfect accuracy every time. Ideas? Thoughts? Are you instantiating a new LINQ to SQL DataContext object for every operation or are you perhaps sharing the same static context for all your calls? Jeremy, we are sharing one static datacontext in the base Controller for the most part: private DBContext _db; /// /// Gets the DataContext to be used by a Request's controllers. /// public DBContext DB { get { if (_db == null) { _db = new DBContext() { SessionName = GetType().Name }; //_db.ExecuteCommand("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED"); } return _db; } } Do you recommend we create a new context for every Controller, or per Page, or.. more often?
According to MSDN: http://msdn.microsoft.com/en-us/library/ms191242.aspx When either the READ COMMITTED SNAPSHOT or ALLOW SNAPSHOT ISOLATION database options are ON, logical copies (versions) are maintained for all data modifications performed in the database. Every time a row is modified by a specific transaction, the instance of the Database Engine stores a version of the previously committed image of the row in tempdb. Each version is marked with the transaction sequence number of the transaction that made the change. The versions of modified rows are chained using a link list. The newest row value is always stored in the current database and chained to the versioned rows stored in tempdb. For short-running transactions, a version of a modified row may get cached in the buffer pool without getting written into the disk files of the tempdb database. If the need for the versioned row is short-lived, it will simply get dropped from the buffer pool and may not necessarily incur I/O overhead. There appears to be a slight performance penalty for the extra overhead, but it may be negligible. We should test to make sure. Try setting this option and REMOVE all NOLOCKs from code queries unless it’s really necessary. NOLOCKs or using global methods in the database context handler to combat database transaction isolation levels are Band-Aids to the problem. NOLOCKS will mask fundamental issues with our data layer and possibly lead to selecting unreliable data, where automatic select / update row versioning appears to be the solution. ALTER Database [StackOverflow.Beta] SET READ_COMMITTED_SNAPSHOT ON
Diagnosing Deadlocks in SQL Server 2005 We're seeing some pernicious, but rare, deadlock conditions in the Stack Overflow SQL Server 2005 database. I attached the profiler, set up a trace profile using this excellent article on troubleshooting deadlocks, and captured a bunch of examples. The weird thing is that the deadlocking write is always the same: UPDATE [dbo].[Posts] SET [AnswerCount] = @p1, [LastActivityDate] = @p2, [LastActivityUserId] = @p3 WHERE [Id] = @p0 The other deadlocking statement varies, but it's usually some kind of trivial, simple read of the posts table. This one always gets killed in the deadlock. Here's an example SELECT [t0].[Id], [t0].[PostTypeId], [t0].[Score], [t0].[Views], [t0].[AnswerCount], [t0].[AcceptedAnswerId], [t0].[IsLocked], [t0].[IsLockedEdit], [t0].[ParentId], [t0].[CurrentRevisionId], [t0].[FirstRevisionId], [t0].[LockedReason], [t0].[LastActivityDate], [t0].[LastActivityUserId] FROM [dbo].[Posts] AS [t0] WHERE [t0].[ParentId] = @p0 To be perfectly clear, we are not seeing write / write deadlocks, but read / write. We have a mixture of LINQ and parameterized SQL queries at the moment. We have added with (nolock) to all the SQL queries. This may have helped some. We also had a single (very) poorly-written badge query that I fixed yesterday, which was taking upwards of 20 seconds to run every time, and was running every minute on top of that. I was hoping this was the source of some of the locking problems! Unfortunately, I got another deadlock error about 2 hours ago. Same exact symptoms, same exact culprit write. The truly strange thing is that the locking write SQL statement you see above is part of a very specific code path. It's only executed when a new answer is added to a question -- it updates the parent question with the new answer count and last date/user. This is, obviously, not that common relative to the massive number of reads we are doing! As far as I can tell, we're not doing huge numbers of writes anywhere in the app. I realize that NOLOCK is sort of a giant hammer, but most of the queries we run here don't need to be that accurate. Will you care if your user profile is a few seconds out of date? Using NOLOCK with Linq is a bit more difficult as Scott Hanselman discusses here. We are flirting with the idea of using SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED on the base database context so that all our LINQ queries have this set. Without that, we'd have to wrap every LINQ call we make (well, the simple reading ones, which is the vast majority of them) in a 3-4 line transaction code block, which is ugly. I guess I'm a little frustrated that trivial reads in SQL 2005 can deadlock on writes. I could see write/write deadlocks being a huge issue, but reads? We're not running a banking site here, we don't need perfect accuracy every time. Ideas? Thoughts? Are you instantiating a new LINQ to SQL DataContext object for every operation or are you perhaps sharing the same static context for all your calls? Jeremy, we are sharing one static datacontext in the base Controller for the most part: private DBContext _db; /// /// Gets the DataContext to be used by a Request's controllers. /// public DBContext DB { get { if (_db == null) { _db = new DBContext() { SessionName = GetType().Name }; //_db.ExecuteCommand("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED"); } return _db; } } Do you recommend we create a new context for every Controller, or per Page, or.. more often?
TITLE: Diagnosing Deadlocks in SQL Server 2005 QUESTION: We're seeing some pernicious, but rare, deadlock conditions in the Stack Overflow SQL Server 2005 database. I attached the profiler, set up a trace profile using this excellent article on troubleshooting deadlocks, and captured a bunch of examples. The weird thing is that the deadlocking write is always the same: UPDATE [dbo].[Posts] SET [AnswerCount] = @p1, [LastActivityDate] = @p2, [LastActivityUserId] = @p3 WHERE [Id] = @p0 The other deadlocking statement varies, but it's usually some kind of trivial, simple read of the posts table. This one always gets killed in the deadlock. Here's an example SELECT [t0].[Id], [t0].[PostTypeId], [t0].[Score], [t0].[Views], [t0].[AnswerCount], [t0].[AcceptedAnswerId], [t0].[IsLocked], [t0].[IsLockedEdit], [t0].[ParentId], [t0].[CurrentRevisionId], [t0].[FirstRevisionId], [t0].[LockedReason], [t0].[LastActivityDate], [t0].[LastActivityUserId] FROM [dbo].[Posts] AS [t0] WHERE [t0].[ParentId] = @p0 To be perfectly clear, we are not seeing write / write deadlocks, but read / write. We have a mixture of LINQ and parameterized SQL queries at the moment. We have added with (nolock) to all the SQL queries. This may have helped some. We also had a single (very) poorly-written badge query that I fixed yesterday, which was taking upwards of 20 seconds to run every time, and was running every minute on top of that. I was hoping this was the source of some of the locking problems! Unfortunately, I got another deadlock error about 2 hours ago. Same exact symptoms, same exact culprit write. The truly strange thing is that the locking write SQL statement you see above is part of a very specific code path. It's only executed when a new answer is added to a question -- it updates the parent question with the new answer count and last date/user. This is, obviously, not that common relative to the massive number of reads we are doing! As far as I can tell, we're not doing huge numbers of writes anywhere in the app. I realize that NOLOCK is sort of a giant hammer, but most of the queries we run here don't need to be that accurate. Will you care if your user profile is a few seconds out of date? Using NOLOCK with Linq is a bit more difficult as Scott Hanselman discusses here. We are flirting with the idea of using SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED on the base database context so that all our LINQ queries have this set. Without that, we'd have to wrap every LINQ call we make (well, the simple reading ones, which is the vast majority of them) in a 3-4 line transaction code block, which is ugly. I guess I'm a little frustrated that trivial reads in SQL 2005 can deadlock on writes. I could see write/write deadlocks being a huge issue, but reads? We're not running a banking site here, we don't need perfect accuracy every time. Ideas? Thoughts? Are you instantiating a new LINQ to SQL DataContext object for every operation or are you perhaps sharing the same static context for all your calls? Jeremy, we are sharing one static datacontext in the base Controller for the most part: private DBContext _db; /// /// Gets the DataContext to be used by a Request's controllers. /// public DBContext DB { get { if (_db == null) { _db = new DBContext() { SessionName = GetType().Name }; //_db.ExecuteCommand("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED"); } return _db; } } Do you recommend we create a new context for every Controller, or per Page, or.. more often? ANSWER: According to MSDN: http://msdn.microsoft.com/en-us/library/ms191242.aspx When either the READ COMMITTED SNAPSHOT or ALLOW SNAPSHOT ISOLATION database options are ON, logical copies (versions) are maintained for all data modifications performed in the database. Every time a row is modified by a specific transaction, the instance of the Database Engine stores a version of the previously committed image of the row in tempdb. Each version is marked with the transaction sequence number of the transaction that made the change. The versions of modified rows are chained using a link list. The newest row value is always stored in the current database and chained to the versioned rows stored in tempdb. For short-running transactions, a version of a modified row may get cached in the buffer pool without getting written into the disk files of the tempdb database. If the need for the versioned row is short-lived, it will simply get dropped from the buffer pool and may not necessarily incur I/O overhead. There appears to be a slight performance penalty for the extra overhead, but it may be negligible. We should test to make sure. Try setting this option and REMOVE all NOLOCKs from code queries unless it’s really necessary. NOLOCKs or using global methods in the database context handler to combat database transaction isolation levels are Band-Aids to the problem. NOLOCKS will mask fundamental issues with our data layer and possibly lead to selecting unreliable data, where automatic select / update row versioning appears to be the solution. ALTER Database [StackOverflow.Beta] SET READ_COMMITTED_SNAPSHOT ON
[ "sql-server", "sql-server-2005", "deadlock" ]
82
44
29,597
22
0
2008-08-21T14:18:41.640000
2008-08-21T20:53:51.283000
20,054
20,072
Any tips on getting Rails to run with an Access back-end?
I shudder to ask, but my client might offer no other SQL (or SQL-like) solution. I know Access has some SQL hooks; are they enough for basic ActiveRecord? Later: I appreciate all the suggestions to use other databases, but trust me: I've tried convincing them. There is an "approved" list, and no SQL databases are on it. Getting something onto the list could take more than a year, and this project will be done in three weeks.
It's a long shot but there's an ODBC adapter for ActiveRecord that might work.
Any tips on getting Rails to run with an Access back-end? I shudder to ask, but my client might offer no other SQL (or SQL-like) solution. I know Access has some SQL hooks; are they enough for basic ActiveRecord? Later: I appreciate all the suggestions to use other databases, but trust me: I've tried convincing them. There is an "approved" list, and no SQL databases are on it. Getting something onto the list could take more than a year, and this project will be done in three weeks.
TITLE: Any tips on getting Rails to run with an Access back-end? QUESTION: I shudder to ask, but my client might offer no other SQL (or SQL-like) solution. I know Access has some SQL hooks; are they enough for basic ActiveRecord? Later: I appreciate all the suggestions to use other databases, but trust me: I've tried convincing them. There is an "approved" list, and no SQL databases are on it. Getting something onto the list could take more than a year, and this project will be done in three weeks. ANSWER: It's a long shot but there's an ODBC adapter for ActiveRecord that might work.
[ "ruby-on-rails", "ruby", "ms-access", "activerecord" ]
5
3
2,370
7
0
2008-08-21T14:21:55.687000
2008-08-21T14:27:24.880000
20,059
20,132
Suggestions on starting a child programming
What languages and tools do you consider a youngster starting out in programming should use in the modern era? Lots of us started with proprietary Basics and they didn't do all of us long term harm:) but given the experiences you have had since then and your knowledge of the domain now are there better options? There are related queries to this one such as " Best ways to teach a beginner to program? " and " One piece of advice " about starting adults programming both of which I submitted answers to but children might require a different tool. Disclosure: it's bloody hard choosing a 'correct' answer to a question like this so who ever has the best score in a few days will get the 'best answer' mark from me based on the communities choice.
I would suggest LEGO Mindstorm, it provides an intuitive drag and drop interface for programming and because it comes with hardware it provides something tangible for a child to grasp. Also, because it is "LEGO" they might think of it as more of a game then a programming exercise.
Suggestions on starting a child programming What languages and tools do you consider a youngster starting out in programming should use in the modern era? Lots of us started with proprietary Basics and they didn't do all of us long term harm:) but given the experiences you have had since then and your knowledge of the domain now are there better options? There are related queries to this one such as " Best ways to teach a beginner to program? " and " One piece of advice " about starting adults programming both of which I submitted answers to but children might require a different tool. Disclosure: it's bloody hard choosing a 'correct' answer to a question like this so who ever has the best score in a few days will get the 'best answer' mark from me based on the communities choice.
TITLE: Suggestions on starting a child programming QUESTION: What languages and tools do you consider a youngster starting out in programming should use in the modern era? Lots of us started with proprietary Basics and they didn't do all of us long term harm:) but given the experiences you have had since then and your knowledge of the domain now are there better options? There are related queries to this one such as " Best ways to teach a beginner to program? " and " One piece of advice " about starting adults programming both of which I submitted answers to but children might require a different tool. Disclosure: it's bloody hard choosing a 'correct' answer to a question like this so who ever has the best score in a few days will get the 'best answer' mark from me based on the communities choice. ANSWER: I would suggest LEGO Mindstorm, it provides an intuitive drag and drop interface for programming and because it comes with hardware it provides something tangible for a child to grasp. Also, because it is "LEGO" they might think of it as more of a game then a programming exercise.
[ "language-agnostic", "children" ]
45
43
8,720
46
0
2008-08-21T14:23:53.483000
2008-08-21T14:43:13.670000
20,061
20,130
Store data from a C# application
I've recently taken up learning some C# and wrote a Yahtzee clone. My next step (now that the game logic is in place and functioning correctly) is to integrate some method of keeping stats across all the games played. My question is this, how should I go about storing this information? My first thought would be to use a database and I have a feeling that's the answer I'll get... if that's the case, can you point me to a good resource for creating and accessing a database from a C# application? Storing in an XML file actually makes more sense to me, but I thought if I suggested that I'd get torn apart;). I'm used to building web applications and for those, text files are generally frowned upon. So, going with an XML file, what classes should I be looking at that would allow for easy manipulation?
Here is one idea: use Xml Serialization. Design your GameStats data structure and optionally use Xml attributes to influence the schema as you like. I like to use this method for small data sets because its quick and easy and all I need to do is design and manipulate the data structure. using (FileStream fs = new FileStream(....)) { // Read in stats XmlSerializer xs = new XmlSerializer(typeof(GameStats)); GameStats stats = (GameStats)xs.Deserialize(fs); // Manipulate stats here... // Write out game stats XmlSerializer xs = new XmlSerializer(typeof(GameStats)); xs.Serialize(fs, stats); fs.Close(); }
Store data from a C# application I've recently taken up learning some C# and wrote a Yahtzee clone. My next step (now that the game logic is in place and functioning correctly) is to integrate some method of keeping stats across all the games played. My question is this, how should I go about storing this information? My first thought would be to use a database and I have a feeling that's the answer I'll get... if that's the case, can you point me to a good resource for creating and accessing a database from a C# application? Storing in an XML file actually makes more sense to me, but I thought if I suggested that I'd get torn apart;). I'm used to building web applications and for those, text files are generally frowned upon. So, going with an XML file, what classes should I be looking at that would allow for easy manipulation?
TITLE: Store data from a C# application QUESTION: I've recently taken up learning some C# and wrote a Yahtzee clone. My next step (now that the game logic is in place and functioning correctly) is to integrate some method of keeping stats across all the games played. My question is this, how should I go about storing this information? My first thought would be to use a database and I have a feeling that's the answer I'll get... if that's the case, can you point me to a good resource for creating and accessing a database from a C# application? Storing in an XML file actually makes more sense to me, but I thought if I suggested that I'd get torn apart;). I'm used to building web applications and for those, text files are generally frowned upon. So, going with an XML file, what classes should I be looking at that would allow for easy manipulation? ANSWER: Here is one idea: use Xml Serialization. Design your GameStats data structure and optionally use Xml attributes to influence the schema as you like. I like to use this method for small data sets because its quick and easy and all I need to do is design and manipulate the data structure. using (FileStream fs = new FileStream(....)) { // Read in stats XmlSerializer xs = new XmlSerializer(typeof(GameStats)); GameStats stats = (GameStats)xs.Deserialize(fs); // Manipulate stats here... // Write out game stats XmlSerializer xs = new XmlSerializer(typeof(GameStats)); xs.Serialize(fs, stats); fs.Close(); }
[ "c#", ".net" ]
16
17
9,509
9
0
2008-08-21T14:24:25.120000
2008-08-21T14:42:36.560000
20,063
26,910
What's the best way to parse command line arguments?
What's the easiest, tersest, and most flexible method or library for parsing Python command line arguments?
This answer suggests optparse which is appropriate for older Python versions. For Python 2.7 and above, argparse replaces optparse. See this answer for more information. As other people pointed out, you are better off going with optparse over getopt. getopt is pretty much a one-to-one mapping of the standard getopt(3) C library functions, and not very easy to use. optparse, while being a bit more verbose, is much better structured and simpler to extend later on. Here's a typical line to add an option to your parser: parser.add_option('-q', '--query', action="store", dest="query", help="query string", default="spam") It pretty much speaks for itself; at processing time, it will accept -q or --query as options, store the argument in an attribute called query and has a default value if you don't specify it. It is also self-documenting in that you declare the help argument (which will be used when run with -h/--help) right there with the option. Usually you parse your arguments with: options, args = parser.parse_args() This will, by default, parse the standard arguments passed to the script (sys.argv[1:]) options.query will then be set to the value you passed to the script. You create a parser simply by doing parser = optparse.OptionParser() These are all the basics you need. Here's a complete Python script that shows this: import optparse parser = optparse.OptionParser() parser.add_option('-q', '--query', action="store", dest="query", help="query string", default="spam") options, args = parser.parse_args() print 'Query string:', options.query 5 lines of python that show you the basics. Save it in sample.py, and run it once with python sample.py and once with python sample.py --query myquery Beyond that, you will find that optparse is very easy to extend. In one of my projects, I created a Command class which allows you to nest subcommands in a command tree easily. It uses optparse heavily to chain commands together. It's not something I can easily explain in a few lines, but feel free to browse around in my repository for the main class, as well as a class that uses it and the option parser
What's the best way to parse command line arguments? What's the easiest, tersest, and most flexible method or library for parsing Python command line arguments?
TITLE: What's the best way to parse command line arguments? QUESTION: What's the easiest, tersest, and most flexible method or library for parsing Python command line arguments? ANSWER: This answer suggests optparse which is appropriate for older Python versions. For Python 2.7 and above, argparse replaces optparse. See this answer for more information. As other people pointed out, you are better off going with optparse over getopt. getopt is pretty much a one-to-one mapping of the standard getopt(3) C library functions, and not very easy to use. optparse, while being a bit more verbose, is much better structured and simpler to extend later on. Here's a typical line to add an option to your parser: parser.add_option('-q', '--query', action="store", dest="query", help="query string", default="spam") It pretty much speaks for itself; at processing time, it will accept -q or --query as options, store the argument in an attribute called query and has a default value if you don't specify it. It is also self-documenting in that you declare the help argument (which will be used when run with -h/--help) right there with the option. Usually you parse your arguments with: options, args = parser.parse_args() This will, by default, parse the standard arguments passed to the script (sys.argv[1:]) options.query will then be set to the value you passed to the script. You create a parser simply by doing parser = optparse.OptionParser() These are all the basics you need. Here's a complete Python script that shows this: import optparse parser = optparse.OptionParser() parser.add_option('-q', '--query', action="store", dest="query", help="query string", default="spam") options, args = parser.parse_args() print 'Query string:', options.query 5 lines of python that show you the basics. Save it in sample.py, and run it once with python sample.py and once with python sample.py --query myquery Beyond that, you will find that optparse is very easy to extend. In one of my projects, I created a Command class which allows you to nest subcommands in a command tree easily. It uses optparse heavily to chain commands together. It's not something I can easily explain in a few lines, but feel free to browse around in my repository for the main class, as well as a class that uses it and the option parser
[ "python", "command-line", "command-line-arguments" ]
360
211
374,143
15
0
2008-08-21T14:24:41.530000
2008-08-25T21:11:03.567000
20,081
97,091
Best way to encapsulate complex Oracle PL/SQL cursor logic as a view?
I've written PL/SQL code to denormalize a table into a much-easer-to-query form. The code uses a temporary table to do some of its work, merging some rows from the original table together. The logic is written as a pipelined table function, following the pattern from the linked article. The table function uses a PRAGMA AUTONOMOUS_TRANSACTION declaration to permit the temporary table manipulation, and also accepts a cursor input parameter to restrict the denormalization to certain ID values. I then created a view to query the table function, passing in all possible ID values as a cursor (other uses of the function will be more restrictive). My question: is this all really necessary? Have I completely missed a much more simple way of accomplishing the same thing? Every time I touch PL/SQL I get the impression that I'm typing way too much. Update: I'll add a sketch of the table I'm dealing with to give everyone an idea of the denormalization that I'm talking about. The table stores a history of employee jobs, each with an activation row, and (possibly) a termination row. It's possible for an employee to have multiple simultaneous jobs, as well as the same job over and over again in non-contiguous date ranges. For example: | EMP_ID | JOB_ID | STATUS | EFF_DATE | other columns... | 1 | 10 | A | 10-JAN-2008 | | 2 | 11 | A | 13-JAN-2008 | | 1 | 12 | A | 20-JAN-2008 | | 2 | 11 | T | 01-FEB-2008 | | 1 | 10 | T | 02-FEB-2008 | | 2 | 11 | A | 20-FEB-2008 | Querying that to figure out who is working when in what job is non-trivial. So, my denormalization function populates the temporary table with just the date ranges for each job, for any EMP_ID s passed in though the cursor. Passing in EMP_ID s 1 and 2 would produce the following: | EMP_ID | JOB_ID | START_DATE | END_DATE | | 1 | 10 | 10-JAN-2008 | 02-FEB-2008 | | 2 | 11 | 13-JAN-2008 | 01-FEB-2008 | | 1 | 12 | 20-JAN-2008 | | | 2 | 11 | 20-FEB-2008 | | ( END_DATE allows NULL s for jobs that don't have a predetermined termination date.) As you can imagine, this denormalized form is much, much easier to query, but creating it--so far as I can tell--requires a temporary table to store the intermediate results (e.g., job records for which the activation row has been found, but not the termination...yet). Using the pipelined table function to populate the temporary table and then return its rows is the only way I've figured out how to do it.
I think a way to approach this is to use analytic functions... I set up your test case using: create table employee_job ( emp_id integer, job_id integer, status varchar2(1 char), eff_date date ); insert into employee_job values (1,10,'A',to_date('10-JAN-2008','DD-MON-YYYY')); insert into employee_job values (2,11,'A',to_date('13-JAN-2008','DD-MON-YYYY')); insert into employee_job values (1,12,'A',to_date('20-JAN-2008','DD-MON-YYYY')); insert into employee_job values (2,11,'T',to_date('01-FEB-2008','DD-MON-YYYY')); insert into employee_job values (1,10,'T',to_date('02-FEB-2008','DD-MON-YYYY')); insert into employee_job values (2,11,'A',to_date('20-FEB-2008','DD-MON-YYYY')); commit; I've used the lead function to get the next date and then wrapped it all as a sub-query just to get the "A" records and add the end date if there is one. select emp_id, job_id, eff_date start_date, decode(next_status,'T',next_eff_date,null) end_date from ( select emp_id, job_id, eff_date, status, lead(eff_date,1,null) over (partition by emp_id, job_id order by eff_date, status) next_eff_date, lead(status,1,null) over (partition by emp_id, job_id order by eff_date, status) next_status from employee_job ) where status = 'A' order by start_date, emp_id, job_id I'm sure there's some use cases I've missed but you get the idea. Analytic functions are your friend:) EMP_ID JOB_ID START_DATE END_DATE 1 10 10-JAN-2008 02-FEB-2008 2 11 13-JAN-2008 01-FEB-2008 2 11 20-FEB-2008 1 12 20-JAN-2008
Best way to encapsulate complex Oracle PL/SQL cursor logic as a view? I've written PL/SQL code to denormalize a table into a much-easer-to-query form. The code uses a temporary table to do some of its work, merging some rows from the original table together. The logic is written as a pipelined table function, following the pattern from the linked article. The table function uses a PRAGMA AUTONOMOUS_TRANSACTION declaration to permit the temporary table manipulation, and also accepts a cursor input parameter to restrict the denormalization to certain ID values. I then created a view to query the table function, passing in all possible ID values as a cursor (other uses of the function will be more restrictive). My question: is this all really necessary? Have I completely missed a much more simple way of accomplishing the same thing? Every time I touch PL/SQL I get the impression that I'm typing way too much. Update: I'll add a sketch of the table I'm dealing with to give everyone an idea of the denormalization that I'm talking about. The table stores a history of employee jobs, each with an activation row, and (possibly) a termination row. It's possible for an employee to have multiple simultaneous jobs, as well as the same job over and over again in non-contiguous date ranges. For example: | EMP_ID | JOB_ID | STATUS | EFF_DATE | other columns... | 1 | 10 | A | 10-JAN-2008 | | 2 | 11 | A | 13-JAN-2008 | | 1 | 12 | A | 20-JAN-2008 | | 2 | 11 | T | 01-FEB-2008 | | 1 | 10 | T | 02-FEB-2008 | | 2 | 11 | A | 20-FEB-2008 | Querying that to figure out who is working when in what job is non-trivial. So, my denormalization function populates the temporary table with just the date ranges for each job, for any EMP_ID s passed in though the cursor. Passing in EMP_ID s 1 and 2 would produce the following: | EMP_ID | JOB_ID | START_DATE | END_DATE | | 1 | 10 | 10-JAN-2008 | 02-FEB-2008 | | 2 | 11 | 13-JAN-2008 | 01-FEB-2008 | | 1 | 12 | 20-JAN-2008 | | | 2 | 11 | 20-FEB-2008 | | ( END_DATE allows NULL s for jobs that don't have a predetermined termination date.) As you can imagine, this denormalized form is much, much easier to query, but creating it--so far as I can tell--requires a temporary table to store the intermediate results (e.g., job records for which the activation row has been found, but not the termination...yet). Using the pipelined table function to populate the temporary table and then return its rows is the only way I've figured out how to do it.
TITLE: Best way to encapsulate complex Oracle PL/SQL cursor logic as a view? QUESTION: I've written PL/SQL code to denormalize a table into a much-easer-to-query form. The code uses a temporary table to do some of its work, merging some rows from the original table together. The logic is written as a pipelined table function, following the pattern from the linked article. The table function uses a PRAGMA AUTONOMOUS_TRANSACTION declaration to permit the temporary table manipulation, and also accepts a cursor input parameter to restrict the denormalization to certain ID values. I then created a view to query the table function, passing in all possible ID values as a cursor (other uses of the function will be more restrictive). My question: is this all really necessary? Have I completely missed a much more simple way of accomplishing the same thing? Every time I touch PL/SQL I get the impression that I'm typing way too much. Update: I'll add a sketch of the table I'm dealing with to give everyone an idea of the denormalization that I'm talking about. The table stores a history of employee jobs, each with an activation row, and (possibly) a termination row. It's possible for an employee to have multiple simultaneous jobs, as well as the same job over and over again in non-contiguous date ranges. For example: | EMP_ID | JOB_ID | STATUS | EFF_DATE | other columns... | 1 | 10 | A | 10-JAN-2008 | | 2 | 11 | A | 13-JAN-2008 | | 1 | 12 | A | 20-JAN-2008 | | 2 | 11 | T | 01-FEB-2008 | | 1 | 10 | T | 02-FEB-2008 | | 2 | 11 | A | 20-FEB-2008 | Querying that to figure out who is working when in what job is non-trivial. So, my denormalization function populates the temporary table with just the date ranges for each job, for any EMP_ID s passed in though the cursor. Passing in EMP_ID s 1 and 2 would produce the following: | EMP_ID | JOB_ID | START_DATE | END_DATE | | 1 | 10 | 10-JAN-2008 | 02-FEB-2008 | | 2 | 11 | 13-JAN-2008 | 01-FEB-2008 | | 1 | 12 | 20-JAN-2008 | | | 2 | 11 | 20-FEB-2008 | | ( END_DATE allows NULL s for jobs that don't have a predetermined termination date.) As you can imagine, this denormalized form is much, much easier to query, but creating it--so far as I can tell--requires a temporary table to store the intermediate results (e.g., job records for which the activation row has been found, but not the termination...yet). Using the pipelined table function to populate the temporary table and then return its rows is the only way I've figured out how to do it. ANSWER: I think a way to approach this is to use analytic functions... I set up your test case using: create table employee_job ( emp_id integer, job_id integer, status varchar2(1 char), eff_date date ); insert into employee_job values (1,10,'A',to_date('10-JAN-2008','DD-MON-YYYY')); insert into employee_job values (2,11,'A',to_date('13-JAN-2008','DD-MON-YYYY')); insert into employee_job values (1,12,'A',to_date('20-JAN-2008','DD-MON-YYYY')); insert into employee_job values (2,11,'T',to_date('01-FEB-2008','DD-MON-YYYY')); insert into employee_job values (1,10,'T',to_date('02-FEB-2008','DD-MON-YYYY')); insert into employee_job values (2,11,'A',to_date('20-FEB-2008','DD-MON-YYYY')); commit; I've used the lead function to get the next date and then wrapped it all as a sub-query just to get the "A" records and add the end date if there is one. select emp_id, job_id, eff_date start_date, decode(next_status,'T',next_eff_date,null) end_date from ( select emp_id, job_id, eff_date, status, lead(eff_date,1,null) over (partition by emp_id, job_id order by eff_date, status) next_eff_date, lead(status,1,null) over (partition by emp_id, job_id order by eff_date, status) next_status from employee_job ) where status = 'A' order by start_date, emp_id, job_id I'm sure there's some use cases I've missed but you get the idea. Analytic functions are your friend:) EMP_ID JOB_ID START_DATE END_DATE 1 10 10-JAN-2008 02-FEB-2008 2 11 13-JAN-2008 01-FEB-2008 2 11 20-FEB-2008 1 12 20-JAN-2008
[ "sql", "oracle", "plsql" ]
4
4
6,463
6
0
2008-08-21T14:29:48.773000
2008-09-18T21:19:12.863000
20,084
985,495
XML Serialization and Inherited Types
Following on from my previous question I have been working on getting my object model to serialize to XML. But I have now run into a problem (quelle surprise!). The problem I have is that I have a collection, which is of a abstract base class type, which is populated by the concrete derived types. I thought it would be fine to just add the XML attributes to all of the classes involved and everything would be peachy. Sadly, thats not the case! So I have done some digging on Google and I now understand why it's not working. In that the XmlSerializer is in fact doing some clever reflection in order to serialize objects to/from XML, and since its based on the abstract type, it cannot figure out what the hell it's talking to. Fine. I did come across this page on CodeProject, which looks like it may well help a lot (yet to read/consume fully), but I thought I would like to bring this problem to the StackOverflow table too, to see if you have any neat hacks/tricks in order to get this up and running in the quickest/lightest way possible. One thing I should also add is that I DO NOT want to go down the XmlInclude route. There is simply too much coupling with it, and this area of the system is under heavy development, so the it would be a real maintenance headache!
Problem Solved! OK, so I finally got there (admittedly with a lot of help from here!). So summarise: Goals: I didn't want to go down the XmlInclude route due to the maintenence headache. Once a solution was found, I wanted it to be quick to implement in other applications. Collections of Abstract types may be used, as well as individual abstract properties. I didn't really want to bother with having to do "special" things in the concrete classes. Identified Issues/Points to Note: XmlSerializer does some pretty cool reflection, but it is very limited when it comes to abstract types (i.e. it will only work with instances of the abstract type itself, not subclasses). The Xml attribute decorators define how the XmlSerializer treats the properties its finds. The physical type can also be specified, but this creates a tight coupling between the class and the serializer (not good). We can implement our own XmlSerializer by creating a class that implements IXmlSerializable. The Solution I created a generic class, in which you specify the generic type as the abstract type you will be working with. This gives the class the ability to "translate" between the abstract type and the concrete type since we can hard-code the casting (i.e. we can get more info than the XmlSerializer can). I then implemented the IXmlSerializable interface, this is pretty straight forward, but when serializing we need to ensure we write the type of the concrete class to the XML, so we can cast it back when de-serializing. It is also important to note it must be fully qualified as the assemblies that the two classes are in are likely to differ. There is of course a little type checking and stuff that needs to happen here. Since the XmlSerializer cannot cast, we need to provide the code to do that, so the implicit operator is then overloaded (I never even knew you could do this!). The code for the AbstractXmlSerializer is this: using System; using System.Collections.Generic; using System.Text; using System.Xml.Serialization; namespace Utility.Xml { public class AbstractXmlSerializer: IXmlSerializable { // Override the Implicit Conversions Since the XmlSerializer // Casts to/from the required types implicitly. public static implicit operator AbstractType(AbstractXmlSerializer o) { return o.Data; } public static implicit operator AbstractXmlSerializer (AbstractType o) { return o == null? null: new AbstractXmlSerializer (o); } private AbstractType _data; /// /// [Concrete] Data to be stored/is stored as XML. /// public AbstractType Data { get { return _data; } set { _data = value; } } /// /// **DO NOT USE** This is only added to enable XML Serialization. /// /// DO NOT USE THIS CONSTRUCTOR public AbstractXmlSerializer() { // Default Ctor (Required for Xml Serialization - DO NOT USE) } /// /// Initialises the Serializer to work with the given data. /// /// Concrete Object of the AbstractType Specified. public AbstractXmlSerializer(AbstractType data) { _data = data; } #region IXmlSerializable Members public System.Xml.Schema.XmlSchema GetSchema() { return null; // this is fine as schema is unknown. } public void ReadXml(System.Xml.XmlReader reader) { // Cast the Data back from the Abstract Type. string typeAttrib = reader.GetAttribute("type"); // Ensure the Type was Specified if (typeAttrib == null) throw new ArgumentNullException("Unable to Read Xml Data for Abstract Type '" + typeof(AbstractType).Name + "' because no 'type' attribute was specified in the XML."); Type type = Type.GetType(typeAttrib); // Check the Type is Found. if (type == null) throw new InvalidCastException("Unable to Read Xml Data for Abstract Type '" + typeof(AbstractType).Name + "' because the type specified in the XML was not found."); // Check the Type is a Subclass of the AbstractType. if (!type.IsSubclassOf(typeof(AbstractType))) throw new InvalidCastException("Unable to Read Xml Data for Abstract Type '" + typeof(AbstractType).Name + "' because the Type specified in the XML differs ('" + type.Name + "')."); // Read the Data, Deserializing based on the (now known) concrete type. reader.ReadStartElement(); this.Data = (AbstractType)new XmlSerializer(type).Deserialize(reader); reader.ReadEndElement(); } public void WriteXml(System.Xml.XmlWriter writer) { // Write the Type Name to the XML Element as an Attrib and Serialize Type type = _data.GetType(); // BugFix: Assembly must be FQN since Types can/are external to current. writer.WriteAttributeString("type", type.AssemblyQualifiedName); new XmlSerializer(type).Serialize(writer, _data); } #endregion } } So, from there, how do we tell the XmlSerializer to work with our serializer rather than the default? We must pass our type within the Xml attributes type property, for example: [XmlRoot("ClassWithAbstractCollection")] public class ClassWithAbstractCollection { private List _list; [XmlArray("ListItems")] [XmlArrayItem("ListItem", Type = typeof(AbstractXmlSerializer ))] public List List { get { return _list; } set { _list = value; } } private AbstractType _prop; [XmlElement("MyProperty", Type=typeof(AbstractXmlSerializer ))] public AbstractType MyProperty { get { return _prop; } set { _prop = value; } } public ClassWithAbstractCollection() { _list = new List (); } } Here you can see, we have a collection and a single property being exposed, and all we need to do is add the type named parameter to the Xml declaration, easy!:D NOTE: If you use this code, I would really appreciate a shout-out. It will also help drive more people to the community:) Now, but unsure as to what to do with answers here since they all had their pro's and con's. I'll upmod those that I feel were useful (no offence to those that weren't) and close this off once I have the rep:) Interesting problem and good fun to solve!:)
XML Serialization and Inherited Types Following on from my previous question I have been working on getting my object model to serialize to XML. But I have now run into a problem (quelle surprise!). The problem I have is that I have a collection, which is of a abstract base class type, which is populated by the concrete derived types. I thought it would be fine to just add the XML attributes to all of the classes involved and everything would be peachy. Sadly, thats not the case! So I have done some digging on Google and I now understand why it's not working. In that the XmlSerializer is in fact doing some clever reflection in order to serialize objects to/from XML, and since its based on the abstract type, it cannot figure out what the hell it's talking to. Fine. I did come across this page on CodeProject, which looks like it may well help a lot (yet to read/consume fully), but I thought I would like to bring this problem to the StackOverflow table too, to see if you have any neat hacks/tricks in order to get this up and running in the quickest/lightest way possible. One thing I should also add is that I DO NOT want to go down the XmlInclude route. There is simply too much coupling with it, and this area of the system is under heavy development, so the it would be a real maintenance headache!
TITLE: XML Serialization and Inherited Types QUESTION: Following on from my previous question I have been working on getting my object model to serialize to XML. But I have now run into a problem (quelle surprise!). The problem I have is that I have a collection, which is of a abstract base class type, which is populated by the concrete derived types. I thought it would be fine to just add the XML attributes to all of the classes involved and everything would be peachy. Sadly, thats not the case! So I have done some digging on Google and I now understand why it's not working. In that the XmlSerializer is in fact doing some clever reflection in order to serialize objects to/from XML, and since its based on the abstract type, it cannot figure out what the hell it's talking to. Fine. I did come across this page on CodeProject, which looks like it may well help a lot (yet to read/consume fully), but I thought I would like to bring this problem to the StackOverflow table too, to see if you have any neat hacks/tricks in order to get this up and running in the quickest/lightest way possible. One thing I should also add is that I DO NOT want to go down the XmlInclude route. There is simply too much coupling with it, and this area of the system is under heavy development, so the it would be a real maintenance headache! ANSWER: Problem Solved! OK, so I finally got there (admittedly with a lot of help from here!). So summarise: Goals: I didn't want to go down the XmlInclude route due to the maintenence headache. Once a solution was found, I wanted it to be quick to implement in other applications. Collections of Abstract types may be used, as well as individual abstract properties. I didn't really want to bother with having to do "special" things in the concrete classes. Identified Issues/Points to Note: XmlSerializer does some pretty cool reflection, but it is very limited when it comes to abstract types (i.e. it will only work with instances of the abstract type itself, not subclasses). The Xml attribute decorators define how the XmlSerializer treats the properties its finds. The physical type can also be specified, but this creates a tight coupling between the class and the serializer (not good). We can implement our own XmlSerializer by creating a class that implements IXmlSerializable. The Solution I created a generic class, in which you specify the generic type as the abstract type you will be working with. This gives the class the ability to "translate" between the abstract type and the concrete type since we can hard-code the casting (i.e. we can get more info than the XmlSerializer can). I then implemented the IXmlSerializable interface, this is pretty straight forward, but when serializing we need to ensure we write the type of the concrete class to the XML, so we can cast it back when de-serializing. It is also important to note it must be fully qualified as the assemblies that the two classes are in are likely to differ. There is of course a little type checking and stuff that needs to happen here. Since the XmlSerializer cannot cast, we need to provide the code to do that, so the implicit operator is then overloaded (I never even knew you could do this!). The code for the AbstractXmlSerializer is this: using System; using System.Collections.Generic; using System.Text; using System.Xml.Serialization; namespace Utility.Xml { public class AbstractXmlSerializer: IXmlSerializable { // Override the Implicit Conversions Since the XmlSerializer // Casts to/from the required types implicitly. public static implicit operator AbstractType(AbstractXmlSerializer o) { return o.Data; } public static implicit operator AbstractXmlSerializer (AbstractType o) { return o == null? null: new AbstractXmlSerializer (o); } private AbstractType _data; /// /// [Concrete] Data to be stored/is stored as XML. /// public AbstractType Data { get { return _data; } set { _data = value; } } /// /// **DO NOT USE** This is only added to enable XML Serialization. /// /// DO NOT USE THIS CONSTRUCTOR public AbstractXmlSerializer() { // Default Ctor (Required for Xml Serialization - DO NOT USE) } /// /// Initialises the Serializer to work with the given data. /// /// Concrete Object of the AbstractType Specified. public AbstractXmlSerializer(AbstractType data) { _data = data; } #region IXmlSerializable Members public System.Xml.Schema.XmlSchema GetSchema() { return null; // this is fine as schema is unknown. } public void ReadXml(System.Xml.XmlReader reader) { // Cast the Data back from the Abstract Type. string typeAttrib = reader.GetAttribute("type"); // Ensure the Type was Specified if (typeAttrib == null) throw new ArgumentNullException("Unable to Read Xml Data for Abstract Type '" + typeof(AbstractType).Name + "' because no 'type' attribute was specified in the XML."); Type type = Type.GetType(typeAttrib); // Check the Type is Found. if (type == null) throw new InvalidCastException("Unable to Read Xml Data for Abstract Type '" + typeof(AbstractType).Name + "' because the type specified in the XML was not found."); // Check the Type is a Subclass of the AbstractType. if (!type.IsSubclassOf(typeof(AbstractType))) throw new InvalidCastException("Unable to Read Xml Data for Abstract Type '" + typeof(AbstractType).Name + "' because the Type specified in the XML differs ('" + type.Name + "')."); // Read the Data, Deserializing based on the (now known) concrete type. reader.ReadStartElement(); this.Data = (AbstractType)new XmlSerializer(type).Deserialize(reader); reader.ReadEndElement(); } public void WriteXml(System.Xml.XmlWriter writer) { // Write the Type Name to the XML Element as an Attrib and Serialize Type type = _data.GetType(); // BugFix: Assembly must be FQN since Types can/are external to current. writer.WriteAttributeString("type", type.AssemblyQualifiedName); new XmlSerializer(type).Serialize(writer, _data); } #endregion } } So, from there, how do we tell the XmlSerializer to work with our serializer rather than the default? We must pass our type within the Xml attributes type property, for example: [XmlRoot("ClassWithAbstractCollection")] public class ClassWithAbstractCollection { private List _list; [XmlArray("ListItems")] [XmlArrayItem("ListItem", Type = typeof(AbstractXmlSerializer ))] public List List { get { return _list; } set { _list = value; } } private AbstractType _prop; [XmlElement("MyProperty", Type=typeof(AbstractXmlSerializer ))] public AbstractType MyProperty { get { return _prop; } set { _prop = value; } } public ClassWithAbstractCollection() { _list = new List (); } } Here you can see, we have a collection and a single property being exposed, and all we need to do is add the type named parameter to the Xml declaration, easy!:D NOTE: If you use this code, I would really appreciate a shout-out. It will also help drive more people to the community:) Now, but unsure as to what to do with answers here since they all had their pro's and con's. I'll upmod those that I feel were useful (no offence to those that weren't) and close this off once I have the rep:) Interesting problem and good fun to solve!:)
[ "c#", "xml", "inheritance", "serialization", "xml-serialization" ]
86
57
58,582
7
0
2008-08-21T14:30:53.497000
2009-06-12T07:42:23.883000
20,088
20,114
Is there a way to make Firefox ignore invalid ssl-certificates?
I am maintaining a few web applications. The development and qa environments use invalid/outdated ssl-certificates. Although it is generally a good thing, that Firefox makes me click like a dozen times to accept the certificate, this is pretty annoying. Is there a configuration-parameter to make Firefox (and possibly IE too) accept any ssl-certificate? EDIT: I have accepted the solution, that worked. But thanks to all the people that have advised to use self-signed certificates. I am totally aware, that the accepted solution leaves me with a gaping security hole. Nonetheless I am to lazy to change the certificate for all the applications and all the environments... But I also advice anybody strongly to leave validation enabled!
Go to Tools > Options > Advanced "Tab"(?) > Encryption Tab Click the "Validation" button, and uncheck the checkbox for checking validity Be advised though that this is pretty unsecure as it leaves you wide open to accept any invalid certificate. I'd only do this if using the browser on an Intranet where the validity of the cert isn't a concern to you, or you aren't concerned in general.
Is there a way to make Firefox ignore invalid ssl-certificates? I am maintaining a few web applications. The development and qa environments use invalid/outdated ssl-certificates. Although it is generally a good thing, that Firefox makes me click like a dozen times to accept the certificate, this is pretty annoying. Is there a configuration-parameter to make Firefox (and possibly IE too) accept any ssl-certificate? EDIT: I have accepted the solution, that worked. But thanks to all the people that have advised to use self-signed certificates. I am totally aware, that the accepted solution leaves me with a gaping security hole. Nonetheless I am to lazy to change the certificate for all the applications and all the environments... But I also advice anybody strongly to leave validation enabled!
TITLE: Is there a way to make Firefox ignore invalid ssl-certificates? QUESTION: I am maintaining a few web applications. The development and qa environments use invalid/outdated ssl-certificates. Although it is generally a good thing, that Firefox makes me click like a dozen times to accept the certificate, this is pretty annoying. Is there a configuration-parameter to make Firefox (and possibly IE too) accept any ssl-certificate? EDIT: I have accepted the solution, that worked. But thanks to all the people that have advised to use self-signed certificates. I am totally aware, that the accepted solution leaves me with a gaping security hole. Nonetheless I am to lazy to change the certificate for all the applications and all the environments... But I also advice anybody strongly to leave validation enabled! ANSWER: Go to Tools > Options > Advanced "Tab"(?) > Encryption Tab Click the "Validation" button, and uncheck the checkbox for checking validity Be advised though that this is pretty unsecure as it leaves you wide open to accept any invalid certificate. I'd only do this if using the browser on an Intranet where the validity of the cert isn't a concern to you, or you aren't concerned in general.
[ "debugging", "ssl", "firefox", "ssl-certificate", "web-development-server" ]
126
26
347,383
10
0
2008-08-21T14:31:50.063000
2008-08-21T14:37:43.293000
20,107
20,118
YUI Reset CSS Makes <strong><em>this not work</em></strong>
This line in YUI's Reset CSS is causing trouble for me: address,caption,cite,code,dfn,em,strong,th,var { font-style: normal; font-weight: normal; } It makes my em not italic and my strong not bold. Which is okay. I know how to override that in my own stylesheet. strong, b { font-weight: bold; } em, i { font-style: italic; } The problem comes in when I have text that's both em and strong. This is bold, and this is italic, but not bold My rule for strong makes it bold, but YUI's rule for em makes it normal again. How do I fix that?
If your strong declaration comes after YUI's yours should override it. You can force it like this: strong, b, strong *, b * { font-weight: bold; } em, i, em *, i * { font-style: italic; } If you still support IE7 you'll need to add!important. strong, b, strong *, b * { font-weight: bold!important; } em, i, em *, i * { font-style: italic!important; } This works - see for yourself: /*YUI styles*/ address,caption,cite,code,dfn,em,strong,th,var { font-style: normal; font-weight: normal; } /*End YUI styles =*/ strong, b, strong *, b * { font-weight: bold; } em, i, em *, i * { font-style: italic; } Bold - Italic - Bold and Italic
YUI Reset CSS Makes <strong><em>this not work</em></strong> This line in YUI's Reset CSS is causing trouble for me: address,caption,cite,code,dfn,em,strong,th,var { font-style: normal; font-weight: normal; } It makes my em not italic and my strong not bold. Which is okay. I know how to override that in my own stylesheet. strong, b { font-weight: bold; } em, i { font-style: italic; } The problem comes in when I have text that's both em and strong. This is bold, and this is italic, but not bold My rule for strong makes it bold, but YUI's rule for em makes it normal again. How do I fix that?
TITLE: YUI Reset CSS Makes <strong><em>this not work</em></strong> QUESTION: This line in YUI's Reset CSS is causing trouble for me: address,caption,cite,code,dfn,em,strong,th,var { font-style: normal; font-weight: normal; } It makes my em not italic and my strong not bold. Which is okay. I know how to override that in my own stylesheet. strong, b { font-weight: bold; } em, i { font-style: italic; } The problem comes in when I have text that's both em and strong. This is bold, and this is italic, but not bold My rule for strong makes it bold, but YUI's rule for em makes it normal again. How do I fix that? ANSWER: If your strong declaration comes after YUI's yours should override it. You can force it like this: strong, b, strong *, b * { font-weight: bold; } em, i, em *, i * { font-style: italic; } If you still support IE7 you'll need to add!important. strong, b, strong *, b * { font-weight: bold!important; } em, i, em *, i * { font-style: italic!important; } This works - see for yourself: /*YUI styles*/ address,caption,cite,code,dfn,em,strong,th,var { font-style: normal; font-weight: normal; } /*End YUI styles =*/ strong, b, strong *, b * { font-weight: bold; } em, i, em *, i * { font-style: italic; } Bold - Italic - Bold and Italic
[ "css", "yui" ]
12
19
11,655
10
0
2008-08-21T14:36:41.097000
2008-08-21T14:39:10.810000
20,127
20,870
Virtual Machine Optimization
I am messing around with a toy interpreter in Java and I was considering trying to write a simple compiler that can generate bytecode for the Java Virtual Machine. Which got me thinking, how much optimization needs to be done by compilers that target virtual machines such as JVM and CLI? Do Just In Time (JIT) compilers do constant folding, peephole optimizations etc?
I'm just gonna add two links which explain Java's bytecode pretty well and some of the various optimization of the JVM during runtime.
Virtual Machine Optimization I am messing around with a toy interpreter in Java and I was considering trying to write a simple compiler that can generate bytecode for the Java Virtual Machine. Which got me thinking, how much optimization needs to be done by compilers that target virtual machines such as JVM and CLI? Do Just In Time (JIT) compilers do constant folding, peephole optimizations etc?
TITLE: Virtual Machine Optimization QUESTION: I am messing around with a toy interpreter in Java and I was considering trying to write a simple compiler that can generate bytecode for the Java Virtual Machine. Which got me thinking, how much optimization needs to be done by compilers that target virtual machines such as JVM and CLI? Do Just In Time (JIT) compilers do constant folding, peephole optimizations etc? ANSWER: I'm just gonna add two links which explain Java's bytecode pretty well and some of the various optimization of the JVM during runtime.
[ "java", "jvm", "jit", "cil" ]
12
6
4,148
7
0
2008-08-21T14:41:31.023000
2008-08-21T19:22:21.300000
20,156
20,175
Is there an easy way to create ordinals in C#?
Is there an easy way in C# to create Ordinals for a number? For example: 1 returns 1st 2 returns 2nd 3 returns 3rd...etc Can this be done through String.Format() or are there any functions available to do this?
This page gives you a complete listing of all custom numerical formatting rules: Custom numeric format strings As you can see, there is nothing in there about ordinals, so it can't be done using String.Format. However its not really that hard to write a function to do it. public static string AddOrdinal(int num) { if( num <= 0 ) return num.ToString(); switch(num % 100) { case 11: case 12: case 13: return num + "th"; } switch(num % 10) { case 1: return num + "st"; case 2: return num + "nd"; case 3: return num + "rd"; default: return num + "th"; } } Update: Technically Ordinals don't exist for <= 0, so I've updated the code above. Also removed the redundant ToString() methods. Also note, this is not internationalized. I've no idea what ordinals look like in other languages.
Is there an easy way to create ordinals in C#? Is there an easy way in C# to create Ordinals for a number? For example: 1 returns 1st 2 returns 2nd 3 returns 3rd...etc Can this be done through String.Format() or are there any functions available to do this?
TITLE: Is there an easy way to create ordinals in C#? QUESTION: Is there an easy way in C# to create Ordinals for a number? For example: 1 returns 1st 2 returns 2nd 3 returns 3rd...etc Can this be done through String.Format() or are there any functions available to do this? ANSWER: This page gives you a complete listing of all custom numerical formatting rules: Custom numeric format strings As you can see, there is nothing in there about ordinals, so it can't be done using String.Format. However its not really that hard to write a function to do it. public static string AddOrdinal(int num) { if( num <= 0 ) return num.ToString(); switch(num % 100) { case 11: case 12: case 13: return num + "th"; } switch(num % 10) { case 1: return num + "st"; case 2: return num + "nd"; case 3: return num + "rd"; default: return num + "th"; } } Update: Technically Ordinals don't exist for <= 0, so I've updated the code above. Also removed the redundant ToString() methods. Also note, this is not internationalized. I've no idea what ordinals look like in other languages.
[ "c#", ".net", "ordinals" ]
231
352
70,767
23
0
2008-08-21T14:55:48.947000
2008-08-21T15:03:47.973000
20,168
20,181
C# application detected as a virus
Regarding the same program as my question a few minutes ago... I added a setup project and built an MSI for the program (just to see if I could figure it out) and it works great except for one thing. When I tried to install it on my parent's laptop, their antivirus (the free Avast Home Edition) set off an alarm and accused my setup.exe of being a Trojan. Does anyone have any idea why this would be happening and how I can fix it?
Indeed, boot from a clean CD (use a known good machine to build BartPE or something similar) and scan your machine thoroughly. Another good thing to check, though, would be exactly which virus Avast! thinks your program is. Once you know that, you should be able to look it up in one of the virus databases and insure that your software can't contain it. The odds are that Avast! is just getting a false positive for some reason, and I don't know that there's much you can do about that other than contacting Avast! and hoping for a reply.
C# application detected as a virus Regarding the same program as my question a few minutes ago... I added a setup project and built an MSI for the program (just to see if I could figure it out) and it works great except for one thing. When I tried to install it on my parent's laptop, their antivirus (the free Avast Home Edition) set off an alarm and accused my setup.exe of being a Trojan. Does anyone have any idea why this would be happening and how I can fix it?
TITLE: C# application detected as a virus QUESTION: Regarding the same program as my question a few minutes ago... I added a setup project and built an MSI for the program (just to see if I could figure it out) and it works great except for one thing. When I tried to install it on my parent's laptop, their antivirus (the free Avast Home Edition) set off an alarm and accused my setup.exe of being a Trojan. Does anyone have any idea why this would be happening and how I can fix it? ANSWER: Indeed, boot from a clean CD (use a known good machine to build BartPE or something similar) and scan your machine thoroughly. Another good thing to check, though, would be exactly which virus Avast! thinks your program is. Once you know that, you should be able to look it up in one of the virus databases and insure that your software can't contain it. The odds are that Avast! is just getting a false positive for some reason, and I don't know that there's much you can do about that other than contacting Avast! and hoping for a reply.
[ "c#", ".net", "antivirus" ]
3
3
5,849
5
0
2008-08-21T14:59:48.157000
2008-08-21T15:10:33.777000
20,173
20,178
MSTest and NHibernate
Does anyone have any experience getting MSTest to copy hibernate.cfg.xml properly to the output directory? All my MSTests fail with a cannot find hibernate.cfg.xml error (I have it set to Copy Always), but my MBUnit tests pass.
You can try adding the DeploymentItemAttribute to one of your tests, or edit your.testrunconfig file and add the file to the Deployment list.
MSTest and NHibernate Does anyone have any experience getting MSTest to copy hibernate.cfg.xml properly to the output directory? All my MSTests fail with a cannot find hibernate.cfg.xml error (I have it set to Copy Always), but my MBUnit tests pass.
TITLE: MSTest and NHibernate QUESTION: Does anyone have any experience getting MSTest to copy hibernate.cfg.xml properly to the output directory? All my MSTests fail with a cannot find hibernate.cfg.xml error (I have it set to Copy Always), but my MBUnit tests pass. ANSWER: You can try adding the DeploymentItemAttribute to one of your tests, or edit your.testrunconfig file and add the file to the Deployment list.
[ "nhibernate", "mstest", "mbunit" ]
7
12
2,129
5
0
2008-08-21T15:02:53.110000
2008-08-21T15:07:13.223000
20,185
20,200
Is there a way to make a constructor only visible to a parent class in C#?
I have a collection of classes that inherit from an abstract class I created. I'd like to use the abstract class as a factory for creating instances of concrete implementations of my abstract class. Is there any way to hide a constructor from all code except a parent class. I'd like to do this basically public abstract class AbstractClass { public static AbstractClass MakeAbstractClass(string args) { if (args == "a") return new ConcreteClassA(); if (args == "b") return new ConcreteClassB(); } } public class ConcreteClassA: AbstractClass { } public class ConcreteClassB: AbstractClass { } But I want to prevent anyone from directly instantiating the 2 concrete classes. I want to ensure that only the MakeAbstractClass() method can instantiate the base classes. Is there any way to do this? UPDATE I don't need to access any specific methods of ConcreteClassA or B from outside of the Abstract class. I only need the public methods my Abstract class provides. I don't really need to prevent the Concrete classes from being instantiated, I'm just trying to avoid it since they provide no new public interfaces, just different implementations of some very specific things internal to the abstract class. To me, the simplest solution is to make child classes as samjudson mentioned. I'd like to avoid this however since it would make my abstract class' file a lot bigger than I'd like it to be. I'd rather keep classes split out over a few files for organization. I guess there's no easy solution to this...
You can make the sub classes child classes, something like this: public abstract class AbstractClass { public static AbstractClass MakeAbstractClass(string args) { if (args == "a") return new ConcreteClassA(); if (args == "b") return new ConcreteClassB(); } private class ConcreteClassA: AbstractClass { } private class ConcreteClassB: AbstractClass { } } @Vaibhav This does indeed mean that the classes are also hidden. But this is as far as I am aware the only way to completely hide the constructor. Edit: As others have mentioned the same thing can be accomplished using Reflection, which might actually be closer to what you would like to be the case - for example the above method replies on the concrete classes being inside the same file as the Abstract class, which probably isn't very convenient. Having said that this way is a nice 'Hack', and good if the number and complexity of the concrete classes is low.
Is there a way to make a constructor only visible to a parent class in C#? I have a collection of classes that inherit from an abstract class I created. I'd like to use the abstract class as a factory for creating instances of concrete implementations of my abstract class. Is there any way to hide a constructor from all code except a parent class. I'd like to do this basically public abstract class AbstractClass { public static AbstractClass MakeAbstractClass(string args) { if (args == "a") return new ConcreteClassA(); if (args == "b") return new ConcreteClassB(); } } public class ConcreteClassA: AbstractClass { } public class ConcreteClassB: AbstractClass { } But I want to prevent anyone from directly instantiating the 2 concrete classes. I want to ensure that only the MakeAbstractClass() method can instantiate the base classes. Is there any way to do this? UPDATE I don't need to access any specific methods of ConcreteClassA or B from outside of the Abstract class. I only need the public methods my Abstract class provides. I don't really need to prevent the Concrete classes from being instantiated, I'm just trying to avoid it since they provide no new public interfaces, just different implementations of some very specific things internal to the abstract class. To me, the simplest solution is to make child classes as samjudson mentioned. I'd like to avoid this however since it would make my abstract class' file a lot bigger than I'd like it to be. I'd rather keep classes split out over a few files for organization. I guess there's no easy solution to this...
TITLE: Is there a way to make a constructor only visible to a parent class in C#? QUESTION: I have a collection of classes that inherit from an abstract class I created. I'd like to use the abstract class as a factory for creating instances of concrete implementations of my abstract class. Is there any way to hide a constructor from all code except a parent class. I'd like to do this basically public abstract class AbstractClass { public static AbstractClass MakeAbstractClass(string args) { if (args == "a") return new ConcreteClassA(); if (args == "b") return new ConcreteClassB(); } } public class ConcreteClassA: AbstractClass { } public class ConcreteClassB: AbstractClass { } But I want to prevent anyone from directly instantiating the 2 concrete classes. I want to ensure that only the MakeAbstractClass() method can instantiate the base classes. Is there any way to do this? UPDATE I don't need to access any specific methods of ConcreteClassA or B from outside of the Abstract class. I only need the public methods my Abstract class provides. I don't really need to prevent the Concrete classes from being instantiated, I'm just trying to avoid it since they provide no new public interfaces, just different implementations of some very specific things internal to the abstract class. To me, the simplest solution is to make child classes as samjudson mentioned. I'd like to avoid this however since it would make my abstract class' file a lot bigger than I'd like it to be. I'd rather keep classes split out over a few files for organization. I guess there's no easy solution to this... ANSWER: You can make the sub classes child classes, something like this: public abstract class AbstractClass { public static AbstractClass MakeAbstractClass(string args) { if (args == "a") return new ConcreteClassA(); if (args == "b") return new ConcreteClassB(); } private class ConcreteClassA: AbstractClass { } private class ConcreteClassB: AbstractClass { } } @Vaibhav This does indeed mean that the classes are also hidden. But this is as far as I am aware the only way to completely hide the constructor. Edit: As others have mentioned the same thing can be accomplished using Reflection, which might actually be closer to what you would like to be the case - for example the above method replies on the concrete classes being inside the same file as the Abstract class, which probably isn't very convenient. Having said that this way is a nice 'Hack', and good if the number and complexity of the concrete classes is low.
[ "c#", "inheritance", "oop" ]
5
2
1,677
9
0
2008-08-21T15:12:48.063000
2008-08-21T15:15:20.647000
20,198
20,219
How does the ASP.NET "Yellow Screen of Death" display code?
I thought.Net code gets compiled into MSIL, so I always wondered how do Yellow Screens produce the faulty code. If it's executing the compiled code, how is the compiler able to produce code from the source files in the error message? Feel free to edit this question/title, I know it doesn't really make sense.
A.Net assembly is compiled with metadata about the bytecode included that allows easy decompilation of the code - that's how tools like.Net Reflector work. The PDB files are debug symbols only - the difference in the Yellow Screen Of Death is that you'll get line numbers in the stack trace. In other words, you'd get the code, even if the PDB files were missing.
How does the ASP.NET "Yellow Screen of Death" display code? I thought.Net code gets compiled into MSIL, so I always wondered how do Yellow Screens produce the faulty code. If it's executing the compiled code, how is the compiler able to produce code from the source files in the error message? Feel free to edit this question/title, I know it doesn't really make sense.
TITLE: How does the ASP.NET "Yellow Screen of Death" display code? QUESTION: I thought.Net code gets compiled into MSIL, so I always wondered how do Yellow Screens produce the faulty code. If it's executing the compiled code, how is the compiler able to produce code from the source files in the error message? Feel free to edit this question/title, I know it doesn't really make sense. ANSWER: A.Net assembly is compiled with metadata about the bytecode included that allows easy decompilation of the code - that's how tools like.Net Reflector work. The PDB files are debug symbols only - the difference in the Yellow Screen Of Death is that you'll get line numbers in the stack trace. In other words, you'd get the code, even if the PDB files were missing.
[ ".net", "asp.net", "yellow-screen-of-death" ]
13
9
3,358
5
0
2008-08-21T15:14:44.827000
2008-08-21T15:21:08.213000
20,207
20,243
Does the Microsoft Report Viewer Redistributable 2008 really require .NET Framework version 3.5?
I'm packaging up a.NET 2.0 based web app for deployment through a Windows Installer based package. Our app uses Report Viewer 2008 and I'm including the Microsoft Report Viewer Redistributable 2008 installer. When I check the download page for Report Viewer 2008, it lists.NET 3.5 as a requirement. Is having.Net 3.5 installed really needed Report Viewer 2008? We targeted.Net 2.0 for our app, there isn't anything in our code that would use the 3.0 or 3.5 Frameworks. We are in the middle of testing and everything seems to be working with out 3.5, but I don't want to miss an edge condition and cause an error for a customer because he was missing a prerequisite run time package.
So far testing with or with out the.NET Framework works as expected. My installer has the user install version 2.0 of the Framework and everything works as expected. My concern is that 3.5 is listed as a prerequisite on the Report Viewer download page.
Does the Microsoft Report Viewer Redistributable 2008 really require .NET Framework version 3.5? I'm packaging up a.NET 2.0 based web app for deployment through a Windows Installer based package. Our app uses Report Viewer 2008 and I'm including the Microsoft Report Viewer Redistributable 2008 installer. When I check the download page for Report Viewer 2008, it lists.NET 3.5 as a requirement. Is having.Net 3.5 installed really needed Report Viewer 2008? We targeted.Net 2.0 for our app, there isn't anything in our code that would use the 3.0 or 3.5 Frameworks. We are in the middle of testing and everything seems to be working with out 3.5, but I don't want to miss an edge condition and cause an error for a customer because he was missing a prerequisite run time package.
TITLE: Does the Microsoft Report Viewer Redistributable 2008 really require .NET Framework version 3.5? QUESTION: I'm packaging up a.NET 2.0 based web app for deployment through a Windows Installer based package. Our app uses Report Viewer 2008 and I'm including the Microsoft Report Viewer Redistributable 2008 installer. When I check the download page for Report Viewer 2008, it lists.NET 3.5 as a requirement. Is having.Net 3.5 installed really needed Report Viewer 2008? We targeted.Net 2.0 for our app, there isn't anything in our code that would use the 3.0 or 3.5 Frameworks. We are in the middle of testing and everything seems to be working with out 3.5, but I don't want to miss an edge condition and cause an error for a customer because he was missing a prerequisite run time package. ANSWER: So far testing with or with out the.NET Framework works as expected. My installer has the user install version 2.0 of the Framework and everything works as expected. My concern is that 3.5 is listed as a prerequisite on the Report Viewer download page.
[ ".net-3.5", "reportviewer", "web-deployment-project", "reportviewer2008" ]
3
0
6,542
5
0
2008-08-21T15:16:53.513000
2008-08-21T15:29:42.640000
20,227
20,670
How do I use 3DES encryption/decryption in Java?
Every method I write to encode a string in Java using 3DES can't be decrypted back to the original string. Does anyone have a simple code snippet that can just encode and then decode the string back to the original string? I know I'm making a very silly mistake somewhere in this code. Here's what I've been working with so far: ** note, I am not returning the BASE64 text from the encrypt method, and I am not base64 un-encoding in the decrypt method because I was trying to see if I was making a mistake in the BASE64 part of the puzzle. public class TripleDESTest { public static void main(String[] args) { String text = "kyle boon"; byte[] codedtext = new TripleDESTest().encrypt(text); String decodedtext = new TripleDESTest().decrypt(codedtext); System.out.println(codedtext); System.out.println(decodedtext); } public byte[] encrypt(String message) { try { final MessageDigest md = MessageDigest.getInstance("md5"); final byte[] digestOfPassword = md.digest("HG58YZ3CR9".getBytes("utf-8")); final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24); for (int j = 0, k = 16; j < 8;) { keyBytes[k++] = keyBytes[j++]; } final SecretKey key = new SecretKeySpec(keyBytes, "DESede"); final IvParameterSpec iv = new IvParameterSpec(new byte[8]); final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key, iv); final byte[] plainTextBytes = message.getBytes("utf-8"); final byte[] cipherText = cipher.doFinal(plainTextBytes); final String encodedCipherText = new sun.misc.BASE64Encoder().encode(cipherText); return cipherText; } catch (java.security.InvalidAlgorithmParameterException e) { System.out.println("Invalid Algorithm"); } catch (javax.crypto.NoSuchPaddingException e) { System.out.println("No Such Padding"); } catch (java.security.NoSuchAlgorithmException e) { System.out.println("No Such Algorithm"); } catch (java.security.InvalidKeyException e) { System.out.println("Invalid Key"); } catch (BadPaddingException e) { System.out.println("Invalid Key");} catch (IllegalBlockSizeException e) { System.out.println("Invalid Key");} catch (UnsupportedEncodingException e) { System.out.println("Invalid Key");} return null; } public String decrypt(byte[] message) { try { final MessageDigest md = MessageDigest.getInstance("md5"); final byte[] digestOfPassword = md.digest("HG58YZ3CR9".getBytes("utf-8")); final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24); for (int j = 0, k = 16; j < 8;) { keyBytes[k++] = keyBytes[j++]; } final SecretKey key = new SecretKeySpec(keyBytes, "DESede"); final IvParameterSpec iv = new IvParameterSpec(new byte[8]); final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); decipher.init(Cipher.DECRYPT_MODE, key, iv); //final byte[] encData = new sun.misc.BASE64Decoder().decodeBuffer(message); final byte[] plainText = decipher.doFinal(message); return plainText.toString(); } catch (java.security.InvalidAlgorithmParameterException e) { System.out.println("Invalid Algorithm"); } catch (javax.crypto.NoSuchPaddingException e) { System.out.println("No Such Padding"); } catch (java.security.NoSuchAlgorithmException e) { System.out.println("No Such Algorithm"); } catch (java.security.InvalidKeyException e) { System.out.println("Invalid Key"); } catch (BadPaddingException e) { System.out.println("Invalid Key");} catch (IllegalBlockSizeException e) { System.out.println("Invalid Key");} catch (UnsupportedEncodingException e) { System.out.println("Invalid Key");} catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }
Your code was fine except for the Base 64 encoding bit (which you mentioned was a test), the reason the output may not have made sense is that you were displaying a raw byte array (doing toString() on a byte array returns its internal Java reference, not the String representation of the contents ). Here's a version that's just a teeny bit cleaned up and which prints "kyle boon" as the decoded string: import java.security.MessageDigest; import java.util.Arrays; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class TripleDESTest { public static void main(String[] args) throws Exception { String text = "kyle boon"; byte[] codedtext = new TripleDESTest().encrypt(text); String decodedtext = new TripleDESTest().decrypt(codedtext); System.out.println(codedtext); // this is a byte array, you'll just see a reference to an array System.out.println(decodedtext); // This correctly shows "kyle boon" } public byte[] encrypt(String message) throws Exception { final MessageDigest md = MessageDigest.getInstance("md5"); final byte[] digestOfPassword = md.digest("HG58YZ3CR9".getBytes("utf-8")); final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24); for (int j = 0, k = 16; j < 8;) { keyBytes[k++] = keyBytes[j++]; } final SecretKey key = new SecretKeySpec(keyBytes, "DESede"); final IvParameterSpec iv = new IvParameterSpec(new byte[8]); final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key, iv); final byte[] plainTextBytes = message.getBytes("utf-8"); final byte[] cipherText = cipher.doFinal(plainTextBytes); // final String encodedCipherText = new sun.misc.BASE64Encoder() //.encode(cipherText); return cipherText; } public String decrypt(byte[] message) throws Exception { final MessageDigest md = MessageDigest.getInstance("md5"); final byte[] digestOfPassword = md.digest("HG58YZ3CR9".getBytes("utf-8")); final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24); for (int j = 0, k = 16; j < 8;) { keyBytes[k++] = keyBytes[j++]; } final SecretKey key = new SecretKeySpec(keyBytes, "DESede"); final IvParameterSpec iv = new IvParameterSpec(new byte[8]); final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); decipher.init(Cipher.DECRYPT_MODE, key, iv); // final byte[] encData = new // sun.misc.BASE64Decoder().decodeBuffer(message); final byte[] plainText = decipher.doFinal(message); return new String(plainText, "UTF-8"); } }
How do I use 3DES encryption/decryption in Java? Every method I write to encode a string in Java using 3DES can't be decrypted back to the original string. Does anyone have a simple code snippet that can just encode and then decode the string back to the original string? I know I'm making a very silly mistake somewhere in this code. Here's what I've been working with so far: ** note, I am not returning the BASE64 text from the encrypt method, and I am not base64 un-encoding in the decrypt method because I was trying to see if I was making a mistake in the BASE64 part of the puzzle. public class TripleDESTest { public static void main(String[] args) { String text = "kyle boon"; byte[] codedtext = new TripleDESTest().encrypt(text); String decodedtext = new TripleDESTest().decrypt(codedtext); System.out.println(codedtext); System.out.println(decodedtext); } public byte[] encrypt(String message) { try { final MessageDigest md = MessageDigest.getInstance("md5"); final byte[] digestOfPassword = md.digest("HG58YZ3CR9".getBytes("utf-8")); final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24); for (int j = 0, k = 16; j < 8;) { keyBytes[k++] = keyBytes[j++]; } final SecretKey key = new SecretKeySpec(keyBytes, "DESede"); final IvParameterSpec iv = new IvParameterSpec(new byte[8]); final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key, iv); final byte[] plainTextBytes = message.getBytes("utf-8"); final byte[] cipherText = cipher.doFinal(plainTextBytes); final String encodedCipherText = new sun.misc.BASE64Encoder().encode(cipherText); return cipherText; } catch (java.security.InvalidAlgorithmParameterException e) { System.out.println("Invalid Algorithm"); } catch (javax.crypto.NoSuchPaddingException e) { System.out.println("No Such Padding"); } catch (java.security.NoSuchAlgorithmException e) { System.out.println("No Such Algorithm"); } catch (java.security.InvalidKeyException e) { System.out.println("Invalid Key"); } catch (BadPaddingException e) { System.out.println("Invalid Key");} catch (IllegalBlockSizeException e) { System.out.println("Invalid Key");} catch (UnsupportedEncodingException e) { System.out.println("Invalid Key");} return null; } public String decrypt(byte[] message) { try { final MessageDigest md = MessageDigest.getInstance("md5"); final byte[] digestOfPassword = md.digest("HG58YZ3CR9".getBytes("utf-8")); final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24); for (int j = 0, k = 16; j < 8;) { keyBytes[k++] = keyBytes[j++]; } final SecretKey key = new SecretKeySpec(keyBytes, "DESede"); final IvParameterSpec iv = new IvParameterSpec(new byte[8]); final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); decipher.init(Cipher.DECRYPT_MODE, key, iv); //final byte[] encData = new sun.misc.BASE64Decoder().decodeBuffer(message); final byte[] plainText = decipher.doFinal(message); return plainText.toString(); } catch (java.security.InvalidAlgorithmParameterException e) { System.out.println("Invalid Algorithm"); } catch (javax.crypto.NoSuchPaddingException e) { System.out.println("No Such Padding"); } catch (java.security.NoSuchAlgorithmException e) { System.out.println("No Such Algorithm"); } catch (java.security.InvalidKeyException e) { System.out.println("Invalid Key"); } catch (BadPaddingException e) { System.out.println("Invalid Key");} catch (IllegalBlockSizeException e) { System.out.println("Invalid Key");} catch (UnsupportedEncodingException e) { System.out.println("Invalid Key");} catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }
TITLE: How do I use 3DES encryption/decryption in Java? QUESTION: Every method I write to encode a string in Java using 3DES can't be decrypted back to the original string. Does anyone have a simple code snippet that can just encode and then decode the string back to the original string? I know I'm making a very silly mistake somewhere in this code. Here's what I've been working with so far: ** note, I am not returning the BASE64 text from the encrypt method, and I am not base64 un-encoding in the decrypt method because I was trying to see if I was making a mistake in the BASE64 part of the puzzle. public class TripleDESTest { public static void main(String[] args) { String text = "kyle boon"; byte[] codedtext = new TripleDESTest().encrypt(text); String decodedtext = new TripleDESTest().decrypt(codedtext); System.out.println(codedtext); System.out.println(decodedtext); } public byte[] encrypt(String message) { try { final MessageDigest md = MessageDigest.getInstance("md5"); final byte[] digestOfPassword = md.digest("HG58YZ3CR9".getBytes("utf-8")); final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24); for (int j = 0, k = 16; j < 8;) { keyBytes[k++] = keyBytes[j++]; } final SecretKey key = new SecretKeySpec(keyBytes, "DESede"); final IvParameterSpec iv = new IvParameterSpec(new byte[8]); final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key, iv); final byte[] plainTextBytes = message.getBytes("utf-8"); final byte[] cipherText = cipher.doFinal(plainTextBytes); final String encodedCipherText = new sun.misc.BASE64Encoder().encode(cipherText); return cipherText; } catch (java.security.InvalidAlgorithmParameterException e) { System.out.println("Invalid Algorithm"); } catch (javax.crypto.NoSuchPaddingException e) { System.out.println("No Such Padding"); } catch (java.security.NoSuchAlgorithmException e) { System.out.println("No Such Algorithm"); } catch (java.security.InvalidKeyException e) { System.out.println("Invalid Key"); } catch (BadPaddingException e) { System.out.println("Invalid Key");} catch (IllegalBlockSizeException e) { System.out.println("Invalid Key");} catch (UnsupportedEncodingException e) { System.out.println("Invalid Key");} return null; } public String decrypt(byte[] message) { try { final MessageDigest md = MessageDigest.getInstance("md5"); final byte[] digestOfPassword = md.digest("HG58YZ3CR9".getBytes("utf-8")); final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24); for (int j = 0, k = 16; j < 8;) { keyBytes[k++] = keyBytes[j++]; } final SecretKey key = new SecretKeySpec(keyBytes, "DESede"); final IvParameterSpec iv = new IvParameterSpec(new byte[8]); final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); decipher.init(Cipher.DECRYPT_MODE, key, iv); //final byte[] encData = new sun.misc.BASE64Decoder().decodeBuffer(message); final byte[] plainText = decipher.doFinal(message); return plainText.toString(); } catch (java.security.InvalidAlgorithmParameterException e) { System.out.println("Invalid Algorithm"); } catch (javax.crypto.NoSuchPaddingException e) { System.out.println("No Such Padding"); } catch (java.security.NoSuchAlgorithmException e) { System.out.println("No Such Algorithm"); } catch (java.security.InvalidKeyException e) { System.out.println("Invalid Key"); } catch (BadPaddingException e) { System.out.println("Invalid Key");} catch (IllegalBlockSizeException e) { System.out.println("Invalid Key");} catch (UnsupportedEncodingException e) { System.out.println("Invalid Key");} catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } } ANSWER: Your code was fine except for the Base 64 encoding bit (which you mentioned was a test), the reason the output may not have made sense is that you were displaying a raw byte array (doing toString() on a byte array returns its internal Java reference, not the String representation of the contents ). Here's a version that's just a teeny bit cleaned up and which prints "kyle boon" as the decoded string: import java.security.MessageDigest; import java.util.Arrays; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class TripleDESTest { public static void main(String[] args) throws Exception { String text = "kyle boon"; byte[] codedtext = new TripleDESTest().encrypt(text); String decodedtext = new TripleDESTest().decrypt(codedtext); System.out.println(codedtext); // this is a byte array, you'll just see a reference to an array System.out.println(decodedtext); // This correctly shows "kyle boon" } public byte[] encrypt(String message) throws Exception { final MessageDigest md = MessageDigest.getInstance("md5"); final byte[] digestOfPassword = md.digest("HG58YZ3CR9".getBytes("utf-8")); final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24); for (int j = 0, k = 16; j < 8;) { keyBytes[k++] = keyBytes[j++]; } final SecretKey key = new SecretKeySpec(keyBytes, "DESede"); final IvParameterSpec iv = new IvParameterSpec(new byte[8]); final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key, iv); final byte[] plainTextBytes = message.getBytes("utf-8"); final byte[] cipherText = cipher.doFinal(plainTextBytes); // final String encodedCipherText = new sun.misc.BASE64Encoder() //.encode(cipherText); return cipherText; } public String decrypt(byte[] message) throws Exception { final MessageDigest md = MessageDigest.getInstance("md5"); final byte[] digestOfPassword = md.digest("HG58YZ3CR9".getBytes("utf-8")); final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24); for (int j = 0, k = 16; j < 8;) { keyBytes[k++] = keyBytes[j++]; } final SecretKey key = new SecretKeySpec(keyBytes, "DESede"); final IvParameterSpec iv = new IvParameterSpec(new byte[8]); final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); decipher.init(Cipher.DECRYPT_MODE, key, iv); // final byte[] encData = new // sun.misc.BASE64Decoder().decodeBuffer(message); final byte[] plainText = decipher.doFinal(message); return new String(plainText, "UTF-8"); } }
[ "java", "encryption", "3des" ]
77
73
199,316
6
0
2008-08-21T15:25:22.540000
2008-08-21T17:59:50.767000