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
2,332
2,333
How do I turn on line numbers by default in TextWrangler on the Mac?
I am fed up having to turn them on every time I open the application.
Go to TextWrangler > Preferences. Choose Text Status Display in the category pane, then check the option "Show line numbers" and close the preferences. This should now be on by default when you open existing documents.
How do I turn on line numbers by default in TextWrangler on the Mac? I am fed up having to turn them on every time I open the application.
TITLE: How do I turn on line numbers by default in TextWrangler on the Mac? QUESTION: I am fed up having to turn them on every time I open the application. ANSWER: Go to TextWrangler > Preferences. Choose Text Status Display in the category pane, then check the option "Show line numbers" and close the preferences. This should now be on by default when you open existing documents.
[ "macos", "textwrangler" ]
23
28
4,736
1
0
2008-08-05T13:57:05.033000
2008-08-05T13:57:10.027000
2,348
2,393
What is the best way to iterate through an array in Classic Asp VBScript?
In the code below For i = LBound(arr) To UBound(arr) What is the point in asking using LBound? Surely that is always 0.
Why not use For Each? That way you don't need to care what the LBound and UBound are. Dim x, y, z x = Array(1, 2, 3) For Each y In x z = DoSomethingWith(y) Next
What is the best way to iterate through an array in Classic Asp VBScript? In the code below For i = LBound(arr) To UBound(arr) What is the point in asking using LBound? Surely that is always 0.
TITLE: What is the best way to iterate through an array in Classic Asp VBScript? QUESTION: In the code below For i = LBound(arr) To UBound(arr) What is the point in asking using LBound? Surely that is always 0. ANSWER: Why not use For Each? That way you don't need to care what the LBound and UBound are. Dim x, y, z x = Array(1, 2, 3) For Each y In x z = DoSomethingWith(y) Next
[ "arrays", "asp-classic", "vbscript" ]
42
64
84,690
6
0
2008-08-05T14:07:58.913000
2008-08-05T14:36:12.693000
2,349
2,360
How to tab focus onto a dropdown field in Mac OSX
In Windows, in any windows form or web browser, you can use the tab button to switch focus through all of the form fields. It will stop on textboxes, radiobuttons, checkboxes, dropdown menus, etc. However, in Mac OSX, tab skips dropdown menus. Is there anyway to change this behavior, or access the above items mentioned, without using a mouse?
Go to System Preferences > Keyboard and Mouse, then choose Keyboard Shortcuts. At the bottom, ensure Full Keyboard Access is set to "All controls". It's a long time since I turned it on but I think that's all you need to do
How to tab focus onto a dropdown field in Mac OSX In Windows, in any windows form or web browser, you can use the tab button to switch focus through all of the form fields. It will stop on textboxes, radiobuttons, checkboxes, dropdown menus, etc. However, in Mac OSX, tab skips dropdown menus. Is there anyway to change this behavior, or access the above items mentioned, without using a mouse?
TITLE: How to tab focus onto a dropdown field in Mac OSX QUESTION: In Windows, in any windows form or web browser, you can use the tab button to switch focus through all of the form fields. It will stop on textboxes, radiobuttons, checkboxes, dropdown menus, etc. However, in Mac OSX, tab skips dropdown menus. Is there anyway to change this behavior, or access the above items mentioned, without using a mouse? ANSWER: Go to System Preferences > Keyboard and Mouse, then choose Keyboard Shortcuts. At the bottom, ensure Full Keyboard Access is set to "All controls". It's a long time since I turned it on but I think that's all you need to do
[ "macos", "mouse", "keyboard-shortcuts" ]
22
28
5,803
4
0
2008-08-05T14:07:58.930000
2008-08-05T14:13:12.740000
2,432
2,462
Have you ever encountered a query that SQL Server could not execute because it referenced too many tables?
Have you ever seen any of there error messages? -- SQL Server 2000 Could not allocate ancillary table for view or function resolution. The maximum number of tables in a query (256) was exceeded. -- SQL Server 2005 Too many table names in the query. The maximum allowable is 256. If yes, what have you done? Given up? Convinced the customer to simplify their demands? Denormalized the database? @(everyone wanting me to post the query): I'm not sure if I can paste 70 kilobytes of code in the answer editing window. Even if I can this this won't help since this 70 kilobytes of code will reference 20 or 30 views that I would also have to post since otherwise the code will be meaningless. I don't want to sound like I am boasting here but the problem is not in the queries. The queries are optimal (or at least almost optimal). I have spent countless hours optimizing them, looking for every single column and every single table that can be removed. Imagine a report that has 200 or 300 columns that has to be filled with a single SELECT statement (because that's how it was designed a few years ago when it was still a small report).
For SQL Server 2005, I'd recommend using table variables and partially building the data as you go. To do this, create a table variable that represents your final result set you want to send to the user. Then find your primary table (say the orders table in your example above) and pull that data, plus a bit of supplementary data that is only say one join away (customer name, product name). You can do a SELECT INTO to put this straight into your table variable. From there, iterate through the table and for each row, do a bunch of small SELECT queries that retrieves all the supplemental data you need for your result set. Insert these into each column as you go. Once complete, you can then do a simple SELECT * from your table variable and return this result set to the user. I don't have any hard numbers for this, but there have been three distinct instances that I have worked on to date where doing these smaller queries has actually worked faster than doing one massive select query with a bunch of joins.
Have you ever encountered a query that SQL Server could not execute because it referenced too many tables? Have you ever seen any of there error messages? -- SQL Server 2000 Could not allocate ancillary table for view or function resolution. The maximum number of tables in a query (256) was exceeded. -- SQL Server 2005 Too many table names in the query. The maximum allowable is 256. If yes, what have you done? Given up? Convinced the customer to simplify their demands? Denormalized the database? @(everyone wanting me to post the query): I'm not sure if I can paste 70 kilobytes of code in the answer editing window. Even if I can this this won't help since this 70 kilobytes of code will reference 20 or 30 views that I would also have to post since otherwise the code will be meaningless. I don't want to sound like I am boasting here but the problem is not in the queries. The queries are optimal (or at least almost optimal). I have spent countless hours optimizing them, looking for every single column and every single table that can be removed. Imagine a report that has 200 or 300 columns that has to be filled with a single SELECT statement (because that's how it was designed a few years ago when it was still a small report).
TITLE: Have you ever encountered a query that SQL Server could not execute because it referenced too many tables? QUESTION: Have you ever seen any of there error messages? -- SQL Server 2000 Could not allocate ancillary table for view or function resolution. The maximum number of tables in a query (256) was exceeded. -- SQL Server 2005 Too many table names in the query. The maximum allowable is 256. If yes, what have you done? Given up? Convinced the customer to simplify their demands? Denormalized the database? @(everyone wanting me to post the query): I'm not sure if I can paste 70 kilobytes of code in the answer editing window. Even if I can this this won't help since this 70 kilobytes of code will reference 20 or 30 views that I would also have to post since otherwise the code will be meaningless. I don't want to sound like I am boasting here but the problem is not in the queries. The queries are optimal (or at least almost optimal). I have spent countless hours optimizing them, looking for every single column and every single table that can be removed. Imagine a report that has 200 or 300 columns that has to be filled with a single SELECT statement (because that's how it was designed a few years ago when it was still a small report). ANSWER: For SQL Server 2005, I'd recommend using table variables and partially building the data as you go. To do this, create a table variable that represents your final result set you want to send to the user. Then find your primary table (say the orders table in your example above) and pull that data, plus a bit of supplementary data that is only say one join away (customer name, product name). You can do a SELECT INTO to put this straight into your table variable. From there, iterate through the table and for each row, do a bunch of small SELECT queries that retrieves all the supplemental data you need for your result set. Insert these into each column as you go. Once complete, you can then do a simple SELECT * from your table variable and return this result set to the user. I don't have any hard numbers for this, but there have been three distinct instances that I have worked on to date where doing these smaller queries has actually worked faster than doing one massive select query with a bunch of joins.
[ "sql-server", "database", "sql-server-2005", "sql-server-2000" ]
20
9
10,573
8
0
2008-08-05T14:54:03.470000
2008-08-05T15:19:41.187000
2,472
2,477
How can I tell if a web client is blocking advertisements?
What is the best way to record statistics on the number of visitors visiting my site that have set their browser to block ads?
Since programs like AdBlock actually never request the advert, you would have to look the server logs to see if the same user accessed a webpage but didn't access an advert. This is assuming the advert is on the same server. If your adverts are on a separate server, then I would suggest it's impossible to do so. The best way to stop users from blocking adverts, is to have inline text adverts which are generated by the server and dished up inside your html.
How can I tell if a web client is blocking advertisements? What is the best way to record statistics on the number of visitors visiting my site that have set their browser to block ads?
TITLE: How can I tell if a web client is blocking advertisements? QUESTION: What is the best way to record statistics on the number of visitors visiting my site that have set their browser to block ads? ANSWER: Since programs like AdBlock actually never request the advert, you would have to look the server logs to see if the same user accessed a webpage but didn't access an advert. This is assuming the advert is on the same server. If your adverts are on a separate server, then I would suggest it's impossible to do so. The best way to stop users from blocking adverts, is to have inline text adverts which are generated by the server and dished up inside your html.
[ "browser", "analytics" ]
16
11
2,077
5
0
2008-08-05T15:30:42.617000
2008-08-05T15:34:18.583000
2,481
2,511
Best self-balancing BST for quick insertion of a large number of nodes
I've been able to find details on several self-balancing BST s through several sources, but I haven't found any good descriptions detailing which one is best to use in different situations (or if it really doesn't matter). I want a BST that is optimal for storing in excess of ten million nodes. The order of insertion of the nodes is basically random, and I will never need to delete nodes, so insertion time is the only thing that would need to be optimized. I intend to use it to store previously visited game states in a puzzle game, so that I can quickly check if a previous configuration has already been encountered.
Red-black is better than AVL for insertion-heavy applications. If you foresee relatively uniform look-up, then Red-black is the way to go. If you foresee a relatively unbalanced look-up where more recently viewed elements are more likely to be viewed again, you want to use splay trees.
Best self-balancing BST for quick insertion of a large number of nodes I've been able to find details on several self-balancing BST s through several sources, but I haven't found any good descriptions detailing which one is best to use in different situations (or if it really doesn't matter). I want a BST that is optimal for storing in excess of ten million nodes. The order of insertion of the nodes is basically random, and I will never need to delete nodes, so insertion time is the only thing that would need to be optimized. I intend to use it to store previously visited game states in a puzzle game, so that I can quickly check if a previous configuration has already been encountered.
TITLE: Best self-balancing BST for quick insertion of a large number of nodes QUESTION: I've been able to find details on several self-balancing BST s through several sources, but I haven't found any good descriptions detailing which one is best to use in different situations (or if it really doesn't matter). I want a BST that is optimal for storing in excess of ten million nodes. The order of insertion of the nodes is basically random, and I will never need to delete nodes, so insertion time is the only thing that would need to be optimized. I intend to use it to store previously visited game states in a puzzle game, so that I can quickly check if a previous configuration has already been encountered. ANSWER: Red-black is better than AVL for insertion-heavy applications. If you foresee relatively uniform look-up, then Red-black is the way to go. If you foresee a relatively unbalanced look-up where more recently viewed elements are more likely to be viewed again, you want to use splay trees.
[ "data-structures", "language-agnostic", "binary-search-tree" ]
11
4
1,464
4
0
2008-08-05T15:40:24.903000
2008-08-05T15:59:27.563000
2,482
2,513
What are some good resources for learning threaded programming?
With the rise of multicore CPUs on the desktop, multithreading skills will become a valuable asset for programmers. Can you recommend some good resources (books, tutorials, websites, etc.) for a programmer who is looking to learn about threaded programming?
Take a look at Herb Sutter's " The Free Lunch Is Over " and then his series of articles on Effective Concurrency.
What are some good resources for learning threaded programming? With the rise of multicore CPUs on the desktop, multithreading skills will become a valuable asset for programmers. Can you recommend some good resources (books, tutorials, websites, etc.) for a programmer who is looking to learn about threaded programming?
TITLE: What are some good resources for learning threaded programming? QUESTION: With the rise of multicore CPUs on the desktop, multithreading skills will become a valuable asset for programmers. Can you recommend some good resources (books, tutorials, websites, etc.) for a programmer who is looking to learn about threaded programming? ANSWER: Take a look at Herb Sutter's " The Free Lunch Is Over " and then his series of articles on Effective Concurrency.
[ "multithreading", "language-agnostic", "concurrency" ]
36
19
12,013
17
0
2008-08-05T15:42:09.847000
2008-08-05T16:02:41.660000
2,483
2,487
Casting: (NewType) vs. Object as NewType
What is actually the difference between these two casts? SomeClass sc = (SomeClass)SomeObject; SomeClass sc2 = SomeObject as SomeClass; Normally, shouldn't they both be explicit casts to the specified type?
The former will throw an exception if the source type can't be cast to the target type. The latter will result in sc2 being a null reference, but no exception. [Edit] My original answer is certainly the most pronounced difference, but as Eric Lippert points out, it's not the only one. Other differences include: You can't use the 'as' operator to cast to a type that doesn't accept 'null' as a value You can't use 'as' to convert things, like numbers to a different representation (float to int, for example). And finally, using 'as' vs. the cast operator, you're also saying "I'm not sure if this will succeed."
Casting: (NewType) vs. Object as NewType What is actually the difference between these two casts? SomeClass sc = (SomeClass)SomeObject; SomeClass sc2 = SomeObject as SomeClass; Normally, shouldn't they both be explicit casts to the specified type?
TITLE: Casting: (NewType) vs. Object as NewType QUESTION: What is actually the difference between these two casts? SomeClass sc = (SomeClass)SomeObject; SomeClass sc2 = SomeObject as SomeClass; Normally, shouldn't they both be explicit casts to the specified type? ANSWER: The former will throw an exception if the source type can't be cast to the target type. The latter will result in sc2 being a null reference, but no exception. [Edit] My original answer is certainly the most pronounced difference, but as Eric Lippert points out, it's not the only one. Other differences include: You can't use the 'as' operator to cast to a type that doesn't accept 'null' as a value You can't use 'as' to convert things, like numbers to a different representation (float to int, for example). And finally, using 'as' vs. the cast operator, you're also saying "I'm not sure if this will succeed."
[ "c#", ".net" ]
92
88
11,837
12
0
2008-08-05T15:42:30.110000
2008-08-05T15:44:46.330000
2,486
2,514
What is Progressive Enhancement?
Jeff mentioned the concept of 'Progressive Enhancement' when talking about using JQuery to write stackoverflow. After a quick Google, I found a couple of high-level discussions about it. Can anyone recommend a good place to start as a programmer. Specifically, I have been writing web apps in PHP and would like to use YUI to improve the pages I am writing, but a lot of them seem very JavaScript based, with most of the donkey work being done using JavaScript. To me, that seems a bit overkill, since viewing the site without Javascript will probably break most of it. Anyone have some good places to start using this idea, I don't really care about the language. Ideally, I would like to see how you start creating the static HTML first, and then adding the YUI (or whatever Ajax framework) to it so that you get the benefits of a richer client?
See also Unobtrusive JavaScript which is the bedrock progressive enhancement is built.
What is Progressive Enhancement? Jeff mentioned the concept of 'Progressive Enhancement' when talking about using JQuery to write stackoverflow. After a quick Google, I found a couple of high-level discussions about it. Can anyone recommend a good place to start as a programmer. Specifically, I have been writing web apps in PHP and would like to use YUI to improve the pages I am writing, but a lot of them seem very JavaScript based, with most of the donkey work being done using JavaScript. To me, that seems a bit overkill, since viewing the site without Javascript will probably break most of it. Anyone have some good places to start using this idea, I don't really care about the language. Ideally, I would like to see how you start creating the static HTML first, and then adding the YUI (or whatever Ajax framework) to it so that you get the benefits of a richer client?
TITLE: What is Progressive Enhancement? QUESTION: Jeff mentioned the concept of 'Progressive Enhancement' when talking about using JQuery to write stackoverflow. After a quick Google, I found a couple of high-level discussions about it. Can anyone recommend a good place to start as a programmer. Specifically, I have been writing web apps in PHP and would like to use YUI to improve the pages I am writing, but a lot of them seem very JavaScript based, with most of the donkey work being done using JavaScript. To me, that seems a bit overkill, since viewing the site without Javascript will probably break most of it. Anyone have some good places to start using this idea, I don't really care about the language. Ideally, I would like to see how you start creating the static HTML first, and then adding the YUI (or whatever Ajax framework) to it so that you get the benefits of a richer client? ANSWER: See also Unobtrusive JavaScript which is the bedrock progressive enhancement is built.
[ "ajax", "progressive-enhancement" ]
24
10
2,515
7
0
2008-08-05T15:44:39.327000
2008-08-05T16:05:29.020000
2,488
2,495
Auto Generate Database Diagram MySQL
I'm tired of opening Dia and creating a database diagram at the beginning of every project. Is there a tool out there that will let me select specific tables and then create a database diagram for me based on a MySQL database? Preferably it would allow me to edit the diagram afterward since none of the foreign keys are set... Here is what I am picturing diagram-wise (please excuse the horrible data design, I didn't design it. Let's focus on the diagram concept and not on the actual data it represents for this example;) ): see full size diagram
Try MySQL Workbench, formerly DBDesigner 4: http://dev.mysql.com/workbench/ This has a "Reverse Engineer Database" mode: Database -> Reverse Engineer
Auto Generate Database Diagram MySQL I'm tired of opening Dia and creating a database diagram at the beginning of every project. Is there a tool out there that will let me select specific tables and then create a database diagram for me based on a MySQL database? Preferably it would allow me to edit the diagram afterward since none of the foreign keys are set... Here is what I am picturing diagram-wise (please excuse the horrible data design, I didn't design it. Let's focus on the diagram concept and not on the actual data it represents for this example;) ): see full size diagram
TITLE: Auto Generate Database Diagram MySQL QUESTION: I'm tired of opening Dia and creating a database diagram at the beginning of every project. Is there a tool out there that will let me select specific tables and then create a database diagram for me based on a MySQL database? Preferably it would allow me to edit the diagram afterward since none of the foreign keys are set... Here is what I am picturing diagram-wise (please excuse the horrible data design, I didn't design it. Let's focus on the diagram concept and not on the actual data it represents for this example;) ): see full size diagram ANSWER: Try MySQL Workbench, formerly DBDesigner 4: http://dev.mysql.com/workbench/ This has a "Reverse Engineer Database" mode: Database -> Reverse Engineer
[ "mysql", "database", "database-design", "diagram" ]
359
440
376,801
14
0
2008-08-05T15:45:02.930000
2008-08-05T15:48:11.707000
2,509
2,548
What are the primary differences between TDD and BDD?
Test Driven Development has been the rage in the.NET community for the last few years. Recently, I have heard grumblings in the ALT.NET community about BDD. What is it? What makes it different from TDD?
I understand BDD to be more about specification than testing. It is linked to Domain Driven Design (don't you love these *DD acronyms?). It is linked with a certain way to write user stories, including high-level tests. An example by Tom ten Thij: Story: User logging in As a user I want to login with my details So that I can get access to the site Scenario: User uses wrong password Given a username 'jdoe' And a password 'letmein' When the user logs in with username and password Then the login form should be shown again (In his article, Tom goes on to directly execute this test specification in Ruby.) The pope of BDD is Dan North. You'll find a great introduction in his Introducing BDD article. You will find a comparison of BDD and TDD in this video. Also an opinion about BDD as "TDD done right" by Jeremy D. Miller March 25, 2013 update The video above has been missing for a while. Here is a recent one by Llewellyn Falco, BDD vs TDD (explained). I find his explanation clear and to the point.
What are the primary differences between TDD and BDD? Test Driven Development has been the rage in the.NET community for the last few years. Recently, I have heard grumblings in the ALT.NET community about BDD. What is it? What makes it different from TDD?
TITLE: What are the primary differences between TDD and BDD? QUESTION: Test Driven Development has been the rage in the.NET community for the last few years. Recently, I have heard grumblings in the ALT.NET community about BDD. What is it? What makes it different from TDD? ANSWER: I understand BDD to be more about specification than testing. It is linked to Domain Driven Design (don't you love these *DD acronyms?). It is linked with a certain way to write user stories, including high-level tests. An example by Tom ten Thij: Story: User logging in As a user I want to login with my details So that I can get access to the site Scenario: User uses wrong password Given a username 'jdoe' And a password 'letmein' When the user logs in with username and password Then the login form should be shown again (In his article, Tom goes on to directly execute this test specification in Ruby.) The pope of BDD is Dan North. You'll find a great introduction in his Introducing BDD article. You will find a comparison of BDD and TDD in this video. Also an opinion about BDD as "TDD done right" by Jeremy D. Miller March 25, 2013 update The video above has been missing for a while. Here is a recent one by Llewellyn Falco, BDD vs TDD (explained). I find his explanation clear and to the point.
[ "unit-testing", "tdd", "bdd" ]
136
108
44,451
12
0
2008-08-05T15:58:08.473000
2008-08-05T16:36:53.840000
2,518
10,020
Using multiple SQLite databases at once
I have 2 SQLite databases, one downloaded from a server ( server.db ), and one used as storage on the client ( client.db ). I need to perform various sync queries on the client database, using data from the server database. For example, I want to delete all rows in the client.db tRole table, and repopulate with all rows in the server.db tRole table. Another example, I want to delete all rows in the client.db tFile table where the fileID is not in the server.db tFile table. In SQL Server you can just prefix the table with the name of the database. Is there anyway to do this in SQLite using Adobe Air?
I just looked at the AIR SQL API, and there's an attach method on SQLConnection it looks exactly what you need. I haven't tested this, but according to the documentation it should work: var connection: SQLConnection = new SQLConnection(); connection.open(firstDbFile); connection.attach(secondDbFile, "otherDb"); var statement: SQLStatement = new SQLStatement(); statement.connection = connection; statement.text = "INSERT INTO main.myTable SELECT * FROM otherDb.myTable"; statement.execute(); There may be errors in that code snippet, I haven't worked much with the AIR SQL API lately. Notice that the tables of the database opened with open are available using main.tableName, any attached database can be given any name at all ( otherDb in the example above).
Using multiple SQLite databases at once I have 2 SQLite databases, one downloaded from a server ( server.db ), and one used as storage on the client ( client.db ). I need to perform various sync queries on the client database, using data from the server database. For example, I want to delete all rows in the client.db tRole table, and repopulate with all rows in the server.db tRole table. Another example, I want to delete all rows in the client.db tFile table where the fileID is not in the server.db tFile table. In SQL Server you can just prefix the table with the name of the database. Is there anyway to do this in SQLite using Adobe Air?
TITLE: Using multiple SQLite databases at once QUESTION: I have 2 SQLite databases, one downloaded from a server ( server.db ), and one used as storage on the client ( client.db ). I need to perform various sync queries on the client database, using data from the server database. For example, I want to delete all rows in the client.db tRole table, and repopulate with all rows in the server.db tRole table. Another example, I want to delete all rows in the client.db tFile table where the fileID is not in the server.db tFile table. In SQL Server you can just prefix the table with the name of the database. Is there anyway to do this in SQLite using Adobe Air? ANSWER: I just looked at the AIR SQL API, and there's an attach method on SQLConnection it looks exactly what you need. I haven't tested this, but according to the documentation it should work: var connection: SQLConnection = new SQLConnection(); connection.open(firstDbFile); connection.attach(secondDbFile, "otherDb"); var statement: SQLStatement = new SQLStatement(); statement.connection = connection; statement.text = "INSERT INTO main.myTable SELECT * FROM otherDb.myTable"; statement.execute(); There may be errors in that code snippet, I haven't worked much with the AIR SQL API lately. Notice that the tables of the database opened with open are available using main.tableName, any attached database can be given any name at all ( otherDb in the example above).
[ "actionscript-3", "apache-flex", "sqlite", "air", "adobe" ]
10
9
20,148
3
0
2008-08-05T16:09:12.570000
2008-08-13T16:16:12.450000
2,524
151,931
Visual Studio "Unable to start debugging on the web server. The web server did not respond in a timely manner."
I get the following error pretty regularly when compiling in Visual Studio and running my web application: "Unable to start debugging on the web server. The web server did not respond in a timely manner. This may be because another debugger is already attached to the web server." Normally this is after having debug the application once already. From the command line I run "iisreset /restart" and it fixes the problem. How do I prevent this from happening in the first place?
I find that this happens if I'm debugging with Firefox as my browser. When I exit Firefox the VS2005/8 debug session doesn't terminate. I have not found a solution for this (yet). If this is what's happening with you then a quicker solution than running iisreset is to hit Shift-F5 when in Visual Studio and this will terminate the current debug session. You can then hit F5 and this will start a new debug session.
Visual Studio "Unable to start debugging on the web server. The web server did not respond in a timely manner." I get the following error pretty regularly when compiling in Visual Studio and running my web application: "Unable to start debugging on the web server. The web server did not respond in a timely manner. This may be because another debugger is already attached to the web server." Normally this is after having debug the application once already. From the command line I run "iisreset /restart" and it fixes the problem. How do I prevent this from happening in the first place?
TITLE: Visual Studio "Unable to start debugging on the web server. The web server did not respond in a timely manner." QUESTION: I get the following error pretty regularly when compiling in Visual Studio and running my web application: "Unable to start debugging on the web server. The web server did not respond in a timely manner. This may be because another debugger is already attached to the web server." Normally this is after having debug the application once already. From the command line I run "iisreset /restart" and it fixes the problem. How do I prevent this from happening in the first place? ANSWER: I find that this happens if I'm debugging with Firefox as my browser. When I exit Firefox the VS2005/8 debug session doesn't terminate. I have not found a solution for this (yet). If this is what's happening with you then a quicker solution than running iisreset is to hit Shift-F5 when in Visual Studio and this will terminate the current debug session. You can then hit F5 and this will start a new debug session.
[ "asp.net", "visual-studio", "visual-studio-2008", "debugging", "iis" ]
56
22
78,949
31
0
2008-08-05T16:18:18.853000
2008-09-30T06:04:38.680000
2,525
8,739
.NET obfuscation tools/strategy
My product has several components: ASP.NET, Windows Forms App and Windows Service. 95% or so of the code is written in VB.NET. For Intellectual Property reasons, I need to obfuscate the code, and until now I have been using a version of dotfuscator which is now over 5 years old. I'm thinking it is time to move to a new generation tool. What I'm looking for is a list of requirements which I should consider when searching for a new obfuscator. What I know I should look for so far: Serialization/De-serialization. In my current solution, I simply tell the tool not to obfuscate any class data members because the pain of not being able to load data which was previously serialized is simply too big. Integration with Build Process Working with ASP.NET. In the past, I have found this problematic due to changing.dll names (you often have one per page) - which not all tools handle well.
Back with.Net 1.1 obfuscation was essential: decompiling code was easy, and you could go from assembly, to IL, to C# code and have it compiled again with very little effort. Now with.Net 3.5 I'm not at all sure. Try decompiling a 3.5 assembly; what you get is a long long way from compiling. Add the optimisations from 3.5 (far better than 1.1) and the way anonymous types, delegates and so on are handled by reflection (they are a nightmare to recompile). Add lambda expressions, compiler 'magic' like Linq-syntax and var, and C#2 functions like yield (which results in new classes with unreadable names). Your decompiled code ends up a long long way from compilable. A professional team with lots of time could still reverse engineer it back again, but then the same is true of any obfuscated code. What code they got out of that would be unmaintainable and highly likely to be very buggy. I would recommend key-signing your assemblies (meaning if hackers can recompile one they have to recompile all) but I don't think obfuscation's worth it.
.NET obfuscation tools/strategy My product has several components: ASP.NET, Windows Forms App and Windows Service. 95% or so of the code is written in VB.NET. For Intellectual Property reasons, I need to obfuscate the code, and until now I have been using a version of dotfuscator which is now over 5 years old. I'm thinking it is time to move to a new generation tool. What I'm looking for is a list of requirements which I should consider when searching for a new obfuscator. What I know I should look for so far: Serialization/De-serialization. In my current solution, I simply tell the tool not to obfuscate any class data members because the pain of not being able to load data which was previously serialized is simply too big. Integration with Build Process Working with ASP.NET. In the past, I have found this problematic due to changing.dll names (you often have one per page) - which not all tools handle well.
TITLE: .NET obfuscation tools/strategy QUESTION: My product has several components: ASP.NET, Windows Forms App and Windows Service. 95% or so of the code is written in VB.NET. For Intellectual Property reasons, I need to obfuscate the code, and until now I have been using a version of dotfuscator which is now over 5 years old. I'm thinking it is time to move to a new generation tool. What I'm looking for is a list of requirements which I should consider when searching for a new obfuscator. What I know I should look for so far: Serialization/De-serialization. In my current solution, I simply tell the tool not to obfuscate any class data members because the pain of not being able to load data which was previously serialized is simply too big. Integration with Build Process Working with ASP.NET. In the past, I have found this problematic due to changing.dll names (you often have one per page) - which not all tools handle well. ANSWER: Back with.Net 1.1 obfuscation was essential: decompiling code was easy, and you could go from assembly, to IL, to C# code and have it compiled again with very little effort. Now with.Net 3.5 I'm not at all sure. Try decompiling a 3.5 assembly; what you get is a long long way from compiling. Add the optimisations from 3.5 (far better than 1.1) and the way anonymous types, delegates and so on are handled by reflection (they are a nightmare to recompile). Add lambda expressions, compiler 'magic' like Linq-syntax and var, and C#2 functions like yield (which results in new classes with unreadable names). Your decompiled code ends up a long long way from compilable. A professional team with lots of time could still reverse engineer it back again, but then the same is true of any obfuscated code. What code they got out of that would be unmaintainable and highly likely to be very buggy. I would recommend key-signing your assemblies (meaning if hackers can recompile one they have to recompile all) but I don't think obfuscation's worth it.
[ ".net", "security", "obfuscation" ]
165
44
152,277
30
0
2008-08-05T16:20:37.773000
2008-08-12T12:19:13.800000
2,527
2,546
Find node clicked under context menu
How can I find out which node in a tree list the context menu has been activated? For instance right-clicking a node and selecting an option from the menu. I can't use the TreeViews' SelectedNode property because the node is only been right-clicked and not selected.
You can add a mouse click event to the TreeView, then select the correct node using GetNodeAt given the mouse coordinates provided by the MouseEventArgs. void treeView1MouseUp(object sender, MouseEventArgs e) { if(e.Button == MouseButtons.Right) { // Select the clicked node treeView1.SelectedNode = treeView1.GetNodeAt(e.X, e.Y); if(treeView1.SelectedNode!= null) { myContextMenuStrip.Show(treeView1, e.Location); } } }
Find node clicked under context menu How can I find out which node in a tree list the context menu has been activated? For instance right-clicking a node and selecting an option from the menu. I can't use the TreeViews' SelectedNode property because the node is only been right-clicked and not selected.
TITLE: Find node clicked under context menu QUESTION: How can I find out which node in a tree list the context menu has been activated? For instance right-clicking a node and selecting an option from the menu. I can't use the TreeViews' SelectedNode property because the node is only been right-clicked and not selected. ANSWER: You can add a mouse click event to the TreeView, then select the correct node using GetNodeAt given the mouse coordinates provided by the MouseEventArgs. void treeView1MouseUp(object sender, MouseEventArgs e) { if(e.Button == MouseButtons.Right) { // Select the clicked node treeView1.SelectedNode = treeView1.GetNodeAt(e.X, e.Y); if(treeView1.SelectedNode!= null) { myContextMenuStrip.Show(treeView1, e.Location); } } }
[ "c#", "winforms", "treeview", "contextmenu" ]
76
97
59,026
10
0
2008-08-05T16:21:14.120000
2008-08-05T16:36:43.463000
2,530
2,531
How do you disable browser autocomplete on web form field / input tags?
How do you disable autocomplete in the major browsers for a specific input (or form field)?
Firefox 30 ignores autocomplete="off" for passwords, opting to prompt the user instead whether the password should be stored on the client. Note the following commentary from May 5, 2014: The password manager always prompts if it wants to save a password. Passwords are not saved without permission from the user. We are the third browser to implement this change, after IE and Chrome. According to the Mozilla Developer Network documentation, the Boolean form element attribute autocomplete prevents form data from being cached in older browsers.
How do you disable browser autocomplete on web form field / input tags? How do you disable autocomplete in the major browsers for a specific input (or form field)?
TITLE: How do you disable browser autocomplete on web form field / input tags? QUESTION: How do you disable autocomplete in the major browsers for a specific input (or form field)? ANSWER: Firefox 30 ignores autocomplete="off" for passwords, opting to prompt the user instead whether the password should be stored on the client. Note the following commentary from May 5, 2014: The password manager always prompts if it wants to save a password. Passwords are not saved without permission from the user. We are the third browser to implement this change, after IE and Chrome. According to the Mozilla Developer Network documentation, the Boolean form element attribute autocomplete prevents form data from being cached in older browsers.
[ "html", "forms", "browser", "autocomplete" ]
3,223
2,889
1,417,408
104
0
2008-08-05T16:22:32.603000
2008-08-05T16:24:53.380000
2,540
2,697
Good STL-like library for C
What are good libraries for C with datastructures like vectors, deques, stacks, hashmaps, treemaps, sets, etc.? Plain C, please, and platform-independent.
The Glib library used on the Gnome project may also be some use. Moreover it is pretty well tested. IBM developer works has a good tutorial on its use: Manage C data using the GLib collections
Good STL-like library for C What are good libraries for C with datastructures like vectors, deques, stacks, hashmaps, treemaps, sets, etc.? Plain C, please, and platform-independent.
TITLE: Good STL-like library for C QUESTION: What are good libraries for C with datastructures like vectors, deques, stacks, hashmaps, treemaps, sets, etc.? Plain C, please, and platform-independent. ANSWER: The Glib library used on the Gnome project may also be some use. Moreover it is pretty well tested. IBM developer works has a good tutorial on its use: Manage C data using the GLib collections
[ "c", "architecture", "data-structures" ]
49
39
8,708
5
0
2008-08-05T16:30:37.377000
2008-08-05T18:50:09.453000
2,543
2,564
What are the best solutions for flash charts and graphs?
I'm aware of FusionCharts, are there other good solutions, or APIs, for creating charts in Adobe Flash?
Is there a reason that you want it in Flash? If a plain, old PNG will work, try the Google Chart API.
What are the best solutions for flash charts and graphs? I'm aware of FusionCharts, are there other good solutions, or APIs, for creating charts in Adobe Flash?
TITLE: What are the best solutions for flash charts and graphs? QUESTION: I'm aware of FusionCharts, are there other good solutions, or APIs, for creating charts in Adobe Flash? ANSWER: Is there a reason that you want it in Flash? If a plain, old PNG will work, try the Google Chart API.
[ "flash", "graph" ]
16
7
5,202
10
0
2008-08-05T16:34:37.057000
2008-08-05T16:49:06.047000
2,550
2,560
What are effective options for embedding video in an ASP.NET web site?
A quick glance at the present-day internet would seem to indicate that Adobe Flash is the obvious choice for embedding video in a web page. Is this accurate, or are they other effective choices? Does the choice of ASP.NET as a platform influence this decision?
Flash is certainly the most ubiquitous and portable solution. 98% of browsers have Flash installed. Other alternatives are Quicktime, Windows Media Player, or even Silverlight (Microsoft's Flash competitor, which can be used to embed several video formats). I would recommend using Flash (and it's FLV video file format) for embedding your video unless you have very specific requirements as far as video quality or DRM.
What are effective options for embedding video in an ASP.NET web site? A quick glance at the present-day internet would seem to indicate that Adobe Flash is the obvious choice for embedding video in a web page. Is this accurate, or are they other effective choices? Does the choice of ASP.NET as a platform influence this decision?
TITLE: What are effective options for embedding video in an ASP.NET web site? QUESTION: A quick glance at the present-day internet would seem to indicate that Adobe Flash is the obvious choice for embedding video in a web page. Is this accurate, or are they other effective choices? Does the choice of ASP.NET as a platform influence this decision? ANSWER: Flash is certainly the most ubiquitous and portable solution. 98% of browsers have Flash installed. Other alternatives are Quicktime, Windows Media Player, or even Silverlight (Microsoft's Flash competitor, which can be used to embed several video formats). I would recommend using Flash (and it's FLV video file format) for embedding your video unless you have very specific requirements as far as video quality or DRM.
[ "asp.net", "flash", "video", "embed" ]
19
21
4,271
7
0
2008-08-05T16:39:04.507000
2008-08-05T16:44:01.157000
2,556
100,758
What's the best online payment processing solution?
Should be available to non-U.S. companies, easy to setup, reliable, cheap, customizable, etc. What are your experiences?
You can't really answer this kind of question with a "I like 'insert provide name here'" type answer because like so many things it is a balance and the reasons for choosing a payment processing solution tend to be complex. Volume / Value The most important factor in choosing a secure payment clearance service (the people who will connect to the banking networks and clear the money for you - will refer to them as SPCS) is how many widgets will you be selling at what cost. The pricing models of all the SCPS providers is based around this equation. This dictates the economics of using the service, which is nearly always the most important factor. For example, in the UK securetrading.net have a large annual fee and high minimum transaction values (been a while since I've seen the exact numbers and they don't make it immediately obvious on the site, but this is for illustration only anyway) making it one of the most expensive solutions to use if you are selling high value low volume. Most smaller clients will fall into this model. High value is really anything over a couple of dollars. Low volume is typically anything less than tens of thousands of units per month. However, if you are running a donations service in the aftermath of an international environmental disaster (relatively low value very high volume) then they become one of the cheapest. Factor in to this the setup costs (relatively high), and the cost to tie the service into the site (in SecureTrading's case it's very easy to do, but still a lot harder than adding a PayPal button) and you start to build up a true picture. On the flip side, a service such as PayPal has very low setup costs (no fee to pay, and trivially easy to integrate), but relatively high transaction costs. It is great for high value / low volume transactions. The Bank There are two main categories of payment clearance service - Bureau and Bank Acquired. In the UK at least NetBanx, SecureTrading and WorldPay offer both bank acquired and bureau services. ProtX and SecPay offer only bank acquired services. PayPal and its ilk operates slightly outside both definitions (see Protection below). A Bank Acquired service plumbs into your normal banking merchant account and clears the funds straight into it. As well as charging you for this service, your bank will also take a slice, typically this is more than the SPCS provider will charge and so it actually is the bank that becomes the deciding factor. Some banks will only work with their preferred provider. In the UK, most banks want you to have a separate Internet Merchant Account even if you already have a Merchant Account with them. I always tell clients to shop around, as this will make a huge difference to how much their e-commerce venture can bring in. All banks are not created equal. Bureau services effectively act as your bank at the same time as providing the clearance service. They were popular in a time when banks hadn't grasped the concept of the Internet and would prefer transactions be chiseled into stone tablets if they got their way. Often the choice between a bureau service and a bank acquired service is made for you based on circumstances. Trading History In many countries (including the UK), most banks won't give you a merchant account until you have been trading for a particular period of time (2 years in the UK). Your only option is then a bureau service. Cash flow Most bureau services will hold onto your cash as security against "charge backs". If you sell me a Ferrari and I am horrified to learn that you've sold me a small metal toy rather than the 1.5 tonnes of Italian automotive passion I was expecting, I will complain to my credit card company who will refund me and then chase your merchant services provider for a refund. They will have to give them the refund and then chase you for the money. It's therefore in their interests to hold on to your money for a period of 4-6 weeks to protect against this. If you sell services or goods with no capital outlay (software for instance), then you can afford this. If on the other hand, you really are having to pay your luxury car importer to provide you with stock, then cash flow becomes very important and you're going to need a bank acquired service where you can be paid immediately. Protection One major downside to PayPal and similar services is that it is not covered under the same regulations that govern credit cards. Simply put, if you buy something on a credit card your card provider is liable for ensure you get what you paid for (broadly speaking, in most countries, does not constitute legal advice etc.) and if you have a problem with your purchase they will refund you very quickly and then will go and chase the person that you paid. This is the kind of protection you hear about when Leo Laporte advertises American Express on his podcasts. It is a "Good Thing"TM. You don't have that protection with PayPal because when you use your credit card on PayPal, you are actually buying PayPal's service. So, even if you are mis-sold a product, the person you paid for the service (PayPal) didn't mis-sell, they provided the service you paid for. This breaks the chain. PayPal don't have a legal obligation to protect you in the same way, and their record on refunding ripped off customers is less than spangly. I'm guessing they have "Caveat Emptor" writ large on the walls of their head office.:) I'm not dissing PayPal, they are way ahead of the curve on many other security features, but just another factor to bear in mind. End to end integration Different services differ in their ease of integration. Oh boy do they differ. I'm sitting on some work right now to do an HSBC integration. I'd rather have a root canal. Some of the systems make big assumptions about the way you have to work with them, and are poorly designed or inflexible. Retro-fitting them to an active site can be very painful. Some of them are beautiful and easy to work with (and not necessarily less secure). The biggest difference is how you choose to integrate though. Most services integrate by allowing you to redirect to a secure site where your customer fills in his / her details. They are finally redirected back to a page on your own site with the results of the transaction. This works well in most cases and is easiest to integrate. When you buy something on Amazon, you don't get redirected to WorldPay, or PayPal however. If you want end-to-end integration, most services now will let the communication happen behind the scenes. Your own site has to have a decent secure server certificate of course, and the integration is necessarily more complex. Reputation It used to be that PayPal was used on dinky sites. You wouldn't catch Amazon using it. That perception has changed a lot, and in fact in some senses PayPal does security better than most. If your audience expects to see PayPal and you give them some other service then you may lose custom, or vice versa. These days many merchants offer a choice to customers. UK Providers WorldPay. Well established. Bureau and bank acquired. Relatively high transaction costs and annual costs. Fairly easy to integrate. Owned ultimately by Royal Bank of Scotland. SecPay. Bank Acquired. Low per transaction cost and low annual cost and flexible payment models. ProtX. Bank Acquired. Low per transaction cost and low annual cost, flexible payment models. Can be quite demanding to integrate. HSBC. Bank Acquired. Low per transaction cost. High set up and annual costs. Very inflexible to integrate. SecureTrading. Bureau and Bank Acquired. Low per transaction cost but high setup and annual costs. Was a doddle to integrate last time I used it (9 years ago!) NetBanx. Bureau and Bank Acquired. Haven't used since 1996 so can't comment! And of course PayPal, Google Checkout and Amazon FPS are well worth looking at and worth a whole answer on their own! Summary Told you it wasn't that simple! Usually, as developers, we're not in the position to choose for ourselves, and these decisions should be driven by the business needs of our employer / client. Most e-commerce projects would start with PayPal or similar. When the business gets enough orders that they could save money by switching to another service, then they've got enough money to pay for the switch. Disclaimer: I am UK based, and have performed many integrations with a whole slew of these services over the years, however the market changes all the time and things may have changed and your mileage may vary! I am not a lawyer or accountant, and if you take my advice it's not my fault:)
What's the best online payment processing solution? Should be available to non-U.S. companies, easy to setup, reliable, cheap, customizable, etc. What are your experiences?
TITLE: What's the best online payment processing solution? QUESTION: Should be available to non-U.S. companies, easy to setup, reliable, cheap, customizable, etc. What are your experiences? ANSWER: You can't really answer this kind of question with a "I like 'insert provide name here'" type answer because like so many things it is a balance and the reasons for choosing a payment processing solution tend to be complex. Volume / Value The most important factor in choosing a secure payment clearance service (the people who will connect to the banking networks and clear the money for you - will refer to them as SPCS) is how many widgets will you be selling at what cost. The pricing models of all the SCPS providers is based around this equation. This dictates the economics of using the service, which is nearly always the most important factor. For example, in the UK securetrading.net have a large annual fee and high minimum transaction values (been a while since I've seen the exact numbers and they don't make it immediately obvious on the site, but this is for illustration only anyway) making it one of the most expensive solutions to use if you are selling high value low volume. Most smaller clients will fall into this model. High value is really anything over a couple of dollars. Low volume is typically anything less than tens of thousands of units per month. However, if you are running a donations service in the aftermath of an international environmental disaster (relatively low value very high volume) then they become one of the cheapest. Factor in to this the setup costs (relatively high), and the cost to tie the service into the site (in SecureTrading's case it's very easy to do, but still a lot harder than adding a PayPal button) and you start to build up a true picture. On the flip side, a service such as PayPal has very low setup costs (no fee to pay, and trivially easy to integrate), but relatively high transaction costs. It is great for high value / low volume transactions. The Bank There are two main categories of payment clearance service - Bureau and Bank Acquired. In the UK at least NetBanx, SecureTrading and WorldPay offer both bank acquired and bureau services. ProtX and SecPay offer only bank acquired services. PayPal and its ilk operates slightly outside both definitions (see Protection below). A Bank Acquired service plumbs into your normal banking merchant account and clears the funds straight into it. As well as charging you for this service, your bank will also take a slice, typically this is more than the SPCS provider will charge and so it actually is the bank that becomes the deciding factor. Some banks will only work with their preferred provider. In the UK, most banks want you to have a separate Internet Merchant Account even if you already have a Merchant Account with them. I always tell clients to shop around, as this will make a huge difference to how much their e-commerce venture can bring in. All banks are not created equal. Bureau services effectively act as your bank at the same time as providing the clearance service. They were popular in a time when banks hadn't grasped the concept of the Internet and would prefer transactions be chiseled into stone tablets if they got their way. Often the choice between a bureau service and a bank acquired service is made for you based on circumstances. Trading History In many countries (including the UK), most banks won't give you a merchant account until you have been trading for a particular period of time (2 years in the UK). Your only option is then a bureau service. Cash flow Most bureau services will hold onto your cash as security against "charge backs". If you sell me a Ferrari and I am horrified to learn that you've sold me a small metal toy rather than the 1.5 tonnes of Italian automotive passion I was expecting, I will complain to my credit card company who will refund me and then chase your merchant services provider for a refund. They will have to give them the refund and then chase you for the money. It's therefore in their interests to hold on to your money for a period of 4-6 weeks to protect against this. If you sell services or goods with no capital outlay (software for instance), then you can afford this. If on the other hand, you really are having to pay your luxury car importer to provide you with stock, then cash flow becomes very important and you're going to need a bank acquired service where you can be paid immediately. Protection One major downside to PayPal and similar services is that it is not covered under the same regulations that govern credit cards. Simply put, if you buy something on a credit card your card provider is liable for ensure you get what you paid for (broadly speaking, in most countries, does not constitute legal advice etc.) and if you have a problem with your purchase they will refund you very quickly and then will go and chase the person that you paid. This is the kind of protection you hear about when Leo Laporte advertises American Express on his podcasts. It is a "Good Thing"TM. You don't have that protection with PayPal because when you use your credit card on PayPal, you are actually buying PayPal's service. So, even if you are mis-sold a product, the person you paid for the service (PayPal) didn't mis-sell, they provided the service you paid for. This breaks the chain. PayPal don't have a legal obligation to protect you in the same way, and their record on refunding ripped off customers is less than spangly. I'm guessing they have "Caveat Emptor" writ large on the walls of their head office.:) I'm not dissing PayPal, they are way ahead of the curve on many other security features, but just another factor to bear in mind. End to end integration Different services differ in their ease of integration. Oh boy do they differ. I'm sitting on some work right now to do an HSBC integration. I'd rather have a root canal. Some of the systems make big assumptions about the way you have to work with them, and are poorly designed or inflexible. Retro-fitting them to an active site can be very painful. Some of them are beautiful and easy to work with (and not necessarily less secure). The biggest difference is how you choose to integrate though. Most services integrate by allowing you to redirect to a secure site where your customer fills in his / her details. They are finally redirected back to a page on your own site with the results of the transaction. This works well in most cases and is easiest to integrate. When you buy something on Amazon, you don't get redirected to WorldPay, or PayPal however. If you want end-to-end integration, most services now will let the communication happen behind the scenes. Your own site has to have a decent secure server certificate of course, and the integration is necessarily more complex. Reputation It used to be that PayPal was used on dinky sites. You wouldn't catch Amazon using it. That perception has changed a lot, and in fact in some senses PayPal does security better than most. If your audience expects to see PayPal and you give them some other service then you may lose custom, or vice versa. These days many merchants offer a choice to customers. UK Providers WorldPay. Well established. Bureau and bank acquired. Relatively high transaction costs and annual costs. Fairly easy to integrate. Owned ultimately by Royal Bank of Scotland. SecPay. Bank Acquired. Low per transaction cost and low annual cost and flexible payment models. ProtX. Bank Acquired. Low per transaction cost and low annual cost, flexible payment models. Can be quite demanding to integrate. HSBC. Bank Acquired. Low per transaction cost. High set up and annual costs. Very inflexible to integrate. SecureTrading. Bureau and Bank Acquired. Low per transaction cost but high setup and annual costs. Was a doddle to integrate last time I used it (9 years ago!) NetBanx. Bureau and Bank Acquired. Haven't used since 1996 so can't comment! And of course PayPal, Google Checkout and Amazon FPS are well worth looking at and worth a whole answer on their own! Summary Told you it wasn't that simple! Usually, as developers, we're not in the position to choose for ourselves, and these decisions should be driven by the business needs of our employer / client. Most e-commerce projects would start with PayPal or similar. When the business gets enough orders that they could save money by switching to another service, then they've got enough money to pay for the switch. Disclaimer: I am UK based, and have performed many integrations with a whole slew of these services over the years, however the market changes all the time and things may have changed and your mileage may vary! I am not a lawyer or accountant, and if you take my advice it's not my fault:)
[ "payment" ]
93
98
25,647
13
0
2008-08-05T16:41:50.413000
2008-09-19T09:37:18.453000
2,563
2,801
What is a good web-based Grid that accepts Excel clipboard data?
Any good recommendations for a platform agnostic (i.e. Javascript) grid control/plugin that will accept pasted Excel data and can emit Excel-compliant clipboard data during a Copy? I believe Excel data is formatted as CSV during "normal" clipboard operations. dhtmlxGrid looks promising, but the online demo's don't actually copy contents to my clipboard!
I'm currently using dhtmlxGrid and we have the Excel copy/paste functionality working. dhtmlXGrid is the most full featured javascript grid package that I've found. On their website, dhtmlXGrid claims to support Clipboard functionality in the Professional version. (However, I noticed the Sample on their site isn't working on my Firefox. EDIT: It's probably the permissions issue that Nathan mentioned.) In any case, we had to do some extra work to get the exact Excel copy and paste functionality we wanted. We essentially had to override some of their functionality to get the desired behavior. Their support was pretty good in helping us come up with a solution. So to answer your question, you should be able to get them to support copy and paste if you purchase the Professional version. I'm just warning you that it may take some additional work to fine tune that behavior. Overall, I'm happy with dhtmlXGrid. We use a lot of their features. Their support is pretty good. They usually take one day to respond since they are in Europe (I think). And Javascript is by its very nature open source so I can always dive in when I need to.
What is a good web-based Grid that accepts Excel clipboard data? Any good recommendations for a platform agnostic (i.e. Javascript) grid control/plugin that will accept pasted Excel data and can emit Excel-compliant clipboard data during a Copy? I believe Excel data is formatted as CSV during "normal" clipboard operations. dhtmlxGrid looks promising, but the online demo's don't actually copy contents to my clipboard!
TITLE: What is a good web-based Grid that accepts Excel clipboard data? QUESTION: Any good recommendations for a platform agnostic (i.e. Javascript) grid control/plugin that will accept pasted Excel data and can emit Excel-compliant clipboard data during a Copy? I believe Excel data is formatted as CSV during "normal" clipboard operations. dhtmlxGrid looks promising, but the online demo's don't actually copy contents to my clipboard! ANSWER: I'm currently using dhtmlxGrid and we have the Excel copy/paste functionality working. dhtmlXGrid is the most full featured javascript grid package that I've found. On their website, dhtmlXGrid claims to support Clipboard functionality in the Professional version. (However, I noticed the Sample on their site isn't working on my Firefox. EDIT: It's probably the permissions issue that Nathan mentioned.) In any case, we had to do some extra work to get the exact Excel copy and paste functionality we wanted. We essentially had to override some of their functionality to get the desired behavior. Their support was pretty good in helping us come up with a solution. So to answer your question, you should be able to get them to support copy and paste if you purchase the Professional version. I'm just warning you that it may take some additional work to fine tune that behavior. Overall, I'm happy with dhtmlXGrid. We use a lot of their features. Their support is pretty good. They usually take one day to respond since they are in Europe (I think). And Javascript is by its very nature open source so I can always dive in when I need to.
[ "excel", "csv", "grid", "clipboard" ]
8
3
3,223
5
0
2008-08-05T16:47:28.873000
2008-08-05T20:27:23.810000
2,588
1,780,172
Appropriate Windows O/S pagefile size for SQL Server
Does any know a good rule of thumb for the appropriate pagefile size for a Windows 2003 server running SQL Server?
Irrelevant of the size of the RAM, you still need a pagefile at least 1.5 times the amount of physical RAM. This is true even if you have a 1 TB RAM machine, you'll need 1.5 TB pagefile on disk (sounds crazy, but is true). When a process asks MEM_COMMIT memory via VirtualAlloc/VirtualAllocEx, the requested size needs to be reserved in the pagefile. This was true in the first Win NT system, and is still true today see Managing Virtual Memory in Win32: When memory is committed, physical pages of memory are allocated and space is reserved in a pagefile. Bare some extreme odd cases, SQL Server will always ask for MEM_COMMIT pages. And given the fact that SQL uses a Dynamic Memory Management policy that reserves upfront as much buffer pool as possible (reserves and commits in terms of VAS), SQL Server will request at start up a huge reservation of space in the pagefile. If the pagefile is not properly sized errors 801/802 will start showing up in SQL's ERRORLOG file and operations. This always causes some confusion, as administrators erroneously assume that a large RAM eliminates the need for a pagefile. In truth the contrary happens, a large RAM increases the need for pagefile, just because of the inner workings of the Windows NT memory manager. The reserved pagefile is, hopefully, never used.
Appropriate Windows O/S pagefile size for SQL Server Does any know a good rule of thumb for the appropriate pagefile size for a Windows 2003 server running SQL Server?
TITLE: Appropriate Windows O/S pagefile size for SQL Server QUESTION: Does any know a good rule of thumb for the appropriate pagefile size for a Windows 2003 server running SQL Server? ANSWER: Irrelevant of the size of the RAM, you still need a pagefile at least 1.5 times the amount of physical RAM. This is true even if you have a 1 TB RAM machine, you'll need 1.5 TB pagefile on disk (sounds crazy, but is true). When a process asks MEM_COMMIT memory via VirtualAlloc/VirtualAllocEx, the requested size needs to be reserved in the pagefile. This was true in the first Win NT system, and is still true today see Managing Virtual Memory in Win32: When memory is committed, physical pages of memory are allocated and space is reserved in a pagefile. Bare some extreme odd cases, SQL Server will always ask for MEM_COMMIT pages. And given the fact that SQL uses a Dynamic Memory Management policy that reserves upfront as much buffer pool as possible (reserves and commits in terms of VAS), SQL Server will request at start up a huge reservation of space in the pagefile. If the pagefile is not properly sized errors 801/802 will start showing up in SQL's ERRORLOG file and operations. This always causes some confusion, as administrators erroneously assume that a large RAM eliminates the need for a pagefile. In truth the contrary happens, a large RAM increases the need for pagefile, just because of the inner workings of the Windows NT memory manager. The reserved pagefile is, hopefully, never used.
[ "sql-server", "windows" ]
19
13
35,600
8
0
2008-08-05T17:07:16.773000
2009-11-22T22:11:18.923000
2,630
64,636
What are your favorite Powershell Cmdlets?
I just found /n softwares free Powershell NetCmdlets, and after playing with them I love the functionality they bring to the command line. So it raises the question what are your favorite Cmdlets, and how do you use them?
As a programmer/hacker, Get-Member and Get-Command are the ones I use more than any others, but the ones I use to show off are Select-Control and Send-Keys from WASP, the PowerGadgets, and some of my own stuff written in WPF against CTP2 or PoshConsole;-)
What are your favorite Powershell Cmdlets? I just found /n softwares free Powershell NetCmdlets, and after playing with them I love the functionality they bring to the command line. So it raises the question what are your favorite Cmdlets, and how do you use them?
TITLE: What are your favorite Powershell Cmdlets? QUESTION: I just found /n softwares free Powershell NetCmdlets, and after playing with them I love the functionality they bring to the command line. So it raises the question what are your favorite Cmdlets, and how do you use them? ANSWER: As a programmer/hacker, Get-Member and Get-Command are the ones I use more than any others, but the ones I use to show off are Select-Control and Send-Keys from WASP, the PowerGadgets, and some of my own stuff written in WPF against CTP2 or PoshConsole;-)
[ "powershell", "powershell-cmdlet" ]
15
8
2,496
13
0
2008-08-05T18:01:32.547000
2008-09-15T16:51:56.900000
2,639
2,712
What are some web-based knowledge-base solutions?
I've used a WordPress blog and a Screwturn Wiki (at two separate jobs) to store private, company-specific KB info, but I'm looking for something that was created to be a knowledge base. Specifically, I'd like to see: Free/low cost Simple method for users to subscribe to KB (or just sections) to get updates Ability to do page versioning/audit changes Limit access to certain pages for certain users Very simple method of posting/editing articles Very simple method of adding images to articles Excellent (fast, accurate) searching abilities Ability to rate and comment on articles I liked using the Wordpress blog because it allowed me to use Live Writer to add/edit articles and images, but it didn't have page versioning (that I could see). I like using Screwturn wiki because of it's ability to track article versions, and I like it's clean look, but some non-technical people balk at the input and editing.
I second Luke's answer. I can Recommend Confluence and here is why: I tested extensively many commercial and free Wiki based solutions. Not a single one is a winner on all accounts, including confluence. Let me try to make your quest a little shorter by summarizing what I have learned to be a pain and what is important: WYSIWYG is a most have feature for the Enterprise. A wiki without it, skip it Saying that, in reality, WYSIWYG doesn't work perfectly. It is more of a feature you must have to get the casual users not be afraid of the monster, and start using it. But you and anyone that wants to seriously create content, will very quickly get used to the wiki markup. it is faster and more reliable. You need good permissions controls (who can see, edit etc' a page). confluence has good, but I have my complaints (to complicated to be put here) You will want a good export feature. Most will give you a single page "PDF" export, but you need much more. For example, lets say you have an FAQ, you want to export the entire FAQ right? will that work? Macros: you want a community creating macros. You asked for example about the ability to rate pages, here is a link to a Macro for Confluence that lets you do that Structure: you want to be able to say that a page is a child of a different page, and be able to browse the data. The wikipedia model, of orphaned pages with no sturcture will not work in the Enterprise. (think FAQ, you want to have a hierarchy no?) Ability to easily attache picture to be embedded in the body of the page/article. In confluence, you need to upload the image and then can embed it, it could be a little better (CTR+V) but I guess this is easy enough for 80% of the users. At the end of the day, remember that a Wiki will be valuable to you the more flexible it is. It needs to be a "blank" canvas, and your imagination is then used to "build" the application. In Confluence, I found 3 different "best practices" on how to create a FAQ. That means I can implement MANY things. Some examples (I use my Wiki for) FAQ: any error, problem is logged. Used by PS and ENG. reduced internal support time dramatically Track account status: I implemetned sophisticated "dashboard" that you can see at a glance which customer is at what state, the software version they have, who in the company 'owns" the custoemr etc' Product: all documentation, installation instructions, the "what's new" etc Technical documentation, DB structure and what the tables mean HR: contact list, Document repository My runner up (15 month ago) was free Deki_Wiki, time has passed, so I don't know if this would be still my runner up. good luck!
What are some web-based knowledge-base solutions? I've used a WordPress blog and a Screwturn Wiki (at two separate jobs) to store private, company-specific KB info, but I'm looking for something that was created to be a knowledge base. Specifically, I'd like to see: Free/low cost Simple method for users to subscribe to KB (or just sections) to get updates Ability to do page versioning/audit changes Limit access to certain pages for certain users Very simple method of posting/editing articles Very simple method of adding images to articles Excellent (fast, accurate) searching abilities Ability to rate and comment on articles I liked using the Wordpress blog because it allowed me to use Live Writer to add/edit articles and images, but it didn't have page versioning (that I could see). I like using Screwturn wiki because of it's ability to track article versions, and I like it's clean look, but some non-technical people balk at the input and editing.
TITLE: What are some web-based knowledge-base solutions? QUESTION: I've used a WordPress blog and a Screwturn Wiki (at two separate jobs) to store private, company-specific KB info, but I'm looking for something that was created to be a knowledge base. Specifically, I'd like to see: Free/low cost Simple method for users to subscribe to KB (or just sections) to get updates Ability to do page versioning/audit changes Limit access to certain pages for certain users Very simple method of posting/editing articles Very simple method of adding images to articles Excellent (fast, accurate) searching abilities Ability to rate and comment on articles I liked using the Wordpress blog because it allowed me to use Live Writer to add/edit articles and images, but it didn't have page versioning (that I could see). I like using Screwturn wiki because of it's ability to track article versions, and I like it's clean look, but some non-technical people balk at the input and editing. ANSWER: I second Luke's answer. I can Recommend Confluence and here is why: I tested extensively many commercial and free Wiki based solutions. Not a single one is a winner on all accounts, including confluence. Let me try to make your quest a little shorter by summarizing what I have learned to be a pain and what is important: WYSIWYG is a most have feature for the Enterprise. A wiki without it, skip it Saying that, in reality, WYSIWYG doesn't work perfectly. It is more of a feature you must have to get the casual users not be afraid of the monster, and start using it. But you and anyone that wants to seriously create content, will very quickly get used to the wiki markup. it is faster and more reliable. You need good permissions controls (who can see, edit etc' a page). confluence has good, but I have my complaints (to complicated to be put here) You will want a good export feature. Most will give you a single page "PDF" export, but you need much more. For example, lets say you have an FAQ, you want to export the entire FAQ right? will that work? Macros: you want a community creating macros. You asked for example about the ability to rate pages, here is a link to a Macro for Confluence that lets you do that Structure: you want to be able to say that a page is a child of a different page, and be able to browse the data. The wikipedia model, of orphaned pages with no sturcture will not work in the Enterprise. (think FAQ, you want to have a hierarchy no?) Ability to easily attache picture to be embedded in the body of the page/article. In confluence, you need to upload the image and then can embed it, it could be a little better (CTR+V) but I guess this is easy enough for 80% of the users. At the end of the day, remember that a Wiki will be valuable to you the more flexible it is. It needs to be a "blank" canvas, and your imagination is then used to "build" the application. In Confluence, I found 3 different "best practices" on how to create a FAQ. That means I can implement MANY things. Some examples (I use my Wiki for) FAQ: any error, problem is logged. Used by PS and ENG. reduced internal support time dramatically Track account status: I implemetned sophisticated "dashboard" that you can see at a glance which customer is at what state, the software version they have, who in the company 'owns" the custoemr etc' Product: all documentation, installation instructions, the "what's new" etc Technical documentation, DB structure and what the tables mean HR: contact list, Document repository My runner up (15 month ago) was free Deki_Wiki, time has passed, so I don't know if this would be still my runner up. good luck!
[ "language-agnostic" ]
12
10
5,178
6
0
2008-08-05T18:07:26.213000
2008-08-05T19:09:08.213000
2,647
2,657
How do I split a delimited string so I can access individual items?
Using SQL Server, how do I split a string so I can access item x? Take a string "Hello John Smith". How can I split the string by space and access the item at index 1 which should return "John"?
You may find the solution in SQL User Defined Function to Parse a Delimited String helpful (from The Code Project ). You can use this simple logic: Declare @products varchar(200) = '1|20|3|343|44|6|8765' Declare @individual varchar(20) = null WHILE LEN(@products) > 0 BEGIN IF PATINDEX('%|%', @products) > 0 BEGIN SET @individual = SUBSTRING(@products, 0, PATINDEX('%|%', @products)) SELECT @individual SET @products = SUBSTRING(@products, LEN(@individual + '|') + 1, LEN(@products)) END ELSE BEGIN SET @individual = @products SET @products = NULL SELECT @individual END END
How do I split a delimited string so I can access individual items? Using SQL Server, how do I split a string so I can access item x? Take a string "Hello John Smith". How can I split the string by space and access the item at index 1 which should return "John"?
TITLE: How do I split a delimited string so I can access individual items? QUESTION: Using SQL Server, how do I split a string so I can access item x? Take a string "Hello John Smith". How can I split the string by space and access the item at index 1 which should return "John"? ANSWER: You may find the solution in SQL User Defined Function to Parse a Delimited String helpful (from The Code Project ). You can use this simple logic: Declare @products varchar(200) = '1|20|3|343|44|6|8765' Declare @individual varchar(20) = null WHILE LEN(@products) > 0 BEGIN IF PATINDEX('%|%', @products) > 0 BEGIN SET @individual = SUBSTRING(@products, 0, PATINDEX('%|%', @products)) SELECT @individual SET @products = SUBSTRING(@products, LEN(@individual + '|') + 1, LEN(@products)) END ELSE BEGIN SET @individual = @products SET @products = NULL SELECT @individual END END
[ "sql", "sql-server", "t-sql", "split" ]
533
194
952,236
46
0
2008-08-05T18:15:47.727000
2008-08-05T18:28:38.653000
2,649
2,653
What's the best way to determine if a temporary table exists in SQL Server?
When writing a T-SQL script that I plan on re-running, often times I use temporary tables to store temporary data. Since the temp table is created on the fly, I'd like to be able to drop that table only if it exists (before I create it). I'll post the method that I use, but I'd like to see if there is a better way.
IF Object_Id('TempDB..#TempTable') IS NOT NULL BEGIN DROP TABLE #TempTable END
What's the best way to determine if a temporary table exists in SQL Server? When writing a T-SQL script that I plan on re-running, often times I use temporary tables to store temporary data. Since the temp table is created on the fly, I'd like to be able to drop that table only if it exists (before I create it). I'll post the method that I use, but I'd like to see if there is a better way.
TITLE: What's the best way to determine if a temporary table exists in SQL Server? QUESTION: When writing a T-SQL script that I plan on re-running, often times I use temporary tables to store temporary data. Since the temp table is created on the fly, I'd like to be able to drop that table only if it exists (before I create it). I'll post the method that I use, but I'd like to see if there is a better way. ANSWER: IF Object_Id('TempDB..#TempTable') IS NOT NULL BEGIN DROP TABLE #TempTable END
[ "sql-server" ]
22
30
4,187
4
0
2008-08-05T18:18:39.373000
2008-08-05T18:21:38.730000
2,658
2,668
Getting started with Version Control System
I need to implement version control, even for just the developing I do at home. I have read about how great subversion is for the past couple of years and was about to dedicate myself to learning this on the side until I heard about Git being the up and coming version control system. Given the situation, should I hold off and see which one comes out on top? What are their relative advantages? One issue I noticed with Git is, there are not many full featured GUIs, which is important to many users on my team. Also, wouldn't mind suggestions on how to get started with one or the other. (tutorials, etc.)
The most important thing about version control is: JUST START USING IT Not using version control is a horrible idea. If you are not using version control, stop reading right now and start using it. It is very easy to convert from cvs<->svn<->git<->hg It doesn't matter which one you choose. Just pick the easiest one for you to use and start recording the history of your code. You can always migrate to another (D)VCS later. If you are looking for a easy to use GUI look at TortoiseSVN (Windows) and Versions (Mac) (Suggested by codingwithoutcomments ) Edit: pix0r said: Git has some nice features, but you won't be able to appreciate them unless you've already used something more standard like CVS or Subversion. This. Using git is pointless if you don't know what version control can do for you. Edit 2: Just saw this link on reddit: Subversion Cheat Sheet. Good quick reference for the svn command line.
Getting started with Version Control System I need to implement version control, even for just the developing I do at home. I have read about how great subversion is for the past couple of years and was about to dedicate myself to learning this on the side until I heard about Git being the up and coming version control system. Given the situation, should I hold off and see which one comes out on top? What are their relative advantages? One issue I noticed with Git is, there are not many full featured GUIs, which is important to many users on my team. Also, wouldn't mind suggestions on how to get started with one or the other. (tutorials, etc.)
TITLE: Getting started with Version Control System QUESTION: I need to implement version control, even for just the developing I do at home. I have read about how great subversion is for the past couple of years and was about to dedicate myself to learning this on the side until I heard about Git being the up and coming version control system. Given the situation, should I hold off and see which one comes out on top? What are their relative advantages? One issue I noticed with Git is, there are not many full featured GUIs, which is important to many users on my team. Also, wouldn't mind suggestions on how to get started with one or the other. (tutorials, etc.) ANSWER: The most important thing about version control is: JUST START USING IT Not using version control is a horrible idea. If you are not using version control, stop reading right now and start using it. It is very easy to convert from cvs<->svn<->git<->hg It doesn't matter which one you choose. Just pick the easiest one for you to use and start recording the history of your code. You can always migrate to another (D)VCS later. If you are looking for a easy to use GUI look at TortoiseSVN (Windows) and Versions (Mac) (Suggested by codingwithoutcomments ) Edit: pix0r said: Git has some nice features, but you won't be able to appreciate them unless you've already used something more standard like CVS or Subversion. This. Using git is pointless if you don't know what version control can do for you. Edit 2: Just saw this link on reddit: Subversion Cheat Sheet. Good quick reference for the svn command line.
[ "git", "svn", "version-control", "language-agnostic", "dvcs" ]
76
82
9,667
34
0
2008-08-05T18:29:14.283000
2008-08-05T18:34:44.350000
2,688
2,741
What do I need to escape when sending a query?
When you execute a SQL query, you have to clean your strings or users can execute malicious SQL on your website. I usually just have a function escape_string(blah), which: Replaces escapes ( \ ) with double escapes ( \\ ). Replaces single quotes ( ' ) with an escaped single quote ( \' ). Is this adequate? Is there a hole in my code? Is there a library which can do this quickly and reliably for me? I'd like to see graceful solutions in Perl, Java, and PHP.
For maximum security, performance, and correctness use prepared statements. Here's how to do this with lots of examples in different languages, including PHP: https://stackoverflow.com/questions/1973/what-is-the-best-way-to-avoid-sql-injection-attacks
What do I need to escape when sending a query? When you execute a SQL query, you have to clean your strings or users can execute malicious SQL on your website. I usually just have a function escape_string(blah), which: Replaces escapes ( \ ) with double escapes ( \\ ). Replaces single quotes ( ' ) with an escaped single quote ( \' ). Is this adequate? Is there a hole in my code? Is there a library which can do this quickly and reliably for me? I'd like to see graceful solutions in Perl, Java, and PHP.
TITLE: What do I need to escape when sending a query? QUESTION: When you execute a SQL query, you have to clean your strings or users can execute malicious SQL on your website. I usually just have a function escape_string(blah), which: Replaces escapes ( \ ) with double escapes ( \\ ). Replaces single quotes ( ' ) with an escaped single quote ( \' ). Is this adequate? Is there a hole in my code? Is there a library which can do this quickly and reliably for me? I'd like to see graceful solutions in Perl, Java, and PHP. ANSWER: For maximum security, performance, and correctness use prepared statements. Here's how to do this with lots of examples in different languages, including PHP: https://stackoverflow.com/questions/1973/what-is-the-best-way-to-avoid-sql-injection-attacks
[ "mysql", "oracle", "security" ]
21
8
3,591
11
0
2008-08-05T18:45:46.747000
2008-08-05T19:38:51.023000
2,702
2,736
How do I use T-SQL Group By
I know I need to have (although I don't know why) a GROUP BY clause on the end of a SQL query that uses any aggregate functions like count, sum, avg, etc: SELECT count(userID), userName FROM users GROUP BY userName When else would GROUP BY be useful, and what are the performance ramifications?
To retrieve the number of widgets from each widget category that has more than 5 widgets, you could do this: SELECT WidgetCategory, count(*) FROM Widgets GROUP BY WidgetCategory HAVING count(*) > 5 The "having" clause is something people often forget about, instead opting to retrieve all their data to the client and iterating through it there.
How do I use T-SQL Group By I know I need to have (although I don't know why) a GROUP BY clause on the end of a SQL query that uses any aggregate functions like count, sum, avg, etc: SELECT count(userID), userName FROM users GROUP BY userName When else would GROUP BY be useful, and what are the performance ramifications?
TITLE: How do I use T-SQL Group By QUESTION: I know I need to have (although I don't know why) a GROUP BY clause on the end of a SQL query that uses any aggregate functions like count, sum, avg, etc: SELECT count(userID), userName FROM users GROUP BY userName When else would GROUP BY be useful, and what are the performance ramifications? ANSWER: To retrieve the number of widgets from each widget category that has more than 5 widgets, you could do this: SELECT WidgetCategory, count(*) FROM Widgets GROUP BY WidgetCategory HAVING count(*) > 5 The "having" clause is something people often forget about, instead opting to retrieve all their data to the client and iterating through it there.
[ "sql", "sql-server", "group-by" ]
32
36
49,480
5
0
2008-08-05T18:55:35.963000
2008-08-05T19:32:03.360000
2,711
2,763
What sites offer free, quality web site design templates?
Let's aggregate a list of free quality web site design templates. There are a million of these sites out there, but most are repetitive and boring. I'll start with freeCSStemplates.org I also think other sites should follow some sort of standards, for example here are freeCSStemplates standards Released for FREE under the Creative Commons Attribution 2.5 license Very lightweight in terms of images Tables-free (ie. they use no tables for layout purposes) W3C standards compliant and valid (XHTML Strict) Provided with public domain photos, generously provided by PDPhoto.org and Wikimedia Commons
Check out: Open Source Web Designs CSS Remix Best Web Gallery CSS Based CSS Beauty CSS Genius
What sites offer free, quality web site design templates? Let's aggregate a list of free quality web site design templates. There are a million of these sites out there, but most are repetitive and boring. I'll start with freeCSStemplates.org I also think other sites should follow some sort of standards, for example here are freeCSStemplates standards Released for FREE under the Creative Commons Attribution 2.5 license Very lightweight in terms of images Tables-free (ie. they use no tables for layout purposes) W3C standards compliant and valid (XHTML Strict) Provided with public domain photos, generously provided by PDPhoto.org and Wikimedia Commons
TITLE: What sites offer free, quality web site design templates? QUESTION: Let's aggregate a list of free quality web site design templates. There are a million of these sites out there, but most are repetitive and boring. I'll start with freeCSStemplates.org I also think other sites should follow some sort of standards, for example here are freeCSStemplates standards Released for FREE under the Creative Commons Attribution 2.5 license Very lightweight in terms of images Tables-free (ie. they use no tables for layout purposes) W3C standards compliant and valid (XHTML Strict) Provided with public domain photos, generously provided by PDPhoto.org and Wikimedia Commons ANSWER: Check out: Open Source Web Designs CSS Remix Best Web Gallery CSS Based CSS Beauty CSS Genius
[ "css", "templates" ]
26
12
7,351
5
0
2008-08-05T19:08:47.543000
2008-08-05T20:00:14.223000
2,714
2,715
I need to know how much disk space a table is using in SQL Server
I think most people know how to do this via the GUI (right click table, properties), but doing this in T-SQL totally rocks.
CREATE TABLE #tmpSizeChar ( table_name sysname, row_count int, reserved_size varchar(50), data_size varchar(50), index_size varchar(50), unused_size varchar(50)) CREATE TABLE #tmpSizeInt ( table_name sysname, row_count int, reserved_size_KB int, data_size_KB int, index_size_KB int, unused_size_KB int) SET NOCOUNT ON INSERT #tmpSizeChar EXEC sp_msforeachtable 'sp_spaceused ''?''' INSERT INTO #tmpSizeInt ( table_name, row_count, reserved_size_KB, data_size_KB, index_size_KB, unused_size_KB ) SELECT [table_name], row_count, CAST(SUBSTRING(reserved_size, 0, PATINDEX('% %', reserved_size)) AS int)reserved_size, CAST(SUBSTRING(data_size, 0, PATINDEX('% %', data_size)) AS int)data_size, CAST(SUBSTRING(index_size, 0, PATINDEX('% %', index_size)) AS int)index_size, CAST(SUBSTRING(unused_size, 0, PATINDEX('% %', unused_size)) AS int)unused_size FROM #tmpSizeChar /* DROP TABLE #tmpSizeChar DROP TABLE #tmpSizeInt */ SELECT * FROM #tmpSizeInt ORDER BY reserved_size_KB DESC
I need to know how much disk space a table is using in SQL Server I think most people know how to do this via the GUI (right click table, properties), but doing this in T-SQL totally rocks.
TITLE: I need to know how much disk space a table is using in SQL Server QUESTION: I think most people know how to do this via the GUI (right click table, properties), but doing this in T-SQL totally rocks. ANSWER: CREATE TABLE #tmpSizeChar ( table_name sysname, row_count int, reserved_size varchar(50), data_size varchar(50), index_size varchar(50), unused_size varchar(50)) CREATE TABLE #tmpSizeInt ( table_name sysname, row_count int, reserved_size_KB int, data_size_KB int, index_size_KB int, unused_size_KB int) SET NOCOUNT ON INSERT #tmpSizeChar EXEC sp_msforeachtable 'sp_spaceused ''?''' INSERT INTO #tmpSizeInt ( table_name, row_count, reserved_size_KB, data_size_KB, index_size_KB, unused_size_KB ) SELECT [table_name], row_count, CAST(SUBSTRING(reserved_size, 0, PATINDEX('% %', reserved_size)) AS int)reserved_size, CAST(SUBSTRING(data_size, 0, PATINDEX('% %', data_size)) AS int)data_size, CAST(SUBSTRING(index_size, 0, PATINDEX('% %', index_size)) AS int)index_size, CAST(SUBSTRING(unused_size, 0, PATINDEX('% %', unused_size)) AS int)unused_size FROM #tmpSizeChar /* DROP TABLE #tmpSizeChar DROP TABLE #tmpSizeInt */ SELECT * FROM #tmpSizeInt ORDER BY reserved_size_KB DESC
[ "sql-server" ]
15
14
4,187
3
0
2008-08-05T19:10:52.327000
2008-08-05T19:11:11.453000
2,750
2,761
Data verifications in Getter/Setter or elsewhere?
I'm wondering if it's a good idea to make verifications in getters and setters, or elsewhere in the code. This might surprise you be when it comes to optimizations and speeding up the code, I think you should not make verifications in getters and setters, but in the code where you're updating your files or database. Am I wrong?
Well, one of the reasons why classes usually contain private members with public getters/setters is exactly because they can verify data. If you have a Number than can be between 1 and 100, i would definitely put something in the setter that validates that and then maybe throw an exception that is being caught by the code. The reason is simple: If you don't do it in the setter, you have to remember that 1 to 100 limitation every time you set it, which leads to duplicated code or when you forget it, it leads to an invalid state. As for performance, i'm with Knuth here: "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil."
Data verifications in Getter/Setter or elsewhere? I'm wondering if it's a good idea to make verifications in getters and setters, or elsewhere in the code. This might surprise you be when it comes to optimizations and speeding up the code, I think you should not make verifications in getters and setters, but in the code where you're updating your files or database. Am I wrong?
TITLE: Data verifications in Getter/Setter or elsewhere? QUESTION: I'm wondering if it's a good idea to make verifications in getters and setters, or elsewhere in the code. This might surprise you be when it comes to optimizations and speeding up the code, I think you should not make verifications in getters and setters, but in the code where you're updating your files or database. Am I wrong? ANSWER: Well, one of the reasons why classes usually contain private members with public getters/setters is exactly because they can verify data. If you have a Number than can be between 1 and 100, i would definitely put something in the setter that validates that and then maybe throw an exception that is being caught by the code. The reason is simple: If you don't do it in the setter, you have to remember that 1 to 100 limitation every time you set it, which leads to duplicated code or when you forget it, it leads to an invalid state. As for performance, i'm with Knuth here: "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil."
[ "optimization", "setter", "getter", "verification" ]
11
15
3,414
8
0
2008-08-05T19:51:29.220000
2008-08-05T19:59:39.157000
2,765
2,774
Is there a keyboard shortcut to view all open documents in Visual Studio 2008
I am trying to learn the keyboard shortcuts in Visual Studio in order to be more productive. So I downloaded a document showing many of the default keybindings in Visual Basic when using the VS 2008 IDE from Microsoft. When I tried what they say is the keyboard shortcut to view all open documents ( CTRL + ALT + DOWN ARROW ), I got a completely unexpected result on my XP machine; my entire screen display was flipped upside down! Was this a prank by someone at Microsoft? I can't imagine what practical value this flipping of the screen would have. Does anyone know what the correct keyboard shortcut is to view all open documents in VS 2008? Oh and if you try the above shortcut and it flips your display the way it did mine, do a CTRL + ALT + UP ARROW to switch it back.
This is a conflict between your graphics driver and Visual Studio. Go to your driver settings page (Control panel) and disable the display rotation shortcuts. With this conflict removed, the shortcut will work in Visual Studio.
Is there a keyboard shortcut to view all open documents in Visual Studio 2008 I am trying to learn the keyboard shortcuts in Visual Studio in order to be more productive. So I downloaded a document showing many of the default keybindings in Visual Basic when using the VS 2008 IDE from Microsoft. When I tried what they say is the keyboard shortcut to view all open documents ( CTRL + ALT + DOWN ARROW ), I got a completely unexpected result on my XP machine; my entire screen display was flipped upside down! Was this a prank by someone at Microsoft? I can't imagine what practical value this flipping of the screen would have. Does anyone know what the correct keyboard shortcut is to view all open documents in VS 2008? Oh and if you try the above shortcut and it flips your display the way it did mine, do a CTRL + ALT + UP ARROW to switch it back.
TITLE: Is there a keyboard shortcut to view all open documents in Visual Studio 2008 QUESTION: I am trying to learn the keyboard shortcuts in Visual Studio in order to be more productive. So I downloaded a document showing many of the default keybindings in Visual Basic when using the VS 2008 IDE from Microsoft. When I tried what they say is the keyboard shortcut to view all open documents ( CTRL + ALT + DOWN ARROW ), I got a completely unexpected result on my XP machine; my entire screen display was flipped upside down! Was this a prank by someone at Microsoft? I can't imagine what practical value this flipping of the screen would have. Does anyone know what the correct keyboard shortcut is to view all open documents in VS 2008? Oh and if you try the above shortcut and it flips your display the way it did mine, do a CTRL + ALT + UP ARROW to switch it back. ANSWER: This is a conflict between your graphics driver and Visual Studio. Go to your driver settings page (Control panel) and disable the display rotation shortcuts. With this conflict removed, the shortcut will work in Visual Studio.
[ "visual-studio", "keyboard", "shortcut" ]
9
15
765
1
0
2008-08-05T20:01:31.057000
2008-08-05T20:08:23.490000
2,767
75,338
Recommended add-ons/plugins for Microsoft Visual Studio
Can anyone recommend any good add-ons or plugins for Microsoft Visual Studio? Freebies are preferred, but if it is worth the cost then that's fine.
SmartPaster - (FREE) Copy/Paste code generator for strings AnkhSvn - (FREE) SVN Source Control Integration for VS.NET VisualSVN Server - (FREE) Source Control ReSharper - IDE enhancement that helps with refactoring and productivity CodeRush - Code gen macros on steroids Refactor - Code refactoring aid CodeMaid (FREE) - Code cleanup, organization and complexity analysis CodeSmith - Code Generator GhostDoc - (FREE) Simple code commenting tool DXCore (FREE) and its many awesome plugins: DxCore Community Plugins, CR_Documentor, CodeStyleEnforcer, RedGreen TestDriven.Net - (FREE/PAY) Unit Testing Aid Reflector - (PAY) Feature rich.Net Disassembler Reflector AddIn's Web Deployment Projects - Provides additional functionality to build and deploy Web sites and Web applications ( source ). StudioTools - (FREE) Navigation assistant, code metrics tool, incremental search, file explorer in visual studio and tear off editor windows. Moved from old site (archive.org) to new site and discontinued.
Recommended add-ons/plugins for Microsoft Visual Studio Can anyone recommend any good add-ons or plugins for Microsoft Visual Studio? Freebies are preferred, but if it is worth the cost then that's fine.
TITLE: Recommended add-ons/plugins for Microsoft Visual Studio QUESTION: Can anyone recommend any good add-ons or plugins for Microsoft Visual Studio? Freebies are preferred, but if it is worth the cost then that's fine. ANSWER: SmartPaster - (FREE) Copy/Paste code generator for strings AnkhSvn - (FREE) SVN Source Control Integration for VS.NET VisualSVN Server - (FREE) Source Control ReSharper - IDE enhancement that helps with refactoring and productivity CodeRush - Code gen macros on steroids Refactor - Code refactoring aid CodeMaid (FREE) - Code cleanup, organization and complexity analysis CodeSmith - Code Generator GhostDoc - (FREE) Simple code commenting tool DXCore (FREE) and its many awesome plugins: DxCore Community Plugins, CR_Documentor, CodeStyleEnforcer, RedGreen TestDriven.Net - (FREE/PAY) Unit Testing Aid Reflector - (PAY) Feature rich.Net Disassembler Reflector AddIn's Web Deployment Projects - Provides additional functionality to build and deploy Web sites and Web applications ( source ). StudioTools - (FREE) Navigation assistant, code metrics tool, incremental search, file explorer in visual studio and tear off editor windows. Moved from old site (archive.org) to new site and discontinued.
[ "visual-studio", "plugins", "add-on" ]
211
139
137,589
77
0
2008-08-05T20:02:33.033000
2008-09-16T18:17:49.600000
2,770
2,779
Global Exception Handling for winforms control
When working on ASP.NET 1.1 projects I always used the Global.asax to catch all errors. I'm looking for a similar way to catch all exceptions in a Windows Forms user control, which ends up being a hosted IE control. What is the proper way to go about doing something like this?
You need to handle the System.Windows.Forms.Application.ThreadException event for Windows Forms. This article really helped me: http://bytes.com/forum/thread236199.html.
Global Exception Handling for winforms control When working on ASP.NET 1.1 projects I always used the Global.asax to catch all errors. I'm looking for a similar way to catch all exceptions in a Windows Forms user control, which ends up being a hosted IE control. What is the proper way to go about doing something like this?
TITLE: Global Exception Handling for winforms control QUESTION: When working on ASP.NET 1.1 projects I always used the Global.asax to catch all errors. I'm looking for a similar way to catch all exceptions in a Windows Forms user control, which ends up being a hosted IE control. What is the proper way to go about doing something like this? ANSWER: You need to handle the System.Windows.Forms.Application.ThreadException event for Windows Forms. This article really helped me: http://bytes.com/forum/thread236199.html.
[ "winforms", "error-handling", "user-controls" ]
35
25
16,712
5
0
2008-08-05T20:05:22.077000
2008-08-05T20:11:45.340000
2,773
2,883
Can't get a Console to VMs
I've followed this otherwise excellent tutorial on getting Xen working with Ubuntu but am not able to get a console into my virtual machine (domU). I've got the extra = '2 console=xvc0' line in my /etc/xen/ hostname_here.cfg file like they say, but am not able to get a console on it. If I statically assign an IP to the VM I can SSH to it, but for now I need to be able to use DHCP to give it an address (and since that's what I'm trying to debug, there's the problem). I know I've got a free DHCP address (although I'm getting more at the moment), so I don't think that's the problem. I've looked on Google and the Xen forums to no avail as well. Any ideas?
I had followed a different tutorial on setting up my xen on ubuntu before 8.04 but now upgraded to 8.04. I used the extra line in my cfg as folows: extra = ' TERM=xterm xencons=tty console=tty1' It allows me to "xm console hostname" from dom0. I think this was from a problem with the xen setup in the version prior to 8.04 (I'm not sure which version that was). I'm not sure if the same change is necessary in 8.04 as I'm an upgrade and didn't change any of my domU configs after the upgrade.
Can't get a Console to VMs I've followed this otherwise excellent tutorial on getting Xen working with Ubuntu but am not able to get a console into my virtual machine (domU). I've got the extra = '2 console=xvc0' line in my /etc/xen/ hostname_here.cfg file like they say, but am not able to get a console on it. If I statically assign an IP to the VM I can SSH to it, but for now I need to be able to use DHCP to give it an address (and since that's what I'm trying to debug, there's the problem). I know I've got a free DHCP address (although I'm getting more at the moment), so I don't think that's the problem. I've looked on Google and the Xen forums to no avail as well. Any ideas?
TITLE: Can't get a Console to VMs QUESTION: I've followed this otherwise excellent tutorial on getting Xen working with Ubuntu but am not able to get a console into my virtual machine (domU). I've got the extra = '2 console=xvc0' line in my /etc/xen/ hostname_here.cfg file like they say, but am not able to get a console on it. If I statically assign an IP to the VM I can SSH to it, but for now I need to be able to use DHCP to give it an address (and since that's what I'm trying to debug, there's the problem). I know I've got a free DHCP address (although I'm getting more at the moment), so I don't think that's the problem. I've looked on Google and the Xen forums to no avail as well. Any ideas? ANSWER: I had followed a different tutorial on setting up my xen on ubuntu before 8.04 but now upgraded to 8.04. I used the extra line in my cfg as folows: extra = ' TERM=xterm xencons=tty console=tty1' It allows me to "xm console hostname" from dom0. I think this was from a problem with the xen setup in the version prior to 8.04 (I'm not sure which version that was). I'm not sure if the same change is necessary in 8.04 as I'm an upgrade and didn't change any of my domU configs after the upgrade.
[ "ubuntu", "virtualization", "xen" ]
7
5
2,545
1
0
2008-08-05T20:06:18.673000
2008-08-05T21:27:45.763000
2,775
3,696,991
How to remove the time portion of a datetime value (SQL Server)?
Here's what I use: SELECT CAST(FLOOR(CAST(getdate() as FLOAT)) as DATETIME) I'm thinking there may be a better and more elegant way. Requirements: It has to be as fast as possible (the less casting, the better). The final result has to be a datetime type, not a string.
SQL Server 2008 and up In SQL Server 2008 and up, of course the fastest way is Convert(date, @date). This can be cast back to a datetime or datetime2 if necessary. What Is Really Best In SQL Server 2005 and Older? I've seen inconsistent claims about what's fastest for truncating the time from a date in SQL Server, and some people even said they did testing, but my experience has been different. So let's do some more stringent testing and let everyone have the script so if I make any mistakes people can correct me. Float Conversions Are Not Accurate First, I would stay away from converting datetime to float, because it does not convert correctly. You may get away with doing the time-removal thing accurately, but I think it's a bad idea to use it because it implicitly communicates to developers that this is a safe operation and it is not. Take a look: declare @d datetime; set @d = '2010-09-12 00:00:00.003'; select Convert(datetime, Convert(float, @d)); -- result: 2010-09-12 00:00:00.000 -- oops This is not something we should be teaching people in our code or in our examples online. Also, it is not even the fastest way! Proof – Performance Testing If you want to perform some tests yourself to see how the different methods really do stack up, then you'll need this setup script to run the tests farther down: create table AllDay (Tm datetime NOT NULL CONSTRAINT PK_AllDay PRIMARY KEY CLUSTERED); declare @d datetime; set @d = DateDiff(Day, 0, GetDate()); insert AllDay select @d; while @@ROWCOUNT!= 0 insert AllDay select * from ( select Tm = DateAdd(ms, (select Max(DateDiff(ms, @d, Tm)) from AllDay) + 3, Tm) from AllDay ) X where Tm < DateAdd(Day, 1, @d); exec sp_spaceused AllDay; -- 25,920,000 rows Please note that this creates a 427.57 MB table in your database and will take something like 15-30 minutes to run. If your database is small and set to 10% growth it will take longer than if you size big enough first. Now for the actual performance testing script. Please note that it's purposeful to not return rows back to the client as this is crazy expensive on 26 million rows and would hide the performance differences between the methods. Performance Results set statistics time on; -- (All queries are the same on io: logical reads 54712) GO declare @dd date, @d datetime, @di int, @df float, @dv varchar(10); -- Round trip back to datetime select @d = CONVERT(date, Tm) from AllDay; -- CPU time = 21234 ms, elapsed time = 22301 ms. select @d = CAST(Tm - 0.50000004 AS int) from AllDay; -- CPU = 23031 ms, elapsed = 24091 ms. select @d = DATEDIFF(DAY, 0, Tm) from AllDay; -- CPU = 23782 ms, elapsed = 24818 ms. select @d = FLOOR(CAST(Tm as float)) from AllDay; -- CPU = 36891 ms, elapsed = 38414 ms. select @d = CONVERT(VARCHAR(8), Tm, 112) from AllDay; -- CPU = 102984 ms, elapsed = 109897 ms. select @d = CONVERT(CHAR(8), Tm, 112) from AllDay; -- CPU = 103390 ms, elapsed = 108236 ms. select @d = CONVERT(VARCHAR(10), Tm, 101) from AllDay; -- CPU = 123375 ms, elapsed = 135179 ms. -- Only to another type but not back select @dd = Tm from AllDay; -- CPU time = 19891 ms, elapsed time = 20937 ms. select @di = CAST(Tm - 0.50000004 AS int) from AllDay; -- CPU = 21453 ms, elapsed = 23079 ms. select @di = DATEDIFF(DAY, 0, Tm) from AllDay; -- CPU = 23218 ms, elapsed = 24700 ms select @df = FLOOR(CAST(Tm as float)) from AllDay; -- CPU = 29312 ms, elapsed = 31101 ms. select @dv = CONVERT(VARCHAR(8), Tm, 112) from AllDay; -- CPU = 64016 ms, elapsed = 67815 ms. select @dv = CONVERT(CHAR(8), Tm, 112) from AllDay; -- CPU = 64297 ms, elapsed = 67987 ms. select @dv = CONVERT(VARCHAR(10), Tm, 101) from AllDay; -- CPU = 65609 ms, elapsed = 68173 ms. GO set statistics time off; Some Rambling Analysis Some notes about this. First of all, if just performing a GROUP BY or a comparison, there's no need to convert back to datetime. So you can save some CPU by avoiding that, unless you need the final value for display purposes. You can even GROUP BY the unconverted value and put the conversion only in the SELECT clause: select Convert(datetime, DateDiff(dd, 0, Tm)) from (select '2010-09-12 00:00:00.003') X (Tm) group by DateDiff(dd, 0, Tm) Also, see how the numeric conversions only take slightly more time to convert back to datetime, but the varchar conversion almost doubles? This reveals the portion of the CPU that is devoted to date calculation in the queries. There are parts of the CPU usage that don't involve date calculation, and this appears to be something close to 19875 ms in the above queries. Then the conversion takes some additional amount, so if there are two conversions, that amount is used up approximately twice. More examination reveals that compared to Convert(, 112), the Convert(, 101) query has some additional CPU expense (since it uses a longer varchar?), because the second conversion back to date doesn't cost as much as the initial conversion to varchar, but with Convert(, 112) it is closer to the same 20000 ms CPU base cost. Here are those calculations on the CPU time that I used for the above analysis: method round single base ----------- ------ ------ ----- date 21324 19891 18458 int 23031 21453 19875 datediff 23782 23218 22654 float 36891 29312 21733 varchar-112 102984 64016 25048 varchar-101 123375 65609 7843 round is the CPU time for a round trip back to datetime. single is CPU time for a single conversion to the alternate data type (the one that has the side effect of removing the time portion). base is the calculation of subtracting from single the difference between the two invocations: single - (round - single). It's a ballpark figure that assumes the conversion to and from that data type and datetime is approximately the same in either direction. It appears this assumption is not perfect but is close because the values are all close to 20000 ms with only one exception. One more interesting thing is that the base cost is nearly equal to the single Convert(date) method (which has to be almost 0 cost, as the server can internally extract the integer day portion right out of the first four bytes of the datetime data type). Conclusion So what it looks like is that the single-direction varchar conversion method takes about 1.8 μs and the single-direction DateDiff method takes about 0.18 μs. I'm basing this on the most conservative "base CPU" time in my testing of 18458 ms total for 25,920,000 rows, so 23218 ms / 25920000 = 0.18 μs. The apparent 10x improvement seems like a lot, but it is frankly pretty small until you are dealing with hundreds of thousands of rows (617k rows = 1 second savings). Even given this small absolute improvement, in my opinion, the DateAdd method wins because it is the best combination of performance and clarity. The answer that requires a "magic number" of 0.50000004 is going to bite someone some day (five zeroes or six???), plus it's harder to understand. Additional Notes When I get some time I'm going to change 0.50000004 to '12:00:00.003' and see how it does. It is converted to the same datetime value and I find it much easier to remember. For those interested, the above tests were run on a server where @@Version returns the following: Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86) Jul 9 2008 14:43:34 Copyright (c) 1988-2008 Microsoft Corporation Standard Edition on Windows NT 5.2 (Build 3790: Service Pack 2)
How to remove the time portion of a datetime value (SQL Server)? Here's what I use: SELECT CAST(FLOOR(CAST(getdate() as FLOAT)) as DATETIME) I'm thinking there may be a better and more elegant way. Requirements: It has to be as fast as possible (the less casting, the better). The final result has to be a datetime type, not a string.
TITLE: How to remove the time portion of a datetime value (SQL Server)? QUESTION: Here's what I use: SELECT CAST(FLOOR(CAST(getdate() as FLOAT)) as DATETIME) I'm thinking there may be a better and more elegant way. Requirements: It has to be as fast as possible (the less casting, the better). The final result has to be a datetime type, not a string. ANSWER: SQL Server 2008 and up In SQL Server 2008 and up, of course the fastest way is Convert(date, @date). This can be cast back to a datetime or datetime2 if necessary. What Is Really Best In SQL Server 2005 and Older? I've seen inconsistent claims about what's fastest for truncating the time from a date in SQL Server, and some people even said they did testing, but my experience has been different. So let's do some more stringent testing and let everyone have the script so if I make any mistakes people can correct me. Float Conversions Are Not Accurate First, I would stay away from converting datetime to float, because it does not convert correctly. You may get away with doing the time-removal thing accurately, but I think it's a bad idea to use it because it implicitly communicates to developers that this is a safe operation and it is not. Take a look: declare @d datetime; set @d = '2010-09-12 00:00:00.003'; select Convert(datetime, Convert(float, @d)); -- result: 2010-09-12 00:00:00.000 -- oops This is not something we should be teaching people in our code or in our examples online. Also, it is not even the fastest way! Proof – Performance Testing If you want to perform some tests yourself to see how the different methods really do stack up, then you'll need this setup script to run the tests farther down: create table AllDay (Tm datetime NOT NULL CONSTRAINT PK_AllDay PRIMARY KEY CLUSTERED); declare @d datetime; set @d = DateDiff(Day, 0, GetDate()); insert AllDay select @d; while @@ROWCOUNT!= 0 insert AllDay select * from ( select Tm = DateAdd(ms, (select Max(DateDiff(ms, @d, Tm)) from AllDay) + 3, Tm) from AllDay ) X where Tm < DateAdd(Day, 1, @d); exec sp_spaceused AllDay; -- 25,920,000 rows Please note that this creates a 427.57 MB table in your database and will take something like 15-30 minutes to run. If your database is small and set to 10% growth it will take longer than if you size big enough first. Now for the actual performance testing script. Please note that it's purposeful to not return rows back to the client as this is crazy expensive on 26 million rows and would hide the performance differences between the methods. Performance Results set statistics time on; -- (All queries are the same on io: logical reads 54712) GO declare @dd date, @d datetime, @di int, @df float, @dv varchar(10); -- Round trip back to datetime select @d = CONVERT(date, Tm) from AllDay; -- CPU time = 21234 ms, elapsed time = 22301 ms. select @d = CAST(Tm - 0.50000004 AS int) from AllDay; -- CPU = 23031 ms, elapsed = 24091 ms. select @d = DATEDIFF(DAY, 0, Tm) from AllDay; -- CPU = 23782 ms, elapsed = 24818 ms. select @d = FLOOR(CAST(Tm as float)) from AllDay; -- CPU = 36891 ms, elapsed = 38414 ms. select @d = CONVERT(VARCHAR(8), Tm, 112) from AllDay; -- CPU = 102984 ms, elapsed = 109897 ms. select @d = CONVERT(CHAR(8), Tm, 112) from AllDay; -- CPU = 103390 ms, elapsed = 108236 ms. select @d = CONVERT(VARCHAR(10), Tm, 101) from AllDay; -- CPU = 123375 ms, elapsed = 135179 ms. -- Only to another type but not back select @dd = Tm from AllDay; -- CPU time = 19891 ms, elapsed time = 20937 ms. select @di = CAST(Tm - 0.50000004 AS int) from AllDay; -- CPU = 21453 ms, elapsed = 23079 ms. select @di = DATEDIFF(DAY, 0, Tm) from AllDay; -- CPU = 23218 ms, elapsed = 24700 ms select @df = FLOOR(CAST(Tm as float)) from AllDay; -- CPU = 29312 ms, elapsed = 31101 ms. select @dv = CONVERT(VARCHAR(8), Tm, 112) from AllDay; -- CPU = 64016 ms, elapsed = 67815 ms. select @dv = CONVERT(CHAR(8), Tm, 112) from AllDay; -- CPU = 64297 ms, elapsed = 67987 ms. select @dv = CONVERT(VARCHAR(10), Tm, 101) from AllDay; -- CPU = 65609 ms, elapsed = 68173 ms. GO set statistics time off; Some Rambling Analysis Some notes about this. First of all, if just performing a GROUP BY or a comparison, there's no need to convert back to datetime. So you can save some CPU by avoiding that, unless you need the final value for display purposes. You can even GROUP BY the unconverted value and put the conversion only in the SELECT clause: select Convert(datetime, DateDiff(dd, 0, Tm)) from (select '2010-09-12 00:00:00.003') X (Tm) group by DateDiff(dd, 0, Tm) Also, see how the numeric conversions only take slightly more time to convert back to datetime, but the varchar conversion almost doubles? This reveals the portion of the CPU that is devoted to date calculation in the queries. There are parts of the CPU usage that don't involve date calculation, and this appears to be something close to 19875 ms in the above queries. Then the conversion takes some additional amount, so if there are two conversions, that amount is used up approximately twice. More examination reveals that compared to Convert(, 112), the Convert(, 101) query has some additional CPU expense (since it uses a longer varchar?), because the second conversion back to date doesn't cost as much as the initial conversion to varchar, but with Convert(, 112) it is closer to the same 20000 ms CPU base cost. Here are those calculations on the CPU time that I used for the above analysis: method round single base ----------- ------ ------ ----- date 21324 19891 18458 int 23031 21453 19875 datediff 23782 23218 22654 float 36891 29312 21733 varchar-112 102984 64016 25048 varchar-101 123375 65609 7843 round is the CPU time for a round trip back to datetime. single is CPU time for a single conversion to the alternate data type (the one that has the side effect of removing the time portion). base is the calculation of subtracting from single the difference between the two invocations: single - (round - single). It's a ballpark figure that assumes the conversion to and from that data type and datetime is approximately the same in either direction. It appears this assumption is not perfect but is close because the values are all close to 20000 ms with only one exception. One more interesting thing is that the base cost is nearly equal to the single Convert(date) method (which has to be almost 0 cost, as the server can internally extract the integer day portion right out of the first four bytes of the datetime data type). Conclusion So what it looks like is that the single-direction varchar conversion method takes about 1.8 μs and the single-direction DateDiff method takes about 0.18 μs. I'm basing this on the most conservative "base CPU" time in my testing of 18458 ms total for 25,920,000 rows, so 23218 ms / 25920000 = 0.18 μs. The apparent 10x improvement seems like a lot, but it is frankly pretty small until you are dealing with hundreds of thousands of rows (617k rows = 1 second savings). Even given this small absolute improvement, in my opinion, the DateAdd method wins because it is the best combination of performance and clarity. The answer that requires a "magic number" of 0.50000004 is going to bite someone some day (five zeroes or six???), plus it's harder to understand. Additional Notes When I get some time I'm going to change 0.50000004 to '12:00:00.003' and see how it does. It is converted to the same datetime value and I find it much easier to remember. For those interested, the above tests were run on a server where @@Version returns the following: Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86) Jul 9 2008 14:43:34 Copyright (c) 1988-2008 Microsoft Corporation Standard Edition on Windows NT 5.2 (Build 3790: Service Pack 2)
[ "sql-server", "datetime", "date-conversion" ]
86
119
65,755
6
0
2008-08-05T20:08:38.653000
2010-09-12T22:57:35.493000
2,780
2,789
Converting ARBG to RGB with alpha blending
Let's say that we have an ARGB color: Color argb = Color.FromARGB(127, 69, 12, 255); //Light Urple. When this is painted on top of an existing color, the colors will blend. So when it is blended with white, the resulting color is Color.FromARGB(255, 162, 133, 255); The solution should work like this: Color blend = Color.White; Color argb = Color.FromARGB(127, 69, 12, 255); //Light Urple. Color rgb = ToRGB(argb, blend); //Same as Color.FromARGB(255, 162, 133, 255); What is ToRGB 's implementation?
It's called alpha blending. In psuedocode, assuming the background color (blend) always has 255 alpha. Also assumes alpha is 0-255. alpha=argb.alpha() r = (alpha/255)*argb.r() + (1 - alpha/255)*blend.r() g = (alpha/255)*argb.g() + (1 - alpha/255)*blend.g() b = (alpha/255)*argb.b() + (1 - alpha/255)*blend.b() note: you probably need to be a bit (more) careful about floating-point/int math and rounding issues, depending on language. Cast intermediates accordingly Edited to add: If you don't have a background color with an alpha of 255, the algebra gets alot more complicated. I've done it before and it's a fun exercise left to the reader (if you really need to know, ask another question:). In other words, what color C blends into some background the same as blending A, then blending B. This is sort of like calculating A+B (which isn't the same as B+A).
Converting ARBG to RGB with alpha blending Let's say that we have an ARGB color: Color argb = Color.FromARGB(127, 69, 12, 255); //Light Urple. When this is painted on top of an existing color, the colors will blend. So when it is blended with white, the resulting color is Color.FromARGB(255, 162, 133, 255); The solution should work like this: Color blend = Color.White; Color argb = Color.FromARGB(127, 69, 12, 255); //Light Urple. Color rgb = ToRGB(argb, blend); //Same as Color.FromARGB(255, 162, 133, 255); What is ToRGB 's implementation?
TITLE: Converting ARBG to RGB with alpha blending QUESTION: Let's say that we have an ARGB color: Color argb = Color.FromARGB(127, 69, 12, 255); //Light Urple. When this is painted on top of an existing color, the colors will blend. So when it is blended with white, the resulting color is Color.FromARGB(255, 162, 133, 255); The solution should work like this: Color blend = Color.White; Color argb = Color.FromARGB(127, 69, 12, 255); //Light Urple. Color rgb = ToRGB(argb, blend); //Same as Color.FromARGB(255, 162, 133, 255); What is ToRGB 's implementation? ANSWER: It's called alpha blending. In psuedocode, assuming the background color (blend) always has 255 alpha. Also assumes alpha is 0-255. alpha=argb.alpha() r = (alpha/255)*argb.r() + (1 - alpha/255)*blend.r() g = (alpha/255)*argb.g() + (1 - alpha/255)*blend.g() b = (alpha/255)*argb.b() + (1 - alpha/255)*blend.b() note: you probably need to be a bit (more) careful about floating-point/int math and rounding issues, depending on language. Cast intermediates accordingly Edited to add: If you don't have a background color with an alpha of 255, the algebra gets alot more complicated. I've done it before and it's a fun exercise left to the reader (if you really need to know, ask another question:). In other words, what color C blends into some background the same as blending A, then blending B. This is sort of like calculating A+B (which isn't the same as B+A).
[ "c#", "colors" ]
25
19
13,312
3
0
2008-08-05T20:12:20.487000
2008-08-05T20:16:03.583000
2,785
2,839
Setting Objects to Null/Nothing after use in .NET
Should you set all the objects to null ( Nothing in VB.NET) once you have finished with them? I understand that in.NET it is essential to dispose of any instances of objects that implement the IDisposable interface to release some resources although the object can still be something after it is disposed (hence the isDisposed property in forms), so I assume it can still reside in memory or at least in part? I also know that when an object goes out of scope it is then marked for collection ready for the next pass of the garbage collector (although this may take time). So with this in mind will setting it to null speed up the system releasing the memory as it does not have to work out that it is no longer in scope and are they any bad side effects? MSDN articles never do this in examples and currently I do this as I cannot see the harm. However I have come across a mixture of opinions so any comments are useful.
Karl is absolutely correct, there is no need to set objects to null after use. If an object implements IDisposable, just make sure you call IDisposable.Dispose() when you're done with that object (wrapped in a try.. finally, or, a using() block). But even if you don't remember to call Dispose(), the finaliser method on the object should be calling Dispose() for you. I thought this was a good treatment: Digging into IDisposable and this Understanding IDisposable There isn't any point in trying to second guess the GC and its management strategies because it's self tuning and opaque. There was a good discussion about the inner workings with Jeffrey Richter on Dot Net Rocks here: Jeffrey Richter on the Windows Memory Model and Richters book CLR via C# chapter 20 has a great treatment:
Setting Objects to Null/Nothing after use in .NET Should you set all the objects to null ( Nothing in VB.NET) once you have finished with them? I understand that in.NET it is essential to dispose of any instances of objects that implement the IDisposable interface to release some resources although the object can still be something after it is disposed (hence the isDisposed property in forms), so I assume it can still reside in memory or at least in part? I also know that when an object goes out of scope it is then marked for collection ready for the next pass of the garbage collector (although this may take time). So with this in mind will setting it to null speed up the system releasing the memory as it does not have to work out that it is no longer in scope and are they any bad side effects? MSDN articles never do this in examples and currently I do this as I cannot see the harm. However I have come across a mixture of opinions so any comments are useful.
TITLE: Setting Objects to Null/Nothing after use in .NET QUESTION: Should you set all the objects to null ( Nothing in VB.NET) once you have finished with them? I understand that in.NET it is essential to dispose of any instances of objects that implement the IDisposable interface to release some resources although the object can still be something after it is disposed (hence the isDisposed property in forms), so I assume it can still reside in memory or at least in part? I also know that when an object goes out of scope it is then marked for collection ready for the next pass of the garbage collector (although this may take time). So with this in mind will setting it to null speed up the system releasing the memory as it does not have to work out that it is no longer in scope and are they any bad side effects? MSDN articles never do this in examples and currently I do this as I cannot see the harm. However I have come across a mixture of opinions so any comments are useful. ANSWER: Karl is absolutely correct, there is no need to set objects to null after use. If an object implements IDisposable, just make sure you call IDisposable.Dispose() when you're done with that object (wrapped in a try.. finally, or, a using() block). But even if you don't remember to call Dispose(), the finaliser method on the object should be calling Dispose() for you. I thought this was a good treatment: Digging into IDisposable and this Understanding IDisposable There isn't any point in trying to second guess the GC and its management strategies because it's self tuning and opaque. There was a good discussion about the inner workings with Jeffrey Richter on Dot Net Rocks here: Jeffrey Richter on the Windows Memory Model and Richters book CLR via C# chapter 20 has a great treatment:
[ "c#", ".net", "vb.net", "memory-management", "null" ]
196
78
115,345
16
0
2008-08-05T20:14:10.560000
2008-08-05T20:56:28.667000
2,786
2,944
What's the best setup for Mono development on Windows?
I started trying to play with Mono, mostly for fun at the moment. I first tried to use the Visual Studio plugin that will convert a csproj into a makefile, but there seemed to be no version available for Visual Studio 2005. I also read about the MonoDevelop IDE, which sounded nice. Unfortunately, there's no pre-fab Windows package for it. I tried to follow some instructions to build it by combining dependencies from other semi-related installs. It didn't work, but that's probably because I'm a Windows-oriented guy and can barely spell "makefile". So, my question is this: What's the lowest-energy way to get up and running to try some Mono-based development on Windows?
I'd recommend getting VMWare Player and using the free Mono development platform image that is provided on the website. Download Mono Setup time for this will be minimal, and it will also allow you to get your code working in.NET and then focus on porting issues without a massive hassle of switching machines and the like. the VMWare Player tools will allow you to simply drag and drop the files over to copy them. I'm looking to take a couple of my.NET apps and make them Mono compliant, and this is the path I'm going to take here shortly.
What's the best setup for Mono development on Windows? I started trying to play with Mono, mostly for fun at the moment. I first tried to use the Visual Studio plugin that will convert a csproj into a makefile, but there seemed to be no version available for Visual Studio 2005. I also read about the MonoDevelop IDE, which sounded nice. Unfortunately, there's no pre-fab Windows package for it. I tried to follow some instructions to build it by combining dependencies from other semi-related installs. It didn't work, but that's probably because I'm a Windows-oriented guy and can barely spell "makefile". So, my question is this: What's the lowest-energy way to get up and running to try some Mono-based development on Windows?
TITLE: What's the best setup for Mono development on Windows? QUESTION: I started trying to play with Mono, mostly for fun at the moment. I first tried to use the Visual Studio plugin that will convert a csproj into a makefile, but there seemed to be no version available for Visual Studio 2005. I also read about the MonoDevelop IDE, which sounded nice. Unfortunately, there's no pre-fab Windows package for it. I tried to follow some instructions to build it by combining dependencies from other semi-related installs. It didn't work, but that's probably because I'm a Windows-oriented guy and can barely spell "makefile". So, my question is this: What's the lowest-energy way to get up and running to try some Mono-based development on Windows? ANSWER: I'd recommend getting VMWare Player and using the free Mono development platform image that is provided on the website. Download Mono Setup time for this will be minimal, and it will also allow you to get your code working in.NET and then focus on porting issues without a massive hassle of switching machines and the like. the VMWare Player tools will allow you to simply drag and drop the files over to copy them. I'm looking to take a couple of my.NET apps and make them Mono compliant, and this is the path I'm going to take here shortly.
[ "windows", "mono" ]
33
15
7,822
10
0
2008-08-05T20:15:22.820000
2008-08-05T22:43:57.013000
2,798
2,803
Map Routing, a la Google Maps?
I've always been intrigued by Map Routing, but I've never found any good introductory (or even advanced!) level tutorials on it. Does anybody have any pointers, hints, etc? Update: I'm primarily looking for pointers as to how a map system is implemented (data structures, algorithms, etc).
Take a look at the open street map project to see how this sort of thing is being tackled in a truely free software project using only user supplied and licensed data and have a wiki containing stuff you might find interesting. A few years back the guys involved where pretty easy going and answered lots of questions I had so I see no reason why they still aren't a nice bunch.
Map Routing, a la Google Maps? I've always been intrigued by Map Routing, but I've never found any good introductory (or even advanced!) level tutorials on it. Does anybody have any pointers, hints, etc? Update: I'm primarily looking for pointers as to how a map system is implemented (data structures, algorithms, etc).
TITLE: Map Routing, a la Google Maps? QUESTION: I've always been intrigued by Map Routing, but I've never found any good introductory (or even advanced!) level tutorials on it. Does anybody have any pointers, hints, etc? Update: I'm primarily looking for pointers as to how a map system is implemented (data structures, algorithms, etc). ANSWER: Take a look at the open street map project to see how this sort of thing is being tackled in a truely free software project using only user supplied and licensed data and have a wiki containing stuff you might find interesting. A few years back the guys involved where pretty easy going and answered lots of questions I had so I see no reason why they still aren't a nice bunch.
[ "google-maps", "google-maps-api-3", "mapping", "gis" ]
24
15
11,055
9
0
2008-08-05T20:24:42.960000
2008-08-05T20:27:36.633000
2,804
2,808
How should I translate from screen space coordinates to image space coordinates in a WinForms PictureBox?
I have an application that displays an image inside of a Windows Forms PictureBox control. The SizeMode of the control is set to Zoom so that the image contained in the PictureBox will be displayed in an aspect-correct way regardless of the dimensions of the PictureBox. This is great for the visual appearance of the application because you can size the window however you want and the image will always be displayed using its best fit. Unfortunately, I also need to handle mouse click events on the picture box and need to be able to translate from screen-space coordinates to image-space coordinates. It looks like it's easy to translate from screen space to control space, but I don't see any obvious way to translate from control space to image space (i.e. the pixel coordinate in the source image that has been scaled in the picture box). Is there an easy way to do this, or should I just duplicate the scaling math that they're using internally to position the image and do the translation myself?
Depending on the scaling, the relative image pixel could be anywhere in a number of pixels. For example, if the image is scaled down significantly, pixel 2, 10 could represent 2, 10 all the way up to 20, 100), so you'll have to do the math yourself and take full responsibility for any inaccuracies!:-)
How should I translate from screen space coordinates to image space coordinates in a WinForms PictureBox? I have an application that displays an image inside of a Windows Forms PictureBox control. The SizeMode of the control is set to Zoom so that the image contained in the PictureBox will be displayed in an aspect-correct way regardless of the dimensions of the PictureBox. This is great for the visual appearance of the application because you can size the window however you want and the image will always be displayed using its best fit. Unfortunately, I also need to handle mouse click events on the picture box and need to be able to translate from screen-space coordinates to image-space coordinates. It looks like it's easy to translate from screen space to control space, but I don't see any obvious way to translate from control space to image space (i.e. the pixel coordinate in the source image that has been scaled in the picture box). Is there an easy way to do this, or should I just duplicate the scaling math that they're using internally to position the image and do the translation myself?
TITLE: How should I translate from screen space coordinates to image space coordinates in a WinForms PictureBox? QUESTION: I have an application that displays an image inside of a Windows Forms PictureBox control. The SizeMode of the control is set to Zoom so that the image contained in the PictureBox will be displayed in an aspect-correct way regardless of the dimensions of the PictureBox. This is great for the visual appearance of the application because you can size the window however you want and the image will always be displayed using its best fit. Unfortunately, I also need to handle mouse click events on the picture box and need to be able to translate from screen-space coordinates to image-space coordinates. It looks like it's easy to translate from screen space to control space, but I don't see any obvious way to translate from control space to image space (i.e. the pixel coordinate in the source image that has been scaled in the picture box). Is there an easy way to do this, or should I just duplicate the scaling math that they're using internally to position the image and do the translation myself? ANSWER: Depending on the scaling, the relative image pixel could be anywhere in a number of pixels. For example, if the image is scaled down significantly, pixel 2, 10 could represent 2, 10 all the way up to 20, 100), so you'll have to do the math yourself and take full responsibility for any inaccuracies!:-)
[ "c#", "winforms", "picturebox" ]
21
2
4,731
2
0
2008-08-05T20:28:30.143000
2008-08-05T20:33:01.693000
2,809
2,842
SQL Server 2000: Is there a way to tell when a record was last modified?
The table doesn't have a last updated field and I need to know when existing data was updated. So adding a last updated field won't help (as far as I know).
SQL Server 2000 does not keep track of this information for you. There may be creative / fuzzy ways to guess what this date was depending on your database model. But, if you are talking about 1 table with no relation to other data, then you are out of luck.
SQL Server 2000: Is there a way to tell when a record was last modified? The table doesn't have a last updated field and I need to know when existing data was updated. So adding a last updated field won't help (as far as I know).
TITLE: SQL Server 2000: Is there a way to tell when a record was last modified? QUESTION: The table doesn't have a last updated field and I need to know when existing data was updated. So adding a last updated field won't help (as far as I know). ANSWER: SQL Server 2000 does not keep track of this information for you. There may be creative / fuzzy ways to guess what this date was depending on your database model. But, if you are talking about 1 table with no relation to other data, then you are out of luck.
[ "sql-server" ]
11
5
2,842
5
0
2008-08-05T20:33:21.757000
2008-08-05T20:58:17.477000
2,811
2,825
SQL Server 2005 For XML Explicit - Need help formatting
I have a table with a structure like the following: LocationID AccountNumber long-guid-here 12345 long-guid-here 54321 To pass into another stored procedure, I need the XML to look like this: 12345 54321 The best I've been able to do so far was getting it like this: I'm using this SQL statement: SELECT 1 as tag, null as parent, AccountNumber as 'root!1!clientID' FROM Location.LocationMDAccount WHERE locationid = 'long-guid-here' FOR XML EXPLICIT So far, I've looked at the documentation on the MSDN page, but I've not come out with the desired results. @KG, Yours gave me this output actually: 10705 I'm going to stick with the FOR XML EXPLICIT from Chris Leon for now.
try SELECT 1 AS Tag, 0 AS Parent, AccountNumber AS [Root!1!AccountNumber!element] FROM Location.LocationMDAccount WHERE LocationID = 'long-guid-here' FOR XML EXPLICIT
SQL Server 2005 For XML Explicit - Need help formatting I have a table with a structure like the following: LocationID AccountNumber long-guid-here 12345 long-guid-here 54321 To pass into another stored procedure, I need the XML to look like this: 12345 54321 The best I've been able to do so far was getting it like this: I'm using this SQL statement: SELECT 1 as tag, null as parent, AccountNumber as 'root!1!clientID' FROM Location.LocationMDAccount WHERE locationid = 'long-guid-here' FOR XML EXPLICIT So far, I've looked at the documentation on the MSDN page, but I've not come out with the desired results. @KG, Yours gave me this output actually: 10705 I'm going to stick with the FOR XML EXPLICIT from Chris Leon for now.
TITLE: SQL Server 2005 For XML Explicit - Need help formatting QUESTION: I have a table with a structure like the following: LocationID AccountNumber long-guid-here 12345 long-guid-here 54321 To pass into another stored procedure, I need the XML to look like this: 12345 54321 The best I've been able to do so far was getting it like this: I'm using this SQL statement: SELECT 1 as tag, null as parent, AccountNumber as 'root!1!clientID' FROM Location.LocationMDAccount WHERE locationid = 'long-guid-here' FOR XML EXPLICIT So far, I've looked at the documentation on the MSDN page, but I've not come out with the desired results. @KG, Yours gave me this output actually: 10705 I'm going to stick with the FOR XML EXPLICIT from Chris Leon for now. ANSWER: try SELECT 1 AS Tag, 0 AS Parent, AccountNumber AS [Root!1!AccountNumber!element] FROM Location.LocationMDAccount WHERE LocationID = 'long-guid-here' FOR XML EXPLICIT
[ "sql", "xml", "sql-server-2005", "formatting", "for-xml" ]
13
3
4,498
5
0
2008-08-05T20:35:56.150000
2008-08-05T20:51:03.547000
2,815
2,819
How to curl or wget a web page?
I would like to make a nightly cron job that fetches my stackoverflow page and diffs it from the previous day's page, so I can see a change summary of my questions, answers, ranking, etc. Unfortunately, I couldn't get the right set of cookies, etc, to make this work. Any ideas? Also, when the beta is finished, will my status page be accessible without logging in?
Your status page is available now without logging in (click logout and try it). When the beta-cookie is disabled, there will be nothing between you and your status page. For wget: wget --no-cookies --header "Cookie: soba=(LookItUpYourself)" https://stackoverflow.com/users/30/myProfile.html
How to curl or wget a web page? I would like to make a nightly cron job that fetches my stackoverflow page and diffs it from the previous day's page, so I can see a change summary of my questions, answers, ranking, etc. Unfortunately, I couldn't get the right set of cookies, etc, to make this work. Any ideas? Also, when the beta is finished, will my status page be accessible without logging in?
TITLE: How to curl or wget a web page? QUESTION: I would like to make a nightly cron job that fetches my stackoverflow page and diffs it from the previous day's page, so I can see a change summary of my questions, answers, ranking, etc. Unfortunately, I couldn't get the right set of cookies, etc, to make this work. Any ideas? Also, when the beta is finished, will my status page be accessible without logging in? ANSWER: Your status page is available now without logging in (click logout and try it). When the beta-cookie is disabled, there will be nothing between you and your status page. For wget: wget --no-cookies --header "Cookie: soba=(LookItUpYourself)" https://stackoverflow.com/users/30/myProfile.html
[ "http", "curl" ]
19
9
8,259
5
0
2008-08-05T20:38:59.293000
2008-08-05T20:43:52.017000
2,840
2,843
Paging SQL Server 2005 Results
How do I page results in SQL Server 2005? I tried it in SQL Server 2000, but there was no reliable way to do this. I'm now wondering if SQL Server 2005 has any built in method? What I mean by paging is, for example, if I list users by their username, I want to be able to only return the first 10 records, then the next 10 records and so on.
You can use the Row_Number() function. Its used as follows: SELECT Row_Number() OVER(ORDER BY UserName) As RowID, UserFirstName, UserLastName FROM Users From which it will yield a result set with a RowID field which you can use to page between. SELECT * FROM ( SELECT Row_Number() OVER(ORDER BY UserName) As RowID, UserFirstName, UserLastName FROM Users ) As RowResults WHERE RowID Between 5 AND 10 etc
Paging SQL Server 2005 Results How do I page results in SQL Server 2005? I tried it in SQL Server 2000, but there was no reliable way to do this. I'm now wondering if SQL Server 2005 has any built in method? What I mean by paging is, for example, if I list users by their username, I want to be able to only return the first 10 records, then the next 10 records and so on.
TITLE: Paging SQL Server 2005 Results QUESTION: How do I page results in SQL Server 2005? I tried it in SQL Server 2000, but there was no reliable way to do this. I'm now wondering if SQL Server 2005 has any built in method? What I mean by paging is, for example, if I list users by their username, I want to be able to only return the first 10 records, then the next 10 records and so on. ANSWER: You can use the Row_Number() function. Its used as follows: SELECT Row_Number() OVER(ORDER BY UserName) As RowID, UserFirstName, UserLastName FROM Users From which it will yield a result set with a RowID field which you can use to page between. SELECT * FROM ( SELECT Row_Number() OVER(ORDER BY UserName) As RowID, UserFirstName, UserLastName FROM Users ) As RowResults WHERE RowID Between 5 AND 10 etc
[ "sql", "sql-server-2005", "paging" ]
42
36
7,435
6
0
2008-08-05T20:57:00.787000
2008-08-05T20:59:21.563000
2,844
2,850
How do you format an unsigned long long int using printf?
#include int main() { unsigned long long int num = 285212672; //FYI: fits in 29 bits int normalInt = 5; printf("My number is %d bytes wide and its value is %ul. A normal number is %d.\n", sizeof(num), num, normalInt); return 0; } Output: My number is 8 bytes wide and its value is 285212672l. A normal number is 0. I assume this unexpected result is from printing the unsigned long long int. How do you printf() an unsigned long long int?
Use the ll (el-el) long-long modifier with the u (unsigned) conversion. (Works in windows, GNU). printf("%llu", 285212672);
How do you format an unsigned long long int using printf? #include int main() { unsigned long long int num = 285212672; //FYI: fits in 29 bits int normalInt = 5; printf("My number is %d bytes wide and its value is %ul. A normal number is %d.\n", sizeof(num), num, normalInt); return 0; } Output: My number is 8 bytes wide and its value is 285212672l. A normal number is 0. I assume this unexpected result is from printing the unsigned long long int. How do you printf() an unsigned long long int?
TITLE: How do you format an unsigned long long int using printf? QUESTION: #include int main() { unsigned long long int num = 285212672; //FYI: fits in 29 bits int normalInt = 5; printf("My number is %d bytes wide and its value is %ul. A normal number is %d.\n", sizeof(num), num, normalInt); return 0; } Output: My number is 8 bytes wide and its value is 285212672l. A normal number is 0. I assume this unexpected result is from printing the unsigned long long int. How do you printf() an unsigned long long int? ANSWER: Use the ll (el-el) long-long modifier with the u (unsigned) conversion. (Works in windows, GNU). printf("%llu", 285212672);
[ "c", "syntax", "printf", "format-specifiers", "long-long" ]
467
603
1,008,617
14
0
2008-08-05T20:59:29.330000
2008-08-05T21:02:35.237000
2,871
2,887
Reading a C/C++ data structure in C# from a byte array
What would be the best way to fill a C# struct from a byte[] array where the data was from a C/C++ struct? The C struct would look something like this (my C is very rusty): typedef OldStuff { CHAR Name[8]; UInt32 User; CHAR Location[8]; UInt32 TimeStamp; UInt32 Sequence; CHAR Tracking[16]; CHAR Filler[12]; } And would fill something like this: [StructLayout(LayoutKind.Explicit, Size = 56, Pack = 1)] public struct NewStuff { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)] [FieldOffset(0)] public string Name; [MarshalAs(UnmanagedType.U4)] [FieldOffset(8)] public uint User; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)] [FieldOffset(12)] public string Location; [MarshalAs(UnmanagedType.U4)] [FieldOffset(20)] public uint TimeStamp; [MarshalAs(UnmanagedType.U4)] [FieldOffset(24)] public uint Sequence; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)] [FieldOffset(28)] public string Tracking; } What is best way to copy OldStuff to NewStuff, if OldStuff was passed as byte[] array? I'm currently doing something like the following, but it feels kind of clunky. GCHandle handle; NewStuff MyStuff; int BufferSize = Marshal.SizeOf(typeof(NewStuff)); byte[] buff = new byte[BufferSize]; Array.Copy(SomeByteArray, 0, buff, 0, BufferSize); handle = GCHandle.Alloc(buff, GCHandleType.Pinned); MyStuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff)); handle.Free(); Is there better way to accomplish this? Would using the BinaryReader class offer any performance gains over pinning the memory and using Marshal.PtrStructure?
From what I can see in that context, you don't need to copy SomeByteArray into a buffer. You simply need to get the handle from SomeByteArray, pin it, copy the IntPtr data using PtrToStructure and then release. No need for a copy. That would be: NewStuff ByteArrayToNewStuff(byte[] bytes) { GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); try { NewStuff stuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff)); } finally { handle.Free(); } return stuff; } Generic version: T ByteArrayToStructure (byte[] bytes) where T: struct { T stuff; GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); try { stuff = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); } finally { handle.Free(); } return stuff; } Simpler version (requires unsafe switch): unsafe T ByteArrayToStructure (byte[] bytes) where T: struct { fixed (byte* ptr = &bytes[0]) { return (T)Marshal.PtrToStructure((IntPtr)ptr, typeof(T)); } }
Reading a C/C++ data structure in C# from a byte array What would be the best way to fill a C# struct from a byte[] array where the data was from a C/C++ struct? The C struct would look something like this (my C is very rusty): typedef OldStuff { CHAR Name[8]; UInt32 User; CHAR Location[8]; UInt32 TimeStamp; UInt32 Sequence; CHAR Tracking[16]; CHAR Filler[12]; } And would fill something like this: [StructLayout(LayoutKind.Explicit, Size = 56, Pack = 1)] public struct NewStuff { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)] [FieldOffset(0)] public string Name; [MarshalAs(UnmanagedType.U4)] [FieldOffset(8)] public uint User; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)] [FieldOffset(12)] public string Location; [MarshalAs(UnmanagedType.U4)] [FieldOffset(20)] public uint TimeStamp; [MarshalAs(UnmanagedType.U4)] [FieldOffset(24)] public uint Sequence; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)] [FieldOffset(28)] public string Tracking; } What is best way to copy OldStuff to NewStuff, if OldStuff was passed as byte[] array? I'm currently doing something like the following, but it feels kind of clunky. GCHandle handle; NewStuff MyStuff; int BufferSize = Marshal.SizeOf(typeof(NewStuff)); byte[] buff = new byte[BufferSize]; Array.Copy(SomeByteArray, 0, buff, 0, BufferSize); handle = GCHandle.Alloc(buff, GCHandleType.Pinned); MyStuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff)); handle.Free(); Is there better way to accomplish this? Would using the BinaryReader class offer any performance gains over pinning the memory and using Marshal.PtrStructure?
TITLE: Reading a C/C++ data structure in C# from a byte array QUESTION: What would be the best way to fill a C# struct from a byte[] array where the data was from a C/C++ struct? The C struct would look something like this (my C is very rusty): typedef OldStuff { CHAR Name[8]; UInt32 User; CHAR Location[8]; UInt32 TimeStamp; UInt32 Sequence; CHAR Tracking[16]; CHAR Filler[12]; } And would fill something like this: [StructLayout(LayoutKind.Explicit, Size = 56, Pack = 1)] public struct NewStuff { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)] [FieldOffset(0)] public string Name; [MarshalAs(UnmanagedType.U4)] [FieldOffset(8)] public uint User; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)] [FieldOffset(12)] public string Location; [MarshalAs(UnmanagedType.U4)] [FieldOffset(20)] public uint TimeStamp; [MarshalAs(UnmanagedType.U4)] [FieldOffset(24)] public uint Sequence; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)] [FieldOffset(28)] public string Tracking; } What is best way to copy OldStuff to NewStuff, if OldStuff was passed as byte[] array? I'm currently doing something like the following, but it feels kind of clunky. GCHandle handle; NewStuff MyStuff; int BufferSize = Marshal.SizeOf(typeof(NewStuff)); byte[] buff = new byte[BufferSize]; Array.Copy(SomeByteArray, 0, buff, 0, BufferSize); handle = GCHandle.Alloc(buff, GCHandleType.Pinned); MyStuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff)); handle.Free(); Is there better way to accomplish this? Would using the BinaryReader class offer any performance gains over pinning the memory and using Marshal.PtrStructure? ANSWER: From what I can see in that context, you don't need to copy SomeByteArray into a buffer. You simply need to get the handle from SomeByteArray, pin it, copy the IntPtr data using PtrToStructure and then release. No need for a copy. That would be: NewStuff ByteArrayToNewStuff(byte[] bytes) { GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); try { NewStuff stuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff)); } finally { handle.Free(); } return stuff; } Generic version: T ByteArrayToStructure (byte[] bytes) where T: struct { T stuff; GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); try { stuff = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); } finally { handle.Free(); } return stuff; } Simpler version (requires unsafe switch): unsafe T ByteArrayToStructure (byte[] bytes) where T: struct { fixed (byte* ptr = &bytes[0]) { return (T)Marshal.PtrToStructure((IntPtr)ptr, typeof(T)); } }
[ "c#", ".net", "data-structures", "marshalling" ]
95
129
62,844
5
0
2008-08-05T21:19:03.147000
2008-08-05T21:29:39.647000
2,872
2,901
Possible to "spin off" several GUI threads? (Not halting the system at Application.Run)
My Goal I would like to have a main processing thread (non GUI), and be able to spin off GUIs in their own background threads as needed, and having my main non GUI thread keep working. Put another way, I want my main non GUI-thread to be the owner of the GUI-thread and not vice versa. I'm not sure this is even possible with Windows Forms(?) Background I have a component based system in which a controller dynamically load assemblies and instantiates and run classes implementing a common IComponent interface with a single method DoStuff(). Which components that gets loaded is configured via a xml configuration file and by adding new assemblies containing different implementations of IComponent. The components provides utility functions to the main application. While the main program is doing it's thing, e.g. controlling a nuclear plant, the components might be performing utility tasks (in their own threads), e.g. cleaning the database, sending emails, printing funny jokes on the printer, what have you. What I would like, is to have one of these components be able to display a GUI, e.g. with status information for the said email sending component. The lifetime of the complete system looks like this Application starts. Check configuration file for components to load. Load them. For each component, run DoStuff() to initialize it and make it live its own life in their own threads. Continue to do main application-thingy king of work, forever. I have not yet been able to successfully perform point 3 if the component fires up a GUI in DoStuff(). It simply just halts until the GUI is closed. And not until the GUI is closed does the program progress to point 4. It would be great if these components were allowed to start up their own Windows Forms GUIs. Problem When a component tries to fire up a GUI in DoStuff() (the exact line of code is when the component runs Application.Run(theForm) ), the component and hence our system "hangs" at the Application.Run() line until the GUI is closed. Well, the just fired up GUI works fine, as expected. Example of components. One hasn't nothing to do with GUI, whilst the second fires up a cute windows with pink fluffy bunnies in them. public class MyComponent1: IComponent { public string DoStuff(...) { // write something to the database } } public class MyComponent2: IComponent { public void DoStuff() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form()); // I want the thread to immediately return after the GUI // is fired up, so that my main thread can continue to work. } } I have tried this with no luck. Even when I try to fire up the GUI in it's own thread, the execution halts until the GUI as closed. public void DoStuff() { new Thread(ThreadedInitialize).Start() } private void ThreadedInitialize() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form()); } Is it possible to spin off a GUI and return after Application.Run()?
Application.Run method displays one (or more) forms and initiates the standard message loop which runs until all the forms are closed. You cannot force a return from that method except by closing all your forms or forcing an application shutdown. You can, however, pass an ApplicationContext (instad of a new Form()) to Application.Run method and ApplicationContext can be used to launch several forms at once. Your application will only end when all of those are closed. See here: http://msdn.microsoft.com/en-us/library/system.windows.forms.application.run.aspx Also, any forms that you Show non-modally will continue to run alongside your main form, which will enable you to have more than one windows that do not block each other. I believe this is actually what you are trying to accomplish.
Possible to "spin off" several GUI threads? (Not halting the system at Application.Run) My Goal I would like to have a main processing thread (non GUI), and be able to spin off GUIs in their own background threads as needed, and having my main non GUI thread keep working. Put another way, I want my main non GUI-thread to be the owner of the GUI-thread and not vice versa. I'm not sure this is even possible with Windows Forms(?) Background I have a component based system in which a controller dynamically load assemblies and instantiates and run classes implementing a common IComponent interface with a single method DoStuff(). Which components that gets loaded is configured via a xml configuration file and by adding new assemblies containing different implementations of IComponent. The components provides utility functions to the main application. While the main program is doing it's thing, e.g. controlling a nuclear plant, the components might be performing utility tasks (in their own threads), e.g. cleaning the database, sending emails, printing funny jokes on the printer, what have you. What I would like, is to have one of these components be able to display a GUI, e.g. with status information for the said email sending component. The lifetime of the complete system looks like this Application starts. Check configuration file for components to load. Load them. For each component, run DoStuff() to initialize it and make it live its own life in their own threads. Continue to do main application-thingy king of work, forever. I have not yet been able to successfully perform point 3 if the component fires up a GUI in DoStuff(). It simply just halts until the GUI is closed. And not until the GUI is closed does the program progress to point 4. It would be great if these components were allowed to start up their own Windows Forms GUIs. Problem When a component tries to fire up a GUI in DoStuff() (the exact line of code is when the component runs Application.Run(theForm) ), the component and hence our system "hangs" at the Application.Run() line until the GUI is closed. Well, the just fired up GUI works fine, as expected. Example of components. One hasn't nothing to do with GUI, whilst the second fires up a cute windows with pink fluffy bunnies in them. public class MyComponent1: IComponent { public string DoStuff(...) { // write something to the database } } public class MyComponent2: IComponent { public void DoStuff() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form()); // I want the thread to immediately return after the GUI // is fired up, so that my main thread can continue to work. } } I have tried this with no luck. Even when I try to fire up the GUI in it's own thread, the execution halts until the GUI as closed. public void DoStuff() { new Thread(ThreadedInitialize).Start() } private void ThreadedInitialize() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form()); } Is it possible to spin off a GUI and return after Application.Run()?
TITLE: Possible to "spin off" several GUI threads? (Not halting the system at Application.Run) QUESTION: My Goal I would like to have a main processing thread (non GUI), and be able to spin off GUIs in their own background threads as needed, and having my main non GUI thread keep working. Put another way, I want my main non GUI-thread to be the owner of the GUI-thread and not vice versa. I'm not sure this is even possible with Windows Forms(?) Background I have a component based system in which a controller dynamically load assemblies and instantiates and run classes implementing a common IComponent interface with a single method DoStuff(). Which components that gets loaded is configured via a xml configuration file and by adding new assemblies containing different implementations of IComponent. The components provides utility functions to the main application. While the main program is doing it's thing, e.g. controlling a nuclear plant, the components might be performing utility tasks (in their own threads), e.g. cleaning the database, sending emails, printing funny jokes on the printer, what have you. What I would like, is to have one of these components be able to display a GUI, e.g. with status information for the said email sending component. The lifetime of the complete system looks like this Application starts. Check configuration file for components to load. Load them. For each component, run DoStuff() to initialize it and make it live its own life in their own threads. Continue to do main application-thingy king of work, forever. I have not yet been able to successfully perform point 3 if the component fires up a GUI in DoStuff(). It simply just halts until the GUI is closed. And not until the GUI is closed does the program progress to point 4. It would be great if these components were allowed to start up their own Windows Forms GUIs. Problem When a component tries to fire up a GUI in DoStuff() (the exact line of code is when the component runs Application.Run(theForm) ), the component and hence our system "hangs" at the Application.Run() line until the GUI is closed. Well, the just fired up GUI works fine, as expected. Example of components. One hasn't nothing to do with GUI, whilst the second fires up a cute windows with pink fluffy bunnies in them. public class MyComponent1: IComponent { public string DoStuff(...) { // write something to the database } } public class MyComponent2: IComponent { public void DoStuff() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form()); // I want the thread to immediately return after the GUI // is fired up, so that my main thread can continue to work. } } I have tried this with no luck. Even when I try to fire up the GUI in it's own thread, the execution halts until the GUI as closed. public void DoStuff() { new Thread(ThreadedInitialize).Start() } private void ThreadedInitialize() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form()); } Is it possible to spin off a GUI and return after Application.Run()? ANSWER: Application.Run method displays one (or more) forms and initiates the standard message loop which runs until all the forms are closed. You cannot force a return from that method except by closing all your forms or forcing an application shutdown. You can, however, pass an ApplicationContext (instad of a new Form()) to Application.Run method and ApplicationContext can be used to launch several forms at once. Your application will only end when all of those are closed. See here: http://msdn.microsoft.com/en-us/library/system.windows.forms.application.run.aspx Also, any forms that you Show non-modally will continue to run alongside your main form, which will enable you to have more than one windows that do not block each other. I believe this is actually what you are trying to accomplish.
[ "c#", ".net", "winforms" ]
26
13
1,475
3
0
2008-08-05T21:19:37.280000
2008-08-05T21:45:17.663000
2,873
2,927
Choosing a static code analysis tool
I'm working on a project where I'm coding in C in a UNIX environment. I've been using the lint tool to check my source code. Lint has been around a long time (since 1979), can anyone suggest a more recent code analysis tool I could use? Preferably a tool that is free.
Don't overlook the compiler itself. Read the compiler's documentation and find all the warnings and errors it can provide, and then enable as many as make sense for you. Also make sure to tell your compiler to treat warnings like errors so you're forced to fix them right away ( -Werror on gcc). By the way, don't be fooled -Wall on gcc does not enable all warnings. You may want to check valgrind (free!) — it "automatically detect[s] many memory management and threading bugs, and profile[s] your programs in detail." It isn't a static checker, but it's a great tool!
Choosing a static code analysis tool I'm working on a project where I'm coding in C in a UNIX environment. I've been using the lint tool to check my source code. Lint has been around a long time (since 1979), can anyone suggest a more recent code analysis tool I could use? Preferably a tool that is free.
TITLE: Choosing a static code analysis tool QUESTION: I'm working on a project where I'm coding in C in a UNIX environment. I've been using the lint tool to check my source code. Lint has been around a long time (since 1979), can anyone suggest a more recent code analysis tool I could use? Preferably a tool that is free. ANSWER: Don't overlook the compiler itself. Read the compiler's documentation and find all the warnings and errors it can provide, and then enable as many as make sense for you. Also make sure to tell your compiler to treat warnings like errors so you're forced to fix them right away ( -Werror on gcc). By the way, don't be fooled -Wall on gcc does not enable all warnings. You may want to check valgrind (free!) — it "automatically detect[s] many memory management and threading bugs, and profile[s] your programs in detail." It isn't a static checker, but it's a great tool!
[ "c", "unix", "testing" ]
69
35
58,297
15
0
2008-08-05T21:19:40.913000
2008-08-05T22:17:24.777000
2,898
2,905
Text Editor For Linux (Besides Vi)?
Let me preface this question by saying I use TextMate on Mac OSX for my text needs and I am in love with it. Anything comparable on the Linux platform? I'll mostly use it for coding python/ruby. Doing a google search yielded outdated answers. Edit: Since there has been some concern about the 'merit' of this question. I am about to start a new Ruby Programming Project in Linux and before I got started I wanted to make sure I had the right tools to do the job. Edit #2: I use VIM on a daily basis -- all. the. time. I enjoy using it. I was just looking for some alternatives.
Emacs is a wonderful text editor. It has huge power once you become a power user. You can access a shell, have as many files open as you want in as many sub-windows and an extremely powerful scripting support that lets you add all kinds of neat features. I have been using a ruby-mode which adds syntax highlighting and whatnot to ruby, and the same exists for every major language. If you keep at it, you can use exclusively the keyboard and never touch the mouse, which increases your editing speed by a significant margin. If you want to start with something a lot more basic though, gedit is nice... it has built in syntax highlighting as well for most languages based on the filename extension. It comes with the OS as well (though emacs you can easily install with apt-get or some similar package finder utility). UPDATE: I think gedit is exclusively GUI based though, so it would be useful to learn emacs in case you are stuck with just a shell (it is fully featured in both shell and graphical mode). FURTHER UPDATE: Just FYI, I am not trying to push Emacs over Vim, it's just what I use, and it's a great editor (as I'm sure Vim is too). It is daunting at first (as I'm sure Vim is too), but the question was about text editors on Linux besides vi... Emacs seems the logical choice to me, but gedit is a great simple text editor with some nice features if that's all you are looking for.
Text Editor For Linux (Besides Vi)? Let me preface this question by saying I use TextMate on Mac OSX for my text needs and I am in love with it. Anything comparable on the Linux platform? I'll mostly use it for coding python/ruby. Doing a google search yielded outdated answers. Edit: Since there has been some concern about the 'merit' of this question. I am about to start a new Ruby Programming Project in Linux and before I got started I wanted to make sure I had the right tools to do the job. Edit #2: I use VIM on a daily basis -- all. the. time. I enjoy using it. I was just looking for some alternatives.
TITLE: Text Editor For Linux (Besides Vi)? QUESTION: Let me preface this question by saying I use TextMate on Mac OSX for my text needs and I am in love with it. Anything comparable on the Linux platform? I'll mostly use it for coding python/ruby. Doing a google search yielded outdated answers. Edit: Since there has been some concern about the 'merit' of this question. I am about to start a new Ruby Programming Project in Linux and before I got started I wanted to make sure I had the right tools to do the job. Edit #2: I use VIM on a daily basis -- all. the. time. I enjoy using it. I was just looking for some alternatives. ANSWER: Emacs is a wonderful text editor. It has huge power once you become a power user. You can access a shell, have as many files open as you want in as many sub-windows and an extremely powerful scripting support that lets you add all kinds of neat features. I have been using a ruby-mode which adds syntax highlighting and whatnot to ruby, and the same exists for every major language. If you keep at it, you can use exclusively the keyboard and never touch the mouse, which increases your editing speed by a significant margin. If you want to start with something a lot more basic though, gedit is nice... it has built in syntax highlighting as well for most languages based on the filename extension. It comes with the OS as well (though emacs you can easily install with apt-get or some similar package finder utility). UPDATE: I think gedit is exclusively GUI based though, so it would be useful to learn emacs in case you are stuck with just a shell (it is fully featured in both shell and graphical mode). FURTHER UPDATE: Just FYI, I am not trying to push Emacs over Vim, it's just what I use, and it's a great editor (as I'm sure Vim is too). It is daunting at first (as I'm sure Vim is too), but the question was about text editors on Linux besides vi... Emacs seems the logical choice to me, but gedit is a great simple text editor with some nice features if that's all you are looking for.
[ "linux", "editor" ]
50
43
130,816
34
0
2008-08-05T21:42:37.763000
2008-08-05T21:49:12.180000
2,900
2,975
MySQL/Apache Error in PHP MySQL query
I am getting the following error: Access denied for user 'apache'@'localhost' (using password: NO) When using the following code: Delete Story "; if (mysql_num_rows($result) > 0) { while($row = mysql_fetch_row($result)){ echo ' '.$row[1].' Delete '; echo ' '.$row[2].' '; } } else { echo "No stories available."; }?> The connect.php file contains my MySQL connect calls that are working fine with my INSERT queries in another portion of the software. If I comment out the $result = mysql_query line, then it goes through to the else statement. So, it is that line or the content in the if. I have been searching the net for any solutions, and most seem to be related to too many MySQL connections or that the user I am logging into MySQL as does not have permission. I have checked both. I can still perform my other queries elsewhere in the software, and I have verified that the account has the correct permissions.
And if it matters at all, apache@localhost is not the name of the user account that I use to get into the database. I don't have any user accounts with the name apache in them at all for that matter. If it is saying 'apache@localhost' the username is not getting passed correctly to the MySQL connection. 'apache' is normally the user that runs the httpd process (at least on Redhat-based systems) and if no username is passed during the connection MySQL uses whomever is calling for the connection. If you do the connection right in your script, not in a called file, do you get the same error?
MySQL/Apache Error in PHP MySQL query I am getting the following error: Access denied for user 'apache'@'localhost' (using password: NO) When using the following code: Delete Story "; if (mysql_num_rows($result) > 0) { while($row = mysql_fetch_row($result)){ echo ' '.$row[1].' Delete '; echo ' '.$row[2].' '; } } else { echo "No stories available."; }?> The connect.php file contains my MySQL connect calls that are working fine with my INSERT queries in another portion of the software. If I comment out the $result = mysql_query line, then it goes through to the else statement. So, it is that line or the content in the if. I have been searching the net for any solutions, and most seem to be related to too many MySQL connections or that the user I am logging into MySQL as does not have permission. I have checked both. I can still perform my other queries elsewhere in the software, and I have verified that the account has the correct permissions.
TITLE: MySQL/Apache Error in PHP MySQL query QUESTION: I am getting the following error: Access denied for user 'apache'@'localhost' (using password: NO) When using the following code: Delete Story "; if (mysql_num_rows($result) > 0) { while($row = mysql_fetch_row($result)){ echo ' '.$row[1].' Delete '; echo ' '.$row[2].' '; } } else { echo "No stories available."; }?> The connect.php file contains my MySQL connect calls that are working fine with my INSERT queries in another portion of the software. If I comment out the $result = mysql_query line, then it goes through to the else statement. So, it is that line or the content in the if. I have been searching the net for any solutions, and most seem to be related to too many MySQL connections or that the user I am logging into MySQL as does not have permission. I have checked both. I can still perform my other queries elsewhere in the software, and I have verified that the account has the correct permissions. ANSWER: And if it matters at all, apache@localhost is not the name of the user account that I use to get into the database. I don't have any user accounts with the name apache in them at all for that matter. If it is saying 'apache@localhost' the username is not getting passed correctly to the MySQL connection. 'apache' is normally the user that runs the httpd process (at least on Redhat-based systems) and if no username is passed during the connection MySQL uses whomever is calling for the connection. If you do the connection right in your script, not in a called file, do you get the same error?
[ "php", "mysql", "apache" ]
29
12
9,896
11
0
2008-08-05T21:45:11.033000
2008-08-06T00:05:34.790000
2,913
2,918
How to Test Web Code?
Does anyone have some good hints for writing test code for database-backend development where there is a heavy dependency on state? Specifically, I want to write tests for code that retrieve records from the database, but the answers will depend on the data in the database (which may change over time). Do people usually make a separate development system with a 'frozen' database so that any given function should always return the exact same result set? I am quite sure this is not a new issue, so I would be very interested to learn from other people's experience. Are there good articles out there that discuss this issue of web-based development in general? I usually write PHP code, but I would expect all of these issues are largely language and framework agnostic.
You should look into DBUnit, or try to find a PHP equivalent (there must be one out there). You can use it to prepare the database with a specific set of data which represents your test data, and thus each test will no longer depend on the database and some existing state. This way, each test is self contained and will not break during further database usage. Update: A quick google search showed a DB unit extension for PHPUnit.
How to Test Web Code? Does anyone have some good hints for writing test code for database-backend development where there is a heavy dependency on state? Specifically, I want to write tests for code that retrieve records from the database, but the answers will depend on the data in the database (which may change over time). Do people usually make a separate development system with a 'frozen' database so that any given function should always return the exact same result set? I am quite sure this is not a new issue, so I would be very interested to learn from other people's experience. Are there good articles out there that discuss this issue of web-based development in general? I usually write PHP code, but I would expect all of these issues are largely language and framework agnostic.
TITLE: How to Test Web Code? QUESTION: Does anyone have some good hints for writing test code for database-backend development where there is a heavy dependency on state? Specifically, I want to write tests for code that retrieve records from the database, but the answers will depend on the data in the database (which may change over time). Do people usually make a separate development system with a 'frozen' database so that any given function should always return the exact same result set? I am quite sure this is not a new issue, so I would be very interested to learn from other people's experience. Are there good articles out there that discuss this issue of web-based development in general? I usually write PHP code, but I would expect all of these issues are largely language and framework agnostic. ANSWER: You should look into DBUnit, or try to find a PHP equivalent (there must be one out there). You can use it to prepare the database with a specific set of data which represents your test data, and thus each test will no longer depend on the database and some existing state. This way, each test is self contained and will not break during further database usage. Update: A quick google search showed a DB unit extension for PHPUnit.
[ "database", "testing" ]
17
6
2,086
10
0
2008-08-05T21:58:51.927000
2008-08-05T22:03:29.750000
2,914
2,917
How can I detect if a browser is blocking a popup?
Occasionally, I've come across a webpage that tries to pop open a new window (for user input, or something important), but the popup blocker prevents this from happening. What methods can the calling window use to make sure the new window launched properly?
If you use JavaScript to open the popup, you can use something like this: var newWin = window.open(url); if(!newWin || newWin.closed || typeof newWin.closed=='undefined') { //POPUP BLOCKED }
How can I detect if a browser is blocking a popup? Occasionally, I've come across a webpage that tries to pop open a new window (for user input, or something important), but the popup blocker prevents this from happening. What methods can the calling window use to make sure the new window launched properly?
TITLE: How can I detect if a browser is blocking a popup? QUESTION: Occasionally, I've come across a webpage that tries to pop open a new window (for user input, or something important), but the popup blocker prevents this from happening. What methods can the calling window use to make sure the new window launched properly? ANSWER: If you use JavaScript to open the popup, you can use something like this: var newWin = window.open(url); if(!newWin || newWin.closed || typeof newWin.closed=='undefined') { //POPUP BLOCKED }
[ "javascript", "html", "popup" ]
165
207
143,178
9
0
2008-08-05T22:01:36.977000
2008-08-05T22:03:27.953000
2,933
2,937
Create a directly-executable cross-platform GUI app using Python
Python works on multiple platforms and can be used for desktop and web applications, thus I conclude that there is some way to compile it into an executable for Mac, Windows and Linux. The problem being I have no idea where to start or how to write a GUI with it, can anybody shed some light on this and point me in the right direction please?
First you will need some GUI library with Python bindings and then (if you want) some program that will convert your python scripts into standalone executables. Cross-platform GUI libraries with Python bindings (Windows, Linux, Mac) Of course, there are many, but the most popular that I've seen in wild are: Tkinter - based on Tk GUI toolkit. De-facto standard GUI library for python, free for commercial projects. WxPython - based on WxWidgets. Popular, and free for commercial projects. Qt using the PyQt bindings or Qt for Python. The former is not free for commercial projects. The latter is less mature, but can be used for free. Qt itself supposedly supports Android and iOS as well, but achiving same with it's bindings should be tricky. Kivy written in Python for Python (update 2023). Supposedly supports Android and iOS as well. Note that users of WxWidgets (hence WxPython users), often need to use WxQt as well, because WxWidgets 's own GUI is not yet at Qt 's level (at time of writting). Complete list is at http://wiki.python.org/moin/GuiProgramming Stand-alone/ single executables For all platforms: PyInstaller - The most active (which could also be used with PyQt ) fbs - if you chose Qt above (commercial, with free plan) For Windows: py2exe - used to be the most popular For Linux: Freeze - works the same way like py2exe but targets Linux platform For MacOS: py2app - again, works like py2exe but targets Mac OS
Create a directly-executable cross-platform GUI app using Python Python works on multiple platforms and can be used for desktop and web applications, thus I conclude that there is some way to compile it into an executable for Mac, Windows and Linux. The problem being I have no idea where to start or how to write a GUI with it, can anybody shed some light on this and point me in the right direction please?
TITLE: Create a directly-executable cross-platform GUI app using Python QUESTION: Python works on multiple platforms and can be used for desktop and web applications, thus I conclude that there is some way to compile it into an executable for Mac, Windows and Linux. The problem being I have no idea where to start or how to write a GUI with it, can anybody shed some light on this and point me in the right direction please? ANSWER: First you will need some GUI library with Python bindings and then (if you want) some program that will convert your python scripts into standalone executables. Cross-platform GUI libraries with Python bindings (Windows, Linux, Mac) Of course, there are many, but the most popular that I've seen in wild are: Tkinter - based on Tk GUI toolkit. De-facto standard GUI library for python, free for commercial projects. WxPython - based on WxWidgets. Popular, and free for commercial projects. Qt using the PyQt bindings or Qt for Python. The former is not free for commercial projects. The latter is less mature, but can be used for free. Qt itself supposedly supports Android and iOS as well, but achiving same with it's bindings should be tricky. Kivy written in Python for Python (update 2023). Supposedly supports Android and iOS as well. Note that users of WxWidgets (hence WxPython users), often need to use WxQt as well, because WxWidgets 's own GUI is not yet at Qt 's level (at time of writting). Complete list is at http://wiki.python.org/moin/GuiProgramming Stand-alone/ single executables For all platforms: PyInstaller - The most active (which could also be used with PyQt ) fbs - if you chose Qt above (commercial, with free plan) For Windows: py2exe - used to be the most popular For Linux: Freeze - works the same way like py2exe but targets Linux platform For MacOS: py2app - again, works like py2exe but targets Mac OS
[ "python", "user-interface", "deployment", "tkinter", "release-management" ]
311
315
224,710
14
0
2008-08-05T22:26:00.797000
2008-08-05T22:34:25.397000
2,968
2,985
What are the different methods to parse strings in Java?
For parsing player commands, I've most often used the split method to split a string by delimiters and then to then just figure out the rest by a series of if s or switch es. What are some different ways of parsing strings in Java?
I assume you're trying to make the command interface as forgiving as possible. If this is the case, I suggest you use an algorithm similar to this: Read in the string Split the string into tokens Use a dictionary to convert synonyms to a common form For example, convert "hit", "punch", "strike", and "kick" all to "hit" Perform actions on an unordered, inclusive base Unordered - "punch the monkey in the face" is the same thing as "the face in the monkey punch" Inclusive - If the command is supposed to be "punch the monkey in the face" and they supply "punch monkey", you should check how many commands this matches. If only one command, do this action. It might even be a good idea to have command priorities, and even if there were even matches, it would perform the top action.
What are the different methods to parse strings in Java? For parsing player commands, I've most often used the split method to split a string by delimiters and then to then just figure out the rest by a series of if s or switch es. What are some different ways of parsing strings in Java?
TITLE: What are the different methods to parse strings in Java? QUESTION: For parsing player commands, I've most often used the split method to split a string by delimiters and then to then just figure out the rest by a series of if s or switch es. What are some different ways of parsing strings in Java? ANSWER: I assume you're trying to make the command interface as forgiving as possible. If this is the case, I suggest you use an algorithm similar to this: Read in the string Split the string into tokens Use a dictionary to convert synonyms to a common form For example, convert "hit", "punch", "strike", and "kick" all to "hit" Perform actions on an unordered, inclusive base Unordered - "punch the monkey in the face" is the same thing as "the face in the monkey punch" Inclusive - If the command is supposed to be "punch the monkey in the face" and they supply "punch monkey", you should check how many commands this matches. If only one command, do this action. It might even be a good idea to have command priorities, and even if there were even matches, it would perform the top action.
[ "java", "string", "parsing" ]
55
17
68,359
15
0
2008-08-05T23:49:53.560000
2008-08-06T00:42:00.817000
2,970
2,976
My website got hacked.. What should I do?
My dad called me today and said people going to his website were getting 168 viruses trying to download to their computers. He isn't technical at all, and built the whole thing with a WYSIWYG editor. I popped his site open and viewed the source, and there was a line of Javascript includes at the bottom of the source right before the closing HTML tag. They included this file (among many others): http://www.98hs.ru/js.js <-- TURN OFF JAVASCRIPT BEFORE YOU GO TO THAT URL. So I commented it out for now. It turns out his FTP password was a plain dictionary word six letters long, so we think that's how it got hacked. We've changed his password to an 8+ digit non-word string (he wouldn't go for a passphrase since he is a hunt-n-peck typer). I did a whois on 98hs.ru and found it is hosted from a server in Chile. There is actually an e-mail address associated with it too, but I seriously doubt this person is the culprit. Probably just some other site that got hacked... I have no idea what to do at this point though as I've never dealt with this sort of thing before. Anyone have any suggestions? He was using plain jane un-secured ftp through webhost4life.com. I don't even see a way to do sftp on their site. I'm thinking his username and password got intercepted? So, to make this more relevant to the community, what are the steps you should take/best practices you should follow to protect your website from getting hacked? For the record, here is the line of code that "magically" got added to his file (and isn't in his file on his computer -- I've left it commented out just to make absolute sure it won't do anything on this page, although I'm sure Jeff would guard against this):
Try and gather as much information as you can. See if the host can give you a log showing all the FTP connections that were made to your account. You can use those to see if it was even an FTP connection that was used to make the change and possibly get an IP address. If you're using a prepacked software like Wordpress, Drupal, or anything else that you didn't code there may be vulnerabilities in upload code that allows for this sort of modification. If it is custom built, double check any places where you allow users to upload files or modify existing files. The second thing would be to take a dump of the site as-is and check everything for other modifications. It may just be one single modification they made, but if they got in via FTP who knows what else is up there. Revert your site back to a known good status and, if need be, upgrade to the latest version. There is a level of return you have to take into account too. Is the damage worth trying to track the person down or is this something where you just live and learn and use stronger passwords?
My website got hacked.. What should I do? My dad called me today and said people going to his website were getting 168 viruses trying to download to their computers. He isn't technical at all, and built the whole thing with a WYSIWYG editor. I popped his site open and viewed the source, and there was a line of Javascript includes at the bottom of the source right before the closing HTML tag. They included this file (among many others): http://www.98hs.ru/js.js <-- TURN OFF JAVASCRIPT BEFORE YOU GO TO THAT URL. So I commented it out for now. It turns out his FTP password was a plain dictionary word six letters long, so we think that's how it got hacked. We've changed his password to an 8+ digit non-word string (he wouldn't go for a passphrase since he is a hunt-n-peck typer). I did a whois on 98hs.ru and found it is hosted from a server in Chile. There is actually an e-mail address associated with it too, but I seriously doubt this person is the culprit. Probably just some other site that got hacked... I have no idea what to do at this point though as I've never dealt with this sort of thing before. Anyone have any suggestions? He was using plain jane un-secured ftp through webhost4life.com. I don't even see a way to do sftp on their site. I'm thinking his username and password got intercepted? So, to make this more relevant to the community, what are the steps you should take/best practices you should follow to protect your website from getting hacked? For the record, here is the line of code that "magically" got added to his file (and isn't in his file on his computer -- I've left it commented out just to make absolute sure it won't do anything on this page, although I'm sure Jeff would guard against this):
TITLE: My website got hacked.. What should I do? QUESTION: My dad called me today and said people going to his website were getting 168 viruses trying to download to their computers. He isn't technical at all, and built the whole thing with a WYSIWYG editor. I popped his site open and viewed the source, and there was a line of Javascript includes at the bottom of the source right before the closing HTML tag. They included this file (among many others): http://www.98hs.ru/js.js <-- TURN OFF JAVASCRIPT BEFORE YOU GO TO THAT URL. So I commented it out for now. It turns out his FTP password was a plain dictionary word six letters long, so we think that's how it got hacked. We've changed his password to an 8+ digit non-word string (he wouldn't go for a passphrase since he is a hunt-n-peck typer). I did a whois on 98hs.ru and found it is hosted from a server in Chile. There is actually an e-mail address associated with it too, but I seriously doubt this person is the culprit. Probably just some other site that got hacked... I have no idea what to do at this point though as I've never dealt with this sort of thing before. Anyone have any suggestions? He was using plain jane un-secured ftp through webhost4life.com. I don't even see a way to do sftp on their site. I'm thinking his username and password got intercepted? So, to make this more relevant to the community, what are the steps you should take/best practices you should follow to protect your website from getting hacked? For the record, here is the line of code that "magically" got added to his file (and isn't in his file on his computer -- I've left it commented out just to make absolute sure it won't do anything on this page, although I'm sure Jeff would guard against this): ANSWER: Try and gather as much information as you can. See if the host can give you a log showing all the FTP connections that were made to your account. You can use those to see if it was even an FTP connection that was used to make the change and possibly get an IP address. If you're using a prepacked software like Wordpress, Drupal, or anything else that you didn't code there may be vulnerabilities in upload code that allows for this sort of modification. If it is custom built, double check any places where you allow users to upload files or modify existing files. The second thing would be to take a dump of the site as-is and check everything for other modifications. It may just be one single modification they made, but if they got in via FTP who knows what else is up there. Revert your site back to a known good status and, if need be, upgrade to the latest version. There is a level of return you have to take into account too. Is the damage worth trying to track the person down or is this something where you just live and learn and use stronger passwords?
[ "security", "cracking" ]
23
15
4,314
8
0
2008-08-05T23:55:25.700000
2008-08-06T00:16:07.797000
2,987
2,992
Bringing Window to the Front in C# using Win32 API
I am writing an application that needs to bring window of an external app to the foreground, and not necessarily steal focus (there is a setting the user can toggle to steal/not steal focus). What is the best way to go about this using the win32 API? I have tried SetForeground() but it always steals focus and does not consistenly work. What is the best way to go about this? Any thoughts?
SetForegroundWindow is supposed to steal focus and there are certain cases where it will fail. The SetForegroundWindow function puts the thread that created the specified window into the foreground and activates the window. Keyboard input is directed to the window Try capturing the focus with SetCapture prior to making the call. Also look into different ways of bringing the window to the front: SetForeGroundWindow, SetActiveWindow, even simulating a mouse click can do this.
Bringing Window to the Front in C# using Win32 API I am writing an application that needs to bring window of an external app to the foreground, and not necessarily steal focus (there is a setting the user can toggle to steal/not steal focus). What is the best way to go about this using the win32 API? I have tried SetForeground() but it always steals focus and does not consistenly work. What is the best way to go about this? Any thoughts?
TITLE: Bringing Window to the Front in C# using Win32 API QUESTION: I am writing an application that needs to bring window of an external app to the foreground, and not necessarily steal focus (there is a setting the user can toggle to steal/not steal focus). What is the best way to go about this using the win32 API? I have tried SetForeground() but it always steals focus and does not consistenly work. What is the best way to go about this? Any thoughts? ANSWER: SetForegroundWindow is supposed to steal focus and there are certain cases where it will fail. The SetForegroundWindow function puts the thread that created the specified window into the foreground and activates the window. Keyboard input is directed to the window Try capturing the focus with SetCapture prior to making the call. Also look into different ways of bringing the window to the front: SetForeGroundWindow, SetActiveWindow, even simulating a mouse click can do this.
[ "c#", "winapi" ]
47
17
17,062
6
0
2008-08-06T00:55:48.277000
2008-08-06T01:06:45.197000
2,988
2,999
What problems can be solved, or tackled more easily, using graphs and trees?
What are the most common problems that can be solved with both these data structures? It would be good for me to have also recommendations on books that: Implement the structures Implement and explain the reasoning of the algorithms that use them
The first thing I think about when I read this question is: what types of things use graphs/trees? and then I think backwards to how I could use them. For example, take two common uses of a tree: The DOM File systems The DOM, and XML for that matter, resemble tree structures. It makes sense, too. It makes sense because of how this data needs to be arranged. A file system, too. On a UNIX system there's a root node, and branching down below. When you mount a new device, you're attaching it onto the tree. You should also be asking yourself: does the data fall into this type of structure? Create data structures that make sense to the problem and the rest will follow. As far as being easier, I think thats relative. Are you good with recursive functions to traverse a tree/graph? What if you need to balance the tree? Think about a program that solves a word search puzzle. You could map out all the letters of the word search into a graph and check surrounding nodes to see if that string is matching any of the words. But couldn't you just do the same with with a single array? All you really need to do is move an index to check letters to the left and right, and by the width to check above and below letters. Solving this problem with a graph isn't difficult, but it can create a lot of extra work and difficulty if you're not comfortable with using them - of course that shouldn't discourage you from doing it, especially if you are learning about them. I hope that helps you think about these structures. As for a book recommendation, I'd have to go with Introduction to Algorithms.
What problems can be solved, or tackled more easily, using graphs and trees? What are the most common problems that can be solved with both these data structures? It would be good for me to have also recommendations on books that: Implement the structures Implement and explain the reasoning of the algorithms that use them
TITLE: What problems can be solved, or tackled more easily, using graphs and trees? QUESTION: What are the most common problems that can be solved with both these data structures? It would be good for me to have also recommendations on books that: Implement the structures Implement and explain the reasoning of the algorithms that use them ANSWER: The first thing I think about when I read this question is: what types of things use graphs/trees? and then I think backwards to how I could use them. For example, take two common uses of a tree: The DOM File systems The DOM, and XML for that matter, resemble tree structures. It makes sense, too. It makes sense because of how this data needs to be arranged. A file system, too. On a UNIX system there's a root node, and branching down below. When you mount a new device, you're attaching it onto the tree. You should also be asking yourself: does the data fall into this type of structure? Create data structures that make sense to the problem and the rest will follow. As far as being easier, I think thats relative. Are you good with recursive functions to traverse a tree/graph? What if you need to balance the tree? Think about a program that solves a word search puzzle. You could map out all the letters of the word search into a graph and check surrounding nodes to see if that string is matching any of the words. But couldn't you just do the same with with a single array? All you really need to do is move an index to check letters to the left and right, and by the width to check above and below letters. Solving this problem with a graph isn't difficult, but it can create a lot of extra work and difficulty if you're not comfortable with using them - of course that shouldn't discourage you from doing it, especially if you are learning about them. I hope that helps you think about these structures. As for a book recommendation, I'd have to go with Introduction to Algorithms.
[ "algorithm", "data-structures", "tree", "computer-science", "graph-theory" ]
17
17
5,999
10
0
2008-08-06T00:56:05.937000
2008-08-06T01:28:13.063000
2,993
5,544,777
Reverse DNS in Ruby?
I'm in an environment with a lot of computers that haven't been properly inventoried. Basically, no one knows which IP goes with which mac address and which hostname. So I wrote the following: # This script goes down the entire IP range and attempts to # retrieve the Hostname and mac address and outputs them # into a file. Yay! require "socket" TwoOctets = "10.26" def computer_exists?(computerip) system("ping -c 1 -W 1 #{computerip}") end def append_to_file(line) file = File.open("output.txt", "a") file.puts(line) file.close end def getInfo(current_ip) begin if computer_exists?(current_ip) arp_output = `arp -v #{current_ip}` mac_addr = arp_output.to_s.match(/..:..:..:..:..:../) host_name = Socket.gethostbyname(current_ip) append_to_file("#{host_name[0]} - #{current_ip} - #{mac_addr}\n") end rescue SocketError => mySocketError append_to_file("unknown - #{current_ip} - #{mac_addr}") end end (6..8).each do |i| case i when 6 for j in (1..190) current_ip = "#{TwoOctets}.#{i}.#{j}" getInfo(current_ip) end when 7 for j in (1..255) current_ip = "#{TwoOctets}.#{i}.#{j}" getInfo(current_ip) end when 8 for j in (1..52) current_ip = "#{TwoOctets}.#{i}.#{j}" getInfo(current_ip) end end end Everything works except it does not find a Reverse DNS. Sample output that I'm getting is this: 10.26.6.12 - 10.26.6.12 - 00:11:11:9B:13:9F 10.26.6.17 - 10.26.6.17 - 08:00:69:9A:97:C3 10.26.6.18 - 10.26.6.18 - 08:00:69:93:2C:E2 If I do nslookup 10.26.6.12 then I get the correct reverse DNS so that shows that my machine is seeing the DNS server. I have tried Socket.gethostbyname, gethostbyaddr, but it doesn't work. Any guidance will be much appreciated.
Today I also needed reverse DNS lookup and I've found very simple standard solution: require 'resolv' host_name = Resolv.getname(ip_address_here) It seems it uses timeout which helps in rough cases.
Reverse DNS in Ruby? I'm in an environment with a lot of computers that haven't been properly inventoried. Basically, no one knows which IP goes with which mac address and which hostname. So I wrote the following: # This script goes down the entire IP range and attempts to # retrieve the Hostname and mac address and outputs them # into a file. Yay! require "socket" TwoOctets = "10.26" def computer_exists?(computerip) system("ping -c 1 -W 1 #{computerip}") end def append_to_file(line) file = File.open("output.txt", "a") file.puts(line) file.close end def getInfo(current_ip) begin if computer_exists?(current_ip) arp_output = `arp -v #{current_ip}` mac_addr = arp_output.to_s.match(/..:..:..:..:..:../) host_name = Socket.gethostbyname(current_ip) append_to_file("#{host_name[0]} - #{current_ip} - #{mac_addr}\n") end rescue SocketError => mySocketError append_to_file("unknown - #{current_ip} - #{mac_addr}") end end (6..8).each do |i| case i when 6 for j in (1..190) current_ip = "#{TwoOctets}.#{i}.#{j}" getInfo(current_ip) end when 7 for j in (1..255) current_ip = "#{TwoOctets}.#{i}.#{j}" getInfo(current_ip) end when 8 for j in (1..52) current_ip = "#{TwoOctets}.#{i}.#{j}" getInfo(current_ip) end end end Everything works except it does not find a Reverse DNS. Sample output that I'm getting is this: 10.26.6.12 - 10.26.6.12 - 00:11:11:9B:13:9F 10.26.6.17 - 10.26.6.17 - 08:00:69:9A:97:C3 10.26.6.18 - 10.26.6.18 - 08:00:69:93:2C:E2 If I do nslookup 10.26.6.12 then I get the correct reverse DNS so that shows that my machine is seeing the DNS server. I have tried Socket.gethostbyname, gethostbyaddr, but it doesn't work. Any guidance will be much appreciated.
TITLE: Reverse DNS in Ruby? QUESTION: I'm in an environment with a lot of computers that haven't been properly inventoried. Basically, no one knows which IP goes with which mac address and which hostname. So I wrote the following: # This script goes down the entire IP range and attempts to # retrieve the Hostname and mac address and outputs them # into a file. Yay! require "socket" TwoOctets = "10.26" def computer_exists?(computerip) system("ping -c 1 -W 1 #{computerip}") end def append_to_file(line) file = File.open("output.txt", "a") file.puts(line) file.close end def getInfo(current_ip) begin if computer_exists?(current_ip) arp_output = `arp -v #{current_ip}` mac_addr = arp_output.to_s.match(/..:..:..:..:..:../) host_name = Socket.gethostbyname(current_ip) append_to_file("#{host_name[0]} - #{current_ip} - #{mac_addr}\n") end rescue SocketError => mySocketError append_to_file("unknown - #{current_ip} - #{mac_addr}") end end (6..8).each do |i| case i when 6 for j in (1..190) current_ip = "#{TwoOctets}.#{i}.#{j}" getInfo(current_ip) end when 7 for j in (1..255) current_ip = "#{TwoOctets}.#{i}.#{j}" getInfo(current_ip) end when 8 for j in (1..52) current_ip = "#{TwoOctets}.#{i}.#{j}" getInfo(current_ip) end end end Everything works except it does not find a Reverse DNS. Sample output that I'm getting is this: 10.26.6.12 - 10.26.6.12 - 00:11:11:9B:13:9F 10.26.6.17 - 10.26.6.17 - 08:00:69:9A:97:C3 10.26.6.18 - 10.26.6.18 - 08:00:69:93:2C:E2 If I do nslookup 10.26.6.12 then I get the correct reverse DNS so that shows that my machine is seeing the DNS server. I have tried Socket.gethostbyname, gethostbyaddr, but it doesn't work. Any guidance will be much appreciated. ANSWER: Today I also needed reverse DNS lookup and I've found very simple standard solution: require 'resolv' host_name = Resolv.getname(ip_address_here) It seems it uses timeout which helps in rough cases.
[ "ruby", "sockets", "dns", "nslookup" ]
22
25
11,235
3
0
2008-08-06T01:07:52.933000
2011-04-04T21:52:07.477000
3,004
3,008
Using ASP.NET Dynamic Data / LINQ to SQL, how do you have two table fields have a relationship to the same foreign key?
I am using ASP.NET Dynamic Data for a project and I have a table that has two seperate fields that link to the same foreign key in a different table. This relationship works fine in SQL Server. However, in the LINQ to SQL model in the ASP.NET Dynamic Data model, only the first field's relationship is reflected. If I attempt to add the second relationship manually, it complains that it "Cannot create an association "ForeignTable_BaseTable". The same property is listed more than once: "Id"." This MSDN article gives such helpful advice as: Examine the message and note the property specified in the message. Click OK to dismiss the message box. Inspect the Association Properties and remove the duplicate entries. Click OK.
The solution is to delete and re-add BOTH tables to the LINQ to SQL diagram, not just the one you have added the second field and keys to. Alternatively, it appears you can make two associations using the LINQ to SQL interface - just don't try and bundle them into a single association.
Using ASP.NET Dynamic Data / LINQ to SQL, how do you have two table fields have a relationship to the same foreign key? I am using ASP.NET Dynamic Data for a project and I have a table that has two seperate fields that link to the same foreign key in a different table. This relationship works fine in SQL Server. However, in the LINQ to SQL model in the ASP.NET Dynamic Data model, only the first field's relationship is reflected. If I attempt to add the second relationship manually, it complains that it "Cannot create an association "ForeignTable_BaseTable". The same property is listed more than once: "Id"." This MSDN article gives such helpful advice as: Examine the message and note the property specified in the message. Click OK to dismiss the message box. Inspect the Association Properties and remove the duplicate entries. Click OK.
TITLE: Using ASP.NET Dynamic Data / LINQ to SQL, how do you have two table fields have a relationship to the same foreign key? QUESTION: I am using ASP.NET Dynamic Data for a project and I have a table that has two seperate fields that link to the same foreign key in a different table. This relationship works fine in SQL Server. However, in the LINQ to SQL model in the ASP.NET Dynamic Data model, only the first field's relationship is reflected. If I attempt to add the second relationship manually, it complains that it "Cannot create an association "ForeignTable_BaseTable". The same property is listed more than once: "Id"." This MSDN article gives such helpful advice as: Examine the message and note the property specified in the message. Click OK to dismiss the message box. Inspect the Association Properties and remove the duplicate entries. Click OK. ANSWER: The solution is to delete and re-add BOTH tables to the LINQ to SQL diagram, not just the one you have added the second field and keys to. Alternatively, it appears you can make two associations using the LINQ to SQL interface - just don't try and bundle them into a single association.
[ "asp.net", "dynamic-data" ]
14
5
2,271
1
0
2008-08-06T01:42:51.333000
2008-08-06T01:53:45.510000
3,017
3,029
How can we generate getters and setters in Visual Studio?
By "generate", I mean auto-generation of the code necessary for a particular selected (set of) variable(s). But any more explicit explication or comment on good practice is welcome.
Rather than using Ctrl + K, X you can also just type prop and then hit Tab twice.
How can we generate getters and setters in Visual Studio? By "generate", I mean auto-generation of the code necessary for a particular selected (set of) variable(s). But any more explicit explication or comment on good practice is welcome.
TITLE: How can we generate getters and setters in Visual Studio? QUESTION: By "generate", I mean auto-generation of the code necessary for a particular selected (set of) variable(s). But any more explicit explication or comment on good practice is welcome. ANSWER: Rather than using Ctrl + K, X you can also just type prop and then hit Tab twice.
[ "c#", "visual-studio", "setter", "getter" ]
261
336
577,809
16
0
2008-08-06T02:15:14.123000
2008-08-06T02:43:21.477000
3,033
3,360
What's the safest way to iterate through the keys of a Perl hash?
If I have a Perl hash with a bunch of (key, value) pairs, what is the preferred method of iterating through all the keys? I have heard that using each may in some way have unintended side effects. So, is that true, and is one of the two following methods best, or is there a better way? # Method 1 while (my ($key, $value) = each(%hash)) { # Something } # Method 2 foreach my $key (keys(%hash)) { # Something }
The rule of thumb is to use the function most suited to your needs. If you just want the keys and do not plan to ever read any of the values, use keys(): foreach my $key (keys %hash) {... } If you just want the values, use values(): foreach my $val (values %hash) {... } If you need the keys and the values, use each(): keys %hash; # reset the internal iterator so a prior each() doesn't affect the loop while(my($k, $v) = each %hash) {... } If you plan to change the keys of the hash in any way except for deleting the current key during the iteration, then you must not use each(). For example, this code to create a new set of uppercase keys with doubled values works fine using keys(): %h = (a => 1, b => 2); foreach my $k (keys %h) { $h{uc $k} = $h{$k} * 2; } producing the expected resulting hash: (a => 1, A => 2, b => 2, B => 4) But using each() to do the same thing: %h = (a => 1, b => 2); keys %h; while(my($k, $v) = each %h) { $h{uc $k} = $h{$k} * 2; # BAD IDEA! } produces incorrect results in hard-to-predict ways. For example: (a => 1, A => 2, b => 2, B => 8) This, however, is safe: keys %h; while(my($k, $v) = each %h) { if(...) { delete $h{$k}; # This is safe } } All of this is described in the perl documentation: % perldoc -f keys % perldoc -f each
What's the safest way to iterate through the keys of a Perl hash? If I have a Perl hash with a bunch of (key, value) pairs, what is the preferred method of iterating through all the keys? I have heard that using each may in some way have unintended side effects. So, is that true, and is one of the two following methods best, or is there a better way? # Method 1 while (my ($key, $value) = each(%hash)) { # Something } # Method 2 foreach my $key (keys(%hash)) { # Something }
TITLE: What's the safest way to iterate through the keys of a Perl hash? QUESTION: If I have a Perl hash with a bunch of (key, value) pairs, what is the preferred method of iterating through all the keys? I have heard that using each may in some way have unintended side effects. So, is that true, and is one of the two following methods best, or is there a better way? # Method 1 while (my ($key, $value) = each(%hash)) { # Something } # Method 2 foreach my $key (keys(%hash)) { # Something } ANSWER: The rule of thumb is to use the function most suited to your needs. If you just want the keys and do not plan to ever read any of the values, use keys(): foreach my $key (keys %hash) {... } If you just want the values, use values(): foreach my $val (values %hash) {... } If you need the keys and the values, use each(): keys %hash; # reset the internal iterator so a prior each() doesn't affect the loop while(my($k, $v) = each %hash) {... } If you plan to change the keys of the hash in any way except for deleting the current key during the iteration, then you must not use each(). For example, this code to create a new set of uppercase keys with doubled values works fine using keys(): %h = (a => 1, b => 2); foreach my $k (keys %h) { $h{uc $k} = $h{$k} * 2; } producing the expected resulting hash: (a => 1, A => 2, b => 2, B => 4) But using each() to do the same thing: %h = (a => 1, b => 2); keys %h; while(my($k, $v) = each %h) { $h{uc $k} = $h{$k} * 2; # BAD IDEA! } produces incorrect results in hard-to-predict ways. For example: (a => 1, A => 2, b => 2, B => 8) This, however, is safe: keys %h; while(my($k, $v) = each %h) { if(...) { delete $h{$k}; # This is safe } } All of this is described in the perl documentation: % perldoc -f keys % perldoc -f each
[ "perl", "hash", "iteration", "each" ]
123
233
141,095
9
0
2008-08-06T02:53:13.033000
2008-08-06T13:22:14.620000
3,045
3,053
Linking two Office documents
Problem: I have two spreadsheets that each serve different purposes but contain one particular piece of data that needs to be the same in both spreadsheets. This piece of data (one of the columns) gets updated in spreadsheet A but needs to also be updated in spreadsheet B. Goal: A solution that would somehow link these two spreadsheets together (keep in mind that they exist on two separate LAN shares on the network) so that when A is updated, B is automatically updated for the corresponding record. *Note that I understand fully that a database would probably be a better plan for tasks such as these but unfortunately I have no say in that matter. **Note also that this needs to work for Office 2003 and Office 2007
So you mean that AD743 on spreadsheet B must be equal to AD743 on spreadsheet A? Try this: Open both spreadsheets on the same machine. Go to AD743 on spreadsheet B. Type =. Go to spreadsheed A and click on AD743. Press enter. You'll notice that the formula is something like ' [path-to-file+file-name].worksheet-name!AD743 '. The value on spreadsheet B will be updated when you open it. In fact, it will ask you if you want to update. Of course, your connection must be up and running for it to update. Also, you can't change the name or the path of spreadsheet A.
Linking two Office documents Problem: I have two spreadsheets that each serve different purposes but contain one particular piece of data that needs to be the same in both spreadsheets. This piece of data (one of the columns) gets updated in spreadsheet A but needs to also be updated in spreadsheet B. Goal: A solution that would somehow link these two spreadsheets together (keep in mind that they exist on two separate LAN shares on the network) so that when A is updated, B is automatically updated for the corresponding record. *Note that I understand fully that a database would probably be a better plan for tasks such as these but unfortunately I have no say in that matter. **Note also that this needs to work for Office 2003 and Office 2007
TITLE: Linking two Office documents QUESTION: Problem: I have two spreadsheets that each serve different purposes but contain one particular piece of data that needs to be the same in both spreadsheets. This piece of data (one of the columns) gets updated in spreadsheet A but needs to also be updated in spreadsheet B. Goal: A solution that would somehow link these two spreadsheets together (keep in mind that they exist on two separate LAN shares on the network) so that when A is updated, B is automatically updated for the corresponding record. *Note that I understand fully that a database would probably be a better plan for tasks such as these but unfortunately I have no say in that matter. **Note also that this needs to work for Office 2003 and Office 2007 ANSWER: So you mean that AD743 on spreadsheet B must be equal to AD743 on spreadsheet A? Try this: Open both spreadsheets on the same machine. Go to AD743 on spreadsheet B. Type =. Go to spreadsheed A and click on AD743. Press enter. You'll notice that the formula is something like ' [path-to-file+file-name].worksheet-name!AD743 '. The value on spreadsheet B will be updated when you open it. In fact, it will ask you if you want to update. Of course, your connection must be up and running for it to update. Also, you can't change the name or the path of spreadsheet A.
[ "office-2007", "office-2003" ]
14
5
554
2
0
2008-08-06T03:14:59.933000
2008-08-06T03:25:25.917000
3,049
3,054
How do I configure and communicate with a serial port?
I need to send and receive data over serial connections (RS-232 and RS-422). How do I set up and communicate with such a connection? How do I figure out what the configuration settings (e.g. baud rate) should be and how do I set them? In particular, I am looking to do this in Java, C/C++, or one of the major Unix shells but I also have some interest in serial programming using Windows/Hyperterminal.
Build a time machine and go back to 1987? Ho ho. Ok, no more snarky comments. How do I figure out what the configuration settings (e.g. baud rate) should be... Read the datasheet? Ok, ok. Seriously, last one. If you don't know the baud rate of the device you are trying to communicate with, you have two choices. Start guessing, or possibly bust out an o-scope. If you need a good starting point, let me suggest 9600-8-N-1. My suspicion is you can get there with brute force relatively quickly. There's a third option of having an old-school ninja who can tell just by the LOOK of the garbled characters at some standard baud rate what actual baud rate is. An impressive party trick to be sure. Hopefully though you have access to this information. In unix/linux, you can get ahold of minicom to play with the serial port directly. This should make it fairly quick to get the configuration figured out. one of the major Unix shells In Unix the serial port(s) is/are file-mapped into the /dev/ subdir. ttyS0, for example. If you setup the correct baud rate and whatnot using minicom, you can even cat stuff to that file to send stuff out there. On to the meat of the question, you can access it programmatically through the POSIX headers. termios.h is the big one. See: http://www.easysw.com/~mike/serial/serial.html#3_1 (NOT AVAILABLE ANYMORE) but I also have some interest in serial programming using Windows/Hyperterminal. Hyperterminal and minicom are basically the same program. As for how Windows let's you get access to the serial port, I'll leave that question for someone else. I haven't done that in Windows since the Win95 days.
How do I configure and communicate with a serial port? I need to send and receive data over serial connections (RS-232 and RS-422). How do I set up and communicate with such a connection? How do I figure out what the configuration settings (e.g. baud rate) should be and how do I set them? In particular, I am looking to do this in Java, C/C++, or one of the major Unix shells but I also have some interest in serial programming using Windows/Hyperterminal.
TITLE: How do I configure and communicate with a serial port? QUESTION: I need to send and receive data over serial connections (RS-232 and RS-422). How do I set up and communicate with such a connection? How do I figure out what the configuration settings (e.g. baud rate) should be and how do I set them? In particular, I am looking to do this in Java, C/C++, or one of the major Unix shells but I also have some interest in serial programming using Windows/Hyperterminal. ANSWER: Build a time machine and go back to 1987? Ho ho. Ok, no more snarky comments. How do I figure out what the configuration settings (e.g. baud rate) should be... Read the datasheet? Ok, ok. Seriously, last one. If you don't know the baud rate of the device you are trying to communicate with, you have two choices. Start guessing, or possibly bust out an o-scope. If you need a good starting point, let me suggest 9600-8-N-1. My suspicion is you can get there with brute force relatively quickly. There's a third option of having an old-school ninja who can tell just by the LOOK of the garbled characters at some standard baud rate what actual baud rate is. An impressive party trick to be sure. Hopefully though you have access to this information. In unix/linux, you can get ahold of minicom to play with the serial port directly. This should make it fairly quick to get the configuration figured out. one of the major Unix shells In Unix the serial port(s) is/are file-mapped into the /dev/ subdir. ttyS0, for example. If you setup the correct baud rate and whatnot using minicom, you can even cat stuff to that file to send stuff out there. On to the meat of the question, you can access it programmatically through the POSIX headers. termios.h is the big one. See: http://www.easysw.com/~mike/serial/serial.html#3_1 (NOT AVAILABLE ANYMORE) but I also have some interest in serial programming using Windows/Hyperterminal. Hyperterminal and minicom are basically the same program. As for how Windows let's you get access to the serial port, I'll leave that question for someone else. I haven't done that in Windows since the Win95 days.
[ "java", "c++", "windows", "unix" ]
49
31
13,949
10
0
2008-08-06T03:19:19.470000
2008-08-06T03:27:43.323000
3,057
3,062
Speed Comparisons - Procedural vs. OO in interpreted languages
In interpreted programming languages, such as PHP and JavaScript, what are the repercussions of going with an Object Oriented approach over a Procedural approach? Specifically what I am looking for is a checklist of things to consider when creating a web application and choosing between Procedural and Object Oriented approaches, to optimize not only for speed, but maintainability as well. Cited research and test cases would be helpful as well if you know of any articles exploring this further. Bottom line: how big (if any) is the performance hit really, when going with OO vs. Procedural in an interpreted language?
Maybe I'm crazy but worrying about speed in cases like this using an interpretive language is like trying to figure out what color to paint the shed. Let's not even get into the idea that this kind of optimization is entirely pre-mature. You hit the nail on the head when you said 'maintainability'. I'd choose the approach that is the most productive and most maintainable. If you need speed later, it ain't gonna come from switching between procedural versus object oriented coding paradigms inside an interpreted language.
Speed Comparisons - Procedural vs. OO in interpreted languages In interpreted programming languages, such as PHP and JavaScript, what are the repercussions of going with an Object Oriented approach over a Procedural approach? Specifically what I am looking for is a checklist of things to consider when creating a web application and choosing between Procedural and Object Oriented approaches, to optimize not only for speed, but maintainability as well. Cited research and test cases would be helpful as well if you know of any articles exploring this further. Bottom line: how big (if any) is the performance hit really, when going with OO vs. Procedural in an interpreted language?
TITLE: Speed Comparisons - Procedural vs. OO in interpreted languages QUESTION: In interpreted programming languages, such as PHP and JavaScript, what are the repercussions of going with an Object Oriented approach over a Procedural approach? Specifically what I am looking for is a checklist of things to consider when creating a web application and choosing between Procedural and Object Oriented approaches, to optimize not only for speed, but maintainability as well. Cited research and test cases would be helpful as well if you know of any articles exploring this further. Bottom line: how big (if any) is the performance hit really, when going with OO vs. Procedural in an interpreted language? ANSWER: Maybe I'm crazy but worrying about speed in cases like this using an interpretive language is like trying to figure out what color to paint the shed. Let's not even get into the idea that this kind of optimization is entirely pre-mature. You hit the nail on the head when you said 'maintainability'. I'd choose the approach that is the most productive and most maintainable. If you need speed later, it ain't gonna come from switching between procedural versus object oriented coding paradigms inside an interpreted language.
[ "performance", "oop", "maintainability", "procedural", "interpreted-language" ]
22
17
9,938
7
0
2008-08-06T03:34:01.517000
2008-08-06T03:36:28.267000
3,058
3,140
What is Inversion of Control?
Inversion of Control (IoC) can be quite confusing when it is first encountered. What is it? Which problem does it solve? When is it appropriate to use and when not?
The Inversion-of-Control (IoC) pattern, is about providing any kind of callback, which "implements" and/or controls reaction, instead of acting ourselves directly (in other words, inversion and/or redirecting control to the external handler/controller). The Dependency-Injection (DI) pattern is a more specific version of IoC pattern, and is all about removing dependencies from your code. Every DI implementation can be considered IoC, but one should not call it IoC, because implementing Dependency-Injection is harder than callback (Don't lower your product's worth by using the general term "IoC" instead). For DI example, say your application has a text-editor component, and you want to provide spell checking. Your standard code would look something like this: public class TextEditor { private SpellChecker checker; public TextEditor() { this.checker = new SpellChecker(); } } What we've done here creates a dependency between the TextEditor and the SpellChecker. In an IoC scenario we would instead do something like this: public class TextEditor { private IocSpellChecker checker; public TextEditor(IocSpellChecker checker) { this.checker = checker; } } In the first code example we are instantiating SpellChecker ( this.checker = new SpellChecker(); ), which means the TextEditor class directly depends on the SpellChecker class. In the second code example we are creating an abstraction by having the SpellChecker dependency class in TextEditor 's constructor signature (not initializing dependency in class). This allows us to call the dependency then pass it to the TextEditor class like so: SpellChecker sc = new SpellChecker(); // dependency TextEditor textEditor = new TextEditor(sc); Now the client creating the TextEditor class has control over which SpellChecker implementation to use because we're injecting the dependency into the TextEditor signature. Note that just like IoC being the base of many other patterns, above sample is only one of many Dependency-Injection kinds, for example: Constructor Injection. Where an instance of IocSpellChecker would be passed to constructor, either automatically or similar to above manually. Setter Injection. Where an instance of IocSpellChecker would be passed through setter-method or public property. Service-lookup and/or Service-locator Where TextEditor would ask a known provider for a globally-used-instance (service) of IocSpellChecker type (and that maybe without storing said instance, and instead, asking the provider again and again).
What is Inversion of Control? Inversion of Control (IoC) can be quite confusing when it is first encountered. What is it? Which problem does it solve? When is it appropriate to use and when not?
TITLE: What is Inversion of Control? QUESTION: Inversion of Control (IoC) can be quite confusing when it is first encountered. What is it? Which problem does it solve? When is it appropriate to use and when not? ANSWER: The Inversion-of-Control (IoC) pattern, is about providing any kind of callback, which "implements" and/or controls reaction, instead of acting ourselves directly (in other words, inversion and/or redirecting control to the external handler/controller). The Dependency-Injection (DI) pattern is a more specific version of IoC pattern, and is all about removing dependencies from your code. Every DI implementation can be considered IoC, but one should not call it IoC, because implementing Dependency-Injection is harder than callback (Don't lower your product's worth by using the general term "IoC" instead). For DI example, say your application has a text-editor component, and you want to provide spell checking. Your standard code would look something like this: public class TextEditor { private SpellChecker checker; public TextEditor() { this.checker = new SpellChecker(); } } What we've done here creates a dependency between the TextEditor and the SpellChecker. In an IoC scenario we would instead do something like this: public class TextEditor { private IocSpellChecker checker; public TextEditor(IocSpellChecker checker) { this.checker = checker; } } In the first code example we are instantiating SpellChecker ( this.checker = new SpellChecker(); ), which means the TextEditor class directly depends on the SpellChecker class. In the second code example we are creating an abstraction by having the SpellChecker dependency class in TextEditor 's constructor signature (not initializing dependency in class). This allows us to call the dependency then pass it to the TextEditor class like so: SpellChecker sc = new SpellChecker(); // dependency TextEditor textEditor = new TextEditor(sc); Now the client creating the TextEditor class has control over which SpellChecker implementation to use because we're injecting the dependency into the TextEditor signature. Note that just like IoC being the base of many other patterns, above sample is only one of many Dependency-Injection kinds, for example: Constructor Injection. Where an instance of IocSpellChecker would be passed to constructor, either automatically or similar to above manually. Setter Injection. Where an instance of IocSpellChecker would be passed through setter-method or public property. Service-lookup and/or Service-locator Where TextEditor would ask a known provider for a globally-used-instance (service) of IocSpellChecker type (and that maybe without storing said instance, and instead, asking the provider again and again).
[ "oop", "design-patterns", "language-agnostic", "inversion-of-control", "terminology" ]
2,316
1,998
707,592
40
0
2008-08-06T03:35:27.380000
2008-08-06T07:22:09.513000
3,061
3,071
Calling a function of a module by using its name (a string)
How do I call a function, using a string with the function's name? For example: import foo func_name = "bar" call(foo, func_name) # calls foo.bar()
Given a module foo with method bar: import foo bar = getattr(foo, 'bar') result = bar() getattr can similarly be used on class instance bound methods, module-level methods, class methods... the list goes on.
Calling a function of a module by using its name (a string) How do I call a function, using a string with the function's name? For example: import foo func_name = "bar" call(foo, func_name) # calls foo.bar()
TITLE: Calling a function of a module by using its name (a string) QUESTION: How do I call a function, using a string with the function's name? For example: import foo func_name = "bar" call(foo, func_name) # calls foo.bar() ANSWER: Given a module foo with method bar: import foo bar = getattr(foo, 'bar') result = bar() getattr can similarly be used on class instance bound methods, module-level methods, class methods... the list goes on.
[ "python", "object", "reflection" ]
2,429
2,922
1,162,529
18
0
2008-08-06T03:36:08.627000
2008-08-06T03:57:16.820000
3,075
3,084
Can ASP.NET AJAX partial rendering work inside a SharePoint 2007 application page?
I have a simple page with my ScriptManager and my UpdatePanel, and my ContentTemplate has one ListBox and one Label. I am just trying to catch its OnSelectionChanged so I can update the text in the Label. No matter what settings I try to tweak, I always get a full-page postback. Is this really not going to work, or am I just screwing this up?
You need to have Sharepoint 2007 service pack 1 -- or else there's no chance. (Sharepoint 2007 predates ajax 1.0 -- they built some support into service pack 1) Next, from a trouble shooting point of view, test that the exact same code functions as expected when hosted in a regular asp.net page. (Literally copy and paste your code across into a fresh page, to rule out any typographical errors). Ruling sharepoint in or out of the problem area will help narrow down the solution space.
Can ASP.NET AJAX partial rendering work inside a SharePoint 2007 application page? I have a simple page with my ScriptManager and my UpdatePanel, and my ContentTemplate has one ListBox and one Label. I am just trying to catch its OnSelectionChanged so I can update the text in the Label. No matter what settings I try to tweak, I always get a full-page postback. Is this really not going to work, or am I just screwing this up?
TITLE: Can ASP.NET AJAX partial rendering work inside a SharePoint 2007 application page? QUESTION: I have a simple page with my ScriptManager and my UpdatePanel, and my ContentTemplate has one ListBox and one Label. I am just trying to catch its OnSelectionChanged so I can update the text in the Label. No matter what settings I try to tweak, I always get a full-page postback. Is this really not going to work, or am I just screwing this up? ANSWER: You need to have Sharepoint 2007 service pack 1 -- or else there's no chance. (Sharepoint 2007 predates ajax 1.0 -- they built some support into service pack 1) Next, from a trouble shooting point of view, test that the exact same code functions as expected when hosted in a regular asp.net page. (Literally copy and paste your code across into a fresh page, to rule out any typographical errors). Ruling sharepoint in or out of the problem area will help narrow down the solution space.
[ "ajax", "sharepoint" ]
14
2
1,580
6
0
2008-08-06T04:20:41.920000
2008-08-06T04:43:31.267000
3,106
3,119
How can I create Debian install packages in Windows for a Visual Studio project?
I'm developing some cross platform software targeting Mono under Visual Studio and would like to be able to build the installers for Windows and Linux (Ubuntu specifically) with a single button click. I figure I could do it by calling cygwin from a post-build event, but I was hoping for at best a Visual Studio plugin or at worst a more Windows-native way of doing it. It seems like the package format is fairly simple and this must be a common need. edit: Re-asked question under other account due to duplicate login issue.
I am not aware of any plugin that does it natively, especially since Mono users seem to prefer MonoDevelop. However, it should be possible to use Cygwin and a custom MSBuild Task or Batch file in order to achieve that by using the native.deb creation tools.
How can I create Debian install packages in Windows for a Visual Studio project? I'm developing some cross platform software targeting Mono under Visual Studio and would like to be able to build the installers for Windows and Linux (Ubuntu specifically) with a single button click. I figure I could do it by calling cygwin from a post-build event, but I was hoping for at best a Visual Studio plugin or at worst a more Windows-native way of doing it. It seems like the package format is fairly simple and this must be a common need. edit: Re-asked question under other account due to duplicate login issue.
TITLE: How can I create Debian install packages in Windows for a Visual Studio project? QUESTION: I'm developing some cross platform software targeting Mono under Visual Studio and would like to be able to build the installers for Windows and Linux (Ubuntu specifically) with a single button click. I figure I could do it by calling cygwin from a post-build event, but I was hoping for at best a Visual Studio plugin or at worst a more Windows-native way of doing it. It seems like the package format is fairly simple and this must be a common need. edit: Re-asked question under other account due to duplicate login issue. ANSWER: I am not aware of any plugin that does it natively, especially since Mono users seem to prefer MonoDevelop. However, it should be possible to use Cygwin and a custom MSBuild Task or Batch file in order to achieve that by using the native.deb creation tools.
[ "windows", "visual-studio", "mono", "cross-platform" ]
22
3
7,562
5
0
2008-08-06T05:36:49.770000
2008-08-06T06:06:45.607000
3,112
3,134
Can you force either a scalar or array ref to be an array in Perl?
I have a perl variable $results that gets returned from a service. The value is supposed to be an array, and $results should be an array reference. However, when the array has only one item in it, $results will be set to that value, and not a referenced array that contains that one item. I want to do a foreach loop on the expected array. Without checking ref($results) eq 'ARRAY', is there any way to have something equivalent to the following: foreach my $result (@$results) { # Process $result } That particular code sample will work for the reference, but will complain for the simple scalar. EDIT: I should clarify that there is no way for me to change what is returned from the service. The problem is that the value will be a scalar when there is only one value and it will be an array reference when there is more than one value.
im not sure there's any other way than: $result = [ $result ] if ref($result) ne 'ARRAY'; foreach.....
Can you force either a scalar or array ref to be an array in Perl? I have a perl variable $results that gets returned from a service. The value is supposed to be an array, and $results should be an array reference. However, when the array has only one item in it, $results will be set to that value, and not a referenced array that contains that one item. I want to do a foreach loop on the expected array. Without checking ref($results) eq 'ARRAY', is there any way to have something equivalent to the following: foreach my $result (@$results) { # Process $result } That particular code sample will work for the reference, but will complain for the simple scalar. EDIT: I should clarify that there is no way for me to change what is returned from the service. The problem is that the value will be a scalar when there is only one value and it will be an array reference when there is more than one value.
TITLE: Can you force either a scalar or array ref to be an array in Perl? QUESTION: I have a perl variable $results that gets returned from a service. The value is supposed to be an array, and $results should be an array reference. However, when the array has only one item in it, $results will be set to that value, and not a referenced array that contains that one item. I want to do a foreach loop on the expected array. Without checking ref($results) eq 'ARRAY', is there any way to have something equivalent to the following: foreach my $result (@$results) { # Process $result } That particular code sample will work for the reference, but will complain for the simple scalar. EDIT: I should clarify that there is no way for me to change what is returned from the service. The problem is that the value will be a scalar when there is only one value and it will be an array reference when there is more than one value. ANSWER: im not sure there's any other way than: $result = [ $result ] if ref($result) ne 'ARRAY'; foreach.....
[ "perl", "arrays", "reference", "scalar" ]
28
26
14,585
6
0
2008-08-06T05:56:00.933000
2008-08-06T07:13:16.753000
3,136
3,139
How to setup a crontab to execute at specific time
How can I set up my crontab to execute X script at 11:59PM every day without emailing me or creating any logs? Right now my crontab looks something like this @daily /path/to/script.sh
When you do crontab -e, try this: 59 23 * * * /usr/sbin/myscript > /dev/null That means: At 59 Minutes and 23 Hours on every day (*) on every month on every weekday, execute myscript. See man crontab for some more info and examples.
How to setup a crontab to execute at specific time How can I set up my crontab to execute X script at 11:59PM every day without emailing me or creating any logs? Right now my crontab looks something like this @daily /path/to/script.sh
TITLE: How to setup a crontab to execute at specific time QUESTION: How can I set up my crontab to execute X script at 11:59PM every day without emailing me or creating any logs? Right now my crontab looks something like this @daily /path/to/script.sh ANSWER: When you do crontab -e, try this: 59 23 * * * /usr/sbin/myscript > /dev/null That means: At 59 Minutes and 23 Hours on every day (*) on every month on every weekday, execute myscript. See man crontab for some more info and examples.
[ "cron", "settings" ]
18
11
1,255
3
0
2008-08-06T07:16:16.373000
2008-08-06T07:21:32.430000
3,143
880,219
Using MBUnit in TeamCity
I'm compiling a NAnt project on linux with TeamCity Continuous Integration server. I have been able to generate a test report by running NAnt on mono thru a Command Line Runner but don't have the options of using the report like a NAnt Runner. I'm also using MBUnit for the testing framework. How can I merge in the test report and display "Tests failed: 1 (1 new), passed: 3049" for the build? Update: take a look at MBUnitTask its a NAnt task that uses sends messages that TeamCity expects from NUnit so it lets you use all of TeamCity's features for tests. MBUnitTask Update: Galio has better support so you just have to reference the Galio MBUnit 3.5 dlls instead of the MBUnit 3.5 dlls and switch to the galio runner to make it work.
Gallio now has an extension to output TeamCity service messages. Just use the included Gallio.NAntTasks.dll and enable the TeamCity extension. (this won't be necessary in the next release )
Using MBUnit in TeamCity I'm compiling a NAnt project on linux with TeamCity Continuous Integration server. I have been able to generate a test report by running NAnt on mono thru a Command Line Runner but don't have the options of using the report like a NAnt Runner. I'm also using MBUnit for the testing framework. How can I merge in the test report and display "Tests failed: 1 (1 new), passed: 3049" for the build? Update: take a look at MBUnitTask its a NAnt task that uses sends messages that TeamCity expects from NUnit so it lets you use all of TeamCity's features for tests. MBUnitTask Update: Galio has better support so you just have to reference the Galio MBUnit 3.5 dlls instead of the MBUnit 3.5 dlls and switch to the galio runner to make it work.
TITLE: Using MBUnit in TeamCity QUESTION: I'm compiling a NAnt project on linux with TeamCity Continuous Integration server. I have been able to generate a test report by running NAnt on mono thru a Command Line Runner but don't have the options of using the report like a NAnt Runner. I'm also using MBUnit for the testing framework. How can I merge in the test report and display "Tests failed: 1 (1 new), passed: 3049" for the build? Update: take a look at MBUnitTask its a NAnt task that uses sends messages that TeamCity expects from NUnit so it lets you use all of TeamCity's features for tests. MBUnitTask Update: Galio has better support so you just have to reference the Galio MBUnit 3.5 dlls instead of the MBUnit 3.5 dlls and switch to the galio runner to make it work. ANSWER: Gallio now has an extension to output TeamCity service messages. Just use the included Gallio.NAntTasks.dll and enable the TeamCity extension. (this won't be necessary in the next release )
[ "mono", "nant", "teamcity", "mbunit" ]
17
6
3,497
4
0
2008-08-06T07:41:11.937000
2009-05-18T23:07:43.877000
3,144
3,146
'Best' Diff Algorithm
I need to implement a Diff algorithm in VB.NET to find the changes between two different versions of a piece of text. I've had a scout around the web and have found a couple of different algorithms. Does anybody here know of a 'best' algorithm that I could implement?
Well I've used the c# version on codeproject and its really good for what I wanted... http://www.codeproject.com/KB/recipes/diffengine.aspx You can probably get this translated into VB.net via an online converter if you can't do it yourself...
'Best' Diff Algorithm I need to implement a Diff algorithm in VB.NET to find the changes between two different versions of a piece of text. I've had a scout around the web and have found a couple of different algorithms. Does anybody here know of a 'best' algorithm that I could implement?
TITLE: 'Best' Diff Algorithm QUESTION: I need to implement a Diff algorithm in VB.NET to find the changes between two different versions of a piece of text. I've had a scout around the web and have found a couple of different algorithms. Does anybody here know of a 'best' algorithm that I could implement? ANSWER: Well I've used the c# version on codeproject and its really good for what I wanted... http://www.codeproject.com/KB/recipes/diffengine.aspx You can probably get this translated into VB.net via an online converter if you can't do it yourself...
[ "vb.net", "diff" ]
18
7
5,972
3
0
2008-08-06T07:42:33.947000
2008-08-06T07:49:32.407000
3,150
35,963
How to set up unit testing for Visual Studio C++
I'm having trouble figuring out how to get the testing framework set up and usable in Visual Studio 2008 for C++ presumably with the built-in unit testing suite. Any links or tutorials would be appreciated.
This page may help, it reviews quite a few C++ unit test frameworks: CppUnit Boost.Test CppUnitLite NanoCppUnit Unit++ CxxTest Check out CPPUnitLite or CPPUnitLite2. CPPUnitLite was created by Michael Feathers, who originally ported Java's JUnit to C++ as CPPUnit (CPPUnit tries mimic the development model of JUnit - but C++ lacks Java's features [e.g. reflection] to make it easy to use). CPPUnitLite attempts to make a true C++-style testing framework, not a Java one ported to C++. (I'm paraphrasing from Feather's Working Effectively with Legacy Code book). CPPUnitLite2 seems to be another rewrite, with more features and bug fixes. I also just stumbled across UnitTest++ which includes stuff from CPPUnitLite2 and some other framework. Microsoft has released WinUnit. Also checkout Catch or Doctest
How to set up unit testing for Visual Studio C++ I'm having trouble figuring out how to get the testing framework set up and usable in Visual Studio 2008 for C++ presumably with the built-in unit testing suite. Any links or tutorials would be appreciated.
TITLE: How to set up unit testing for Visual Studio C++ QUESTION: I'm having trouble figuring out how to get the testing framework set up and usable in Visual Studio 2008 for C++ presumably with the built-in unit testing suite. Any links or tutorials would be appreciated. ANSWER: This page may help, it reviews quite a few C++ unit test frameworks: CppUnit Boost.Test CppUnitLite NanoCppUnit Unit++ CxxTest Check out CPPUnitLite or CPPUnitLite2. CPPUnitLite was created by Michael Feathers, who originally ported Java's JUnit to C++ as CPPUnit (CPPUnit tries mimic the development model of JUnit - but C++ lacks Java's features [e.g. reflection] to make it easy to use). CPPUnitLite attempts to make a true C++-style testing framework, not a Java one ported to C++. (I'm paraphrasing from Feather's Working Effectively with Legacy Code book). CPPUnitLite2 seems to be another rewrite, with more features and bug fixes. I also just stumbled across UnitTest++ which includes stuff from CPPUnitLite2 and some other framework. Microsoft has released WinUnit. Also checkout Catch or Doctest
[ "c++", "unit-testing", "testing", "visual-studio-2008", "frameworks" ]
94
57
62,191
12
0
2008-08-06T07:57:50.017000
2008-08-30T13:51:31.510000
3,157
4,449
.htaccess directives to *not* redirect certain URLs
In an application that heavily relies on.htaccess RewriteRules for its PrettyURLs (CakePHP in my case), how do I correctly set up directives to exclude certain directories from this rewriting? That is: /appRoot/.htaccess app/ static/ By default, every request to /appRoot/* is being rewritten to be picked up by app/webroot/index.php, where it's being analyzed and corresponding controller actions are being invoked. This is done by these directives in.htaccess: RewriteBase /appRoot RewriteRule ^$ app/webroot/ [L] RewriteRule (.*) app/webroot/$1 [L] I now want to exclude a few directories like static/ from this rewriting. I tried this before the Cake RewriteRules: RewriteCond $1 ^(static|otherDir).*$ [NC] RewriteRule (.*) - [L] It works in so far that requests are no longer rewritten, but now all requests are being skipped, even legitimate Cake requests which should not match ^(static|otherDir).*$. I tried several variations of these rules but can't get it to work the way I want.
And the correct answer iiiiis... RewriteRule ^(a|bunch|of|old|directories).* - [NC,L] # all other requests will be forwarded to Cake RewriteRule ^$ app/webroot/ [L] RewriteRule (.*) app/webroot/$1 [L] I still don't get why the index.php file in the root directory was called initially even with these directives in place. It is now located in /appRoot/app/views/pages/home.ctp and handled through Cake as well. With this in place now, I suppose this would have worked as well (slightly altered version of Mike's suggestion, untested): RewriteCond $1!^(a|bunch|of|old|directories).*$ [NC] RewriteRule ^(.*)$ app/webroot/$1 [L]
.htaccess directives to *not* redirect certain URLs In an application that heavily relies on.htaccess RewriteRules for its PrettyURLs (CakePHP in my case), how do I correctly set up directives to exclude certain directories from this rewriting? That is: /appRoot/.htaccess app/ static/ By default, every request to /appRoot/* is being rewritten to be picked up by app/webroot/index.php, where it's being analyzed and corresponding controller actions are being invoked. This is done by these directives in.htaccess: RewriteBase /appRoot RewriteRule ^$ app/webroot/ [L] RewriteRule (.*) app/webroot/$1 [L] I now want to exclude a few directories like static/ from this rewriting. I tried this before the Cake RewriteRules: RewriteCond $1 ^(static|otherDir).*$ [NC] RewriteRule (.*) - [L] It works in so far that requests are no longer rewritten, but now all requests are being skipped, even legitimate Cake requests which should not match ^(static|otherDir).*$. I tried several variations of these rules but can't get it to work the way I want.
TITLE: .htaccess directives to *not* redirect certain URLs QUESTION: In an application that heavily relies on.htaccess RewriteRules for its PrettyURLs (CakePHP in my case), how do I correctly set up directives to exclude certain directories from this rewriting? That is: /appRoot/.htaccess app/ static/ By default, every request to /appRoot/* is being rewritten to be picked up by app/webroot/index.php, where it's being analyzed and corresponding controller actions are being invoked. This is done by these directives in.htaccess: RewriteBase /appRoot RewriteRule ^$ app/webroot/ [L] RewriteRule (.*) app/webroot/$1 [L] I now want to exclude a few directories like static/ from this rewriting. I tried this before the Cake RewriteRules: RewriteCond $1 ^(static|otherDir).*$ [NC] RewriteRule (.*) - [L] It works in so far that requests are no longer rewritten, but now all requests are being skipped, even legitimate Cake requests which should not match ^(static|otherDir).*$. I tried several variations of these rules but can't get it to work the way I want. ANSWER: And the correct answer iiiiis... RewriteRule ^(a|bunch|of|old|directories).* - [NC,L] # all other requests will be forwarded to Cake RewriteRule ^$ app/webroot/ [L] RewriteRule (.*) app/webroot/$1 [L] I still don't get why the index.php file in the root directory was called initially even with these directives in place. It is now located in /appRoot/app/views/pages/home.ctp and handled through Cake as well. With this in place now, I suppose this would have worked as well (slightly altered version of Mike's suggestion, untested): RewriteCond $1!^(a|bunch|of|old|directories).*$ [NC] RewriteRule ^(.*)$ app/webroot/$1 [L]
[ "apache", ".htaccess", "mod-rewrite" ]
22
6
4,031
3
0
2008-08-06T08:15:28.233000
2008-08-07T06:09:54.337000
3,163
10,030
Actionscript 3 - Fastest way to parse yyyy-mm-dd hh:mm:ss to a Date object?
I have been trying to find a really fast way to parse yyyy-mm-dd [hh:mm:ss] into a Date object. Here are the 3 ways I have tried doing it and the times it takes each method to parse 50,000 date time strings. Does anyone know any faster ways of doing this or tips to speed up the methods? castMethod1 takes 3673 ms castMethod2 takes 3812 ms castMethod3 takes 3931 ms Code: private function castMethod1(dateString:String):Date { if ( dateString == null ) { return null; } var year:int = int(dateString.substr(0,4)); var month:int = int(dateString.substr(5,2))-1; var day:int = int(dateString.substr(8,2)); if ( year == 0 && month == 0 && day == 0 ) { return null; } if ( dateString.length == 10 ) { return new Date(year, month, day); } var hour:int = int(dateString.substr(11,2)); var minute:int = int(dateString.substr(14,2)); var second:int = int(dateString.substr(17,2)); return new Date(year, month, day, hour, minute, second); } - private function castMethod2(dateString:String):Date { if ( dateString == null ) { return null; } if ( dateString.indexOf("0000-00-00")!= -1 ) { return null; } dateString = dateString.split("-").join("/"); return new Date(Date.parse( dateString )); } - private function castMethod3(dateString:String):Date { if ( dateString == null ) { return null; } var mainParts:Array = dateString.split(" "); var dateParts:Array = mainParts[0].split("-"); if ( Number(dateParts[0])+Number(dateParts[1])+Number(dateParts[2]) == 0 ) { return null; } return new Date( Date.parse( dateParts.join("/")+(mainParts[1]?" "+mainParts[1]:" ") ) ); } No, Date.parse will not handle dashes by default. And I need to return null for date time strings like "0000-00-00".
I've been using the following snipplet to parse UTC date strings: private function parseUTCDate( str: String ): Date { var matches: Array = str.match(/(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)Z/); var d: Date = new Date(); d.setUTCFullYear(int(matches[1]), int(matches[2]) - 1, int(matches[3])); d.setUTCHours(int(matches[4]), int(matches[5]), int(matches[6]), 0); return d; } Just remove the time part and it should work fine for your needs: private function parseDate( str: String ): Date { var matches: Array = str.match(/(\d\d\d\d)-(\d\d)-(\d\d)/); var d: Date = new Date(); d.setUTCFullYear(int(matches[1]), int(matches[2]) - 1, int(matches[3])); return d; } No idea about the speed, I haven't been worried about that in my applications. 50K iterations in significantly less than a second on my machine.
Actionscript 3 - Fastest way to parse yyyy-mm-dd hh:mm:ss to a Date object? I have been trying to find a really fast way to parse yyyy-mm-dd [hh:mm:ss] into a Date object. Here are the 3 ways I have tried doing it and the times it takes each method to parse 50,000 date time strings. Does anyone know any faster ways of doing this or tips to speed up the methods? castMethod1 takes 3673 ms castMethod2 takes 3812 ms castMethod3 takes 3931 ms Code: private function castMethod1(dateString:String):Date { if ( dateString == null ) { return null; } var year:int = int(dateString.substr(0,4)); var month:int = int(dateString.substr(5,2))-1; var day:int = int(dateString.substr(8,2)); if ( year == 0 && month == 0 && day == 0 ) { return null; } if ( dateString.length == 10 ) { return new Date(year, month, day); } var hour:int = int(dateString.substr(11,2)); var minute:int = int(dateString.substr(14,2)); var second:int = int(dateString.substr(17,2)); return new Date(year, month, day, hour, minute, second); } - private function castMethod2(dateString:String):Date { if ( dateString == null ) { return null; } if ( dateString.indexOf("0000-00-00")!= -1 ) { return null; } dateString = dateString.split("-").join("/"); return new Date(Date.parse( dateString )); } - private function castMethod3(dateString:String):Date { if ( dateString == null ) { return null; } var mainParts:Array = dateString.split(" "); var dateParts:Array = mainParts[0].split("-"); if ( Number(dateParts[0])+Number(dateParts[1])+Number(dateParts[2]) == 0 ) { return null; } return new Date( Date.parse( dateParts.join("/")+(mainParts[1]?" "+mainParts[1]:" ") ) ); } No, Date.parse will not handle dashes by default. And I need to return null for date time strings like "0000-00-00".
TITLE: Actionscript 3 - Fastest way to parse yyyy-mm-dd hh:mm:ss to a Date object? QUESTION: I have been trying to find a really fast way to parse yyyy-mm-dd [hh:mm:ss] into a Date object. Here are the 3 ways I have tried doing it and the times it takes each method to parse 50,000 date time strings. Does anyone know any faster ways of doing this or tips to speed up the methods? castMethod1 takes 3673 ms castMethod2 takes 3812 ms castMethod3 takes 3931 ms Code: private function castMethod1(dateString:String):Date { if ( dateString == null ) { return null; } var year:int = int(dateString.substr(0,4)); var month:int = int(dateString.substr(5,2))-1; var day:int = int(dateString.substr(8,2)); if ( year == 0 && month == 0 && day == 0 ) { return null; } if ( dateString.length == 10 ) { return new Date(year, month, day); } var hour:int = int(dateString.substr(11,2)); var minute:int = int(dateString.substr(14,2)); var second:int = int(dateString.substr(17,2)); return new Date(year, month, day, hour, minute, second); } - private function castMethod2(dateString:String):Date { if ( dateString == null ) { return null; } if ( dateString.indexOf("0000-00-00")!= -1 ) { return null; } dateString = dateString.split("-").join("/"); return new Date(Date.parse( dateString )); } - private function castMethod3(dateString:String):Date { if ( dateString == null ) { return null; } var mainParts:Array = dateString.split(" "); var dateParts:Array = mainParts[0].split("-"); if ( Number(dateParts[0])+Number(dateParts[1])+Number(dateParts[2]) == 0 ) { return null; } return new Date( Date.parse( dateParts.join("/")+(mainParts[1]?" "+mainParts[1]:" ") ) ); } No, Date.parse will not handle dashes by default. And I need to return null for date time strings like "0000-00-00". ANSWER: I've been using the following snipplet to parse UTC date strings: private function parseUTCDate( str: String ): Date { var matches: Array = str.match(/(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)Z/); var d: Date = new Date(); d.setUTCFullYear(int(matches[1]), int(matches[2]) - 1, int(matches[3])); d.setUTCHours(int(matches[4]), int(matches[5]), int(matches[6]), 0); return d; } Just remove the time part and it should work fine for your needs: private function parseDate( str: String ): Date { var matches: Array = str.match(/(\d\d\d\d)-(\d\d)-(\d\d)/); var d: Date = new Date(); d.setUTCFullYear(int(matches[1]), int(matches[2]) - 1, int(matches[3])); return d; } No idea about the speed, I haven't been worried about that in my applications. 50K iterations in significantly less than a second on my machine.
[ "apache-flex", "actionscript-3" ]
24
18
33,994
7
0
2008-08-06T08:33:53.097000
2008-08-13T16:21:37.243000
3,164
3,218
Absolute path back to web-relative path
If I have managed to locate and verify the existence of a file using Server.MapPath and I now want to send the user directly to that file, what is the fastest way to convert that absolute path back into a relative web path?
Perhaps this might work: String RelativePath = AbsolutePath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], String.Empty); I'm using c# but could be adapted to vb.
Absolute path back to web-relative path If I have managed to locate and verify the existence of a file using Server.MapPath and I now want to send the user directly to that file, what is the fastest way to convert that absolute path back into a relative web path?
TITLE: Absolute path back to web-relative path QUESTION: If I have managed to locate and verify the existence of a file using Server.MapPath and I now want to send the user directly to that file, what is the fastest way to convert that absolute path back into a relative web path? ANSWER: Perhaps this might work: String RelativePath = AbsolutePath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], String.Empty); I'm using c# but could be adapted to vb.
[ "c#", "asp.net", ".net", "path", "mappath" ]
66
56
59,862
6
0
2008-08-06T08:34:13.983000
2008-08-06T09:28:50.940000
3,180
3,188
Anyone soloing using fogbugz?
Is there anyone working solo and using fogbugz out there? I'm interested in personal experience/overhead versus paper. I am involved in several projects and get pretty hammered with lots of details to keep track of... Any experience welcome. (Yes I know Mr. Joel is on the stackoverflow team... I still want good answers:)
I use it, especially since the hosted Version of FugBugz is free for up to 2 people. I found it a lot nicer than paper as I'm working on multiple projects, and my paper tends to get rather messy once you start making annotations or if you want to re-organize and shuffle tasks around, mark them as complete only to see that they are not complete after all... Plus, the Visual Studio integration is really neat, something paper just cannot compete with. Also, if you lay the project to rest for 6 months and come back, all your tasks and notes are still there, whereas with paper you may need to search all the old documents and notes again, if you did not discard it. But that is just the point of view from someone who is not really good at staying organized:-) If you are a really tidy and organized person, paper may work better for you than it does for me. Bonus suggestion: Run Fogbugz on a second PC (or a small Laptop like the eeePC) so that you always have it at your fingertips. The main problem with Task tracking programs - be it FogBugz, Outlook, Excel or just notepad - is that they take up screen space, and my two monitors are usually full with Visual Studio, e-Mail, Web Browsers, some Notepads etc.
Anyone soloing using fogbugz? Is there anyone working solo and using fogbugz out there? I'm interested in personal experience/overhead versus paper. I am involved in several projects and get pretty hammered with lots of details to keep track of... Any experience welcome. (Yes I know Mr. Joel is on the stackoverflow team... I still want good answers:)
TITLE: Anyone soloing using fogbugz? QUESTION: Is there anyone working solo and using fogbugz out there? I'm interested in personal experience/overhead versus paper. I am involved in several projects and get pretty hammered with lots of details to keep track of... Any experience welcome. (Yes I know Mr. Joel is on the stackoverflow team... I still want good answers:) ANSWER: I use it, especially since the hosted Version of FugBugz is free for up to 2 people. I found it a lot nicer than paper as I'm working on multiple projects, and my paper tends to get rather messy once you start making annotations or if you want to re-organize and shuffle tasks around, mark them as complete only to see that they are not complete after all... Plus, the Visual Studio integration is really neat, something paper just cannot compete with. Also, if you lay the project to rest for 6 months and come back, all your tasks and notes are still there, whereas with paper you may need to search all the old documents and notes again, if you did not discard it. But that is just the point of view from someone who is not really good at staying organized:-) If you are a really tidy and organized person, paper may work better for you than it does for me. Bonus suggestion: Run Fogbugz on a second PC (or a small Laptop like the eeePC) so that you always have it at your fingertips. The main problem with Task tracking programs - be it FogBugz, Outlook, Excel or just notepad - is that they take up screen space, and my two monitors are usually full with Visual Studio, e-Mail, Web Browsers, some Notepads etc.
[ "fogbugz" ]
35
35
6,522
7
0
2008-08-06T08:47:45.423000
2008-08-06T08:52:51.980000
3,196
3,197
SQL query, count and group by
If I have data like this: Key Name 1 Dan 2 Tom 3 Jon 4 Tom 5 Sam 6 Dan What is the SQL query to bring back the records where Name is repeated 2 or more times? So the result I would want is Tom Dan
Couldn't be simpler... Select Name, Count(Name) As Count From Table Group By Name Having Count(Name) > 1 Order By Count(Name) Desc This could also be extended to delete duplicates: Delete From Table Where Key In ( Select Max(Key) From Table Group By Name Having Count(Name) > 1 )
SQL query, count and group by If I have data like this: Key Name 1 Dan 2 Tom 3 Jon 4 Tom 5 Sam 6 Dan What is the SQL query to bring back the records where Name is repeated 2 or more times? So the result I would want is Tom Dan
TITLE: SQL query, count and group by QUESTION: If I have data like this: Key Name 1 Dan 2 Tom 3 Jon 4 Tom 5 Sam 6 Dan What is the SQL query to bring back the records where Name is repeated 2 or more times? So the result I would want is Tom Dan ANSWER: Couldn't be simpler... Select Name, Count(Name) As Count From Table Group By Name Having Count(Name) > 1 Order By Count(Name) Desc This could also be extended to delete duplicates: Delete From Table Where Key In ( Select Max(Key) From Table Group By Name Having Count(Name) > 1 )
[ "sql" ]
26
40
23,484
3
0
2008-08-06T09:00:58.063000
2008-08-06T09:02:36.907000
3,213
3,267
Convert integers to written numbers
Is there an efficient method of converting an integer into the written numbers, for example: string Written = IntegerToWritten(21); would return "Twenty One". Is there any way of doing this that doesn't involve a massive look-up table?
This should work reasonably well: public static class HumanFriendlyInteger { static string[] ones = new string[] { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" }; static string[] teens = new string[] { "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" }; static string[] tens = new string[] { "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" }; static string[] thousandsGroups = { "", " Thousand", " Million", " Billion" }; private static string FriendlyInteger(int n, string leftDigits, int thousands) { if (n == 0) { return leftDigits; } string friendlyInt = leftDigits; if (friendlyInt.Length > 0) { friendlyInt += " "; } if (n < 10) { friendlyInt += ones[n]; } else if (n < 20) { friendlyInt += teens[n - 10]; } else if (n < 100) { friendlyInt += FriendlyInteger(n % 10, tens[n / 10 - 2], 0); } else if (n < 1000) { friendlyInt += FriendlyInteger(n % 100, (ones[n / 100] + " Hundred"), 0); } else { friendlyInt += FriendlyInteger(n % 1000, FriendlyInteger(n / 1000, "", thousands+1), 0); if (n % 1000 == 0) { return friendlyInt; } } return friendlyInt + thousandsGroups[thousands]; } public static string IntegerToWritten(int n) { if (n == 0) { return "Zero"; } else if (n < 0) { return "Negative " + IntegerToWritten(-n); } return FriendlyInteger(n, "", 0); } } (Edited to fix a bug w/ million, billion, etc.)
Convert integers to written numbers Is there an efficient method of converting an integer into the written numbers, for example: string Written = IntegerToWritten(21); would return "Twenty One". Is there any way of doing this that doesn't involve a massive look-up table?
TITLE: Convert integers to written numbers QUESTION: Is there an efficient method of converting an integer into the written numbers, for example: string Written = IntegerToWritten(21); would return "Twenty One". Is there any way of doing this that doesn't involve a massive look-up table? ANSWER: This should work reasonably well: public static class HumanFriendlyInteger { static string[] ones = new string[] { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" }; static string[] teens = new string[] { "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" }; static string[] tens = new string[] { "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" }; static string[] thousandsGroups = { "", " Thousand", " Million", " Billion" }; private static string FriendlyInteger(int n, string leftDigits, int thousands) { if (n == 0) { return leftDigits; } string friendlyInt = leftDigits; if (friendlyInt.Length > 0) { friendlyInt += " "; } if (n < 10) { friendlyInt += ones[n]; } else if (n < 20) { friendlyInt += teens[n - 10]; } else if (n < 100) { friendlyInt += FriendlyInteger(n % 10, tens[n / 10 - 2], 0); } else if (n < 1000) { friendlyInt += FriendlyInteger(n % 100, (ones[n / 100] + " Hundred"), 0); } else { friendlyInt += FriendlyInteger(n % 1000, FriendlyInteger(n / 1000, "", thousands+1), 0); if (n % 1000 == 0) { return friendlyInt; } } return friendlyInt + thousandsGroups[thousands]; } public static string IntegerToWritten(int n) { if (n == 0) { return "Zero"; } else if (n < 0) { return "Negative " + IntegerToWritten(-n); } return FriendlyInteger(n, "", 0); } } (Edited to fix a bug w/ million, billion, etc.)
[ "c#", "integer" ]
62
70
49,024
11
0
2008-08-06T09:21:09.490000
2008-08-06T10:31:24.170000
3,224
3,225
How can I make the browser see CSS and Javascript changes?
CSS and Javascript files don't change very often, so I want them to be cached by the web browser. But I also want the web browser to see changes made to these files without requiring the user to clear their browser cache. Also want a solution that works well with a version control system such as Subversion. Some solutions I have seen involve adding a version number to the end of the file in the form of a query string. Could use the SVN revision number to automate this for you: ASP.NET Display SVN Revision Number Can you specify how you include the Revision variable of another file? That is in the HTML file I can include the Revision number in the URL to the CSS or Javascript file. In the Subversion book it says about Revision: "This keyword describes the last known revision in which this file changed in the repository". Firefox also allows pressing CTRL + R to reload everything on a particular page. To clarify I am looking for solutions that don't require the user to do anything on their part.
I found that if you append the last modified timestamp of the file onto the end of the URL the browser will request the files when it is modified. For example in PHP: function urlmtime($url) { $parsed_url = parse_url($url); $path = $parsed_url['path']; if ($path[0] == "/") { $filename = $_SERVER['DOCUMENT_ROOT']. "/". $path; } else { $filename = $path; } if (!file_exists($filename)) { // If not a file then use the current time $lastModified = date('YmdHis'); } else { $lastModified = date('YmdHis', filemtime($filename)); } if (strpos($url, '?') === false) { $url.= '?ts='. $lastModified; } else { $url.= '&ts='. $lastModified; } return $url; } function include_css($css_url, $media='all') { // According to Yahoo, using link allows for progressive // rendering in IE where as @import url($css_url) does not echo ' '."\n"; } function include_javascript($javascript_url) { echo ' '."\n"; }
How can I make the browser see CSS and Javascript changes? CSS and Javascript files don't change very often, so I want them to be cached by the web browser. But I also want the web browser to see changes made to these files without requiring the user to clear their browser cache. Also want a solution that works well with a version control system such as Subversion. Some solutions I have seen involve adding a version number to the end of the file in the form of a query string. Could use the SVN revision number to automate this for you: ASP.NET Display SVN Revision Number Can you specify how you include the Revision variable of another file? That is in the HTML file I can include the Revision number in the URL to the CSS or Javascript file. In the Subversion book it says about Revision: "This keyword describes the last known revision in which this file changed in the repository". Firefox also allows pressing CTRL + R to reload everything on a particular page. To clarify I am looking for solutions that don't require the user to do anything on their part.
TITLE: How can I make the browser see CSS and Javascript changes? QUESTION: CSS and Javascript files don't change very often, so I want them to be cached by the web browser. But I also want the web browser to see changes made to these files without requiring the user to clear their browser cache. Also want a solution that works well with a version control system such as Subversion. Some solutions I have seen involve adding a version number to the end of the file in the form of a query string. Could use the SVN revision number to automate this for you: ASP.NET Display SVN Revision Number Can you specify how you include the Revision variable of another file? That is in the HTML file I can include the Revision number in the URL to the CSS or Javascript file. In the Subversion book it says about Revision: "This keyword describes the last known revision in which this file changed in the repository". Firefox also allows pressing CTRL + R to reload everything on a particular page. To clarify I am looking for solutions that don't require the user to do anything on their part. ANSWER: I found that if you append the last modified timestamp of the file onto the end of the URL the browser will request the files when it is modified. For example in PHP: function urlmtime($url) { $parsed_url = parse_url($url); $path = $parsed_url['path']; if ($path[0] == "/") { $filename = $_SERVER['DOCUMENT_ROOT']. "/". $path; } else { $filename = $path; } if (!file_exists($filename)) { // If not a file then use the current time $lastModified = date('YmdHis'); } else { $lastModified = date('YmdHis', filemtime($filename)); } if (strpos($url, '?') === false) { $url.= '?ts='. $lastModified; } else { $url.= '&ts='. $lastModified; } return $url; } function include_css($css_url, $media='all') { // According to Yahoo, using link allows for progressive // rendering in IE where as @import url($css_url) does not echo ' '."\n"; } function include_javascript($javascript_url) { echo ' '."\n"; }
[ "javascript", "css", "http", "caching" ]
64
30
7,885
5
0
2008-08-06T09:38:15.417000
2008-08-06T09:41:02.353000
3,230
10,141
How do you pack a visual studio c++ project for release?
I'm wondering how to make a release build that includes all necessary DLL files into the.exe so the program can be run on a non-development machine without having to install the Microsoft redistributable on the target machine. Without doing this you get the error message that the application configuration is not correct and to reinstall.
Choose Project -> Properties Select Configuration -> General In the box for how you should link MFC, choose to statically link it. Choose Linker -> Input. Under Additional Dependencies, add any libraries you need your app to statically link in.
How do you pack a visual studio c++ project for release? I'm wondering how to make a release build that includes all necessary DLL files into the.exe so the program can be run on a non-development machine without having to install the Microsoft redistributable on the target machine. Without doing this you get the error message that the application configuration is not correct and to reinstall.
TITLE: How do you pack a visual studio c++ project for release? QUESTION: I'm wondering how to make a release build that includes all necessary DLL files into the.exe so the program can be run on a non-development machine without having to install the Microsoft redistributable on the target machine. Without doing this you get the error message that the application configuration is not correct and to reinstall. ANSWER: Choose Project -> Properties Select Configuration -> General In the box for how you should link MFC, choose to statically link it. Choose Linker -> Input. Under Additional Dependencies, add any libraries you need your app to statically link in.
[ "c++", "visual-studio", "build" ]
38
18
34,680
6
0
2008-08-06T09:49:27.467000
2008-08-13T18:10:34.870000
3,231
842,632
C/C++ library for reading MIDI signals from a USB MIDI device
I want to write C/C++ programs that take input from a MIDI device. The MIDI device connects to my PC using a USB connector. I'm looking for a (C/C++ implemented) library that I can use to read the MIDI signals from the MIDI device through the USB port. I'm happy manipulating the MIDI data once I get it, I just don't want to have to implement the code for its capture. I'm planning on writing my code using the Bloodshed Dev-C++ IDE on Windows XP.
PortMidi is another open source cross-platform MIDI I/O library worth checking out. On the other hand, if you are working on a sysex type of app, then direct Win32 works easily enough. Just came across another open source cross-platform framework that includes MIDI support: Juce. Also, I should note that there isn't anything special about a USB connected MIDI device. It will still be presented as a MIDI device in Windows and you will use standard MIDI APIs (mmsystem) to communicate with it. [July 2014] I just came across RtMidi that looks to be a nice, compact, open source cross-platform C++ library.
C/C++ library for reading MIDI signals from a USB MIDI device I want to write C/C++ programs that take input from a MIDI device. The MIDI device connects to my PC using a USB connector. I'm looking for a (C/C++ implemented) library that I can use to read the MIDI signals from the MIDI device through the USB port. I'm happy manipulating the MIDI data once I get it, I just don't want to have to implement the code for its capture. I'm planning on writing my code using the Bloodshed Dev-C++ IDE on Windows XP.
TITLE: C/C++ library for reading MIDI signals from a USB MIDI device QUESTION: I want to write C/C++ programs that take input from a MIDI device. The MIDI device connects to my PC using a USB connector. I'm looking for a (C/C++ implemented) library that I can use to read the MIDI signals from the MIDI device through the USB port. I'm happy manipulating the MIDI data once I get it, I just don't want to have to implement the code for its capture. I'm planning on writing my code using the Bloodshed Dev-C++ IDE on Windows XP. ANSWER: PortMidi is another open source cross-platform MIDI I/O library worth checking out. On the other hand, if you are working on a sysex type of app, then direct Win32 works easily enough. Just came across another open source cross-platform framework that includes MIDI support: Juce. Also, I should note that there isn't anything special about a USB connected MIDI device. It will still be presented as a MIDI device in Windows and you will use standard MIDI APIs (mmsystem) to communicate with it. [July 2014] I just came across RtMidi that looks to be a nice, compact, open source cross-platform C++ library.
[ "c++", "c", "signal-processing", "midi", "dev-c++" ]
31
22
31,022
3
0
2008-08-06T09:51:06.153000
2009-05-09T04:11:32.773000
3,234
14,496
Displaying ad content from Respose.WriteFile()/ Response.ContentType
How would one display any add content from a "dynamic" aspx page? Currently I am working on using the System.Web.HttpResponse "Page.Response" to write a file that is stored on a web server to a web request. This would allow people to hit a url to the type http://www.foo.com?Image=test.jpg and have the image display in their browser. So as you may know this revolves around the use of Response.ContentType. By using Response.ContentType = "application/octet-stream"; I am able to display images of type gif/jpeg/png (all i have tested so far), bit trying to display.swf or.ico files gives me a nice little error. using Response.ContentType = "application/x-shockwave-flash"; I can get flash files to play, but then the images are messed. So how do i easily choose the contenttype?
This is ugly, but the best way is to look at the file and set the content type as appropriate: switch ( fileExtension ) { case "pdf": Response.ContentType = "application/pdf"; break; case "swf": Response.ContentType = "application/x-shockwave-flash"; break; case "gif": Response.ContentType = "image/gif"; break; case "jpeg": Response.ContentType = "image/jpg"; break; case "jpg": Response.ContentType = "image/jpg"; break; case "png": Response.ContentType = "image/png"; break; case "mp4": Response.ContentType = "video/mp4"; break; case "mpeg": Response.ContentType = "video/mpeg"; break; case "mov": Response.ContentType = "video/quicktime"; break; case "wmv": case "avi": Response.ContentType = "video/x-ms-wmv"; break; //and so on default: Response.ContentType = "application/octet-stream"; break; }
Displaying ad content from Respose.WriteFile()/ Response.ContentType How would one display any add content from a "dynamic" aspx page? Currently I am working on using the System.Web.HttpResponse "Page.Response" to write a file that is stored on a web server to a web request. This would allow people to hit a url to the type http://www.foo.com?Image=test.jpg and have the image display in their browser. So as you may know this revolves around the use of Response.ContentType. By using Response.ContentType = "application/octet-stream"; I am able to display images of type gif/jpeg/png (all i have tested so far), bit trying to display.swf or.ico files gives me a nice little error. using Response.ContentType = "application/x-shockwave-flash"; I can get flash files to play, but then the images are messed. So how do i easily choose the contenttype?
TITLE: Displaying ad content from Respose.WriteFile()/ Response.ContentType QUESTION: How would one display any add content from a "dynamic" aspx page? Currently I am working on using the System.Web.HttpResponse "Page.Response" to write a file that is stored on a web server to a web request. This would allow people to hit a url to the type http://www.foo.com?Image=test.jpg and have the image display in their browser. So as you may know this revolves around the use of Response.ContentType. By using Response.ContentType = "application/octet-stream"; I am able to display images of type gif/jpeg/png (all i have tested so far), bit trying to display.swf or.ico files gives me a nice little error. using Response.ContentType = "application/x-shockwave-flash"; I can get flash files to play, but then the images are messed. So how do i easily choose the contenttype? ANSWER: This is ugly, but the best way is to look at the file and set the content type as appropriate: switch ( fileExtension ) { case "pdf": Response.ContentType = "application/pdf"; break; case "swf": Response.ContentType = "application/x-shockwave-flash"; break; case "gif": Response.ContentType = "image/gif"; break; case "jpeg": Response.ContentType = "image/jpg"; break; case "jpg": Response.ContentType = "image/jpg"; break; case "png": Response.ContentType = "image/png"; break; case "mp4": Response.ContentType = "video/mp4"; break; case "mpeg": Response.ContentType = "video/mpeg"; break; case "mov": Response.ContentType = "video/quicktime"; break; case "wmv": case "avi": Response.ContentType = "video/x-ms-wmv"; break; //and so on default: Response.ContentType = "application/octet-stream"; break; }
[ "c#" ]
21
10
19,034
4
0
2008-08-06T09:52:36.603000
2008-08-18T12:10:43.100000
3,255
4,852,666
Big O, how do you calculate/approximate it?
Most people with a degree in CS will certainly know what Big O stands for. It helps us to measure how well an algorithm scales. But I'm curious, how do you calculate or approximate the complexity of your algorithms?
I'll do my best to explain it here on simple terms, but be warned that this topic takes my students a couple of months to finally grasp. You can find more information on the Chapter 2 of the Data Structures and Algorithms in Java book. There is no mechanical procedure that can be used to get the BigOh. As a "cookbook", to obtain the BigOh from a piece of code you first need to realize that you are creating a math formula to count how many steps of computations get executed given an input of some size. The purpose is simple: to compare algorithms from a theoretical point of view, without the need to execute the code. The lesser the number of steps, the faster the algorithm. For example, let's say you have this piece of code: int sum(int* data, int N) { int result = 0; // 1 for (int i = 0; i < N; i++) { // 2 result += data[i]; // 3 } return result; // 4 } This function returns the sum of all the elements of the array, and we want to create a formula to count the computational complexity of that function: Number_Of_Steps = f(N) So we have f(N), a function to count the number of computational steps. The input of the function is the size of the structure to process. It means that this function is called such as: Number_Of_Steps = f(data.length) The parameter N takes the data.length value. Now we need the actual definition of the function f(). This is done from the source code, in which each interesting line is numbered from 1 to 4. There are many ways to calculate the BigOh. From this point forward we are going to assume that every sentence that doesn't depend on the size of the input data takes a constant C number computational steps. We are going to add the individual number of steps of the function, and neither the local variable declaration nor the return statement depends on the size of the data array. That means that lines 1 and 4 takes C amount of steps each, and the function is somewhat like this: f(N) = C +??? + C The next part is to define the value of the for statement. Remember that we are counting the number of computational steps, meaning that the body of the for statement gets executed N times. That's the same as adding C, N times: f(N) = C + (C + C +... + C) + C = C + N * C + C There is no mechanical rule to count how many times the body of the for gets executed, you need to count it by looking at what does the code do. To simplify the calculations, we are ignoring the variable initialization, condition and increment parts of the for statement. To get the actual BigOh we need the Asymptotic analysis of the function. This is roughly done like this: Take away all the constants C. From f() get the polynomium in its standard form. Divide the terms of the polynomium and sort them by the rate of growth. Keep the one that grows bigger when N approaches infinity. Our f() has two terms: f(N) = 2 * C * N ^ 0 + 1 * C * N ^ 1 Taking away all the C constants and redundant parts: f(N) = 1 + N ^ 1 Since the last term is the one which grows bigger when f() approaches infinity (think on limits ) this is the BigOh argument, and the sum() function has a BigOh of: O(N) There are a few tricks to solve some tricky ones: use summations whenever you can. As an example, this code can be easily solved using summations: for (i = 0; i < 2*n; i += 2) { // 1 for (j=n; j > i; j--) { // 2 foo(); // 3 } } The first thing you needed to be asked is the order of execution of foo(). While the usual is to be O(1), you need to ask your professors about it. O(1) means (almost, mostly) constant C, independent of the size N. The for statement on the sentence number one is tricky. While the index ends at 2 * N, the increment is done by two. That means that the first for gets executed only N steps, and we need to divide the count by two. f(N) = Summation(i from 1 to 2 * N / 2)(... ) = = Summation(i from 1 to N)(... ) The sentence number two is even trickier since it depends on the value of i. Take a look: the index i takes the values: 0, 2, 4, 6, 8,..., 2 * N, and the second for get executed: N times the first one, N - 2 the second, N - 4 the third... up to the N / 2 stage, on which the second for never gets executed. On formula, that means: f(N) = Summation(i from 1 to N)( Summation(j =???)( ) ) Again, we are counting the number of steps. And by definition, every summation should always start at one, and end at a number bigger-or-equal than one. f(N) = Summation(i from 1 to N)( Summation(j = 1 to (N - (i - 1) * 2)( C ) ) (We are assuming that foo() is O(1) and takes C steps.) We have a problem here: when i takes the value N / 2 + 1 upwards, the inner Summation ends at a negative number! That's impossible and wrong. We need to split the summation in two, being the pivotal point the moment i takes N / 2 + 1. f(N) = Summation(i from 1 to N / 2)( Summation(j = 1 to (N - (i - 1) * 2)) * ( C ) ) + Summation(i from 1 to N / 2) * ( C ) Since the pivotal moment i > N / 2, the inner for won't get executed, and we are assuming a constant C execution complexity on its body. Now the summations can be simplified using some identity rules: Summation(w from 1 to N)( C ) = N * C Summation(w from 1 to N)( A (+/-) B ) = Summation(w from 1 to N)( A ) (+/-) Summation(w from 1 to N)( B ) Summation(w from 1 to N)( w * C ) = C * Summation(w from 1 to N)( w ) (C is a constant, independent of w ) Summation(w from 1 to N)( w ) = (N * (N + 1)) / 2 Applying some algebra: f(N) = Summation(i from 1 to N / 2)( (N - (i - 1) * 2) * ( C ) ) + (N / 2)( C ) f(N) = C * Summation(i from 1 to N / 2)( (N - (i - 1) * 2)) + (N / 2)( C ) f(N) = C * (Summation(i from 1 to N / 2)( N ) - Summation(i from 1 to N / 2)( (i - 1) * 2)) + (N / 2)( C ) f(N) = C * (( N ^ 2 / 2 ) - 2 * Summation(i from 1 to N / 2)( i - 1 )) + (N / 2)( C ) => Summation(i from 1 to N / 2)( i - 1 ) = Summation(i from 1 to N / 2 - 1)( i ) f(N) = C * (( N ^ 2 / 2 ) - 2 * Summation(i from 1 to N / 2 - 1)( i )) + (N / 2)( C ) f(N) = C * (( N ^ 2 / 2 ) - 2 * ( (N / 2 - 1) * (N / 2 - 1 + 1) / 2) ) + (N / 2)( C ) => (N / 2 - 1) * (N / 2 - 1 + 1) / 2 = (N / 2 - 1) * (N / 2) / 2 = ((N ^ 2 / 4) - (N / 2)) / 2 = (N ^ 2 / 8) - (N / 4) f(N) = C * (( N ^ 2 / 2 ) - 2 * ( (N ^ 2 / 8) - (N / 4) )) + (N / 2)( C ) f(N) = C * (( N ^ 2 / 2 ) - ( (N ^ 2 / 4) - (N / 2) )) + (N / 2)( C ) f(N) = C * (( N ^ 2 / 2 ) - (N ^ 2 / 4) + (N / 2)) + (N / 2)( C ) f(N) = C * ( N ^ 2 / 4 ) + C * (N / 2) + C * (N / 2) f(N) = C * ( N ^ 2 / 4 ) + 2 * C * (N / 2) f(N) = C * ( N ^ 2 / 4 ) + C * N f(N) = C * 1/4 * N ^ 2 + C * N And the BigOh is: O(N²)
Big O, how do you calculate/approximate it? Most people with a degree in CS will certainly know what Big O stands for. It helps us to measure how well an algorithm scales. But I'm curious, how do you calculate or approximate the complexity of your algorithms?
TITLE: Big O, how do you calculate/approximate it? QUESTION: Most people with a degree in CS will certainly know what Big O stands for. It helps us to measure how well an algorithm scales. But I'm curious, how do you calculate or approximate the complexity of your algorithms? ANSWER: I'll do my best to explain it here on simple terms, but be warned that this topic takes my students a couple of months to finally grasp. You can find more information on the Chapter 2 of the Data Structures and Algorithms in Java book. There is no mechanical procedure that can be used to get the BigOh. As a "cookbook", to obtain the BigOh from a piece of code you first need to realize that you are creating a math formula to count how many steps of computations get executed given an input of some size. The purpose is simple: to compare algorithms from a theoretical point of view, without the need to execute the code. The lesser the number of steps, the faster the algorithm. For example, let's say you have this piece of code: int sum(int* data, int N) { int result = 0; // 1 for (int i = 0; i < N; i++) { // 2 result += data[i]; // 3 } return result; // 4 } This function returns the sum of all the elements of the array, and we want to create a formula to count the computational complexity of that function: Number_Of_Steps = f(N) So we have f(N), a function to count the number of computational steps. The input of the function is the size of the structure to process. It means that this function is called such as: Number_Of_Steps = f(data.length) The parameter N takes the data.length value. Now we need the actual definition of the function f(). This is done from the source code, in which each interesting line is numbered from 1 to 4. There are many ways to calculate the BigOh. From this point forward we are going to assume that every sentence that doesn't depend on the size of the input data takes a constant C number computational steps. We are going to add the individual number of steps of the function, and neither the local variable declaration nor the return statement depends on the size of the data array. That means that lines 1 and 4 takes C amount of steps each, and the function is somewhat like this: f(N) = C +??? + C The next part is to define the value of the for statement. Remember that we are counting the number of computational steps, meaning that the body of the for statement gets executed N times. That's the same as adding C, N times: f(N) = C + (C + C +... + C) + C = C + N * C + C There is no mechanical rule to count how many times the body of the for gets executed, you need to count it by looking at what does the code do. To simplify the calculations, we are ignoring the variable initialization, condition and increment parts of the for statement. To get the actual BigOh we need the Asymptotic analysis of the function. This is roughly done like this: Take away all the constants C. From f() get the polynomium in its standard form. Divide the terms of the polynomium and sort them by the rate of growth. Keep the one that grows bigger when N approaches infinity. Our f() has two terms: f(N) = 2 * C * N ^ 0 + 1 * C * N ^ 1 Taking away all the C constants and redundant parts: f(N) = 1 + N ^ 1 Since the last term is the one which grows bigger when f() approaches infinity (think on limits ) this is the BigOh argument, and the sum() function has a BigOh of: O(N) There are a few tricks to solve some tricky ones: use summations whenever you can. As an example, this code can be easily solved using summations: for (i = 0; i < 2*n; i += 2) { // 1 for (j=n; j > i; j--) { // 2 foo(); // 3 } } The first thing you needed to be asked is the order of execution of foo(). While the usual is to be O(1), you need to ask your professors about it. O(1) means (almost, mostly) constant C, independent of the size N. The for statement on the sentence number one is tricky. While the index ends at 2 * N, the increment is done by two. That means that the first for gets executed only N steps, and we need to divide the count by two. f(N) = Summation(i from 1 to 2 * N / 2)(... ) = = Summation(i from 1 to N)(... ) The sentence number two is even trickier since it depends on the value of i. Take a look: the index i takes the values: 0, 2, 4, 6, 8,..., 2 * N, and the second for get executed: N times the first one, N - 2 the second, N - 4 the third... up to the N / 2 stage, on which the second for never gets executed. On formula, that means: f(N) = Summation(i from 1 to N)( Summation(j =???)( ) ) Again, we are counting the number of steps. And by definition, every summation should always start at one, and end at a number bigger-or-equal than one. f(N) = Summation(i from 1 to N)( Summation(j = 1 to (N - (i - 1) * 2)( C ) ) (We are assuming that foo() is O(1) and takes C steps.) We have a problem here: when i takes the value N / 2 + 1 upwards, the inner Summation ends at a negative number! That's impossible and wrong. We need to split the summation in two, being the pivotal point the moment i takes N / 2 + 1. f(N) = Summation(i from 1 to N / 2)( Summation(j = 1 to (N - (i - 1) * 2)) * ( C ) ) + Summation(i from 1 to N / 2) * ( C ) Since the pivotal moment i > N / 2, the inner for won't get executed, and we are assuming a constant C execution complexity on its body. Now the summations can be simplified using some identity rules: Summation(w from 1 to N)( C ) = N * C Summation(w from 1 to N)( A (+/-) B ) = Summation(w from 1 to N)( A ) (+/-) Summation(w from 1 to N)( B ) Summation(w from 1 to N)( w * C ) = C * Summation(w from 1 to N)( w ) (C is a constant, independent of w ) Summation(w from 1 to N)( w ) = (N * (N + 1)) / 2 Applying some algebra: f(N) = Summation(i from 1 to N / 2)( (N - (i - 1) * 2) * ( C ) ) + (N / 2)( C ) f(N) = C * Summation(i from 1 to N / 2)( (N - (i - 1) * 2)) + (N / 2)( C ) f(N) = C * (Summation(i from 1 to N / 2)( N ) - Summation(i from 1 to N / 2)( (i - 1) * 2)) + (N / 2)( C ) f(N) = C * (( N ^ 2 / 2 ) - 2 * Summation(i from 1 to N / 2)( i - 1 )) + (N / 2)( C ) => Summation(i from 1 to N / 2)( i - 1 ) = Summation(i from 1 to N / 2 - 1)( i ) f(N) = C * (( N ^ 2 / 2 ) - 2 * Summation(i from 1 to N / 2 - 1)( i )) + (N / 2)( C ) f(N) = C * (( N ^ 2 / 2 ) - 2 * ( (N / 2 - 1) * (N / 2 - 1 + 1) / 2) ) + (N / 2)( C ) => (N / 2 - 1) * (N / 2 - 1 + 1) / 2 = (N / 2 - 1) * (N / 2) / 2 = ((N ^ 2 / 4) - (N / 2)) / 2 = (N ^ 2 / 8) - (N / 4) f(N) = C * (( N ^ 2 / 2 ) - 2 * ( (N ^ 2 / 8) - (N / 4) )) + (N / 2)( C ) f(N) = C * (( N ^ 2 / 2 ) - ( (N ^ 2 / 4) - (N / 2) )) + (N / 2)( C ) f(N) = C * (( N ^ 2 / 2 ) - (N ^ 2 / 4) + (N / 2)) + (N / 2)( C ) f(N) = C * ( N ^ 2 / 4 ) + C * (N / 2) + C * (N / 2) f(N) = C * ( N ^ 2 / 4 ) + 2 * C * (N / 2) f(N) = C * ( N ^ 2 / 4 ) + C * N f(N) = C * 1/4 * N ^ 2 + C * N And the BigOh is: O(N²)
[ "algorithm", "optimization", "complexity-theory", "big-o", "performance" ]
978
1,554
536,408
24
0
2008-08-06T10:18:16.067000
2011-01-31T15:33:54.120000
3,260
3,288
Peak detection of measured signal
We use a data acquisition card to take readings from a device that increases its signal to a peak and then falls back to near the original value. To find the peak value we currently search the array for the highest reading and use the index to determine the timing of the peak value which is used in our calculations. This works well if the highest value is the peak we are looking for but if the device is not working correctly we can see a second peak which can be higher than the initial peak. We take 10 readings a second from 16 devices over a 90 second period. My initial thoughts are to cycle through the readings checking to see if the previous and next points are less than the current to find a peak and construct an array of peaks. Maybe we should be looking at a average of a number of points either side of the current position to allow for noise in the system. Is this the best way to proceed or are there better techniques? We do use LabVIEW and I have checked the LAVA forums and there are a number of interesting examples. This is part of our test software and we are trying to avoid using too many non-standard VI libraries so I was hoping for feedback on the process/algorithms involved rather than specific code.
You could try signal averaging, i.e. for each point, average the value with the surrounding 3 or more points. If the noise blips are huge, then even this may not help. I realise that this was language agnostic, but guessing that you are using LabView, there are lots of pre-packaged signal processing VIs that come with LabView that you can use to do smoothing and noise reduction. The NI forums are a great place to get more specialised help on this sort of thing.
Peak detection of measured signal We use a data acquisition card to take readings from a device that increases its signal to a peak and then falls back to near the original value. To find the peak value we currently search the array for the highest reading and use the index to determine the timing of the peak value which is used in our calculations. This works well if the highest value is the peak we are looking for but if the device is not working correctly we can see a second peak which can be higher than the initial peak. We take 10 readings a second from 16 devices over a 90 second period. My initial thoughts are to cycle through the readings checking to see if the previous and next points are less than the current to find a peak and construct an array of peaks. Maybe we should be looking at a average of a number of points either side of the current position to allow for noise in the system. Is this the best way to proceed or are there better techniques? We do use LabVIEW and I have checked the LAVA forums and there are a number of interesting examples. This is part of our test software and we are trying to avoid using too many non-standard VI libraries so I was hoping for feedback on the process/algorithms involved rather than specific code.
TITLE: Peak detection of measured signal QUESTION: We use a data acquisition card to take readings from a device that increases its signal to a peak and then falls back to near the original value. To find the peak value we currently search the array for the highest reading and use the index to determine the timing of the peak value which is used in our calculations. This works well if the highest value is the peak we are looking for but if the device is not working correctly we can see a second peak which can be higher than the initial peak. We take 10 readings a second from 16 devices over a 90 second period. My initial thoughts are to cycle through the readings checking to see if the previous and next points are less than the current to find a peak and construct an array of peaks. Maybe we should be looking at a average of a number of points either side of the current position to allow for noise in the system. Is this the best way to proceed or are there better techniques? We do use LabVIEW and I have checked the LAVA forums and there are a number of interesting examples. This is part of our test software and we are trying to avoid using too many non-standard VI libraries so I was hoping for feedback on the process/algorithms involved rather than specific code. ANSWER: You could try signal averaging, i.e. for each point, average the value with the surrounding 3 or more points. If the noise blips are huge, then even this may not help. I realise that this was language agnostic, but guessing that you are using LabView, there are lots of pre-packaged signal processing VIs that come with LabView that you can use to do smoothing and noise reduction. The NI forums are a great place to get more specialised help on this sort of thing.
[ "algorithm", "language-agnostic" ]
60
10
63,004
9
0
2008-08-06T10:23:18.833000
2008-08-06T11:12:48.890000
3,272
5,101
Timer-based event triggers
I am currently working on a project with specific requirements. A brief overview of these are as follows: Data is retrieved from external webservices Data is stored in SQL 2005 Data is manipulated via a web GUI The windows service that communicates with the web services has no coupling with our internal web UI, except via the database. Communication with the web services needs to be both time-based, and triggered via user intervention on the web UI. The current (pre-pre-production) model for web service communication triggering is via a database table that stores trigger requests generated from the manual intervention. I do not really want to have multiple trigger mechanisms, but would like to be able to populate the database table with triggers based upon the time of the call. As I see it there are two ways to accomplish this. 1) Adapt the trigger table to store two extra parameters. One being "Is this time-based or manually added?" and a nullable field to store the timing details (exact format to be determined). If it is a manaully created trigger, mark it as processed when the trigger has been fired, but not if it is a timed trigger. or 2) Create a second windows service that creates the triggers on-the-fly at timed intervals. The second option seems like a fudge to me, but the management of option 1 could easily turn into a programming nightmare (how do you know if the last poll of the table returned the event that needs to fire, and how do you then stop it re-triggering on the next poll) I'd appreciate it if anyone could spare a few minutes to help me decide which route (one of these two, or possibly a third, unlisted one) to take.
Why not use a SQL Job instead of the Windows Service? You can encapsulate all of you db "trigger" code in Stored Procedures. Then your UI and SQL Job can call the same Stored Procedures and create the triggers the same way whether it's manually or at a time interval.
Timer-based event triggers I am currently working on a project with specific requirements. A brief overview of these are as follows: Data is retrieved from external webservices Data is stored in SQL 2005 Data is manipulated via a web GUI The windows service that communicates with the web services has no coupling with our internal web UI, except via the database. Communication with the web services needs to be both time-based, and triggered via user intervention on the web UI. The current (pre-pre-production) model for web service communication triggering is via a database table that stores trigger requests generated from the manual intervention. I do not really want to have multiple trigger mechanisms, but would like to be able to populate the database table with triggers based upon the time of the call. As I see it there are two ways to accomplish this. 1) Adapt the trigger table to store two extra parameters. One being "Is this time-based or manually added?" and a nullable field to store the timing details (exact format to be determined). If it is a manaully created trigger, mark it as processed when the trigger has been fired, but not if it is a timed trigger. or 2) Create a second windows service that creates the triggers on-the-fly at timed intervals. The second option seems like a fudge to me, but the management of option 1 could easily turn into a programming nightmare (how do you know if the last poll of the table returned the event that needs to fire, and how do you then stop it re-triggering on the next poll) I'd appreciate it if anyone could spare a few minutes to help me decide which route (one of these two, or possibly a third, unlisted one) to take.
TITLE: Timer-based event triggers QUESTION: I am currently working on a project with specific requirements. A brief overview of these are as follows: Data is retrieved from external webservices Data is stored in SQL 2005 Data is manipulated via a web GUI The windows service that communicates with the web services has no coupling with our internal web UI, except via the database. Communication with the web services needs to be both time-based, and triggered via user intervention on the web UI. The current (pre-pre-production) model for web service communication triggering is via a database table that stores trigger requests generated from the manual intervention. I do not really want to have multiple trigger mechanisms, but would like to be able to populate the database table with triggers based upon the time of the call. As I see it there are two ways to accomplish this. 1) Adapt the trigger table to store two extra parameters. One being "Is this time-based or manually added?" and a nullable field to store the timing details (exact format to be determined). If it is a manaully created trigger, mark it as processed when the trigger has been fired, but not if it is a timed trigger. or 2) Create a second windows service that creates the triggers on-the-fly at timed intervals. The second option seems like a fudge to me, but the management of option 1 could easily turn into a programming nightmare (how do you know if the last poll of the table returned the event that needs to fire, and how do you then stop it re-triggering on the next poll) I'd appreciate it if anyone could spare a few minutes to help me decide which route (one of these two, or possibly a third, unlisted one) to take. ANSWER: Why not use a SQL Job instead of the Windows Service? You can encapsulate all of you db "trigger" code in Stored Procedures. Then your UI and SQL Job can call the same Stored Procedures and create the triggers the same way whether it's manually or at a time interval.
[ "sql", "web-services", "service", "triggers", "timer" ]
15
3
3,280
3
0
2008-08-06T10:43:16.720000
2008-08-07T18:24:09.863000
3,281
4,270
Mapping values from two array in Ruby
I'm wondering if there's a way to do what I can do below with Python, in Ruby: sum = reduce(lambda x, y: x + y, map(lambda x, y: x * y, weights, data)) I have two arrays of equal sizes with the weights and data but I can't seem to find a function similar to map in Ruby, reduce I have working.
@Michiel de Mare Your Ruby 1.9 example can be shortened a bit further: weights.zip(data).map(:*).reduce(:+) Also note that in Ruby 1.8, if you require ActiveSupport (from Rails) you can use: weights.zip(data).map(&:*).reduce(&:+)
Mapping values from two array in Ruby I'm wondering if there's a way to do what I can do below with Python, in Ruby: sum = reduce(lambda x, y: x + y, map(lambda x, y: x * y, weights, data)) I have two arrays of equal sizes with the weights and data but I can't seem to find a function similar to map in Ruby, reduce I have working.
TITLE: Mapping values from two array in Ruby QUESTION: I'm wondering if there's a way to do what I can do below with Python, in Ruby: sum = reduce(lambda x, y: x + y, map(lambda x, y: x * y, weights, data)) I have two arrays of equal sizes with the weights and data but I can't seem to find a function similar to map in Ruby, reduce I have working. ANSWER: @Michiel de Mare Your Ruby 1.9 example can be shortened a bit further: weights.zip(data).map(:*).reduce(:+) Also note that in Ruby 1.8, if you require ActiveSupport (from Rails) you can use: weights.zip(data).map(&:*).reduce(&:+)
[ "ruby", "maps", "reduce" ]
23
14
15,847
6
0
2008-08-06T11:02:20.597000
2008-08-07T01:29:05.777000
3,284
3,294
Why can't I have abstract static methods in C#?
I've been working with providers a fair bit lately, and I came across an interesting situation where I wanted to have an abstract class that had an abstract static method. I read a few posts on the topic, and it sort of made sense, but is there a nice clear explanation?
Static methods are not instantiated as such, they're just available without an object reference. A call to a static method is done through the class name, not through an object reference, and the Intermediate Language (IL) code to call it will call the abstract method through the name of the class that defined it, not necessarily the name of the class you used. Let me show an example. With the following code: public class A { public static void Test() { } } public class B: A { } If you call B.Test, like this: class Program { static void Main(string[] args) { B.Test(); } } Then the actual code inside the Main method is as follows:.entrypoint.maxstack 8 L0000: nop L0001: call void ConsoleApplication1.A::Test() L0006: nop L0007: ret As you can see, the call is made to A.Test, because it was the A class that defined it, and not to B.Test, even though you can write the code that way. If you had class types, like in the Delphi Programming Language, where you can make a variable referring to a type and not an object, you would have more use for virtual and thus abstract static methods (and also constructors), but they aren't available and thus static calls are non-virtual in.NET. I realize that the IL designers could allow the code to be compiled to call B.Test, and resolve the call at runtime, but it still wouldn't be virtual, as you would still have to write some kind of class name there. Virtual methods, and thus abstract ones, are only useful when you're using a variable which, at runtime, can contain many different types of objects, and you thus want to call the right method for the current object you have in the variable. With static methods you need to go through a class name anyway, so the exact method to call is known at compile time because it can't and won't change. Thus, virtual/abstract static methods are not available in.NET.
Why can't I have abstract static methods in C#? I've been working with providers a fair bit lately, and I came across an interesting situation where I wanted to have an abstract class that had an abstract static method. I read a few posts on the topic, and it sort of made sense, but is there a nice clear explanation?
TITLE: Why can't I have abstract static methods in C#? QUESTION: I've been working with providers a fair bit lately, and I came across an interesting situation where I wanted to have an abstract class that had an abstract static method. I read a few posts on the topic, and it sort of made sense, but is there a nice clear explanation? ANSWER: Static methods are not instantiated as such, they're just available without an object reference. A call to a static method is done through the class name, not through an object reference, and the Intermediate Language (IL) code to call it will call the abstract method through the name of the class that defined it, not necessarily the name of the class you used. Let me show an example. With the following code: public class A { public static void Test() { } } public class B: A { } If you call B.Test, like this: class Program { static void Main(string[] args) { B.Test(); } } Then the actual code inside the Main method is as follows:.entrypoint.maxstack 8 L0000: nop L0001: call void ConsoleApplication1.A::Test() L0006: nop L0007: ret As you can see, the call is made to A.Test, because it was the A class that defined it, and not to B.Test, even though you can write the code that way. If you had class types, like in the Delphi Programming Language, where you can make a variable referring to a type and not an object, you would have more use for virtual and thus abstract static methods (and also constructors), but they aren't available and thus static calls are non-virtual in.NET. I realize that the IL designers could allow the code to be compiled to call B.Test, and resolve the call at runtime, but it still wouldn't be virtual, as you would still have to write some kind of class name there. Virtual methods, and thus abstract ones, are only useful when you're using a variable which, at runtime, can contain many different types of objects, and you thus want to call the right method for the current object you have in the variable. With static methods you need to go through a class name anyway, so the exact method to call is known at compile time because it can't and won't change. Thus, virtual/abstract static methods are not available in.NET.
[ "c#", ".net", "language-design" ]
215
164
136,119
10
0
2008-08-06T11:04:33.587000
2008-08-06T11:30:07.093000
3,315
3,316
Can I have a method returning IEnumerator<T> and use it in a foreach loop?
I need to set the height of every textbox on my form, some of which are nested within other controls. I thought I could do something like this: private static IEnumerator FindTextBoxes(Control rootControl) { foreach (Control control in rootControl.Controls) { if (control.Controls.Count > 0) { // Recursively search for any TextBoxes within each child control foreach (TextBox textBox in FindTextBoxes(control)) { yield return textBox; } } TextBox textBox2 = control as TextBox; if (textBox2!= null) { yield return textBox2; } } } Using it like this: foreach(TextBox textBox in FindTextBoxes(this)) { textBox.Height = height; } But of course the compiler spits its dummy, because foreach expects an IEnumerable rather than an IEnumerator. Is there a way to do this without having to create a separate class with a GetEnumerator() method?
As the compiler is telling you, you need to change your return type to IEnumerable. That is how the yield return syntax works.
Can I have a method returning IEnumerator<T> and use it in a foreach loop? I need to set the height of every textbox on my form, some of which are nested within other controls. I thought I could do something like this: private static IEnumerator FindTextBoxes(Control rootControl) { foreach (Control control in rootControl.Controls) { if (control.Controls.Count > 0) { // Recursively search for any TextBoxes within each child control foreach (TextBox textBox in FindTextBoxes(control)) { yield return textBox; } } TextBox textBox2 = control as TextBox; if (textBox2!= null) { yield return textBox2; } } } Using it like this: foreach(TextBox textBox in FindTextBoxes(this)) { textBox.Height = height; } But of course the compiler spits its dummy, because foreach expects an IEnumerable rather than an IEnumerator. Is there a way to do this without having to create a separate class with a GetEnumerator() method?
TITLE: Can I have a method returning IEnumerator<T> and use it in a foreach loop? QUESTION: I need to set the height of every textbox on my form, some of which are nested within other controls. I thought I could do something like this: private static IEnumerator FindTextBoxes(Control rootControl) { foreach (Control control in rootControl.Controls) { if (control.Controls.Count > 0) { // Recursively search for any TextBoxes within each child control foreach (TextBox textBox in FindTextBoxes(control)) { yield return textBox; } } TextBox textBox2 = control as TextBox; if (textBox2!= null) { yield return textBox2; } } } Using it like this: foreach(TextBox textBox in FindTextBoxes(this)) { textBox.Height = height; } But of course the compiler spits its dummy, because foreach expects an IEnumerable rather than an IEnumerator. Is there a way to do this without having to create a separate class with a GetEnumerator() method? ANSWER: As the compiler is telling you, you need to change your return type to IEnumerable. That is how the yield return syntax works.
[ "c#", "foreach", "ienumerable", "ienumerator" ]
22
14
13,369
5
0
2008-08-06T12:17:31.320000
2008-08-06T12:19:57.367000
3,319
3,321
How to set background color of HTML element using css properties in JavaScript
How can I set the background color of an HTML element using css in JavaScript?
In general, CSS properties are converted to JavaScript by making them camelCase without any dashes. So background-color becomes backgroundColor. function setColor(element, color) { element.style.backgroundColor = color; } // where el is the concerned element var el = document.getElementById('elementId'); setColor(el, 'green');
How to set background color of HTML element using css properties in JavaScript How can I set the background color of an HTML element using css in JavaScript?
TITLE: How to set background color of HTML element using css properties in JavaScript QUESTION: How can I set the background color of an HTML element using css in JavaScript? ANSWER: In general, CSS properties are converted to JavaScript by making them camelCase without any dashes. So background-color becomes backgroundColor. function setColor(element, color) { element.style.backgroundColor = color; } // where el is the concerned element var el = document.getElementById('elementId'); setColor(el, 'green');
[ "javascript", "css", "background-color" ]
129
167
187,932
17
0
2008-08-06T12:23:22.413000
2008-08-06T12:25:54.920000
3,362
13,130
Capturing TAB key in text box
I would like to be able to use the Tab key within a text box to tab over four spaces. The way it is now, the Tab key jumps my cursor to the next input. Is there some JavaScript that will capture the Tab key in the text box before it bubbles up to the UI? I understand some browsers (i.e. FireFox) may not allow this. How about a custom key-combo like Shift + Tab, or Ctrl + Q?
Even if you capture the keydown / keyup event, those are the only events that the tab key fires, you still need some way to prevent the default action, moving to the next item in the tab order, from occurring. In Firefox you can call the preventDefault() method on the event object passed to your event handler. In IE, you have to return false from the event handle. The JQuery library provides a preventDefault method on its event object that works in IE and FF.
Capturing TAB key in text box I would like to be able to use the Tab key within a text box to tab over four spaces. The way it is now, the Tab key jumps my cursor to the next input. Is there some JavaScript that will capture the Tab key in the text box before it bubbles up to the UI? I understand some browsers (i.e. FireFox) may not allow this. How about a custom key-combo like Shift + Tab, or Ctrl + Q?
TITLE: Capturing TAB key in text box QUESTION: I would like to be able to use the Tab key within a text box to tab over four spaces. The way it is now, the Tab key jumps my cursor to the next input. Is there some JavaScript that will capture the Tab key in the text box before it bubbles up to the UI? I understand some browsers (i.e. FireFox) may not allow this. How about a custom key-combo like Shift + Tab, or Ctrl + Q? ANSWER: Even if you capture the keydown / keyup event, those are the only events that the tab key fires, you still need some way to prevent the default action, moving to the next item in the tab order, from occurring. In Firefox you can call the preventDefault() method on the event object passed to your event handler. In IE, you have to return false from the event handle. The JQuery library provides a preventDefault method on its event object that works in IE and FF.
[ "javascript", "user-interface" ]
110
115
180,443
6
0
2008-08-06T13:27:05.453000
2008-08-16T13:55:26.087000
3,385
10,747
MAC addresses in JavaScript
I know that we can get the MAC address of a user via IE (ActiveX objects). Is there a way to obtain a user's MAC address using JavaScript?
I concur with all the previous answers that it would be a privacy/security vulnerability if you would be able to do this directly from Javascript. There are two things I can think of: Using Java (with a signed applet) Using signed Javascript, which in FF (and Mozilla in general) gets higher privileges than normal JS (but it is fairly complicated to set up)
MAC addresses in JavaScript I know that we can get the MAC address of a user via IE (ActiveX objects). Is there a way to obtain a user's MAC address using JavaScript?
TITLE: MAC addresses in JavaScript QUESTION: I know that we can get the MAC address of a user via IE (ActiveX objects). Is there a way to obtain a user's MAC address using JavaScript? ANSWER: I concur with all the previous answers that it would be a privacy/security vulnerability if you would be able to do this directly from Javascript. There are two things I can think of: Using Java (with a signed applet) Using signed Javascript, which in FF (and Mozilla in general) gets higher privileges than normal JS (but it is fairly complicated to set up)
[ "javascript", "mac-address" ]
124
74
267,011
8
0
2008-08-06T13:43:44.983000
2008-08-14T06:21:12.150000
3,404
3,409
JavaScript Troubleshooting Tools in Internet Explorer
I use Firebug and the Mozilla JS console heavily, but every now and then I run into an IE-only JavaScript bug, which is really hard to locate (ex: error on line 724, when the source HTML only has 200 lines). I would love to have a lightweight JS tool ( a la firebug) for Internet Explorer, something I can install in seconds on a client's PC if I run into an error and then uninstall. Some Microsoft tools take some serious download and configuration time. Any ideas?
You might find Firebug Lite useful for that. Its bookmarklet should be especially useful when debugging on a user's machine.
JavaScript Troubleshooting Tools in Internet Explorer I use Firebug and the Mozilla JS console heavily, but every now and then I run into an IE-only JavaScript bug, which is really hard to locate (ex: error on line 724, when the source HTML only has 200 lines). I would love to have a lightweight JS tool ( a la firebug) for Internet Explorer, something I can install in seconds on a client's PC if I run into an error and then uninstall. Some Microsoft tools take some serious download and configuration time. Any ideas?
TITLE: JavaScript Troubleshooting Tools in Internet Explorer QUESTION: I use Firebug and the Mozilla JS console heavily, but every now and then I run into an IE-only JavaScript bug, which is really hard to locate (ex: error on line 724, when the source HTML only has 200 lines). I would love to have a lightweight JS tool ( a la firebug) for Internet Explorer, something I can install in seconds on a client's PC if I run into an error and then uninstall. Some Microsoft tools take some serious download and configuration time. Any ideas? ANSWER: You might find Firebug Lite useful for that. Its bookmarklet should be especially useful when debugging on a user's machine.
[ "javascript", "internet-explorer", "debugging" ]
44
30
7,212
7
0
2008-08-06T13:56:42.210000
2008-08-06T13:59:47.213000
3,408
166,705
Ruby On Rails with Windows Vista - Best Setup?
What do you think is the best set-up for RoR in a Win Vista environment? I've tried the radrails eclipse plug-in, and it just seemed too bulky for me, I've also started to just use Textpad and the command line, but I'm used to having somewhat of an IDE to work with.
I don't know about "best", because that's a subjective question, but I can tell you what setup I use and recommend: Editor: E Text Editor TextMate seems to be the editor of choice for Rails on Mac. E Text Editor is essentially TextMate for Windows. Its bundles are broadly compatible with TextMate's including the Rails 2 bundle which is included with the basic install. Alternatively, if you're into the whole Visual Studio ecosystem, then Ruby in Steel PE might be a better bet. It's a really nice all-in-one package that actually comes with (a stripped-down version of) Visual Studio now. Environment: VirtualBox running Ubuntu Server Deploying a Rails app can be a pain at the best of times; deploying a Rails app from a Windows environment onto a *nix server is even worse. Plus, running Rails apps on Windows is slow. Running your tests is slow. So I use VirtualBox to host a VM on my Windows machine that mirrors my target deployment environment as closely as possible. In my case I run Ubuntu Server because there are a really nice set of step-by-step tutorials for getting up-and-running with a full Ubuntu-based Rails stack on the SliceHost wiki. Here are the benefits of developing using a VM: I map a network drive to the VM so that I can edit the code on it directly from Windows using E Text Editor. The VM acts and feels just like a command line window. So you don't feel like you're in a completely alien environment. It runs Rails and other Ruby scripts (like tests) faster than running it natively in Windows Everything is contained and snapshottable, so I can experiment and generally play around without worrying about breaking anything. If something does break, I just roll back to a previous good state. It uses hardly any RAM. It will typically use less that 100MB (it's currently using ~43MB, but I don't have a Rails app spun-up). Contrast this with, say, Firefox which will typically be hogging >200MB and you realize that running a Linux-based VM like this is amazingly efficient. I can move my environment between machines I have much more robust deployment workflow I can limit the VM to have exactly the same amount of RAM as the server I'll be hosting on. E.g., if I'm to be using a SliceHost 256MB slice, I would limit the RAM to 256MB. I can build a seperate environment for different hosts. If I wanted to host on Joyent, for example, I could build an Open Solaris VM Gems and other binaries won't need recompiling for your target environment It's "a good thing"™ to get to grips with the environment your Rails app is likely to be running on. Seeing as most, if not all, commercial Rails hosts run some sort of *nix derivative, you're going to want to be comfortable with the *nix environment.
Ruby On Rails with Windows Vista - Best Setup? What do you think is the best set-up for RoR in a Win Vista environment? I've tried the radrails eclipse plug-in, and it just seemed too bulky for me, I've also started to just use Textpad and the command line, but I'm used to having somewhat of an IDE to work with.
TITLE: Ruby On Rails with Windows Vista - Best Setup? QUESTION: What do you think is the best set-up for RoR in a Win Vista environment? I've tried the radrails eclipse plug-in, and it just seemed too bulky for me, I've also started to just use Textpad and the command line, but I'm used to having somewhat of an IDE to work with. ANSWER: I don't know about "best", because that's a subjective question, but I can tell you what setup I use and recommend: Editor: E Text Editor TextMate seems to be the editor of choice for Rails on Mac. E Text Editor is essentially TextMate for Windows. Its bundles are broadly compatible with TextMate's including the Rails 2 bundle which is included with the basic install. Alternatively, if you're into the whole Visual Studio ecosystem, then Ruby in Steel PE might be a better bet. It's a really nice all-in-one package that actually comes with (a stripped-down version of) Visual Studio now. Environment: VirtualBox running Ubuntu Server Deploying a Rails app can be a pain at the best of times; deploying a Rails app from a Windows environment onto a *nix server is even worse. Plus, running Rails apps on Windows is slow. Running your tests is slow. So I use VirtualBox to host a VM on my Windows machine that mirrors my target deployment environment as closely as possible. In my case I run Ubuntu Server because there are a really nice set of step-by-step tutorials for getting up-and-running with a full Ubuntu-based Rails stack on the SliceHost wiki. Here are the benefits of developing using a VM: I map a network drive to the VM so that I can edit the code on it directly from Windows using E Text Editor. The VM acts and feels just like a command line window. So you don't feel like you're in a completely alien environment. It runs Rails and other Ruby scripts (like tests) faster than running it natively in Windows Everything is contained and snapshottable, so I can experiment and generally play around without worrying about breaking anything. If something does break, I just roll back to a previous good state. It uses hardly any RAM. It will typically use less that 100MB (it's currently using ~43MB, but I don't have a Rails app spun-up). Contrast this with, say, Firefox which will typically be hogging >200MB and you realize that running a Linux-based VM like this is amazingly efficient. I can move my environment between machines I have much more robust deployment workflow I can limit the VM to have exactly the same amount of RAM as the server I'll be hosting on. E.g., if I'm to be using a SliceHost 256MB slice, I would limit the RAM to 256MB. I can build a seperate environment for different hosts. If I wanted to host on Joyent, for example, I could build an Open Solaris VM Gems and other binaries won't need recompiling for your target environment It's "a good thing"™ to get to grips with the environment your Rails app is likely to be running on. Seeing as most, if not all, commercial Rails hosts run some sort of *nix derivative, you're going to want to be comfortable with the *nix environment.
[ "ruby-on-rails", "windows", "ruby", "ide" ]
17
14
4,390
11
0
2008-08-06T13:59:16.793000
2008-10-03T12:59:40.110000
3,432
3,466
Multiple Updates in MySQL
I know that you can insert multiple rows at once, is there a way to update multiple rows at once (as in, in one query) in MySQL? Edit: For example I have the following Name id Col1 Col2 Row1 1 6 1 Row2 2 2 3 Row3 3 9 5 Row4 4 16 8 I want to combine all the following Updates into one query UPDATE table SET Col1 = 1 WHERE id = 1; UPDATE table SET Col1 = 2 WHERE id = 2; UPDATE table SET Col2 = 3 WHERE id = 3; UPDATE table SET Col1 = 10 WHERE id = 4; UPDATE table SET Col2 = 12 WHERE id = 4;
Yes, that's possible - you can use INSERT... ON DUPLICATE KEY UPDATE. Using your example: INSERT INTO table (id,Col1,Col2) VALUES (1,1,1),(2,2,3),(3,9,3),(4,10,12) ON DUPLICATE KEY UPDATE Col1=VALUES(Col1),Col2=VALUES(Col2);
Multiple Updates in MySQL I know that you can insert multiple rows at once, is there a way to update multiple rows at once (as in, in one query) in MySQL? Edit: For example I have the following Name id Col1 Col2 Row1 1 6 1 Row2 2 2 3 Row3 3 9 5 Row4 4 16 8 I want to combine all the following Updates into one query UPDATE table SET Col1 = 1 WHERE id = 1; UPDATE table SET Col1 = 2 WHERE id = 2; UPDATE table SET Col2 = 3 WHERE id = 3; UPDATE table SET Col1 = 10 WHERE id = 4; UPDATE table SET Col2 = 12 WHERE id = 4;
TITLE: Multiple Updates in MySQL QUESTION: I know that you can insert multiple rows at once, is there a way to update multiple rows at once (as in, in one query) in MySQL? Edit: For example I have the following Name id Col1 Col2 Row1 1 6 1 Row2 2 2 3 Row3 3 9 5 Row4 4 16 8 I want to combine all the following Updates into one query UPDATE table SET Col1 = 1 WHERE id = 1; UPDATE table SET Col1 = 2 WHERE id = 2; UPDATE table SET Col2 = 3 WHERE id = 3; UPDATE table SET Col1 = 10 WHERE id = 4; UPDATE table SET Col2 = 12 WHERE id = 4; ANSWER: Yes, that's possible - you can use INSERT... ON DUPLICATE KEY UPDATE. Using your example: INSERT INTO table (id,Col1,Col2) VALUES (1,1,1),(2,2,3),(3,9,3),(4,10,12) ON DUPLICATE KEY UPDATE Col1=VALUES(Col1),Col2=VALUES(Col2);
[ "mysql", "sql", "sql-update" ]
448
726
500,717
20
0
2008-08-06T14:12:09.903000
2008-08-06T14:33:41.560000
3,437
20,612
Options for Google Maps over SSL
We recently discovered that the Google Maps API does not play nicely with SSL. Fair enough, but what are some options for overcoming this that others have used effectively? Will the Maps API work over SSL (HTTPS)? At this time, the Maps API is not available over a secure (SSL) connection. If you are running the Maps API on a secure site, the browser may warn the user about non-secure objects on the screen. We have considered the following options Splitting the page so that credit card collection (the requirement for SSL) is not on the same page as the Google Map. Switching to another map provider, such as Virtual Earth. Rumor has it that they support SSL. Playing tricks with IFRAMEs. Sounds kludgy. Proxying the calls to Google. Sounds like a lot of overhead. Are there other options, or does anyone have insight into the options that we have considered?
I'd agree with the previous two answers that in this instance it may be better from a usability perspective to split the two functions into separate screens. You really want your users to be focussed on entering complete and accurate credit card information, and having a map on the same screen may be distracting. For the record though, Virtual Earth certainly does fully support SSL. To enable it you simple need to change the script reference from http:// to https:// and append &s=1 to the URL, e.g. becomes
Options for Google Maps over SSL We recently discovered that the Google Maps API does not play nicely with SSL. Fair enough, but what are some options for overcoming this that others have used effectively? Will the Maps API work over SSL (HTTPS)? At this time, the Maps API is not available over a secure (SSL) connection. If you are running the Maps API on a secure site, the browser may warn the user about non-secure objects on the screen. We have considered the following options Splitting the page so that credit card collection (the requirement for SSL) is not on the same page as the Google Map. Switching to another map provider, such as Virtual Earth. Rumor has it that they support SSL. Playing tricks with IFRAMEs. Sounds kludgy. Proxying the calls to Google. Sounds like a lot of overhead. Are there other options, or does anyone have insight into the options that we have considered?
TITLE: Options for Google Maps over SSL QUESTION: We recently discovered that the Google Maps API does not play nicely with SSL. Fair enough, but what are some options for overcoming this that others have used effectively? Will the Maps API work over SSL (HTTPS)? At this time, the Maps API is not available over a secure (SSL) connection. If you are running the Maps API on a secure site, the browser may warn the user about non-secure objects on the screen. We have considered the following options Splitting the page so that credit card collection (the requirement for SSL) is not on the same page as the Google Map. Switching to another map provider, such as Virtual Earth. Rumor has it that they support SSL. Playing tricks with IFRAMEs. Sounds kludgy. Proxying the calls to Google. Sounds like a lot of overhead. Are there other options, or does anyone have insight into the options that we have considered? ANSWER: I'd agree with the previous two answers that in this instance it may be better from a usability perspective to split the two functions into separate screens. You really want your users to be focussed on entering complete and accurate credit card information, and having a map on the same screen may be distracting. For the record though, Virtual Earth certainly does fully support SSL. To enable it you simple need to change the script reference from http:// to https:// and append &s=1 to the URL, e.g. becomes
[ "google-maps", "iframe", "ssl", "https" ]
20
15
15,432
7
0
2008-08-06T14:14:29.383000
2008-08-21T17:32:37.307000
3,448
3,492
Is it acceptable for invalid XHTML?
I've noticed a lot of sites, SO included, use XHTML as their mark-up language and then fail to adhere to the spec. Just browsing the source for SO there are missing closing tags for paragraphs, invalid elements, etc. So should tools (and developers) use the XHTML doctype if they are going to produce invalid mark up? And should browsers be more firm in their acceptance of poor mark-up? And before anyone shouts hypocrite, my blog has one piece of invalid mark-up involving the captha (or it did the last time I checked) which involves styling the noscript tag.
There are many reasons to use valid markup. My favorite is that it allows you to use validation as a form of regression testing, preventing the markup equivalent of "delta rot" from leading to real rendering problems once the errors reach some critical mass. And really, it's just plain sloppy to allow "lazy" errors like typos and mis-nested/unclosed tags to accumulate. Valid markup is one way to identify passionate programmers. There's also the issue of debugging: valid markup also gives you a stable baseline from which to work on the inevitable cross-browser compatibility woes. No web developer who values his time should begin debugging browser compatibility problems without first ensuring that the markup is at least syntactically valid—and any other invalid markup should have a good reason for being there. (Incidentally, stackoverflow.com fails both these tests, and suggestions to fix the problems were declined.) All of that said, to answer your specific question, it's probably not worthwhile to use one of the XHTML doctypes unless you plan to produce valid (or at least well-formed) markup. XHTML's primary advantages are derived from the fact that XHTML is XML, allowing it to be processed and transformed by tools and technologies that work with XML. If you don't plan to make your XHTML well-formed XML, then there's little point in choosing that doctype. The latest HTML 4 spec will probably do everything you need, and it's much more forgiving.
Is it acceptable for invalid XHTML? I've noticed a lot of sites, SO included, use XHTML as their mark-up language and then fail to adhere to the spec. Just browsing the source for SO there are missing closing tags for paragraphs, invalid elements, etc. So should tools (and developers) use the XHTML doctype if they are going to produce invalid mark up? And should browsers be more firm in their acceptance of poor mark-up? And before anyone shouts hypocrite, my blog has one piece of invalid mark-up involving the captha (or it did the last time I checked) which involves styling the noscript tag.
TITLE: Is it acceptable for invalid XHTML? QUESTION: I've noticed a lot of sites, SO included, use XHTML as their mark-up language and then fail to adhere to the spec. Just browsing the source for SO there are missing closing tags for paragraphs, invalid elements, etc. So should tools (and developers) use the XHTML doctype if they are going to produce invalid mark up? And should browsers be more firm in their acceptance of poor mark-up? And before anyone shouts hypocrite, my blog has one piece of invalid mark-up involving the captha (or it did the last time I checked) which involves styling the noscript tag. ANSWER: There are many reasons to use valid markup. My favorite is that it allows you to use validation as a form of regression testing, preventing the markup equivalent of "delta rot" from leading to real rendering problems once the errors reach some critical mass. And really, it's just plain sloppy to allow "lazy" errors like typos and mis-nested/unclosed tags to accumulate. Valid markup is one way to identify passionate programmers. There's also the issue of debugging: valid markup also gives you a stable baseline from which to work on the inevitable cross-browser compatibility woes. No web developer who values his time should begin debugging browser compatibility problems without first ensuring that the markup is at least syntactically valid—and any other invalid markup should have a good reason for being there. (Incidentally, stackoverflow.com fails both these tests, and suggestions to fix the problems were declined.) All of that said, to answer your specific question, it's probably not worthwhile to use one of the XHTML doctypes unless you plan to produce valid (or at least well-formed) markup. XHTML's primary advantages are derived from the fact that XHTML is XML, allowing it to be processed and transformed by tools and technologies that work with XML. If you don't plan to make your XHTML well-formed XML, then there's little point in choosing that doctype. The latest HTML 4 spec will probably do everything you need, and it's much more forgiving.
[ "xhtml", "markup" ]
22
16
2,094
14
0
2008-08-06T14:21:18.823000
2008-08-06T14:46:40.660000
3,452
34,153
SQL Client for Mac OS X that works with MS SQL Server
How can I connect to a remote SQL server using Mac OS X? I don't really need a GUI, but it would be nice to have for the color coding and resultset grid. I'd rather not have to use a VM. Is there a SQL client for Mac OS X that works with MS SQL Server?
Let's work together on a canonical answer. Native Apps SQLPro for MSSQL Navicat Valentina Studio TablePlus Java-Based Oracle SQL Developer (free) SQuirrel SQL (free, open source) Razor SQL DB Visualizer DBeaver (free, open source) SQL Workbench/J (free, open source) JetBrains DataGrip Metabase (free, open source) Netbeans (free, open source, full development environment) Electron-Based Visual Studio Code with mssql extension Azure Data Studio SQLectron (TODO: Add others mentioned below)
SQL Client for Mac OS X that works with MS SQL Server How can I connect to a remote SQL server using Mac OS X? I don't really need a GUI, but it would be nice to have for the color coding and resultset grid. I'd rather not have to use a VM. Is there a SQL client for Mac OS X that works with MS SQL Server?
TITLE: SQL Client for Mac OS X that works with MS SQL Server QUESTION: How can I connect to a remote SQL server using Mac OS X? I don't really need a GUI, but it would be nice to have for the color coding and resultset grid. I'd rather not have to use a VM. Is there a SQL client for Mac OS X that works with MS SQL Server? ANSWER: Let's work together on a canonical answer. Native Apps SQLPro for MSSQL Navicat Valentina Studio TablePlus Java-Based Oracle SQL Developer (free) SQuirrel SQL (free, open source) Razor SQL DB Visualizer DBeaver (free, open source) SQL Workbench/J (free, open source) JetBrains DataGrip Metabase (free, open source) Netbeans (free, open source, full development environment) Electron-Based Visual Studio Code with mssql extension Azure Data Studio SQLectron (TODO: Add others mentioned below)
[ "sql-server", "macos" ]
484
373
714,735
25
0
2008-08-06T14:25:17.457000
2008-08-29T08:05:06.120000