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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
34,328 | 34,418 | How do I make Windows aware of a service I have written in Python? | In another question I posted yesterday, I got very good advice on how a Python script could be run as a service in Windows. What I'm left wondering is: How is Windows aware of the services that can be managed in the native tools ("services" window in "administrative tools"). I. e. what is the Windows equivalent of putting a start/stop script in /etc/init.d under Linux? | As with most "aware" things in Windows, the answer is "Registry". Take a look at this Microsoft Knowledge Base article: http://support.microsoft.com/kb/103000 Search for "A Win32 program that can be started by the Service Controller and that obeys the service control protocol." This is the kind of service you're interested in. The service registration (contents of KEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services \myservice) carries information about the service, including things like its executable location, what to do when it fails (halt the OS?), what services must be started before this one, what user it runs as. As to service control protocol, main() of your program is supposed to invoke a Windows API call, setting up callbacks for start, stop, pause for your service. What you do in those callbacks is all up to you. | How do I make Windows aware of a service I have written in Python? In another question I posted yesterday, I got very good advice on how a Python script could be run as a service in Windows. What I'm left wondering is: How is Windows aware of the services that can be managed in the native tools ("services" window in "administrative tools"). I. e. what is the Windows equivalent of putting a start/stop script in /etc/init.d under Linux? | TITLE:
How do I make Windows aware of a service I have written in Python?
QUESTION:
In another question I posted yesterday, I got very good advice on how a Python script could be run as a service in Windows. What I'm left wondering is: How is Windows aware of the services that can be managed in the native tools ("services" window in "administrative tools"). I. e. what is the Windows equivalent of putting a start/stop script in /etc/init.d under Linux?
ANSWER:
As with most "aware" things in Windows, the answer is "Registry". Take a look at this Microsoft Knowledge Base article: http://support.microsoft.com/kb/103000 Search for "A Win32 program that can be started by the Service Controller and that obeys the service control protocol." This is the kind of service you're interested in. The service registration (contents of KEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services \myservice) carries information about the service, including things like its executable location, what to do when it fails (halt the OS?), what services must be started before this one, what user it runs as. As to service control protocol, main() of your program is supposed to invoke a Windows API call, setting up callbacks for start, stop, pause for your service. What you do in those callbacks is all up to you. | [
"python",
"windows",
"cross-platform"
] | 11 | 3 | 8,535 | 4 | 0 | 2008-08-29T10:18:21.167000 | 2008-08-29T15:00:52.333000 |
34,345 | 34,966 | Finding your own number in a box | 100 (or some even number 2N:-) ) prisoners are in a room A. They are numbered from 1 to 100. One by one (from prisoner #1 to prisoner #100, in order), they will be let into a room B in which 100 boxes (numbered from 1 to 100) await them. Inside the (closed) boxes are numbers from 1 to 100 (the numbers inside the boxes are randomly permuted!). Once inside room B, each prisoner gets to open 50 boxes (he chooses which one he opens). If he finds the number that was assigned to him in one of these 50 boxes, the prisoner gets to walk into a room C and all boxes are closed again before the next one walks into room B from room A. Otherwise, all prisoners (in rooms A, B and C) gets killed. Before entering room B, the prisoners can agree on a strategy (algorithm). There is no way to communicate between rooms (and no message can be left in room B!). Is there an algorithm that maximizes the probability that all prisoners survive? What probability does that algorithm achieve? Notes: Doing things randomly (what you call 'no strategy') indeed gives a probability of 1/2 for each prisoner, but then the probability of all of them surviving is 1/2^100 (which is quite low). One can do much better! The prisoners are not allowed to reorder the boxes! All prisoners are killed the first time a prisoner fails to find his number. And no communication is possible. Hint: one can save more than 30 prisoners on average, which is much more that (50/100) * (50/99) * [...] * 1 | This puzzle is explained at http://www.math.princeton.edu/~wwong/blog/blog200608191813.shtml and that person does a much better job of explaining the problem. The "all prisoners are killed" statement is wrong. The "you can save 30+ on average" is also wrong, the article says that 30% of the time you can save 100% of the prisoners. | Finding your own number in a box 100 (or some even number 2N:-) ) prisoners are in a room A. They are numbered from 1 to 100. One by one (from prisoner #1 to prisoner #100, in order), they will be let into a room B in which 100 boxes (numbered from 1 to 100) await them. Inside the (closed) boxes are numbers from 1 to 100 (the numbers inside the boxes are randomly permuted!). Once inside room B, each prisoner gets to open 50 boxes (he chooses which one he opens). If he finds the number that was assigned to him in one of these 50 boxes, the prisoner gets to walk into a room C and all boxes are closed again before the next one walks into room B from room A. Otherwise, all prisoners (in rooms A, B and C) gets killed. Before entering room B, the prisoners can agree on a strategy (algorithm). There is no way to communicate between rooms (and no message can be left in room B!). Is there an algorithm that maximizes the probability that all prisoners survive? What probability does that algorithm achieve? Notes: Doing things randomly (what you call 'no strategy') indeed gives a probability of 1/2 for each prisoner, but then the probability of all of them surviving is 1/2^100 (which is quite low). One can do much better! The prisoners are not allowed to reorder the boxes! All prisoners are killed the first time a prisoner fails to find his number. And no communication is possible. Hint: one can save more than 30 prisoners on average, which is much more that (50/100) * (50/99) * [...] * 1 | TITLE:
Finding your own number in a box
QUESTION:
100 (or some even number 2N:-) ) prisoners are in a room A. They are numbered from 1 to 100. One by one (from prisoner #1 to prisoner #100, in order), they will be let into a room B in which 100 boxes (numbered from 1 to 100) await them. Inside the (closed) boxes are numbers from 1 to 100 (the numbers inside the boxes are randomly permuted!). Once inside room B, each prisoner gets to open 50 boxes (he chooses which one he opens). If he finds the number that was assigned to him in one of these 50 boxes, the prisoner gets to walk into a room C and all boxes are closed again before the next one walks into room B from room A. Otherwise, all prisoners (in rooms A, B and C) gets killed. Before entering room B, the prisoners can agree on a strategy (algorithm). There is no way to communicate between rooms (and no message can be left in room B!). Is there an algorithm that maximizes the probability that all prisoners survive? What probability does that algorithm achieve? Notes: Doing things randomly (what you call 'no strategy') indeed gives a probability of 1/2 for each prisoner, but then the probability of all of them surviving is 1/2^100 (which is quite low). One can do much better! The prisoners are not allowed to reorder the boxes! All prisoners are killed the first time a prisoner fails to find his number. And no communication is possible. Hint: one can save more than 30 prisoners on average, which is much more that (50/100) * (50/99) * [...] * 1
ANSWER:
This puzzle is explained at http://www.math.princeton.edu/~wwong/blog/blog200608191813.shtml and that person does a much better job of explaining the problem. The "all prisoners are killed" statement is wrong. The "you can save 30+ on average" is also wrong, the article says that 30% of the time you can save 100% of the prisoners. | [
"algorithm",
"puzzle"
] | 8 | 7 | 1,554 | 10 | 0 | 2008-08-29T10:39:13.537000 | 2008-08-29T18:35:28.947000 |
34,365 | 34,375 | Updating/Intercepting HttpContext.Current.Request.QueryString | Here's a wierd one. I'm reusing a code base that unfortunately must not be updated. This code makes a call to HttpContext.Current.Request.QueryString. Ideally, I need to push a value into this collection with every request that is made. Is this possible - perhaps in an HTTP Module? | Without using reflection, the simplest way to do it would be to use the RewritePath function on the current HttpContext object in order to modify the querystring. Using an IHttpModule, it might look something like: context.RewritePath(context.Request.Path, context.Request.PathInfo, newQueryStringHere!); Hope this helps! | Updating/Intercepting HttpContext.Current.Request.QueryString Here's a wierd one. I'm reusing a code base that unfortunately must not be updated. This code makes a call to HttpContext.Current.Request.QueryString. Ideally, I need to push a value into this collection with every request that is made. Is this possible - perhaps in an HTTP Module? | TITLE:
Updating/Intercepting HttpContext.Current.Request.QueryString
QUESTION:
Here's a wierd one. I'm reusing a code base that unfortunately must not be updated. This code makes a call to HttpContext.Current.Request.QueryString. Ideally, I need to push a value into this collection with every request that is made. Is this possible - perhaps in an HTTP Module?
ANSWER:
Without using reflection, the simplest way to do it would be to use the RewritePath function on the current HttpContext object in order to modify the querystring. Using an IHttpModule, it might look something like: context.RewritePath(context.Request.Path, context.Request.PathInfo, newQueryStringHere!); Hope this helps! | [
"asp.net",
".net-3.5",
"query-string"
] | 3 | 6 | 3,546 | 2 | 0 | 2008-08-29T11:03:19.763000 | 2008-08-29T11:20:34.420000 |
34,390 | 34,502 | How to make user controls know about css classes in ASP.NET | Since there are no header sections for user controls in asp.net, user controls have no way of knowing about stylesheet files. So css classes in the user controls are not recognized by visual studio and produces warnings. How can I make a user control know that it will relate to a css class, so if it is warning me about a non-existing css class, it means that the class really do not exist? Edit: Or should I go for a different design like exposing css classes as properties like "HeaderStyle-CssClass" of GridView? | Here's what I did: It fools Visual Studio into thinking you've added a stylesheet to the page but it doesn't get rendered. Here's an even more concise way to do this with multiple references; <% if (false) { %> <% } %> As seen in this blog post from Phil Haack. | How to make user controls know about css classes in ASP.NET Since there are no header sections for user controls in asp.net, user controls have no way of knowing about stylesheet files. So css classes in the user controls are not recognized by visual studio and produces warnings. How can I make a user control know that it will relate to a css class, so if it is warning me about a non-existing css class, it means that the class really do not exist? Edit: Or should I go for a different design like exposing css classes as properties like "HeaderStyle-CssClass" of GridView? | TITLE:
How to make user controls know about css classes in ASP.NET
QUESTION:
Since there are no header sections for user controls in asp.net, user controls have no way of knowing about stylesheet files. So css classes in the user controls are not recognized by visual studio and produces warnings. How can I make a user control know that it will relate to a css class, so if it is warning me about a non-existing css class, it means that the class really do not exist? Edit: Or should I go for a different design like exposing css classes as properties like "HeaderStyle-CssClass" of GridView?
ANSWER:
Here's what I did: It fools Visual Studio into thinking you've added a stylesheet to the page but it doesn't get rendered. Here's an even more concise way to do this with multiple references; <% if (false) { %> <% } %> As seen in this blog post from Phil Haack. | [
"asp.net",
"css",
"visual-studio-2008",
"user-controls"
] | 52 | 65 | 59,611 | 4 | 0 | 2008-08-29T11:37:54.783000 | 2008-08-29T15:52:43.770000 |
34,394 | 34,412 | How would you abbriviate XHTML to an arbitrary number of words? | How would you programmacially abbreviate XHTML to an arbitrary number of words without leaving unclosed or corrupted tags? i.e. Proin tristique dapibus neque. Nam eget purus sit amet leo tincidunt accumsan. Proin semper, orci at mattis blandit, augue justo blandit nulla. Quisque ante congue justo, ultrices aliquet, mattis eget, hendrerit, justo. Abbreviated to 25 words would be: Proin tristique dapibus neque. Nam eget purus sit amet leo tincidunt accumsan. Proin semper, orci at mattis blandit, augue justo blandit nulla. Quisque ante congue... | Recurse through the DOM tree, keeping a word count variable up to date. When the word count exceeds your maximum word count, insert "..." and remove all following siblings of the current node, then, as you go back up through the recursion, remove all the following siblings of each of its ancestors. | How would you abbriviate XHTML to an arbitrary number of words? How would you programmacially abbreviate XHTML to an arbitrary number of words without leaving unclosed or corrupted tags? i.e. Proin tristique dapibus neque. Nam eget purus sit amet leo tincidunt accumsan. Proin semper, orci at mattis blandit, augue justo blandit nulla. Quisque ante congue justo, ultrices aliquet, mattis eget, hendrerit, justo. Abbreviated to 25 words would be: Proin tristique dapibus neque. Nam eget purus sit amet leo tincidunt accumsan. Proin semper, orci at mattis blandit, augue justo blandit nulla. Quisque ante congue... | TITLE:
How would you abbriviate XHTML to an arbitrary number of words?
QUESTION:
How would you programmacially abbreviate XHTML to an arbitrary number of words without leaving unclosed or corrupted tags? i.e. Proin tristique dapibus neque. Nam eget purus sit amet leo tincidunt accumsan. Proin semper, orci at mattis blandit, augue justo blandit nulla. Quisque ante congue justo, ultrices aliquet, mattis eget, hendrerit, justo. Abbreviated to 25 words would be: Proin tristique dapibus neque. Nam eget purus sit amet leo tincidunt accumsan. Proin semper, orci at mattis blandit, augue justo blandit nulla. Quisque ante congue...
ANSWER:
Recurse through the DOM tree, keeping a word count variable up to date. When the word count exceeds your maximum word count, insert "..." and remove all following siblings of the current node, then, as you go back up through the recursion, remove all the following siblings of each of its ancestors. | [
"html",
"regex",
"dom",
"xhtml",
"dom-traversal"
] | 2 | 1 | 171 | 2 | 0 | 2008-08-29T14:51:10.953000 | 2008-08-29T14:59:06.783000 |
34,395 | 34,431 | How do I truncate a string while converting to bytes in C#? | I would like to put a string into a byte array, but the string may be too big to fit. In the case where it's too large, I would like to put as much of the string as possible into the array. Is there an efficient way to find out how many characters will fit? | In order to truncate a string to a UTF8 byte array without splitting in the middle of a character I use this: static string Truncate(string s, int maxLength) { if (Encoding.UTF8.GetByteCount(s) <= maxLength) return s; var cs = s.ToCharArray(); int length = 0; int i = 0; while (i < cs.Length){ int charSize = 1; if (i < (cs.Length - 1) && char.IsSurrogate(cs[i])) charSize = 2; int byteSize = Encoding.UTF8.GetByteCount(cs, i, charSize); if ((byteSize + length) <= maxLength){ i = i + charSize; length += byteSize; } else break; } return s.Substring(0, i); } The returned string can then be safely transferred to a byte array of length maxLength. | How do I truncate a string while converting to bytes in C#? I would like to put a string into a byte array, but the string may be too big to fit. In the case where it's too large, I would like to put as much of the string as possible into the array. Is there an efficient way to find out how many characters will fit? | TITLE:
How do I truncate a string while converting to bytes in C#?
QUESTION:
I would like to put a string into a byte array, but the string may be too big to fit. In the case where it's too large, I would like to put as much of the string as possible into the array. Is there an efficient way to find out how many characters will fit?
ANSWER:
In order to truncate a string to a UTF8 byte array without splitting in the middle of a character I use this: static string Truncate(string s, int maxLength) { if (Encoding.UTF8.GetByteCount(s) <= maxLength) return s; var cs = s.ToCharArray(); int length = 0; int i = 0; while (i < cs.Length){ int charSize = 1; if (i < (cs.Length - 1) && char.IsSurrogate(cs[i])) charSize = 2; int byteSize = Encoding.UTF8.GetByteCount(cs, i, charSize); if ((byteSize + length) <= maxLength){ i = i + charSize; length += byteSize; } else break; } return s.Substring(0, i); } The returned string can then be safely transferred to a byte array of length maxLength. | [
"c#",
".net",
"arrays",
"string",
"truncate"
] | 10 | 7 | 4,067 | 4 | 0 | 2008-08-29T14:51:24.727000 | 2008-08-29T15:03:27.040000 |
34,398 | 34,480 | How should I model a field that can contain both numeric and string values in SQL Server 2005? | I have a new database table I need to create... It logically contains an ID, a name, and a "value". That value field could be either numeric or a character string in nature. I don't think I want to just make the field a varchar, because I also want to be able to query with filters like WHERE value > 0.5 and such. What's the best way to model this concept in SQL Server 2005? EDIT: I'm not opposed to creating multiple fields here (one for numbers, one for non-numbers), but since they're all really the same concept, I wasn't sure that was a great idea. I guess I could create separate fields, then have a view that sort of coalesces them into a single logical column. Any opinions on that? What I want to achieve is really pretty simple... usually this data will just be blindly displayed in a grid-type view. I want to be also able to filter on the numeric values in that grid. This table will end up being in the tens of millions of records, so I don't want to paint myself into a corner with querying performance. That querying performance is my main concern. | Your issue with mixing data may be how Sql 2005 sorts text data. It's not a 'natural' sort. If you have a varchar field and you do: where value > '20.5' Values like "5" will be in your result (as in a character based sort "5" comes after "20.5") You're going to be better off with separate columns for storage. Use Coalesce to merge them into one column if you need them merged in your results: select [ID], [Name], Coalesce( [value_str], [value_num] ) from [tablename] | How should I model a field that can contain both numeric and string values in SQL Server 2005? I have a new database table I need to create... It logically contains an ID, a name, and a "value". That value field could be either numeric or a character string in nature. I don't think I want to just make the field a varchar, because I also want to be able to query with filters like WHERE value > 0.5 and such. What's the best way to model this concept in SQL Server 2005? EDIT: I'm not opposed to creating multiple fields here (one for numbers, one for non-numbers), but since they're all really the same concept, I wasn't sure that was a great idea. I guess I could create separate fields, then have a view that sort of coalesces them into a single logical column. Any opinions on that? What I want to achieve is really pretty simple... usually this data will just be blindly displayed in a grid-type view. I want to be also able to filter on the numeric values in that grid. This table will end up being in the tens of millions of records, so I don't want to paint myself into a corner with querying performance. That querying performance is my main concern. | TITLE:
How should I model a field that can contain both numeric and string values in SQL Server 2005?
QUESTION:
I have a new database table I need to create... It logically contains an ID, a name, and a "value". That value field could be either numeric or a character string in nature. I don't think I want to just make the field a varchar, because I also want to be able to query with filters like WHERE value > 0.5 and such. What's the best way to model this concept in SQL Server 2005? EDIT: I'm not opposed to creating multiple fields here (one for numbers, one for non-numbers), but since they're all really the same concept, I wasn't sure that was a great idea. I guess I could create separate fields, then have a view that sort of coalesces them into a single logical column. Any opinions on that? What I want to achieve is really pretty simple... usually this data will just be blindly displayed in a grid-type view. I want to be also able to filter on the numeric values in that grid. This table will end up being in the tens of millions of records, so I don't want to paint myself into a corner with querying performance. That querying performance is my main concern.
ANSWER:
Your issue with mixing data may be how Sql 2005 sorts text data. It's not a 'natural' sort. If you have a varchar field and you do: where value > '20.5' Values like "5" will be in your result (as in a character based sort "5" comes after "20.5") You're going to be better off with separate columns for storage. Use Coalesce to merge them into one column if you need them merged in your results: select [ID], [Name], Coalesce( [value_str], [value_num] ) from [tablename] | [
"sql-server",
"database-design"
] | 4 | 2 | 3,931 | 9 | 0 | 2008-08-29T14:53:55.487000 | 2008-08-29T15:44:36.673000 |
34,399 | 34,656 | How to dispay unordered list inline with bullets? | I have an html file with an unordered list. I want to show the list items horizontally but still keep the bullets. No matter what I try, whenever I set the style to inline to meet the horizontal requirement I can't get the bullets to display. | The best option I saw in other answers was to use float:left;. Unfortunately, it doesn't work in IE7 which is a requirement here * — you still lose the bullet. I'm not really keen on using a background image either. What I'm gonna do instead (that no one else suggested, hence the self-answer) is go with manually adding • to the my html, rather than styling this. It's less than ideal, but it's the most compatible option I found. edit: * Current readers take note of the original post date. IE7 is unlikely to be a concern anymore. | How to dispay unordered list inline with bullets? I have an html file with an unordered list. I want to show the list items horizontally but still keep the bullets. No matter what I try, whenever I set the style to inline to meet the horizontal requirement I can't get the bullets to display. | TITLE:
How to dispay unordered list inline with bullets?
QUESTION:
I have an html file with an unordered list. I want to show the list items horizontally but still keep the bullets. No matter what I try, whenever I set the style to inline to meet the horizontal requirement I can't get the bullets to display.
ANSWER:
The best option I saw in other answers was to use float:left;. Unfortunately, it doesn't work in IE7 which is a requirement here * — you still lose the bullet. I'm not really keen on using a background image either. What I'm gonna do instead (that no one else suggested, hence the self-answer) is go with manually adding • to the my html, rather than styling this. It's less than ideal, but it's the most compatible option I found. edit: * Current readers take note of the original post date. IE7 is unlikely to be a concern anymore. | [
"html",
"css"
] | 53 | 40 | 86,308 | 13 | 0 | 2008-08-29T14:55:05.170000 | 2008-08-29T16:34:13.280000 |
34,401 | 34,435 | Send email from Elmah? | Is anyone using Elmah to send exceptions via email? I've got Elmah logging set up via SQL Server, and can view the errors page via the Elmah.axd page, but I am unable to get the email component working. The idea here is to get the email notification so we can react more quickly to exceptions. Here is my web.config (unnecessary sectionss omitted), with all the sensitive data replaced by * * *. Even though I am specifying a server to connect to, does the SMTP service need to be running on the local machine? | You need the ErrorMail httpModule. add this line inside the section If you're using a remote SMTP server (which it looks like you are) you don't need SMTP on the server. | Send email from Elmah? Is anyone using Elmah to send exceptions via email? I've got Elmah logging set up via SQL Server, and can view the errors page via the Elmah.axd page, but I am unable to get the email component working. The idea here is to get the email notification so we can react more quickly to exceptions. Here is my web.config (unnecessary sectionss omitted), with all the sensitive data replaced by * * *. Even though I am specifying a server to connect to, does the SMTP service need to be running on the local machine? | TITLE:
Send email from Elmah?
QUESTION:
Is anyone using Elmah to send exceptions via email? I've got Elmah logging set up via SQL Server, and can view the errors page via the Elmah.axd page, but I am unable to get the email component working. The idea here is to get the email notification so we can react more quickly to exceptions. Here is my web.config (unnecessary sectionss omitted), with all the sensitive data replaced by * * *. Even though I am specifying a server to connect to, does the SMTP service need to be running on the local machine?
ANSWER:
You need the ErrorMail httpModule. add this line inside the section If you're using a remote SMTP server (which it looks like you are) you don't need SMTP on the server. | [
".net",
"asp.net",
"elmah"
] | 90 | 79 | 34,880 | 3 | 0 | 2008-08-29T14:56:47.680000 | 2008-08-29T15:04:44.617000 |
34,411 | 36,026 | How do I generate a friendly URL in Symfony PHP? | I always tend to forget these built-in Symfony functions for making links. | If your goal is to have user-friendly URLs throughout your application, use the following approach: 1) Create a routing rule for your module/action in the application's routing.yml file. The following example is a routing rule for an action that shows the most recent questions in an application, defaulting to page 1 (using a pager): recent_questions: url: questions/recent/:page param: { module: questions, action: recent, page: 1 } 2) Once the routing rule is set, use the url_for() helper in your template to format outgoing URLs. Recent Questions In this example, the following URL will be constructed: http://myapp/questions/recent/1.html. 3) Incoming URLs (requests) will be analyzed by the routing system, and if a pattern match is found in the routing rule configuration, the named wildcards (ie. the:/page portion of the URL) will become request parameters. You can also use the link_to() helper to output a URL without using the HTML tag. | How do I generate a friendly URL in Symfony PHP? I always tend to forget these built-in Symfony functions for making links. | TITLE:
How do I generate a friendly URL in Symfony PHP?
QUESTION:
I always tend to forget these built-in Symfony functions for making links.
ANSWER:
If your goal is to have user-friendly URLs throughout your application, use the following approach: 1) Create a routing rule for your module/action in the application's routing.yml file. The following example is a routing rule for an action that shows the most recent questions in an application, defaulting to page 1 (using a pager): recent_questions: url: questions/recent/:page param: { module: questions, action: recent, page: 1 } 2) Once the routing rule is set, use the url_for() helper in your template to format outgoing URLs. Recent Questions In this example, the following URL will be constructed: http://myapp/questions/recent/1.html. 3) Incoming URLs (requests) will be analyzed by the routing system, and if a pattern match is found in the routing rule configuration, the named wildcards (ie. the:/page portion of the URL) will become request parameters. You can also use the link_to() helper to output a URL without using the HTML tag. | [
"php",
"url",
"seo",
"symfony1"
] | 7 | 9 | 8,449 | 4 | 0 | 2008-08-29T14:58:58.873000 | 2008-08-30T15:08:25.020000 |
34,413 | 34,419 | Why am I getting a NoClassDefFoundError in Java? | I am getting a NoClassDefFoundError when I run my Java application. What is typically the cause of this? | This is caused when there is a class file that your code depends on and it is present at compile time but not found at runtime. Look for differences in your build time and runtime classpaths. | Why am I getting a NoClassDefFoundError in Java? I am getting a NoClassDefFoundError when I run my Java application. What is typically the cause of this? | TITLE:
Why am I getting a NoClassDefFoundError in Java?
QUESTION:
I am getting a NoClassDefFoundError when I run my Java application. What is typically the cause of this?
ANSWER:
This is caused when there is a class file that your code depends on and it is present at compile time but not found at runtime. Look for differences in your build time and runtime classpaths. | [
"java",
"noclassdeffounderror"
] | 671 | 308 | 1,126,387 | 32 | 0 | 2008-08-29T14:59:30.747000 | 2008-08-29T15:01:07.607000 |
34,428 | 35,405 | How to Format Numbers in WinForms 1.1 DataGrid? | Is there a simple way to format numbers in a Winforms 1.1 datagrid? The Format property of the DataGridTextBoxColumn seems to be completely ignored. I know there is a solution that involves subclassing a Column control, and it's fairly simple, but was hoping there might be some trick to making the Format property just work. | My personal opinion is that a datagridcolumnstyle is the way to go. Without seeing the code that you have, I can't say for certain why your formatting isn't taking hold when no style is defined - but mixing in formatting with data calculations and other parts of the code can get very messy very quickly. Creating a new column style class is very clean, and if you have to use the same formatting again in another datagrid, it's as easy as pie to reuse it. Here's the Microsoft Documentation that may get you started in the right direction. | How to Format Numbers in WinForms 1.1 DataGrid? Is there a simple way to format numbers in a Winforms 1.1 datagrid? The Format property of the DataGridTextBoxColumn seems to be completely ignored. I know there is a solution that involves subclassing a Column control, and it's fairly simple, but was hoping there might be some trick to making the Format property just work. | TITLE:
How to Format Numbers in WinForms 1.1 DataGrid?
QUESTION:
Is there a simple way to format numbers in a Winforms 1.1 datagrid? The Format property of the DataGridTextBoxColumn seems to be completely ignored. I know there is a solution that involves subclassing a Column control, and it's fairly simple, but was hoping there might be some trick to making the Format property just work.
ANSWER:
My personal opinion is that a datagridcolumnstyle is the way to go. Without seeing the code that you have, I can't say for certain why your formatting isn't taking hold when no style is defined - but mixing in formatting with data calculations and other parts of the code can get very messy very quickly. Creating a new column style class is very clean, and if you have to use the same formatting again in another datagrid, it's as easy as pie to reuse it. Here's the Microsoft Documentation that may get you started in the right direction. | [
"winforms"
] | 1 | 1 | 407 | 2 | 0 | 2008-08-29T15:02:41.953000 | 2008-08-29T22:15:07.360000 |
34,439 | 34,452 | Finding what methods a Python object has | Given a Python object of any kind, is there an easy way to get the list of all methods that this object has? Or if this is not possible, is there at least an easy way to check if it has a particular method, other than checking if an error occurs when the method is called? | For many objects, you can use this code, replacing 'object' with the object you're interested in: object_methods = [method_name for method_name in dir(object) if callable(getattr(object, method_name))] I discovered it at diveintopython.net (now archived), that should provide some further details! If you get an AttributeError, you can use this instead: getattr() is intolerant of pandas style Python 3.6 abstract virtual sub-classes. This code does the same as above and ignores exceptions. import pandas as pd df = pd.DataFrame([[10, 20, 30], [100, 200, 300]], columns=['foo', 'bar', 'baz']) def get_methods(object, spacing=20): methodList = [] for method_name in dir(object): try: if callable(getattr(object, method_name)): methodList.append(str(method_name)) except Exception: methodList.append(str(method_name)) processFunc = (lambda s: ' '.join(s.split())) or (lambda s: s) for method in methodList: try: print(str(method.ljust(spacing)) + ' ' + processFunc(str(getattr(object, method).__doc__)[0:90])) except Exception: print(method.ljust(spacing) + ' ' + ' getattr() failed')
get_methods(df['foo']) | Finding what methods a Python object has Given a Python object of any kind, is there an easy way to get the list of all methods that this object has? Or if this is not possible, is there at least an easy way to check if it has a particular method, other than checking if an error occurs when the method is called? | TITLE:
Finding what methods a Python object has
QUESTION:
Given a Python object of any kind, is there an easy way to get the list of all methods that this object has? Or if this is not possible, is there at least an easy way to check if it has a particular method, other than checking if an error occurs when the method is called?
ANSWER:
For many objects, you can use this code, replacing 'object' with the object you're interested in: object_methods = [method_name for method_name in dir(object) if callable(getattr(object, method_name))] I discovered it at diveintopython.net (now archived), that should provide some further details! If you get an AttributeError, you can use this instead: getattr() is intolerant of pandas style Python 3.6 abstract virtual sub-classes. This code does the same as above and ignores exceptions. import pandas as pd df = pd.DataFrame([[10, 20, 30], [100, 200, 300]], columns=['foo', 'bar', 'baz']) def get_methods(object, spacing=20): methodList = [] for method_name in dir(object): try: if callable(getattr(object, method_name)): methodList.append(str(method_name)) except Exception: methodList.append(str(method_name)) processFunc = (lambda s: ' '.join(s.split())) or (lambda s: s) for method in methodList: try: print(str(method.ljust(spacing)) + ' ' + processFunc(str(getattr(object, method).__doc__)[0:90])) except Exception: print(method.ljust(spacing) + ' ' + ' getattr() failed')
get_methods(df['foo']) | [
"python",
"introspection"
] | 693 | 758 | 722,838 | 22 | 0 | 2008-08-29T15:05:17.237000 | 2008-08-29T15:09:05.667000 |
34,463 | 34,547 | Technical Hurdles for Win32 rsync port | Despite primarily being a windows user, I am a huge fan of rsync. Now, I don't want to argue the virtues of rsync vs any other tool...this is not my point. The only way I've ever found of running rsync on windows is via a version that is built to run on top of Cygwin, and as Cygwin has issues with Unicode, so does rsync. Is anyone familiar enough with the workings of rsync to say if there are any real technical programming hurdles to porting rsync to a native Win32 binary? Or is it maybe that there has just never been enough interest from windows users to care to port it over? Partly I ask because I'm am considering trying to take on the task of starting a port, but I want to make sure there's not something I'm missing in terms of why it may not be possible. | The way that windows locks open files might cause an issue requiring you to hook into the Volume Shadowcopy Service. About two years ago this fellow ported the algorithm to C#. I haven't taken a look at the code (or the provided binary), but it might be a place to start looking or someone to try contacting. http://www.russiantequila.com/wordpress/?p=8 | Technical Hurdles for Win32 rsync port Despite primarily being a windows user, I am a huge fan of rsync. Now, I don't want to argue the virtues of rsync vs any other tool...this is not my point. The only way I've ever found of running rsync on windows is via a version that is built to run on top of Cygwin, and as Cygwin has issues with Unicode, so does rsync. Is anyone familiar enough with the workings of rsync to say if there are any real technical programming hurdles to porting rsync to a native Win32 binary? Or is it maybe that there has just never been enough interest from windows users to care to port it over? Partly I ask because I'm am considering trying to take on the task of starting a port, but I want to make sure there's not something I'm missing in terms of why it may not be possible. | TITLE:
Technical Hurdles for Win32 rsync port
QUESTION:
Despite primarily being a windows user, I am a huge fan of rsync. Now, I don't want to argue the virtues of rsync vs any other tool...this is not my point. The only way I've ever found of running rsync on windows is via a version that is built to run on top of Cygwin, and as Cygwin has issues with Unicode, so does rsync. Is anyone familiar enough with the workings of rsync to say if there are any real technical programming hurdles to porting rsync to a native Win32 binary? Or is it maybe that there has just never been enough interest from windows users to care to port it over? Partly I ask because I'm am considering trying to take on the task of starting a port, but I want to make sure there's not something I'm missing in terms of why it may not be possible.
ANSWER:
The way that windows locks open files might cause an issue requiring you to hook into the Volume Shadowcopy Service. About two years ago this fellow ported the algorithm to C#. I haven't taken a look at the code (or the provided binary), but it might be a place to start looking or someone to try contacting. http://www.russiantequila.com/wordpress/?p=8 | [
"winapi",
"rsync",
"porting"
] | 9 | 5 | 4,955 | 5 | 0 | 2008-08-29T15:33:06.687000 | 2008-08-29T16:04:44.177000 |
34,476 | 34,504 | What is in your JavaScript development toolbox? | I have to do some JavaScript in the future, so it is time to update my toolbox. Right now I use Firefox with some addons: JavaScript Shell from https://www.squarefree.com/bookmarklets/webdevel.html Firefox Dom Inspector Firebug Greasemonkey Stylish I plan to use Venkman Javascript debugger as well as jsunit and js-lint. For programming I'm stick with vim. So what other tools do you use when developing JavaScript? | I use both Firefox and IE for Web Development and a few add-ons in each: Firefox: Firebug Web Developer Toolbar Internet Explorer: IE Developer Toolbar Fiddler Visual Studio for JS Debugging | What is in your JavaScript development toolbox? I have to do some JavaScript in the future, so it is time to update my toolbox. Right now I use Firefox with some addons: JavaScript Shell from https://www.squarefree.com/bookmarklets/webdevel.html Firefox Dom Inspector Firebug Greasemonkey Stylish I plan to use Venkman Javascript debugger as well as jsunit and js-lint. For programming I'm stick with vim. So what other tools do you use when developing JavaScript? | TITLE:
What is in your JavaScript development toolbox?
QUESTION:
I have to do some JavaScript in the future, so it is time to update my toolbox. Right now I use Firefox with some addons: JavaScript Shell from https://www.squarefree.com/bookmarklets/webdevel.html Firefox Dom Inspector Firebug Greasemonkey Stylish I plan to use Venkman Javascript debugger as well as jsunit and js-lint. For programming I'm stick with vim. So what other tools do you use when developing JavaScript?
ANSWER:
I use both Firefox and IE for Web Development and a few add-ons in each: Firefox: Firebug Web Developer Toolbar Internet Explorer: IE Developer Toolbar Fiddler Visual Studio for JS Debugging | [
"javascript",
"debugging"
] | 12 | 8 | 701 | 7 | 0 | 2008-08-29T15:41:45.060000 | 2008-08-29T15:54:11.580000 |
34,486 | 34,538 | What more is needed for Ajax than this function | I have a small JS function that does Ajax for me and another like it that adds in POST data to the request. With Ajax being such a big topic with so many libraries about it, what am I missing from my function, is it insecure or something else worrying? function loadPage(pagePath, displayElement) { var xmlHttp;
try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("Your browser does not support AJAX!"); return false; } } }
xmlHttp.onreadystatechange=function() { if(xmlHttp.readyState==4) { document.getElementById(displayElement).innerHTML = xmlHttp.responseText; } }
xmlHttp.open("GET", pagePath, true); xmlHttp.send(null); } | I strongly recommend you not roll your own Ajax code. Instead, use a framework such as Prototype, Dojo, or any of the others. They've taken care of handling all the ReadyStates you're not handling (2 means it's been sent, 3 means it's in process, etc.), and they should escape the reponse you're getting so you don't insert potentially insecure javascript or something into your page. Another thing a more robust framework will give you is the ability to do more than just use innerHTML to replace items in the DOM. Your function here can only be used to replace one element with the response from the ajax call. There's a lot more you can do with Ajax. | What more is needed for Ajax than this function I have a small JS function that does Ajax for me and another like it that adds in POST data to the request. With Ajax being such a big topic with so many libraries about it, what am I missing from my function, is it insecure or something else worrying? function loadPage(pagePath, displayElement) { var xmlHttp;
try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("Your browser does not support AJAX!"); return false; } } }
xmlHttp.onreadystatechange=function() { if(xmlHttp.readyState==4) { document.getElementById(displayElement).innerHTML = xmlHttp.responseText; } }
xmlHttp.open("GET", pagePath, true); xmlHttp.send(null); } | TITLE:
What more is needed for Ajax than this function
QUESTION:
I have a small JS function that does Ajax for me and another like it that adds in POST data to the request. With Ajax being such a big topic with so many libraries about it, what am I missing from my function, is it insecure or something else worrying? function loadPage(pagePath, displayElement) { var xmlHttp;
try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("Your browser does not support AJAX!"); return false; } } }
xmlHttp.onreadystatechange=function() { if(xmlHttp.readyState==4) { document.getElementById(displayElement).innerHTML = xmlHttp.responseText; } }
xmlHttp.open("GET", pagePath, true); xmlHttp.send(null); }
ANSWER:
I strongly recommend you not roll your own Ajax code. Instead, use a framework such as Prototype, Dojo, or any of the others. They've taken care of handling all the ReadyStates you're not handling (2 means it's been sent, 3 means it's in process, etc.), and they should escape the reponse you're getting so you don't insert potentially insecure javascript or something into your page. Another thing a more robust framework will give you is the ability to do more than just use innerHTML to replace items in the DOM. Your function here can only be used to replace one element with the response from the ajax call. There's a lot more you can do with Ajax. | [
"javascript",
"ajax"
] | 5 | 13 | 354 | 6 | 0 | 2008-08-29T15:48:16.307000 | 2008-08-29T16:03:11.933000 |
34,488 | 34,500 | Does limiting a query to one record improve performance | Will limiting a query to one result record, improve performance in a large(ish) MySQL table if the table only has one matching result? for example select * from people where name = "Re0sless" limit 1 if there is only one record with that name? and what about if name was the primary key/ set to unique? and is it worth updating the query or will the gain be minimal? | If the column has a unique index: no, it's no faster a non-unique index: maybe, because it will prevent sending any additional rows beyond the first matched, if any exist no index: sometimes if 1 or more rows match the query, yes, because the full table scan will be halted after the first row is matched. if no rows match the query, no, because it will need to complete a full table scan | Does limiting a query to one record improve performance Will limiting a query to one result record, improve performance in a large(ish) MySQL table if the table only has one matching result? for example select * from people where name = "Re0sless" limit 1 if there is only one record with that name? and what about if name was the primary key/ set to unique? and is it worth updating the query or will the gain be minimal? | TITLE:
Does limiting a query to one record improve performance
QUESTION:
Will limiting a query to one result record, improve performance in a large(ish) MySQL table if the table only has one matching result? for example select * from people where name = "Re0sless" limit 1 if there is only one record with that name? and what about if name was the primary key/ set to unique? and is it worth updating the query or will the gain be minimal?
ANSWER:
If the column has a unique index: no, it's no faster a non-unique index: maybe, because it will prevent sending any additional rows beyond the first matched, if any exist no index: sometimes if 1 or more rows match the query, yes, because the full table scan will be halted after the first row is matched. if no rows match the query, no, because it will need to complete a full table scan | [
"sql",
"mysql",
"database"
] | 35 | 50 | 14,711 | 6 | 0 | 2008-08-29T15:48:23.390000 | 2008-08-29T15:51:55.847000 |
34,493 | 34,719 | Excel: list ranges targeted by INDIRECT formulas | We have a few very large Excel workbooks (dozens of tabs, over a MB each, very complex calculations) with many dozens, perhaps hundreds of formulas that use the dreaded INDIRECT function. These formulas are spread out throughout the workbook, and target several tables of data to look-up for values. Now I need to move the ranges of data that are targeted by these formulas to a different location in the same workbook. (The reason is not particularly relevant, but interesting on its own. We need to run these things in Excel Calculation Services and the latency hit of loading each of the rather large tables one at a time proved to be unacceptably high. We are moving the tables in a contiguous range so we can load them all in one shot.) Is there any way to locate all the INDIRECT formulas that currently refer to the tables we want to move? I don't need to do this on-line. I'll happily take something that takes 4 hours to run as long as it is reliable. Be aware that the.Precedent,.Dependent, etc methods only track direct formulas. (Also, rewriting the spreadsheets in whatever is not an option for us). Thanks! | You could iterate over the entire Workbook using vba (i've included the code from @PabloG and @euro-micelli ): Sub iterateOverWorkbook() For Each i In ThisWorkbook.Worksheets Set rRng = i.UsedRange For Each j In rRng If (Not IsEmpty(j)) Then If (j.HasFormula) Then If InStr(oCell.Formula, "INDIRECT") Then j.Value = Replace(j.Formula, "INDIRECT(D4)", "INDIRECT(C4)") End If End If End If Next j Next i End Sub This example substitues every occurrence of "indirect(D4)" with "indirect(C4)". You can easily swap the replace-function with something more sophisticated, if you have more complicated indirect-functions. Performance is not that bad, even for bigger Workbooks. | Excel: list ranges targeted by INDIRECT formulas We have a few very large Excel workbooks (dozens of tabs, over a MB each, very complex calculations) with many dozens, perhaps hundreds of formulas that use the dreaded INDIRECT function. These formulas are spread out throughout the workbook, and target several tables of data to look-up for values. Now I need to move the ranges of data that are targeted by these formulas to a different location in the same workbook. (The reason is not particularly relevant, but interesting on its own. We need to run these things in Excel Calculation Services and the latency hit of loading each of the rather large tables one at a time proved to be unacceptably high. We are moving the tables in a contiguous range so we can load them all in one shot.) Is there any way to locate all the INDIRECT formulas that currently refer to the tables we want to move? I don't need to do this on-line. I'll happily take something that takes 4 hours to run as long as it is reliable. Be aware that the.Precedent,.Dependent, etc methods only track direct formulas. (Also, rewriting the spreadsheets in whatever is not an option for us). Thanks! | TITLE:
Excel: list ranges targeted by INDIRECT formulas
QUESTION:
We have a few very large Excel workbooks (dozens of tabs, over a MB each, very complex calculations) with many dozens, perhaps hundreds of formulas that use the dreaded INDIRECT function. These formulas are spread out throughout the workbook, and target several tables of data to look-up for values. Now I need to move the ranges of data that are targeted by these formulas to a different location in the same workbook. (The reason is not particularly relevant, but interesting on its own. We need to run these things in Excel Calculation Services and the latency hit of loading each of the rather large tables one at a time proved to be unacceptably high. We are moving the tables in a contiguous range so we can load them all in one shot.) Is there any way to locate all the INDIRECT formulas that currently refer to the tables we want to move? I don't need to do this on-line. I'll happily take something that takes 4 hours to run as long as it is reliable. Be aware that the.Precedent,.Dependent, etc methods only track direct formulas. (Also, rewriting the spreadsheets in whatever is not an option for us). Thanks!
ANSWER:
You could iterate over the entire Workbook using vba (i've included the code from @PabloG and @euro-micelli ): Sub iterateOverWorkbook() For Each i In ThisWorkbook.Worksheets Set rRng = i.UsedRange For Each j In rRng If (Not IsEmpty(j)) Then If (j.HasFormula) Then If InStr(oCell.Formula, "INDIRECT") Then j.Value = Replace(j.Formula, "INDIRECT(D4)", "INDIRECT(C4)") End If End If End If Next j Next i End Sub This example substitues every occurrence of "indirect(D4)" with "indirect(C4)". You can easily swap the replace-function with something more sophisticated, if you have more complicated indirect-functions. Performance is not that bad, even for bigger Workbooks. | [
"excel",
"vba"
] | 5 | 5 | 2,527 | 5 | 0 | 2008-08-29T15:49:25.307000 | 2008-08-29T16:53:09.723000 |
34,505 | 34,541 | Is Object.GetHashCode() unique to a reference or a value? | The MSDN documentation on Object.GetHashCode() describes 3 contradicting rules for how the method should work. If two objects of the same type represent the same value, the hash function must return the same constant value for either object. For the best performance, a hash function must generate a random distribution for all input. The hash function must return exactly the same value regardless of any changes that are made to the object. Rules 1 & 3 are contradictory to me. Does Object.GetHashCode() return a unique number based on the value of an object, or the reference to the object. If I override the method I can choose what to use, but I'd like to know what is used internally if anyone knows. | Rules 1 & 3 are contradictory to me. To a certain extent, they are. The reason is: if an object is stored in a hash table and, by changing its value, you change its hash then the hash table has lost the value and you can't find it again by querying the hash table. — It is therefore important that while objects are stored in a hash table, they retain their hash value. To ensure this it is often simplest to make hashable objects immutable, thus side-stepping the problem wholly. But it is actually sufficient to make only those fields immutable that determine the hash value. Consider the following example: struct Person { public readonly string FirstName; public readonly string Name; public readonly DateTime Birthday;
public int ShoeSize; } People rarely change their name, and even less frequently their birthday. However, their shoe size may grow arbitrarily, or even shrink. It is therefore reasonable to identify people using their birthday and name but not their shoe size. The hash value should reflect this: public override int GetHashCode() { return HashCode.Combine(FirstName, Name, Birthday); } And remember to override Equals whenever you override GetHashCode (and vice-versa)! | Is Object.GetHashCode() unique to a reference or a value? The MSDN documentation on Object.GetHashCode() describes 3 contradicting rules for how the method should work. If two objects of the same type represent the same value, the hash function must return the same constant value for either object. For the best performance, a hash function must generate a random distribution for all input. The hash function must return exactly the same value regardless of any changes that are made to the object. Rules 1 & 3 are contradictory to me. Does Object.GetHashCode() return a unique number based on the value of an object, or the reference to the object. If I override the method I can choose what to use, but I'd like to know what is used internally if anyone knows. | TITLE:
Is Object.GetHashCode() unique to a reference or a value?
QUESTION:
The MSDN documentation on Object.GetHashCode() describes 3 contradicting rules for how the method should work. If two objects of the same type represent the same value, the hash function must return the same constant value for either object. For the best performance, a hash function must generate a random distribution for all input. The hash function must return exactly the same value regardless of any changes that are made to the object. Rules 1 & 3 are contradictory to me. Does Object.GetHashCode() return a unique number based on the value of an object, or the reference to the object. If I override the method I can choose what to use, but I'd like to know what is used internally if anyone knows.
ANSWER:
Rules 1 & 3 are contradictory to me. To a certain extent, they are. The reason is: if an object is stored in a hash table and, by changing its value, you change its hash then the hash table has lost the value and you can't find it again by querying the hash table. — It is therefore important that while objects are stored in a hash table, they retain their hash value. To ensure this it is often simplest to make hashable objects immutable, thus side-stepping the problem wholly. But it is actually sufficient to make only those fields immutable that determine the hash value. Consider the following example: struct Person { public readonly string FirstName; public readonly string Name; public readonly DateTime Birthday;
public int ShoeSize; } People rarely change their name, and even less frequently their birthday. However, their shoe size may grow arbitrarily, or even shrink. It is therefore reasonable to identify people using their birthday and name but not their shoe size. The hash value should reflect this: public override int GetHashCode() { return HashCode.Combine(FirstName, Name, Birthday); } And remember to override Equals whenever you override GetHashCode (and vice-versa)! | [
"c#",
".net"
] | 26 | 30 | 9,723 | 6 | 0 | 2008-08-29T15:54:15.870000 | 2008-08-29T16:03:42.247000 |
34,506 | 35,201 | Simulating a virtual static member of a class in c++? | Is there anyway to have a sort of virtual static member in C++? For example: class BaseClass { public: BaseClass(const string& name): _name(name) {} string GetName() const { return _name; } virtual void UseClass() = 0; private: const string _name; };
class DerivedClass: public BaseClass { public: DerivedClass(): BaseClass("DerivedClass") {} virtual void UseClass() { /* do something */ } }; I know this example is trivial, but if I have a vector of complex data that is going to be always the same for all derived class but is needed to be accessed from base class methods? class BaseClass { public: BaseClass() {} virtual string GetName() const = 0; virtual void UseClass() = 0; };
class DerivedClass: public BaseClass { public: DerivedClass() {} virtual string GetName() const { return _name; } virtual void UseClass() { /* do something */ } private: static const string _name; };
string DerivedClass::_name = "DerivedClass"; This solution does not satify me because I need reimplement the member _name and its accessor GetName() in every class. In my case I have several members that follows _name behavior and tenths of derived classes. Any idea? | Here is one solution: struct BaseData { const string my_word; const int my_number; };
class Base { public: Base(const BaseData* apBaseData) { mpBaseData = apBaseData; } const string getMyWord() { return mpBaseData->my_word; } int getMyNumber() { return mpBaseData->my_number; } private: const BaseData* mpBaseData; };
class Derived: public Base { public: Derived(): Base(&sBaseData) { } private: static BaseData sBaseData; }
BaseData Derived::BaseData = { "Foo", 42 }; | Simulating a virtual static member of a class in c++? Is there anyway to have a sort of virtual static member in C++? For example: class BaseClass { public: BaseClass(const string& name): _name(name) {} string GetName() const { return _name; } virtual void UseClass() = 0; private: const string _name; };
class DerivedClass: public BaseClass { public: DerivedClass(): BaseClass("DerivedClass") {} virtual void UseClass() { /* do something */ } }; I know this example is trivial, but if I have a vector of complex data that is going to be always the same for all derived class but is needed to be accessed from base class methods? class BaseClass { public: BaseClass() {} virtual string GetName() const = 0; virtual void UseClass() = 0; };
class DerivedClass: public BaseClass { public: DerivedClass() {} virtual string GetName() const { return _name; } virtual void UseClass() { /* do something */ } private: static const string _name; };
string DerivedClass::_name = "DerivedClass"; This solution does not satify me because I need reimplement the member _name and its accessor GetName() in every class. In my case I have several members that follows _name behavior and tenths of derived classes. Any idea? | TITLE:
Simulating a virtual static member of a class in c++?
QUESTION:
Is there anyway to have a sort of virtual static member in C++? For example: class BaseClass { public: BaseClass(const string& name): _name(name) {} string GetName() const { return _name; } virtual void UseClass() = 0; private: const string _name; };
class DerivedClass: public BaseClass { public: DerivedClass(): BaseClass("DerivedClass") {} virtual void UseClass() { /* do something */ } }; I know this example is trivial, but if I have a vector of complex data that is going to be always the same for all derived class but is needed to be accessed from base class methods? class BaseClass { public: BaseClass() {} virtual string GetName() const = 0; virtual void UseClass() = 0; };
class DerivedClass: public BaseClass { public: DerivedClass() {} virtual string GetName() const { return _name; } virtual void UseClass() { /* do something */ } private: static const string _name; };
string DerivedClass::_name = "DerivedClass"; This solution does not satify me because I need reimplement the member _name and its accessor GetName() in every class. In my case I have several members that follows _name behavior and tenths of derived classes. Any idea?
ANSWER:
Here is one solution: struct BaseData { const string my_word; const int my_number; };
class Base { public: Base(const BaseData* apBaseData) { mpBaseData = apBaseData; } const string getMyWord() { return mpBaseData->my_word; } int getMyNumber() { return mpBaseData->my_number; } private: const BaseData* mpBaseData; };
class Derived: public Base { public: Derived(): Base(&sBaseData) { } private: static BaseData sBaseData; }
BaseData Derived::BaseData = { "Foo", 42 }; | [
"c++",
"virtual-functions"
] | 12 | 9 | 6,886 | 5 | 0 | 2008-08-29T15:54:46.167000 | 2008-08-29T20:11:52.930000 |
34,509 | 2,060,952 | Natural (human alpha-numeric) sort in Microsoft SQL 2005 | We have a large database on which we have DB side pagination. This is quick, returning a page of 50 rows from millions of records in a small fraction of a second. Users can define their own sort, basically choosing what column to sort by. Columns are dynamic - some have numeric values, some dates and some text. While most sort as expected text sorts in a dumb way. Well, I say dumb, it makes sense to computers, but frustrates users. For instance, sorting by a string record id gives something like: rec1 rec10 rec14 rec2 rec20 rec3 rec4...and so on. I want this to take account of the number, so: rec1 rec2 rec3 rec4 rec10 rec14 rec20 I can't control the input (otherwise I'd just format in leading 000s) and I can't rely on a single format - some are things like "{alpha code}-{dept code}-{rec id}". I know a few ways to do this in C#, but can't pull down all the records to sort them, as that would be to slow. Does anyone know a way to quickly apply a natural sort in Sql server? We're using: ROW_NUMBER() over (order by {field name} asc) And then we're paging by that. We can add triggers, although we wouldn't. All their input is parametrised and the like, but I can't change the format - if they put in "rec2" and "rec10" they expect them to be returned just like that, and in natural order. We have valid user input that follows different formats for different clients. One might go rec1, rec2, rec3,... rec100, rec101 While another might go: grp1rec1, grp1rec2,... grp20rec300, grp20rec301 When I say we can't control the input I mean that we can't force users to change these standards - they have a value like grp1rec1 and I can't reformat it as grp01rec001, as that would be changing something used for lookups and linking to external systems. These formats vary a lot, but are often mixtures of letters and numbers. Sorting these in C# is easy - just break it up into { "grp", 20, "rec", 301 } and then compare sequence values in turn. However there may be millions of records and the data is paged, I need the sort to be done on the SQL server. SQL server sorts by value, not comparison - in C# I can split the values out to compare, but in SQL I need some logic that (very quickly) gets a single value that consistently sorts. @moebius - your answer might work, but it does feel like an ugly compromise to add a sort-key for all these text values. | Most of the SQL-based solutions I have seen break when the data gets complex enough (e.g. more than one or two numbers in it). Initially I tried implementing a NaturalSort function in T-SQL that met my requirements (among other things, handles an arbitrary number of numbers within the string), but the performance was way too slow. Ultimately, I wrote a scalar CLR function in C# to allow for a natural sort, and even with unoptimized code the performance calling it from SQL Server is blindingly fast. It has the following characteristics: will sort the first 1,000 characters or so correctly (easily modified in code or made into a parameter) properly sorts decimals, so 123.333 comes before 123.45 because of above, will likely NOT sort things like IP addresses correctly; if you wish different behaviour, modify the code supports sorting a string with an arbitrary number of numbers within it will correctly sort numbers up to 25 digits long (easily modified in code or made into a parameter) The code is here: using System; using System.Data.SqlTypes; using System.Text; using Microsoft.SqlServer.Server;
public class UDF { [SqlFunction(DataAccess = DataAccessKind.None, IsDeterministic=true)] public static SqlString Naturalize(string val) { if (String.IsNullOrEmpty(val)) return val;
while(val.Contains(" ")) val = val.Replace(" ", " ");
const int maxLength = 1000; const int padLength = 25;
bool inNumber = false; bool isDecimal = false; int numStart = 0; int numLength = 0; int length = val.Length < maxLength? val.Length: maxLength;
//TODO: optimize this so that we exit for loop once sb.ToString() >= maxLength var sb = new StringBuilder(); for (var i = 0; i < length; i++) { int charCode = (int)val[i]; if (charCode >= 48 && charCode <= 57) { if (!inNumber) { numStart = i; numLength = 1; inNumber = true; continue; } numLength++; continue; } if (inNumber) { sb.Append(PadNumber(val.Substring(numStart, numLength), isDecimal, padLength)); inNumber = false; } isDecimal = (charCode == 46); sb.Append(val[i]); } if (inNumber) sb.Append(PadNumber(val.Substring(numStart, numLength), isDecimal, padLength));
var ret = sb.ToString(); if (ret.Length > maxLength) return ret.Substring(0, maxLength);
return ret; }
static string PadNumber(string num, bool isDecimal, int padLength) { return isDecimal? num.PadRight(padLength, '0'): num.PadLeft(padLength, '0'); } } To register this so that you can call it from SQL Server, run the following commands in Query Analyzer: CREATE ASSEMBLY SqlServerClr FROM 'SqlServerClr.dll' --put the full path to DLL here go CREATE FUNCTION Naturalize(@val as nvarchar(max)) RETURNS nvarchar(1000) EXTERNAL NAME SqlServerClr.UDF.Naturalize go Then, you can use it like so: select * from MyTable order by dbo.Naturalize(MyTextField) Note: If you get an error in SQL Server along the lines of Execution of user code in the.NET Framework is disabled. Enable "clr enabled" configuration option., follow the instructions here to enable it. Make sure you consider the security implications before doing so. If you are not the db admin, make sure you discuss this with your admin before making any changes to the server configuration. Note2: This code does not properly support internationalization (e.g., assumes the decimal marker is ".", is not optimized for speed, etc. Suggestions on improving it are welcome! Edit: Renamed the function to Naturalize instead of NaturalSort, since it does not do any actual sorting. | Natural (human alpha-numeric) sort in Microsoft SQL 2005 We have a large database on which we have DB side pagination. This is quick, returning a page of 50 rows from millions of records in a small fraction of a second. Users can define their own sort, basically choosing what column to sort by. Columns are dynamic - some have numeric values, some dates and some text. While most sort as expected text sorts in a dumb way. Well, I say dumb, it makes sense to computers, but frustrates users. For instance, sorting by a string record id gives something like: rec1 rec10 rec14 rec2 rec20 rec3 rec4...and so on. I want this to take account of the number, so: rec1 rec2 rec3 rec4 rec10 rec14 rec20 I can't control the input (otherwise I'd just format in leading 000s) and I can't rely on a single format - some are things like "{alpha code}-{dept code}-{rec id}". I know a few ways to do this in C#, but can't pull down all the records to sort them, as that would be to slow. Does anyone know a way to quickly apply a natural sort in Sql server? We're using: ROW_NUMBER() over (order by {field name} asc) And then we're paging by that. We can add triggers, although we wouldn't. All their input is parametrised and the like, but I can't change the format - if they put in "rec2" and "rec10" they expect them to be returned just like that, and in natural order. We have valid user input that follows different formats for different clients. One might go rec1, rec2, rec3,... rec100, rec101 While another might go: grp1rec1, grp1rec2,... grp20rec300, grp20rec301 When I say we can't control the input I mean that we can't force users to change these standards - they have a value like grp1rec1 and I can't reformat it as grp01rec001, as that would be changing something used for lookups and linking to external systems. These formats vary a lot, but are often mixtures of letters and numbers. Sorting these in C# is easy - just break it up into { "grp", 20, "rec", 301 } and then compare sequence values in turn. However there may be millions of records and the data is paged, I need the sort to be done on the SQL server. SQL server sorts by value, not comparison - in C# I can split the values out to compare, but in SQL I need some logic that (very quickly) gets a single value that consistently sorts. @moebius - your answer might work, but it does feel like an ugly compromise to add a sort-key for all these text values. | TITLE:
Natural (human alpha-numeric) sort in Microsoft SQL 2005
QUESTION:
We have a large database on which we have DB side pagination. This is quick, returning a page of 50 rows from millions of records in a small fraction of a second. Users can define their own sort, basically choosing what column to sort by. Columns are dynamic - some have numeric values, some dates and some text. While most sort as expected text sorts in a dumb way. Well, I say dumb, it makes sense to computers, but frustrates users. For instance, sorting by a string record id gives something like: rec1 rec10 rec14 rec2 rec20 rec3 rec4...and so on. I want this to take account of the number, so: rec1 rec2 rec3 rec4 rec10 rec14 rec20 I can't control the input (otherwise I'd just format in leading 000s) and I can't rely on a single format - some are things like "{alpha code}-{dept code}-{rec id}". I know a few ways to do this in C#, but can't pull down all the records to sort them, as that would be to slow. Does anyone know a way to quickly apply a natural sort in Sql server? We're using: ROW_NUMBER() over (order by {field name} asc) And then we're paging by that. We can add triggers, although we wouldn't. All their input is parametrised and the like, but I can't change the format - if they put in "rec2" and "rec10" they expect them to be returned just like that, and in natural order. We have valid user input that follows different formats for different clients. One might go rec1, rec2, rec3,... rec100, rec101 While another might go: grp1rec1, grp1rec2,... grp20rec300, grp20rec301 When I say we can't control the input I mean that we can't force users to change these standards - they have a value like grp1rec1 and I can't reformat it as grp01rec001, as that would be changing something used for lookups and linking to external systems. These formats vary a lot, but are often mixtures of letters and numbers. Sorting these in C# is easy - just break it up into { "grp", 20, "rec", 301 } and then compare sequence values in turn. However there may be millions of records and the data is paged, I need the sort to be done on the SQL server. SQL server sorts by value, not comparison - in C# I can split the values out to compare, but in SQL I need some logic that (very quickly) gets a single value that consistently sorts. @moebius - your answer might work, but it does feel like an ugly compromise to add a sort-key for all these text values.
ANSWER:
Most of the SQL-based solutions I have seen break when the data gets complex enough (e.g. more than one or two numbers in it). Initially I tried implementing a NaturalSort function in T-SQL that met my requirements (among other things, handles an arbitrary number of numbers within the string), but the performance was way too slow. Ultimately, I wrote a scalar CLR function in C# to allow for a natural sort, and even with unoptimized code the performance calling it from SQL Server is blindingly fast. It has the following characteristics: will sort the first 1,000 characters or so correctly (easily modified in code or made into a parameter) properly sorts decimals, so 123.333 comes before 123.45 because of above, will likely NOT sort things like IP addresses correctly; if you wish different behaviour, modify the code supports sorting a string with an arbitrary number of numbers within it will correctly sort numbers up to 25 digits long (easily modified in code or made into a parameter) The code is here: using System; using System.Data.SqlTypes; using System.Text; using Microsoft.SqlServer.Server;
public class UDF { [SqlFunction(DataAccess = DataAccessKind.None, IsDeterministic=true)] public static SqlString Naturalize(string val) { if (String.IsNullOrEmpty(val)) return val;
while(val.Contains(" ")) val = val.Replace(" ", " ");
const int maxLength = 1000; const int padLength = 25;
bool inNumber = false; bool isDecimal = false; int numStart = 0; int numLength = 0; int length = val.Length < maxLength? val.Length: maxLength;
//TODO: optimize this so that we exit for loop once sb.ToString() >= maxLength var sb = new StringBuilder(); for (var i = 0; i < length; i++) { int charCode = (int)val[i]; if (charCode >= 48 && charCode <= 57) { if (!inNumber) { numStart = i; numLength = 1; inNumber = true; continue; } numLength++; continue; } if (inNumber) { sb.Append(PadNumber(val.Substring(numStart, numLength), isDecimal, padLength)); inNumber = false; } isDecimal = (charCode == 46); sb.Append(val[i]); } if (inNumber) sb.Append(PadNumber(val.Substring(numStart, numLength), isDecimal, padLength));
var ret = sb.ToString(); if (ret.Length > maxLength) return ret.Substring(0, maxLength);
return ret; }
static string PadNumber(string num, bool isDecimal, int padLength) { return isDecimal? num.PadRight(padLength, '0'): num.PadLeft(padLength, '0'); } } To register this so that you can call it from SQL Server, run the following commands in Query Analyzer: CREATE ASSEMBLY SqlServerClr FROM 'SqlServerClr.dll' --put the full path to DLL here go CREATE FUNCTION Naturalize(@val as nvarchar(max)) RETURNS nvarchar(1000) EXTERNAL NAME SqlServerClr.UDF.Naturalize go Then, you can use it like so: select * from MyTable order by dbo.Naturalize(MyTextField) Note: If you get an error in SQL Server along the lines of Execution of user code in the.NET Framework is disabled. Enable "clr enabled" configuration option., follow the instructions here to enable it. Make sure you consider the security implications before doing so. If you are not the db admin, make sure you discuss this with your admin before making any changes to the server configuration. Note2: This code does not properly support internationalization (e.g., assumes the decimal marker is ".", is not optimized for speed, etc. Suggestions on improving it are welcome! Edit: Renamed the function to Naturalize instead of NaturalSort, since it does not do any actual sorting. | [
"sql-server",
"sql-server-2005",
"sorting",
"natural-sort"
] | 49 | 31 | 39,608 | 14 | 0 | 2008-08-29T15:55:10.223000 | 2010-01-13T22:59:22.020000 |
34,510 | 34,550 | What is a race condition? | When writing multithreaded applications, one of the most common problems experienced is race conditions. My questions to the community are: What is the race condition? How do you detect them? How do you handle them? Finally, how do you prevent them from occurring? | A race condition occurs when two or more threads can access shared data and they try to change it at the same time. Because the thread scheduling algorithm can swap between threads at any time, you don't know the order in which the threads will attempt to access the shared data. Therefore, the result of the change in data is dependent on the thread scheduling algorithm, i.e. both threads are "racing" to access/change the data. Problems often occur when one thread does a "check-then-act" (e.g. "check" if the value is X, then "act" to do something that depends on the value being X) and another thread does something to the value in between the "check" and the "act". E.g: if (x == 5) // The "Check" { y = x * 2; // The "Act"
// If another thread changed x in between "if (x == 5)" and "y = x * 2" above, // y will not be equal to 10. } The point being, y could be 10, or it could be anything, depending on whether another thread changed x in between the check and act. You have no real way of knowing. In order to prevent race conditions from occurring, you would typically put a lock around the shared data to ensure only one thread can access the data at a time. This would mean something like this: // Obtain lock for x if (x == 5) { y = x * 2; // Now, nothing can change x until the lock is released. // Therefore y = 10 } // release lock for x | What is a race condition? When writing multithreaded applications, one of the most common problems experienced is race conditions. My questions to the community are: What is the race condition? How do you detect them? How do you handle them? Finally, how do you prevent them from occurring? | TITLE:
What is a race condition?
QUESTION:
When writing multithreaded applications, one of the most common problems experienced is race conditions. My questions to the community are: What is the race condition? How do you detect them? How do you handle them? Finally, how do you prevent them from occurring?
ANSWER:
A race condition occurs when two or more threads can access shared data and they try to change it at the same time. Because the thread scheduling algorithm can swap between threads at any time, you don't know the order in which the threads will attempt to access the shared data. Therefore, the result of the change in data is dependent on the thread scheduling algorithm, i.e. both threads are "racing" to access/change the data. Problems often occur when one thread does a "check-then-act" (e.g. "check" if the value is X, then "act" to do something that depends on the value being X) and another thread does something to the value in between the "check" and the "act". E.g: if (x == 5) // The "Check" { y = x * 2; // The "Act"
// If another thread changed x in between "if (x == 5)" and "y = x * 2" above, // y will not be equal to 10. } The point being, y could be 10, or it could be anything, depending on whether another thread changed x in between the check and act. You have no real way of knowing. In order to prevent race conditions from occurring, you would typically put a lock around the shared data to ensure only one thread can access the data at a time. This would mean something like this: // Obtain lock for x if (x == 5) { y = x * 2; // Now, nothing can change x until the lock is released. // Therefore y = 10 } // release lock for x | [
"multithreading",
"concurrency",
"terminology",
"race-condition"
] | 1,324 | 1,657 | 876,000 | 19 | 0 | 2008-08-29T15:55:10.457000 | 2008-08-29T16:05:23.100000 |
34,512 | 34,520 | What is a deadlock? | When writing multi-threaded applications, one of the most common problems experienced are deadlocks. My questions to the community are: What is a deadlock? How do you detect them? Do you handle them? And finally, how do you prevent them from occurring? | A lock occurs when multiple processes try to access the same resource at the same time. One process loses out and must wait for the other to finish. A deadlock occurs when the waiting process is still holding on to another resource that the first needs before it can finish. So, an example: Resource A and resource B are used by process X and process Y X starts to use A. X and Y try to start using B Y 'wins' and gets B first now Y needs to use A A is locked by X, which is waiting for Y The best way to avoid deadlocks is to avoid having processes cross over in this way. Reduce the need to lock anything as much as you can. In databases avoid making lots of changes to different tables in a single transaction, avoid triggers and switch to optimistic/dirty/nolock reads as much as possible. | What is a deadlock? When writing multi-threaded applications, one of the most common problems experienced are deadlocks. My questions to the community are: What is a deadlock? How do you detect them? Do you handle them? And finally, how do you prevent them from occurring? | TITLE:
What is a deadlock?
QUESTION:
When writing multi-threaded applications, one of the most common problems experienced are deadlocks. My questions to the community are: What is a deadlock? How do you detect them? Do you handle them? And finally, how do you prevent them from occurring?
ANSWER:
A lock occurs when multiple processes try to access the same resource at the same time. One process loses out and must wait for the other to finish. A deadlock occurs when the waiting process is still holding on to another resource that the first needs before it can finish. So, an example: Resource A and resource B are used by process X and process Y X starts to use A. X and Y try to start using B Y 'wins' and gets B first now Y needs to use A A is locked by X, which is waiting for Y The best way to avoid deadlocks is to avoid having processes cross over in this way. Reduce the need to lock anything as much as you can. In databases avoid making lots of changes to different tables in a single transaction, avoid triggers and switch to optimistic/dirty/nolock reads as much as possible. | [
"multithreading",
"concurrency",
"locking",
"deadlock"
] | 203 | 258 | 163,588 | 18 | 0 | 2008-08-29T15:56:27.020000 | 2008-08-29T15:58:34.957000 |
34,516 | 34,533 | Is there a standard (like phpdoc or python's docstring) for commenting C# code? | Is there a standard convention (like phpdoc or python's docstring) for commenting C# code so that class documentation can be automatically generated from the source code? | You can use XML style comments, and use tools to pull those comments out into API documentation. Here is an example of the comment style: /// /// Authenticates a user based on a username and password. /// /// The username. /// The password. /// /// True, if authentication is successful, otherwise False. /// /// /// For use with local systems /// public override bool Authenticate(string username, string password) Some items to facilitate this are: GhostDoc, which give a single shortcut key to automatically generate comments for a class or method. Sandcastle, which generates MSDN style documentation from XML comments. | Is there a standard (like phpdoc or python's docstring) for commenting C# code? Is there a standard convention (like phpdoc or python's docstring) for commenting C# code so that class documentation can be automatically generated from the source code? | TITLE:
Is there a standard (like phpdoc or python's docstring) for commenting C# code?
QUESTION:
Is there a standard convention (like phpdoc or python's docstring) for commenting C# code so that class documentation can be automatically generated from the source code?
ANSWER:
You can use XML style comments, and use tools to pull those comments out into API documentation. Here is an example of the comment style: /// /// Authenticates a user based on a username and password. /// /// The username. /// The password. /// /// True, if authentication is successful, otherwise False. /// /// /// For use with local systems /// public override bool Authenticate(string username, string password) Some items to facilitate this are: GhostDoc, which give a single shortcut key to automatically generate comments for a class or method. Sandcastle, which generates MSDN style documentation from XML comments. | [
"c#",
"comments"
] | 41 | 43 | 25,195 | 6 | 0 | 2008-08-29T15:57:44.537000 | 2008-08-29T16:02:39.923000 |
34,536 | 34,710 | How do you swap DIVs on mouseover (jQuery)? | This most be the second most simple rollover effect, still I don't find any simple solution. Wanted: I have a list of items and a corresponding list of slides (DIVs). After loading, the first list item should be selected (bold) and the first slide should be visible. When the user hovers over another list item, that list item should be selected instead and the corresponding slide be shown. The following code works, but is awful. How can I get this behaviour in an elegant way? jquery has dozens of animated and complicated rollover effects, but I didn't come up with a clean way for this effect. First slide Second slide Third slide Fourth slide Well well. Oh no! You again? I'm gone! | Rather than displaying all slides when JS is off (which would likely break the page layout) I would place inside the switch LIs real A links to server-side code which returns the page with the "active" class pre-set on the proper switch/slide. $(document).ready(function() {
switches = $('#switches > li');
slides = $('#slides > div');
switches.each(function(idx) {
$(this).data('slide', slides.eq(idx));
}).hover(
function() {
switches.removeClass('active');
slides.removeClass('active');
$(this).addClass('active');
$(this).data('slide').addClass('active');
});
}); #switches.active {
font-weight: bold;
}
#slides div {
display: none;
}
#slides div.active {
display: block;
} test First slide Second slide Third slide Fourth slide Well well. Oh no! You again? I'm gone! | How do you swap DIVs on mouseover (jQuery)? This most be the second most simple rollover effect, still I don't find any simple solution. Wanted: I have a list of items and a corresponding list of slides (DIVs). After loading, the first list item should be selected (bold) and the first slide should be visible. When the user hovers over another list item, that list item should be selected instead and the corresponding slide be shown. The following code works, but is awful. How can I get this behaviour in an elegant way? jquery has dozens of animated and complicated rollover effects, but I didn't come up with a clean way for this effect. First slide Second slide Third slide Fourth slide Well well. Oh no! You again? I'm gone! | TITLE:
How do you swap DIVs on mouseover (jQuery)?
QUESTION:
This most be the second most simple rollover effect, still I don't find any simple solution. Wanted: I have a list of items and a corresponding list of slides (DIVs). After loading, the first list item should be selected (bold) and the first slide should be visible. When the user hovers over another list item, that list item should be selected instead and the corresponding slide be shown. The following code works, but is awful. How can I get this behaviour in an elegant way? jquery has dozens of animated and complicated rollover effects, but I didn't come up with a clean way for this effect. First slide Second slide Third slide Fourth slide Well well. Oh no! You again? I'm gone!
ANSWER:
Rather than displaying all slides when JS is off (which would likely break the page layout) I would place inside the switch LIs real A links to server-side code which returns the page with the "active" class pre-set on the proper switch/slide. $(document).ready(function() {
switches = $('#switches > li');
slides = $('#slides > div');
switches.each(function(idx) {
$(this).data('slide', slides.eq(idx));
}).hover(
function() {
switches.removeClass('active');
slides.removeClass('active');
$(this).addClass('active');
$(this).data('slide').addClass('active');
});
}); #switches.active {
font-weight: bold;
}
#slides div {
display: none;
}
#slides div.active {
display: block;
} test First slide Second slide Third slide Fourth slide Well well. Oh no! You again? I'm gone! | [
"javascript",
"jquery",
"html",
"css"
] | 21 | 19 | 42,724 | 5 | 0 | 2008-08-29T16:02:59.050000 | 2008-08-29T16:49:56.673000 |
34,571 | 34,658 | How do I test a class that has private methods, fields or inner classes? | How do I use JUnit to test a class that has internal private methods, fields or nested classes? It seems bad to change the access modifier for a method just to be able to run a test. | If you have somewhat of a legacy Java application, and you're not allowed to change the visibility of your methods, the best way to test private methods is to use reflection. Internally we're using helpers to get/set private and private static variables as well as invoke private and private static methods. The following patterns will let you do pretty much anything related to the private methods and fields. Of course, you can't change private static final variables through reflection. Method method = TargetClass.getDeclaredMethod(methodName, argClasses); method.setAccessible(true); return method.invoke(targetObject, argObjects); And for fields: Field field = TargetClass.getDeclaredField(fieldName); field.setAccessible(true); field.set(object, value); Notes: TargetClass.getDeclaredMethod(methodName, argClasses) lets you look into private methods. The same thing applies for getDeclaredField. The setAccessible(true) is required to play around with privates. | How do I test a class that has private methods, fields or inner classes? How do I use JUnit to test a class that has internal private methods, fields or nested classes? It seems bad to change the access modifier for a method just to be able to run a test. | TITLE:
How do I test a class that has private methods, fields or inner classes?
QUESTION:
How do I use JUnit to test a class that has internal private methods, fields or nested classes? It seems bad to change the access modifier for a method just to be able to run a test.
ANSWER:
If you have somewhat of a legacy Java application, and you're not allowed to change the visibility of your methods, the best way to test private methods is to use reflection. Internally we're using helpers to get/set private and private static variables as well as invoke private and private static methods. The following patterns will let you do pretty much anything related to the private methods and fields. Of course, you can't change private static final variables through reflection. Method method = TargetClass.getDeclaredMethod(methodName, argClasses); method.setAccessible(true); return method.invoke(targetObject, argObjects); And for fields: Field field = TargetClass.getDeclaredField(fieldName); field.setAccessible(true); field.set(object, value); Notes: TargetClass.getDeclaredMethod(methodName, argClasses) lets you look into private methods. The same thing applies for getDeclaredField. The setAccessible(true) is required to play around with privates. | [
"java",
"unit-testing",
"junit",
"tdd"
] | 3,220 | 1,844 | 1,257,561 | 59 | 0 | 2008-08-29T16:11:09.933000 | 2008-08-29T16:35:11.560000 |
34,581 | 34,587 | inline-block on span | I expected the two span tags in the following sample to display next to each other, instead they display one below the other. If I set the width of the class span.right to 49% they display next to each other. I am not able to figure out why the right span is pushed down like the right span has some invisible padding/margin which makes it take more than 50%. I am trying to get this done without using html tables. Any ideas? * { margin: 0; }
html, body { margin: 0; padding: 0; height: 100%; width: 100%; border: none; }
div.header { width: 100%; height: 80px; vertical-align: top; }
span.left { height: 80px; width: 50%; display: inline-block; background-color: pink; }
span.right { vertical-align: top; display: inline-block; text-align: right; height: 80px; width: 50%; background-color: red; } Test Page Left Span 50% width Right Span 50% width Thanks for the explanation. The float:left works beautifully with expected results in FF 3.1. Unfortunately, in IE6 the right side span renders 50% of the 50%, in effect giving it a width of 25% of the browser window. Setting its width to 100% achieves the desired results but breaks in FF 3.1 which is in standards compliance mode and I understand that. Getting it to work both in FF and IE 6, without resorting to hacks or using multiple CSS sheets has been a challenge | float: left; Try adding that to span.left It will cause it to float to the left (as suggested by the syntax). I am not a CSS expert by any means so please don't take this as unarguable fact but I find that when something is floated, it makes no difference to the vertical position of things below it. If you float the span.right to the right then add text beneath them you should get some interesting results, to stop these "interesting results" you can use "clear: left/right/both" which will cause the block with the clear styling to be under anything floated to the left/right/both. W3Schools have a page on this property too. And welcome to Stackoverflow. | inline-block on span I expected the two span tags in the following sample to display next to each other, instead they display one below the other. If I set the width of the class span.right to 49% they display next to each other. I am not able to figure out why the right span is pushed down like the right span has some invisible padding/margin which makes it take more than 50%. I am trying to get this done without using html tables. Any ideas? * { margin: 0; }
html, body { margin: 0; padding: 0; height: 100%; width: 100%; border: none; }
div.header { width: 100%; height: 80px; vertical-align: top; }
span.left { height: 80px; width: 50%; display: inline-block; background-color: pink; }
span.right { vertical-align: top; display: inline-block; text-align: right; height: 80px; width: 50%; background-color: red; } Test Page Left Span 50% width Right Span 50% width Thanks for the explanation. The float:left works beautifully with expected results in FF 3.1. Unfortunately, in IE6 the right side span renders 50% of the 50%, in effect giving it a width of 25% of the browser window. Setting its width to 100% achieves the desired results but breaks in FF 3.1 which is in standards compliance mode and I understand that. Getting it to work both in FF and IE 6, without resorting to hacks or using multiple CSS sheets has been a challenge | TITLE:
inline-block on span
QUESTION:
I expected the two span tags in the following sample to display next to each other, instead they display one below the other. If I set the width of the class span.right to 49% they display next to each other. I am not able to figure out why the right span is pushed down like the right span has some invisible padding/margin which makes it take more than 50%. I am trying to get this done without using html tables. Any ideas? * { margin: 0; }
html, body { margin: 0; padding: 0; height: 100%; width: 100%; border: none; }
div.header { width: 100%; height: 80px; vertical-align: top; }
span.left { height: 80px; width: 50%; display: inline-block; background-color: pink; }
span.right { vertical-align: top; display: inline-block; text-align: right; height: 80px; width: 50%; background-color: red; } Test Page Left Span 50% width Right Span 50% width Thanks for the explanation. The float:left works beautifully with expected results in FF 3.1. Unfortunately, in IE6 the right side span renders 50% of the 50%, in effect giving it a width of 25% of the browser window. Setting its width to 100% achieves the desired results but breaks in FF 3.1 which is in standards compliance mode and I understand that. Getting it to work both in FF and IE 6, without resorting to hacks or using multiple CSS sheets has been a challenge
ANSWER:
float: left; Try adding that to span.left It will cause it to float to the left (as suggested by the syntax). I am not a CSS expert by any means so please don't take this as unarguable fact but I find that when something is floated, it makes no difference to the vertical position of things below it. If you float the span.right to the right then add text beneath them you should get some interesting results, to stop these "interesting results" you can use "clear: left/right/both" which will cause the block with the clear styling to be under anything floated to the left/right/both. W3Schools have a page on this property too. And welcome to Stackoverflow. | [
"html",
"css",
"css-float",
"internet-explorer-6"
] | 7 | 3 | 22,327 | 3 | 0 | 2008-08-29T16:13:11.880000 | 2008-08-29T16:14:25.247000 |
34,588 | 34,645 | How do I change the number of open files limit in Linux? | When running my application I sometimes get an error about too many files open. Running ulimit -a reports that the limit is 1024. How do I increase the limit above 1024? Edit ulimit -n 2048 results in a permission error. | You could always try doing a ulimit -n 2048. This will only reset the limit for your current shell and the number you specify must not exceed the hard limit Each operating system has a different hard limit setup in a configuration file. For instance, the hard open file limit on Solaris can be set on boot from /etc/system. set rlim_fd_max = 166384 set rlim_fd_cur = 8192 On OS X, this same data must be set in /etc/sysctl.conf. kern.maxfilesperproc=166384 kern.maxfiles=8192 Under Linux, these settings are often in /etc/security/limits.conf. There are two kinds of limits: soft limits are simply the currently enforced limits hard limits mark the maximum value which cannot be exceeded by setting a soft limit Soft limits could be set by any user while hard limits are changeable only by root. Limits are a property of a process. They are inherited when a child process is created so system-wide limits should be set during the system initialization in init scripts and user limits should be set during user login for example by using pam_limits. There are often defaults set when the machine boots. So, even though you may reset your ulimit in an individual shell, you may find that it resets back to the previous value on reboot. You may want to grep your boot scripts for the existence ulimit commands if you want to change the default. | How do I change the number of open files limit in Linux? When running my application I sometimes get an error about too many files open. Running ulimit -a reports that the limit is 1024. How do I increase the limit above 1024? Edit ulimit -n 2048 results in a permission error. | TITLE:
How do I change the number of open files limit in Linux?
QUESTION:
When running my application I sometimes get an error about too many files open. Running ulimit -a reports that the limit is 1024. How do I increase the limit above 1024? Edit ulimit -n 2048 results in a permission error.
ANSWER:
You could always try doing a ulimit -n 2048. This will only reset the limit for your current shell and the number you specify must not exceed the hard limit Each operating system has a different hard limit setup in a configuration file. For instance, the hard open file limit on Solaris can be set on boot from /etc/system. set rlim_fd_max = 166384 set rlim_fd_cur = 8192 On OS X, this same data must be set in /etc/sysctl.conf. kern.maxfilesperproc=166384 kern.maxfiles=8192 Under Linux, these settings are often in /etc/security/limits.conf. There are two kinds of limits: soft limits are simply the currently enforced limits hard limits mark the maximum value which cannot be exceeded by setting a soft limit Soft limits could be set by any user while hard limits are changeable only by root. Limits are a property of a process. They are inherited when a child process is created so system-wide limits should be set during the system initialization in init scripts and user limits should be set during user login for example by using pam_limits. There are often defaults set when the machine boots. So, even though you may reset your ulimit in an individual shell, you may find that it resets back to the previous value on reboot. You may want to grep your boot scripts for the existence ulimit commands if you want to change the default. | [
"linux"
] | 220 | 171 | 574,001 | 4 | 0 | 2008-08-29T16:14:25.417000 | 2008-08-29T16:30:04.443000 |
34,611 | 35,741 | Toolkit Options for 2D Python Game Programming | What are some toolkits for developing 2D games in Python? An option that I have heard of is Pygame, but is there anything that has more range to do more things? What are the good and bad parts about the modules? | I use pygame myself and it is very good. It has good documentation and tutorials, and is quite well designed. I've also heard wonderful reviews of pyglet. | Toolkit Options for 2D Python Game Programming What are some toolkits for developing 2D games in Python? An option that I have heard of is Pygame, but is there anything that has more range to do more things? What are the good and bad parts about the modules? | TITLE:
Toolkit Options for 2D Python Game Programming
QUESTION:
What are some toolkits for developing 2D games in Python? An option that I have heard of is Pygame, but is there anything that has more range to do more things? What are the good and bad parts about the modules?
ANSWER:
I use pygame myself and it is very good. It has good documentation and tutorials, and is quite well designed. I've also heard wonderful reviews of pyglet. | [
"python-3.x",
"pygame",
"libraries",
"toolkit",
"2d-games"
] | 13 | 11 | 6,154 | 7 | 0 | 2008-08-29T16:20:43.467000 | 2008-08-30T06:39:35.977000 |
34,623 | 85,788 | Why is HTML form redirection used in OpenID 2? | Why would you do an automatic HTML post rather than a simple redirect? Is this so developers can automatically generate a login form that posts directory to the remote server when the OpenID is known? eg. User is not logged in and visits your login page. You detect the user's openID from a cookie. Form is generated that directly posts to remote OpenID server. Remote server redirects user back to website. Website logs in the user. If this is the case I can see the benefit. However this assumes that you keep the user's openID in a cookie when they log out. I can find very little information on how this spec should be best implemented. See HTML FORM Redirection in the official specs: http://openid.net/specs/openid-authentication-2_0.html#indirect_comm I found this out from looking at the PHP OpenID Library (version 2.1.1). // Redirect the user to the OpenID server for authentication. // Store the token for this authentication so we can verify the // response.
// For OpenID 1, send a redirect. For OpenID 2, use a Javascript // form to send a POST request to the server. if ($auth_request->shouldSendRedirect()) { $redirect_url = $auth_request->redirectURL(getTrustRoot(), getReturnTo());
// If the redirect URL can't be built, display an error // message. if (Auth_OpenID::isFailure($redirect_url)) { displayError("Could not redirect to server: ". $redirect_url->message); } else { // Send redirect. header("Location: ".$redirect_url); } } else { // Generate form markup and render it. $form_id = 'openid_message'; $form_html = $auth_request->htmlMarkup(getTrustRoot(), getReturnTo(), false, array('id' => $form_id));
// Display an error if the form markup couldn't be generated; // otherwise, render the HTML. if (Auth_OpenID::isFailure($form_html)) { displayError("Could not redirect to server: ". $form_html->message); } else { print $form_html; } } | The primary motivation was, as Mark Brackett says, the limits on payload size imposed by using redirects and GET. Some implementations are smart enough to only use POST when the message goes over a certain size, as there are certainly disadvantages to the POST technique. (Chief among them being the fact that your Back button doesn't work.) Other implementations, like the example code you cited, go for simplicity and consistency and leave out that conditional. | Why is HTML form redirection used in OpenID 2? Why would you do an automatic HTML post rather than a simple redirect? Is this so developers can automatically generate a login form that posts directory to the remote server when the OpenID is known? eg. User is not logged in and visits your login page. You detect the user's openID from a cookie. Form is generated that directly posts to remote OpenID server. Remote server redirects user back to website. Website logs in the user. If this is the case I can see the benefit. However this assumes that you keep the user's openID in a cookie when they log out. I can find very little information on how this spec should be best implemented. See HTML FORM Redirection in the official specs: http://openid.net/specs/openid-authentication-2_0.html#indirect_comm I found this out from looking at the PHP OpenID Library (version 2.1.1). // Redirect the user to the OpenID server for authentication. // Store the token for this authentication so we can verify the // response.
// For OpenID 1, send a redirect. For OpenID 2, use a Javascript // form to send a POST request to the server. if ($auth_request->shouldSendRedirect()) { $redirect_url = $auth_request->redirectURL(getTrustRoot(), getReturnTo());
// If the redirect URL can't be built, display an error // message. if (Auth_OpenID::isFailure($redirect_url)) { displayError("Could not redirect to server: ". $redirect_url->message); } else { // Send redirect. header("Location: ".$redirect_url); } } else { // Generate form markup and render it. $form_id = 'openid_message'; $form_html = $auth_request->htmlMarkup(getTrustRoot(), getReturnTo(), false, array('id' => $form_id));
// Display an error if the form markup couldn't be generated; // otherwise, render the HTML. if (Auth_OpenID::isFailure($form_html)) { displayError("Could not redirect to server: ". $form_html->message); } else { print $form_html; } } | TITLE:
Why is HTML form redirection used in OpenID 2?
QUESTION:
Why would you do an automatic HTML post rather than a simple redirect? Is this so developers can automatically generate a login form that posts directory to the remote server when the OpenID is known? eg. User is not logged in and visits your login page. You detect the user's openID from a cookie. Form is generated that directly posts to remote OpenID server. Remote server redirects user back to website. Website logs in the user. If this is the case I can see the benefit. However this assumes that you keep the user's openID in a cookie when they log out. I can find very little information on how this spec should be best implemented. See HTML FORM Redirection in the official specs: http://openid.net/specs/openid-authentication-2_0.html#indirect_comm I found this out from looking at the PHP OpenID Library (version 2.1.1). // Redirect the user to the OpenID server for authentication. // Store the token for this authentication so we can verify the // response.
// For OpenID 1, send a redirect. For OpenID 2, use a Javascript // form to send a POST request to the server. if ($auth_request->shouldSendRedirect()) { $redirect_url = $auth_request->redirectURL(getTrustRoot(), getReturnTo());
// If the redirect URL can't be built, display an error // message. if (Auth_OpenID::isFailure($redirect_url)) { displayError("Could not redirect to server: ". $redirect_url->message); } else { // Send redirect. header("Location: ".$redirect_url); } } else { // Generate form markup and render it. $form_id = 'openid_message'; $form_html = $auth_request->htmlMarkup(getTrustRoot(), getReturnTo(), false, array('id' => $form_id));
// Display an error if the form markup couldn't be generated; // otherwise, render the HTML. if (Auth_OpenID::isFailure($form_html)) { displayError("Could not redirect to server: ". $form_html->message); } else { print $form_html; } }
ANSWER:
The primary motivation was, as Mark Brackett says, the limits on payload size imposed by using redirects and GET. Some implementations are smart enough to only use POST when the message goes over a certain size, as there are certainly disadvantages to the POST technique. (Chief among them being the fact that your Back button doesn't work.) Other implementations, like the example code you cited, go for simplicity and consistency and leave out that conditional. | [
"openid",
"redirect",
"openid2"
] | 10 | 6 | 2,221 | 3 | 0 | 2008-08-29T16:21:47.600000 | 2008-09-17T17:48:25.357000 |
34,635 | 34,651 | How do I get the assembler output from a C file in VS2005 | I think the file that is produced is an.asm file, any idea how to produce this in Visual Studio when you do a build? | Open the Properties page for a project Select the Configuration Properties -> C/C++ -> Output Files branch Change the Assembler Output option to something other than No Listing Make sure ASM List Location is set to a valid path or sub-path Build. | How do I get the assembler output from a C file in VS2005 I think the file that is produced is an.asm file, any idea how to produce this in Visual Studio when you do a build? | TITLE:
How do I get the assembler output from a C file in VS2005
QUESTION:
I think the file that is produced is an.asm file, any idea how to produce this in Visual Studio when you do a build?
ANSWER:
Open the Properties page for a project Select the Configuration Properties -> C/C++ -> Output Files branch Change the Assembler Output option to something other than No Listing Make sure ASM List Location is set to a valid path or sub-path Build. | [
"c",
"visual-studio",
"assembly"
] | 8 | 5 | 6,199 | 3 | 0 | 2008-08-29T16:25:58.633000 | 2008-08-29T16:31:32.117000 |
34,638 | 34,917 | data 'security' with java and hibernate | The system I am currently working on requires some role-based security, which is well catered for in the Java EE stack. The system intends to be a framework for business domain experts to write their code on top of. However, there is also a requirement for data security. That is, what information is visible to an end user. This effectively means reducing visibility to rows (and perhaps even columns) in the database. We are using Hibernate for our persistence. However, we are using our own annotations so as not to expose our persistence choice to the business domain experts. For row based security this means we could add an annotation such as @Secured at the entity level, which would cause an extra column to be added to the underlying table to constrain our selects? For column based security, we could perhaps have @Secured to either assist in query generation, or perhaps use an aspect to filter the information returned? I'm curious to know how this might affect hibernate's caching mechanisms as well? I'm sure a lot of others will have had the same issue, and I was wondering how you approached this? Much appreciated... | Hibernate has a filter mechanism that may work for you. The filters will rewrite the queries hibernate generates to include an additional clause to limit the rows returned. I'm not aware of anything in hibernate to mask/hide columns. Your database may also have support for this functionality. Oracle, for example, has the Virtual Private Database (VPD) which will rewrite your queries at the database level. This solution has the added benefit that any external program (e.g. reporting tools) that goes against your db will have your security restrictions enforced. VPD also has support to mask restricted columns with NULLs. Unfortunately, the above solutions have not been adequate to support the security requirements for the types projects I typically work on. There is usually some sort of context that cannot be easily expressed in the above solutions. For example, users can view data that they have created, or that have been been marked as public, or belong to a project which they manage. We typically create query/finder/DAO objects where we pass in the values required to enforce the security and then create the query accordingly. I hope this helps | data 'security' with java and hibernate The system I am currently working on requires some role-based security, which is well catered for in the Java EE stack. The system intends to be a framework for business domain experts to write their code on top of. However, there is also a requirement for data security. That is, what information is visible to an end user. This effectively means reducing visibility to rows (and perhaps even columns) in the database. We are using Hibernate for our persistence. However, we are using our own annotations so as not to expose our persistence choice to the business domain experts. For row based security this means we could add an annotation such as @Secured at the entity level, which would cause an extra column to be added to the underlying table to constrain our selects? For column based security, we could perhaps have @Secured to either assist in query generation, or perhaps use an aspect to filter the information returned? I'm curious to know how this might affect hibernate's caching mechanisms as well? I'm sure a lot of others will have had the same issue, and I was wondering how you approached this? Much appreciated... | TITLE:
data 'security' with java and hibernate
QUESTION:
The system I am currently working on requires some role-based security, which is well catered for in the Java EE stack. The system intends to be a framework for business domain experts to write their code on top of. However, there is also a requirement for data security. That is, what information is visible to an end user. This effectively means reducing visibility to rows (and perhaps even columns) in the database. We are using Hibernate for our persistence. However, we are using our own annotations so as not to expose our persistence choice to the business domain experts. For row based security this means we could add an annotation such as @Secured at the entity level, which would cause an extra column to be added to the underlying table to constrain our selects? For column based security, we could perhaps have @Secured to either assist in query generation, or perhaps use an aspect to filter the information returned? I'm curious to know how this might affect hibernate's caching mechanisms as well? I'm sure a lot of others will have had the same issue, and I was wondering how you approached this? Much appreciated...
ANSWER:
Hibernate has a filter mechanism that may work for you. The filters will rewrite the queries hibernate generates to include an additional clause to limit the rows returned. I'm not aware of anything in hibernate to mask/hide columns. Your database may also have support for this functionality. Oracle, for example, has the Virtual Private Database (VPD) which will rewrite your queries at the database level. This solution has the added benefit that any external program (e.g. reporting tools) that goes against your db will have your security restrictions enforced. VPD also has support to mask restricted columns with NULLs. Unfortunately, the above solutions have not been adequate to support the security requirements for the types projects I typically work on. There is usually some sort of context that cannot be easily expressed in the above solutions. For example, users can view data that they have created, or that have been been marked as public, or belong to a project which they manage. We typically create query/finder/DAO objects where we pass in the values required to enforce the security and then create the query accordingly. I hope this helps | [
"java",
"security",
"hibernate",
"jakarta-ee"
] | 6 | 6 | 5,382 | 2 | 0 | 2008-08-29T16:27:43 | 2008-08-29T18:12:36.350000 |
34,655 | 34,686 | Making an iframe take vertical space | I would like to have an iframe take as much vertical space as it needs to display its content and not display a scrollbar. Is it at all possible? Are there any workarounds? | This should set the IFRAME height to its content's height: You may want to add scrolling="no" to your IFRAME to turn off the scrollbars. edit: Oops, forgot to declare the_height. | Making an iframe take vertical space I would like to have an iframe take as much vertical space as it needs to display its content and not display a scrollbar. Is it at all possible? Are there any workarounds? | TITLE:
Making an iframe take vertical space
QUESTION:
I would like to have an iframe take as much vertical space as it needs to display its content and not display a scrollbar. Is it at all possible? Are there any workarounds?
ANSWER:
This should set the IFRAME height to its content's height: You may want to add scrolling="no" to your IFRAME to turn off the scrollbars. edit: Oops, forgot to declare the_height. | [
"javascript",
"html",
"css",
"iframe"
] | 9 | 11 | 5,057 | 5 | 0 | 2008-08-29T16:34:05.027000 | 2008-08-29T16:43:18.030000 |
34,661 | 34,693 | Automate test of web service communication | I have an application that sends messages to an external web service. I build and deploy this application using MSBuild and Cruisecontrol.NET. As CCNET build and deploys the app it also runs a set of test using NUnit. I'd now like to test the web service communication as well. My idea is that as part of the build process a web service should be generated (based on the external web services WSDL) and deployed to the build servers local web server. All the web service should do is to receive the message and place it on the file system so I then can check it using ordinary NUnit for example. This would also make development easier as new developers would only have to run the build script and be up and running (not have to spend time to set up a connection to the third party service). Are there any existing utilities out there that easily mock a web service based on a WSDL? Anyone done something similar using MSBuild? Are there other ways of testing this scenario? | I just started looking into http://www.soapui.org/ and it seems like it will work nicely for testing web services. Also, maybe look at adding an abstraction layer in your web service, each service call would directly call a testable method (outside of the web scope)? I just did this with a bigger project I'm working on, and it's testability is working nicely. | Automate test of web service communication I have an application that sends messages to an external web service. I build and deploy this application using MSBuild and Cruisecontrol.NET. As CCNET build and deploys the app it also runs a set of test using NUnit. I'd now like to test the web service communication as well. My idea is that as part of the build process a web service should be generated (based on the external web services WSDL) and deployed to the build servers local web server. All the web service should do is to receive the message and place it on the file system so I then can check it using ordinary NUnit for example. This would also make development easier as new developers would only have to run the build script and be up and running (not have to spend time to set up a connection to the third party service). Are there any existing utilities out there that easily mock a web service based on a WSDL? Anyone done something similar using MSBuild? Are there other ways of testing this scenario? | TITLE:
Automate test of web service communication
QUESTION:
I have an application that sends messages to an external web service. I build and deploy this application using MSBuild and Cruisecontrol.NET. As CCNET build and deploys the app it also runs a set of test using NUnit. I'd now like to test the web service communication as well. My idea is that as part of the build process a web service should be generated (based on the external web services WSDL) and deployed to the build servers local web server. All the web service should do is to receive the message and place it on the file system so I then can check it using ordinary NUnit for example. This would also make development easier as new developers would only have to run the build script and be up and running (not have to spend time to set up a connection to the third party service). Are there any existing utilities out there that easily mock a web service based on a WSDL? Anyone done something similar using MSBuild? Are there other ways of testing this scenario?
ANSWER:
I just started looking into http://www.soapui.org/ and it seems like it will work nicely for testing web services. Also, maybe look at adding an abstraction layer in your web service, each service call would directly call a testable method (outside of the web scope)? I just did this with a bigger project I'm working on, and it's testability is working nicely. | [
"web-services",
"msbuild",
"build-process",
"nunit",
"cruisecontrol.net"
] | 5 | 3 | 1,526 | 5 | 0 | 2008-08-29T16:35:53.790000 | 2008-08-29T16:45:58.120000 |
34,664 | 708,594 | DesignMode with nested Controls | Has anyone found a useful solution to the DesignMode problem when developing controls? The issue is that if you nest controls then DesignMode only works for the first level. The second and lower levels DesignMode will always return FALSE. The standard hack has been to look at the name of the process that is running and if it is "DevEnv.EXE" then it must be studio thus DesignMode is really TRUE. The problem with that is looking for the ProcessName works its way around through the registry and other strange parts with the end result that the user might not have the required rights to see the process name. In addition this strange route is very slow. So we have had to pile additional hacks to use a singleton and if an error is thrown when asking for the process name then assume that DesignMode is FALSE. A nice clean way to determine DesignMode is in order. Acually getting Microsoft to fix it internally to the framework would be even better! | Revisiting this question, I have now 'discovered' 5 different ways of doing this, which are as follows: System.ComponentModel.DesignMode property
System.ComponentModel.LicenseManager.UsageMode property
private string ServiceString() { if (GetService(typeof(System.ComponentModel.Design.IDesignerHost))!= null) return "Present"; else return "Not present"; }
public bool IsDesignerHosted { get { Control ctrl = this;
while(ctrl!= null) { if((ctrl.Site!= null) && ctrl.Site.DesignMode) return true; ctrl = ctrl.Parent; } return false; } } public static bool IsInDesignMode() { return System.Reflection.Assembly.GetExecutingAssembly().Location.Contains("VisualStudio")) } To try and get a hang on the three solutions proposed, I created a little test solution - with three projects: TestApp (winforms application), SubControl (dll) SubSubControl (dll) I then embedded the SubSubControl in the SubControl, then one of each in the TestApp.Form. This screenshot shows the result when running. This screenshot shows the result with the form open in Visual Studio: Conclusion: It would appear that without reflection the only one that is reliable within the constructor is LicenseUsage, and the only one which is reliable outside the constructor is 'IsDesignedHosted' (by BlueRaja below) PS: See ToolmakerSteve's comment below (which I haven't tested): "Note that IsDesignerHosted answer has been updated to include LicenseUsage..., so now the test can simply be if (IsDesignerHosted). An alternative approach is test LicenseManager in constructor and cache the result." | DesignMode with nested Controls Has anyone found a useful solution to the DesignMode problem when developing controls? The issue is that if you nest controls then DesignMode only works for the first level. The second and lower levels DesignMode will always return FALSE. The standard hack has been to look at the name of the process that is running and if it is "DevEnv.EXE" then it must be studio thus DesignMode is really TRUE. The problem with that is looking for the ProcessName works its way around through the registry and other strange parts with the end result that the user might not have the required rights to see the process name. In addition this strange route is very slow. So we have had to pile additional hacks to use a singleton and if an error is thrown when asking for the process name then assume that DesignMode is FALSE. A nice clean way to determine DesignMode is in order. Acually getting Microsoft to fix it internally to the framework would be even better! | TITLE:
DesignMode with nested Controls
QUESTION:
Has anyone found a useful solution to the DesignMode problem when developing controls? The issue is that if you nest controls then DesignMode only works for the first level. The second and lower levels DesignMode will always return FALSE. The standard hack has been to look at the name of the process that is running and if it is "DevEnv.EXE" then it must be studio thus DesignMode is really TRUE. The problem with that is looking for the ProcessName works its way around through the registry and other strange parts with the end result that the user might not have the required rights to see the process name. In addition this strange route is very slow. So we have had to pile additional hacks to use a singleton and if an error is thrown when asking for the process name then assume that DesignMode is FALSE. A nice clean way to determine DesignMode is in order. Acually getting Microsoft to fix it internally to the framework would be even better!
ANSWER:
Revisiting this question, I have now 'discovered' 5 different ways of doing this, which are as follows: System.ComponentModel.DesignMode property
System.ComponentModel.LicenseManager.UsageMode property
private string ServiceString() { if (GetService(typeof(System.ComponentModel.Design.IDesignerHost))!= null) return "Present"; else return "Not present"; }
public bool IsDesignerHosted { get { Control ctrl = this;
while(ctrl!= null) { if((ctrl.Site!= null) && ctrl.Site.DesignMode) return true; ctrl = ctrl.Parent; } return false; } } public static bool IsInDesignMode() { return System.Reflection.Assembly.GetExecutingAssembly().Location.Contains("VisualStudio")) } To try and get a hang on the three solutions proposed, I created a little test solution - with three projects: TestApp (winforms application), SubControl (dll) SubSubControl (dll) I then embedded the SubSubControl in the SubControl, then one of each in the TestApp.Form. This screenshot shows the result when running. This screenshot shows the result with the form open in Visual Studio: Conclusion: It would appear that without reflection the only one that is reliable within the constructor is LicenseUsage, and the only one which is reliable outside the constructor is 'IsDesignedHosted' (by BlueRaja below) PS: See ToolmakerSteve's comment below (which I haven't tested): "Note that IsDesignerHosted answer has been updated to include LicenseUsage..., so now the test can simply be if (IsDesignerHosted). An alternative approach is test LicenseManager in constructor and cache the result." | [
".net",
"user-controls"
] | 93 | 86 | 22,976 | 14 | 0 | 2008-08-29T16:37:10.323000 | 2009-04-02T07:02:22.477000 |
34,669 | 34,716 | How to keep a "things done" count in a recursive algorithm in Java? | I have a recursive algorithm which steps through a string, character by character, and parses it to create a tree-like structure. I want to be able to keep track of the character index the parser is currently at (for error messages as much as anything else) but am not keen on implementing something like a tuple to handle multiple returned types. I tried using an Integer type, declared outside the method and passed into the recursive method, but because it's final, recursive call increments are "forgotten" when I return. (Because the increment of the Integer value makes the passed-by-value object reference point at a new object) Is there a way to get something similar to work which won't pollute my code? | Since you've already discovered the pseudo-mutable integer "hack," how about this option: Does it make sense for you to make a separate Parser class? If you do this, you can store the current state in a member variable. You probably need to think about how you're going to handle any thread safety issues, and it might be overkill for this particular application, but it might work for you. | How to keep a "things done" count in a recursive algorithm in Java? I have a recursive algorithm which steps through a string, character by character, and parses it to create a tree-like structure. I want to be able to keep track of the character index the parser is currently at (for error messages as much as anything else) but am not keen on implementing something like a tuple to handle multiple returned types. I tried using an Integer type, declared outside the method and passed into the recursive method, but because it's final, recursive call increments are "forgotten" when I return. (Because the increment of the Integer value makes the passed-by-value object reference point at a new object) Is there a way to get something similar to work which won't pollute my code? | TITLE:
How to keep a "things done" count in a recursive algorithm in Java?
QUESTION:
I have a recursive algorithm which steps through a string, character by character, and parses it to create a tree-like structure. I want to be able to keep track of the character index the parser is currently at (for error messages as much as anything else) but am not keen on implementing something like a tuple to handle multiple returned types. I tried using an Integer type, declared outside the method and passed into the recursive method, but because it's final, recursive call increments are "forgotten" when I return. (Because the increment of the Integer value makes the passed-by-value object reference point at a new object) Is there a way to get something similar to work which won't pollute my code?
ANSWER:
Since you've already discovered the pseudo-mutable integer "hack," how about this option: Does it make sense for you to make a separate Parser class? If you do this, you can store the current state in a member variable. You probably need to think about how you're going to handle any thread safety issues, and it might be overkill for this particular application, but it might work for you. | [
"java",
"recursion",
"coding-style",
"integer",
"final"
] | 4 | 2 | 6,310 | 8 | 0 | 2008-08-29T16:38:09.637000 | 2008-08-29T16:52:37.917000 |
34,674 | 35,636 | Performance difference between dot notation versus method call in Objective-C | You can use a standard dot notation or a method call in Objective-C to access a property of an object in Objective-C. myObject.property = YES; or [myObject setProperty:YES]; Is there a difference in performance (in terms of accessing the property)? Is it just a matter of preference in terms of coding style? | Dot notation for property access in Objective-C is a message send, just as bracket notation. That is, given this: @interface Foo: NSObject @property BOOL bar; @end
Foo *foo = [[Foo alloc] init]; foo.bar = YES; [foo setBar:YES]; The last two lines will compile exactly the same. The only thing that changes this is if a property has a getter and/or setter attribute specified; however, all it does is change what message gets sent, not whether a message is sent: @interface MyView: NSView @property(getter=isEmpty) BOOL empty; @end
if ([someView isEmpty]) { /*... */ } if (someView.empty) { /*... */ } Both of the last two lines will compile identically. | Performance difference between dot notation versus method call in Objective-C You can use a standard dot notation or a method call in Objective-C to access a property of an object in Objective-C. myObject.property = YES; or [myObject setProperty:YES]; Is there a difference in performance (in terms of accessing the property)? Is it just a matter of preference in terms of coding style? | TITLE:
Performance difference between dot notation versus method call in Objective-C
QUESTION:
You can use a standard dot notation or a method call in Objective-C to access a property of an object in Objective-C. myObject.property = YES; or [myObject setProperty:YES]; Is there a difference in performance (in terms of accessing the property)? Is it just a matter of preference in terms of coding style?
ANSWER:
Dot notation for property access in Objective-C is a message send, just as bracket notation. That is, given this: @interface Foo: NSObject @property BOOL bar; @end
Foo *foo = [[Foo alloc] init]; foo.bar = YES; [foo setBar:YES]; The last two lines will compile exactly the same. The only thing that changes this is if a property has a getter and/or setter attribute specified; however, all it does is change what message gets sent, not whether a message is sent: @interface MyView: NSView @property(getter=isEmpty) BOOL empty; @end
if ([someView isEmpty]) { /*... */ } if (someView.empty) { /*... */ } Both of the last two lines will compile identically. | [
"objective-c",
"performance"
] | 13 | 21 | 5,403 | 5 | 0 | 2008-08-29T16:39:51.737000 | 2008-08-30T03:06:31.170000 |
34,687 | 38,386 | Subversion ignoring "--password" and "--username" options | When I try to do any svn command and supply the --username and/or --password options, it prompts me for my password anyways, and always will attempt to use my current user instead of the one specified by --username. Neither --no-auth-cache nor --non-interactive have any effect on this. This is a problem because I'm trying to call svn commands from a script, and I can't have it show the prompt. For example, logged in as user1: # $ svn update --username 'user2' --password 'password' # user1@domain.com's password: Other options work correctly: # $ svn --version --quiet # 1.3.2 Why does it prompt me? And why is it asking for user1's password instead of user2's? I'm 99% sure all of my permissions are set correctly. Is there some config option for svn that switches off command-line passwords? Or is it something else entirely? I'm running svn 1.3.2 (r19776) on Fedora Core 5 (Bordeaux). Here's a list of my environment variables (with sensitive information X'ed out). None of them seem to apply to SVN: # HOSTNAME=XXXXXX # TERM=xterm # SHELL=/bin/sh # HISTSIZE=1000 # KDE_NO_IPV6=1 # SSH_CLIENT=XXX.XXX.XXX.XXX XXXXX XX # QTDIR=/usr/lib/qt-3.3 # QTINC=/usr/lib/qt-3.3/include # SSH_TTY=/dev/pts/2 # USER=XXXXXX # LS_COLORS=no=00:fi=00:di=00;34:ln=00;36:pi=40;33:so=00;35:bd=40;33;01:cd=40;33;01:or=01;05;37;41:mi=01;05;37;41:ex=00;32:*.cmd=00;32:*.exe=00;32:*.com=00;32:*.btm=00;32:*.bat=00;32:*.sh=00;32:*.csh=00;32:*.tar=00;31:*.tgz=00;31:*.arj=00;31:*.taz=00;31:*.lzh=00;31:*.zip=00;31:*.z=00;31:*.Z=00;31:*.gz=00;31:*.bz2=00;31:*.bz=00;31:*.tz=00;31:*.rpm=00;31:*.cpio=00;31:*.jpg=00;35:*.gif=00;35:*.bmp=00;35:*.xbm=00;35:*.xpm=00;35:*.png=00;35:*.tif=00;35: # KDEDIR=/usr # MAIL=/var/spool/mail/XXXXXX # PATH=/usr/lib/qt-3.3/bin:/usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin # INPUTRC=/etc/inputrc # PWD=/home/users/XXXXXX/my_repository # KDE_IS_PRELINKED=1 # LANG=en_US.UTF-8 # SSH_ASKPASS=/usr/libexec/openssh/gnome-ssh-askpass # SHLVL=1 # HOME=/home/users/XXXXXX # LOGNAME=XXXXXX # QTLIB=/usr/lib/qt-3.3/lib # CVS_RSH=ssh # SSH_CONNECTION=69.202.73.122 60998 216.7.19.47 22 # LESSOPEN=|/usr/bin/lesspipe.sh %s # G_BROKEN_FILENAMES=1 # _=/bin/env # OLDPWD=/home/users/XXXXXX | The prompt you're getting doesn't look like Subversion asking you for a password, it looks like ssh asking for a password. So my guess is that you have checked out an svn+ssh:// checkout, not an svn:// or http:// or https:// checkout. IIRC all the options you're trying only work for the svn/http/https checkouts. Can you run svn info to confirm what kind of repository you are using? If you are using ssh, you should set up key-based authentication so that your scripts will work without prompting for a password. | Subversion ignoring "--password" and "--username" options When I try to do any svn command and supply the --username and/or --password options, it prompts me for my password anyways, and always will attempt to use my current user instead of the one specified by --username. Neither --no-auth-cache nor --non-interactive have any effect on this. This is a problem because I'm trying to call svn commands from a script, and I can't have it show the prompt. For example, logged in as user1: # $ svn update --username 'user2' --password 'password' # user1@domain.com's password: Other options work correctly: # $ svn --version --quiet # 1.3.2 Why does it prompt me? And why is it asking for user1's password instead of user2's? I'm 99% sure all of my permissions are set correctly. Is there some config option for svn that switches off command-line passwords? Or is it something else entirely? I'm running svn 1.3.2 (r19776) on Fedora Core 5 (Bordeaux). Here's a list of my environment variables (with sensitive information X'ed out). None of them seem to apply to SVN: # HOSTNAME=XXXXXX # TERM=xterm # SHELL=/bin/sh # HISTSIZE=1000 # KDE_NO_IPV6=1 # SSH_CLIENT=XXX.XXX.XXX.XXX XXXXX XX # QTDIR=/usr/lib/qt-3.3 # QTINC=/usr/lib/qt-3.3/include # SSH_TTY=/dev/pts/2 # USER=XXXXXX # LS_COLORS=no=00:fi=00:di=00;34:ln=00;36:pi=40;33:so=00;35:bd=40;33;01:cd=40;33;01:or=01;05;37;41:mi=01;05;37;41:ex=00;32:*.cmd=00;32:*.exe=00;32:*.com=00;32:*.btm=00;32:*.bat=00;32:*.sh=00;32:*.csh=00;32:*.tar=00;31:*.tgz=00;31:*.arj=00;31:*.taz=00;31:*.lzh=00;31:*.zip=00;31:*.z=00;31:*.Z=00;31:*.gz=00;31:*.bz2=00;31:*.bz=00;31:*.tz=00;31:*.rpm=00;31:*.cpio=00;31:*.jpg=00;35:*.gif=00;35:*.bmp=00;35:*.xbm=00;35:*.xpm=00;35:*.png=00;35:*.tif=00;35: # KDEDIR=/usr # MAIL=/var/spool/mail/XXXXXX # PATH=/usr/lib/qt-3.3/bin:/usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin # INPUTRC=/etc/inputrc # PWD=/home/users/XXXXXX/my_repository # KDE_IS_PRELINKED=1 # LANG=en_US.UTF-8 # SSH_ASKPASS=/usr/libexec/openssh/gnome-ssh-askpass # SHLVL=1 # HOME=/home/users/XXXXXX # LOGNAME=XXXXXX # QTLIB=/usr/lib/qt-3.3/lib # CVS_RSH=ssh # SSH_CONNECTION=69.202.73.122 60998 216.7.19.47 22 # LESSOPEN=|/usr/bin/lesspipe.sh %s # G_BROKEN_FILENAMES=1 # _=/bin/env # OLDPWD=/home/users/XXXXXX | TITLE:
Subversion ignoring "--password" and "--username" options
QUESTION:
When I try to do any svn command and supply the --username and/or --password options, it prompts me for my password anyways, and always will attempt to use my current user instead of the one specified by --username. Neither --no-auth-cache nor --non-interactive have any effect on this. This is a problem because I'm trying to call svn commands from a script, and I can't have it show the prompt. For example, logged in as user1: # $ svn update --username 'user2' --password 'password' # user1@domain.com's password: Other options work correctly: # $ svn --version --quiet # 1.3.2 Why does it prompt me? And why is it asking for user1's password instead of user2's? I'm 99% sure all of my permissions are set correctly. Is there some config option for svn that switches off command-line passwords? Or is it something else entirely? I'm running svn 1.3.2 (r19776) on Fedora Core 5 (Bordeaux). Here's a list of my environment variables (with sensitive information X'ed out). None of them seem to apply to SVN: # HOSTNAME=XXXXXX # TERM=xterm # SHELL=/bin/sh # HISTSIZE=1000 # KDE_NO_IPV6=1 # SSH_CLIENT=XXX.XXX.XXX.XXX XXXXX XX # QTDIR=/usr/lib/qt-3.3 # QTINC=/usr/lib/qt-3.3/include # SSH_TTY=/dev/pts/2 # USER=XXXXXX # LS_COLORS=no=00:fi=00:di=00;34:ln=00;36:pi=40;33:so=00;35:bd=40;33;01:cd=40;33;01:or=01;05;37;41:mi=01;05;37;41:ex=00;32:*.cmd=00;32:*.exe=00;32:*.com=00;32:*.btm=00;32:*.bat=00;32:*.sh=00;32:*.csh=00;32:*.tar=00;31:*.tgz=00;31:*.arj=00;31:*.taz=00;31:*.lzh=00;31:*.zip=00;31:*.z=00;31:*.Z=00;31:*.gz=00;31:*.bz2=00;31:*.bz=00;31:*.tz=00;31:*.rpm=00;31:*.cpio=00;31:*.jpg=00;35:*.gif=00;35:*.bmp=00;35:*.xbm=00;35:*.xpm=00;35:*.png=00;35:*.tif=00;35: # KDEDIR=/usr # MAIL=/var/spool/mail/XXXXXX # PATH=/usr/lib/qt-3.3/bin:/usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin # INPUTRC=/etc/inputrc # PWD=/home/users/XXXXXX/my_repository # KDE_IS_PRELINKED=1 # LANG=en_US.UTF-8 # SSH_ASKPASS=/usr/libexec/openssh/gnome-ssh-askpass # SHLVL=1 # HOME=/home/users/XXXXXX # LOGNAME=XXXXXX # QTLIB=/usr/lib/qt-3.3/lib # CVS_RSH=ssh # SSH_CONNECTION=69.202.73.122 60998 216.7.19.47 22 # LESSOPEN=|/usr/bin/lesspipe.sh %s # G_BROKEN_FILENAMES=1 # _=/bin/env # OLDPWD=/home/users/XXXXXX
ANSWER:
The prompt you're getting doesn't look like Subversion asking you for a password, it looks like ssh asking for a password. So my guess is that you have checked out an svn+ssh:// checkout, not an svn:// or http:// or https:// checkout. IIRC all the options you're trying only work for the svn/http/https checkouts. Can you run svn info to confirm what kind of repository you are using? If you are using ssh, you should set up key-based authentication so that your scripts will work without prompting for a password. | [
"svn",
"version-control"
] | 57 | 33 | 185,876 | 7 | 0 | 2008-08-29T16:43:21.150000 | 2008-09-01T20:29:02.970000 |
34,698 | 34,702 | How to turn off sounds in TortoiseSVN? | I do not want TortoiseSVN to alert me with sounds - e.g. when it fails to update. How do I turn off sounds in TortoiseSVN? | Right click > TortoiseSVN > Settings > System Sounds.. Scroll down to the bottom. | How to turn off sounds in TortoiseSVN? I do not want TortoiseSVN to alert me with sounds - e.g. when it fails to update. How do I turn off sounds in TortoiseSVN? | TITLE:
How to turn off sounds in TortoiseSVN?
QUESTION:
I do not want TortoiseSVN to alert me with sounds - e.g. when it fails to update. How do I turn off sounds in TortoiseSVN?
ANSWER:
Right click > TortoiseSVN > Settings > System Sounds.. Scroll down to the bottom. | [
"tortoisesvn",
"system-sounds"
] | 2 | 3 | 374 | 2 | 0 | 2008-08-29T16:47:45.977000 | 2008-08-29T16:48:31.170000 |
34,705 | 34,753 | Best practices with jQuery form binding code in an application | We have an application with a good amount of jQuery JSON calls to server side code. Because of this, we have a large amount of binding code to parse responses and bind the appropriate values to the form. This is a two part question. What is the reccomended approach for dealing with a large number of forms that all have different data. Right now were are trying to take a structured approach in setting up a js "class" for each page, with an init, wireClickEvents etc.. to try to have everything conformed. Is there any "best practices" with creating repetitive jQuery code or any type of reccomended structure other than just throwing a bunch of functions in a js file? | Not 100% sure example what you are asking, but personally, and I use MochiKit, I create JavaScript "classes" (or widgets, if you prefer) for every significant client-side UI structure. These know, of course, how to populate themselves with data. I don't know what more there is to say - writing UI code for the browser in JavaScript is no different than writing UI code for other types of apps, as far as I am concerned. Build classes and instantiate them as needed, populate them with data, have them throw events, etc. etc. Am I up in the night on this?:) EDIT: In other words, yes - do what you are doing, for the most part. I see too many novice JavaScript hackers write a bunch of poorly-cohesive functions that don't appear to be a part of anything specific other than they are all in a single file. Hope that makes sense. | Best practices with jQuery form binding code in an application We have an application with a good amount of jQuery JSON calls to server side code. Because of this, we have a large amount of binding code to parse responses and bind the appropriate values to the form. This is a two part question. What is the reccomended approach for dealing with a large number of forms that all have different data. Right now were are trying to take a structured approach in setting up a js "class" for each page, with an init, wireClickEvents etc.. to try to have everything conformed. Is there any "best practices" with creating repetitive jQuery code or any type of reccomended structure other than just throwing a bunch of functions in a js file? | TITLE:
Best practices with jQuery form binding code in an application
QUESTION:
We have an application with a good amount of jQuery JSON calls to server side code. Because of this, we have a large amount of binding code to parse responses and bind the appropriate values to the form. This is a two part question. What is the reccomended approach for dealing with a large number of forms that all have different data. Right now were are trying to take a structured approach in setting up a js "class" for each page, with an init, wireClickEvents etc.. to try to have everything conformed. Is there any "best practices" with creating repetitive jQuery code or any type of reccomended structure other than just throwing a bunch of functions in a js file?
ANSWER:
Not 100% sure example what you are asking, but personally, and I use MochiKit, I create JavaScript "classes" (or widgets, if you prefer) for every significant client-side UI structure. These know, of course, how to populate themselves with data. I don't know what more there is to say - writing UI code for the browser in JavaScript is no different than writing UI code for other types of apps, as far as I am concerned. Build classes and instantiate them as needed, populate them with data, have them throw events, etc. etc. Am I up in the night on this?:) EDIT: In other words, yes - do what you are doing, for the most part. I see too many novice JavaScript hackers write a bunch of poorly-cohesive functions that don't appear to be a part of anything specific other than they are all in a single file. Hope that makes sense. | [
"javascript",
"jquery",
"ooad"
] | 6 | 3 | 2,044 | 3 | 0 | 2008-08-29T16:48:58.890000 | 2008-08-29T17:05:14.733000 |
34,711 | 35,502 | Google Talk's Graphics Toolkit? | What graphics toolkit is used for the Window's Google Talk application? | There isn't much information on this out there but it seems to be their own customized controls plus an IE component (and not Qt like Google Earth). This forum thread has a little bit of information. | Google Talk's Graphics Toolkit? What graphics toolkit is used for the Window's Google Talk application? | TITLE:
Google Talk's Graphics Toolkit?
QUESTION:
What graphics toolkit is used for the Window's Google Talk application?
ANSWER:
There isn't much information on this out there but it seems to be their own customized controls plus an IE component (and not Qt like Google Earth). This forum thread has a little bit of information. | [
"windows",
"user-interface",
"toolkit"
] | 2 | 1 | 888 | 2 | 0 | 2008-08-29T16:50:20.743000 | 2008-08-30T00:16:34.743000 |
34,712 | 34,729 | .Net - Detecting the Appearance Setting (Classic or XP?) | I have some UI in VB 2005 that looks great in XP Style, but goes hideous in Classic Style. Any ideas about how to detect which mode the user is in and re-format the forms on the fly? Post Answer Edit: Thanks Daniel, looks like this will work. I'm using the first solution you posted with the GetCurrentThemeName() function. I'm doing the following: Function Declaration: Private Declare Unicode Function GetCurrentThemeName Lib "uxtheme" (ByVal stringThemeName As System.Text.StringBuilder, ByVal lengthThemeName As Integer, ByVal stringColorName As System.Text.StringBuilder, ByVal lengthColorName As Integer, ByVal stringSizeName As System.Text.StringBuilder, ByVal lengthSizeName As Integer) As Int32 Code Body: Dim stringThemeName As New System.Text.StringBuilder(260) Dim stringColorName As New System.Text.StringBuilder(260) Dim stringSizeName As New System.Text.StringBuilder(260) GetCurrentThemeName(stringThemeName, 260, stringColorName, 260, stringSizeName, 260) MsgBox(stringThemeName.ToString) The MessageBox comes up Empty when i'm in Windows Classic Style/theme, and Comes up with "C:\WINDOWS\resources\Themes\luna\luna.msstyles" if it's in Windows XP style/theme. I'll have to do a little more checking to see what happens if the user sets another theme than these two, but shouldn't be a big issue. | Try using a combination of GetCurrentThemeName ( MSDN Page ) and DwmIsCompositionEnabled I linked the first to PInvoke so you can just drop it in your code, and for the second one you can use the code provided in the MSDN comment: [DllImport("dwmapi.dll", PreserveSig = false)] public static extern bool DwmIsCompositionEnabled(); See what results you get out of those two functions; they should be enough to determine when you want to use a different theme! | .Net - Detecting the Appearance Setting (Classic or XP?) I have some UI in VB 2005 that looks great in XP Style, but goes hideous in Classic Style. Any ideas about how to detect which mode the user is in and re-format the forms on the fly? Post Answer Edit: Thanks Daniel, looks like this will work. I'm using the first solution you posted with the GetCurrentThemeName() function. I'm doing the following: Function Declaration: Private Declare Unicode Function GetCurrentThemeName Lib "uxtheme" (ByVal stringThemeName As System.Text.StringBuilder, ByVal lengthThemeName As Integer, ByVal stringColorName As System.Text.StringBuilder, ByVal lengthColorName As Integer, ByVal stringSizeName As System.Text.StringBuilder, ByVal lengthSizeName As Integer) As Int32 Code Body: Dim stringThemeName As New System.Text.StringBuilder(260) Dim stringColorName As New System.Text.StringBuilder(260) Dim stringSizeName As New System.Text.StringBuilder(260) GetCurrentThemeName(stringThemeName, 260, stringColorName, 260, stringSizeName, 260) MsgBox(stringThemeName.ToString) The MessageBox comes up Empty when i'm in Windows Classic Style/theme, and Comes up with "C:\WINDOWS\resources\Themes\luna\luna.msstyles" if it's in Windows XP style/theme. I'll have to do a little more checking to see what happens if the user sets another theme than these two, but shouldn't be a big issue. | TITLE:
.Net - Detecting the Appearance Setting (Classic or XP?)
QUESTION:
I have some UI in VB 2005 that looks great in XP Style, but goes hideous in Classic Style. Any ideas about how to detect which mode the user is in and re-format the forms on the fly? Post Answer Edit: Thanks Daniel, looks like this will work. I'm using the first solution you posted with the GetCurrentThemeName() function. I'm doing the following: Function Declaration: Private Declare Unicode Function GetCurrentThemeName Lib "uxtheme" (ByVal stringThemeName As System.Text.StringBuilder, ByVal lengthThemeName As Integer, ByVal stringColorName As System.Text.StringBuilder, ByVal lengthColorName As Integer, ByVal stringSizeName As System.Text.StringBuilder, ByVal lengthSizeName As Integer) As Int32 Code Body: Dim stringThemeName As New System.Text.StringBuilder(260) Dim stringColorName As New System.Text.StringBuilder(260) Dim stringSizeName As New System.Text.StringBuilder(260) GetCurrentThemeName(stringThemeName, 260, stringColorName, 260, stringSizeName, 260) MsgBox(stringThemeName.ToString) The MessageBox comes up Empty when i'm in Windows Classic Style/theme, and Comes up with "C:\WINDOWS\resources\Themes\luna\luna.msstyles" if it's in Windows XP style/theme. I'll have to do a little more checking to see what happens if the user sets another theme than these two, but shouldn't be a big issue.
ANSWER:
Try using a combination of GetCurrentThemeName ( MSDN Page ) and DwmIsCompositionEnabled I linked the first to PInvoke so you can just drop it in your code, and for the second one you can use the code provided in the MSDN comment: [DllImport("dwmapi.dll", PreserveSig = false)] public static extern bool DwmIsCompositionEnabled(); See what results you get out of those two functions; they should be enough to determine when you want to use a different theme! | [
"vb.net",
"windows-xp",
"appearance"
] | 3 | 2 | 1,309 | 3 | 0 | 2008-08-29T16:50:22.990000 | 2008-08-29T16:56:40.620000 |
34,717 | 35,143 | Can an audio object be embedded in an InfoPath form? | Is it possible to embed an audio object (mp3, wma, whatever) in a web-enabled InfoPath form? If it is, how do you do it? | It looks like you can't embed tags in a richtext field. I'm getting nothing when I do it. | Can an audio object be embedded in an InfoPath form? Is it possible to embed an audio object (mp3, wma, whatever) in a web-enabled InfoPath form? If it is, how do you do it? | TITLE:
Can an audio object be embedded in an InfoPath form?
QUESTION:
Is it possible to embed an audio object (mp3, wma, whatever) in a web-enabled InfoPath form? If it is, how do you do it?
ANSWER:
It looks like you can't embed tags in a richtext field. I'm getting nothing when I do it. | [
"sharepoint",
"audio",
"moss",
"infopath"
] | 1 | 1 | 987 | 4 | 0 | 2008-08-29T16:52:41.503000 | 2008-08-29T19:44:42.120000 |
34,728 | 67,355 | SharePoint List Scalability | I am particularly interested in Document Libraries, but in terms of general SharePoint lists, can anyone answer the following...? What is the maximum number of items that a SharePoint list can contain? What is the maximum number of lists that a single SharePoint server can host? When the number of items in the list approaches the maximum, does filtering slow down, and if so, what can be done to improve it? | In SharePoint v.2: Max # list items: 2000 (per folder level) Max lists per site: 2000 is a "reasonable" number Effect when we reach the limit: Exponential degradation of performance. More info: http://technet.microsoft.com/en-us/library/cc287743.aspx In SharePoint v.3: Max # list items: 2000 (per view, you can have million items as long as you don't display in a single view more than 2000 items) Max lists per site: 2000 is a "reasonable" number Effect when we reach the limit: Exponential degradation of performance when we enumerate more than 2000 items using the OM. An alternative is to use Search API or CAML queries. More info: http://technet.microsoft.com/en-us/library/cc287790.aspx | SharePoint List Scalability I am particularly interested in Document Libraries, but in terms of general SharePoint lists, can anyone answer the following...? What is the maximum number of items that a SharePoint list can contain? What is the maximum number of lists that a single SharePoint server can host? When the number of items in the list approaches the maximum, does filtering slow down, and if so, what can be done to improve it? | TITLE:
SharePoint List Scalability
QUESTION:
I am particularly interested in Document Libraries, but in terms of general SharePoint lists, can anyone answer the following...? What is the maximum number of items that a SharePoint list can contain? What is the maximum number of lists that a single SharePoint server can host? When the number of items in the list approaches the maximum, does filtering slow down, and if so, what can be done to improve it?
ANSWER:
In SharePoint v.2: Max # list items: 2000 (per folder level) Max lists per site: 2000 is a "reasonable" number Effect when we reach the limit: Exponential degradation of performance. More info: http://technet.microsoft.com/en-us/library/cc287743.aspx In SharePoint v.3: Max # list items: 2000 (per view, you can have million items as long as you don't display in a single view more than 2000 items) Max lists per site: 2000 is a "reasonable" number Effect when we reach the limit: Exponential degradation of performance when we enumerate more than 2000 items using the OM. An alternative is to use Search API or CAML queries. More info: http://technet.microsoft.com/en-us/library/cc287790.aspx | [
"sharepoint",
"scalability"
] | 16 | 18 | 26,145 | 9 | 0 | 2008-08-29T16:56:39.637000 | 2008-09-15T21:50:00.053000 |
34,732 | 34,796 | How do I list the symbols in a .so file | How do I list the symbols being exported from a.so file? If possible, I'd also like to know their source (e.g. if they are pulled in from a static library). I'm using gcc 4.0.2, if that makes a difference. | The standard tool for listing symbols is nm, you can use it simply like this: nm -gD yourLib.so If you want to see symbols of a C++ library, add the "-C" option which demangle the symbols (it's far more readable demangled). nm -gDC yourLib.so If your.so file is in elf format, you have two options: Either objdump ( -C is also useful for demangling C++): $ objdump -TC libz.so
libz.so: file format elf64-x86-64
DYNAMIC SYMBOL TABLE: 0000000000002010 l d.init 0000000000000000.init 0000000000000000 DF *UND* 0000000000000000 GLIBC_2.2.5 free 0000000000000000 DF *UND* 0000000000000000 GLIBC_2.2.5 __errno_location 0000000000000000 w D *UND* 0000000000000000 _ITM_deregisterTMCloneTable Or use readelf: $ readelf -Ws libz.so Symbol table '.dynsym' contains 112 entries: Num: Value Size Type Bind Vis Ndx Name 0: 0000000000000000 0 NOTYPE LOCAL DEFAULT UND 1: 0000000000002010 0 SECTION LOCAL DEFAULT 10 2: 0000000000000000 0 FUNC GLOBAL DEFAULT UND free@GLIBC_2.2.5 (14) 3: 0000000000000000 0 FUNC GLOBAL DEFAULT UND __errno_location@GLIBC_2.2.5 (14) 4: 0000000000000000 0 NOTYPE WEAK DEFAULT UND _ITM_deregisterTMCloneTable | How do I list the symbols in a .so file How do I list the symbols being exported from a.so file? If possible, I'd also like to know their source (e.g. if they are pulled in from a static library). I'm using gcc 4.0.2, if that makes a difference. | TITLE:
How do I list the symbols in a .so file
QUESTION:
How do I list the symbols being exported from a.so file? If possible, I'd also like to know their source (e.g. if they are pulled in from a static library). I'm using gcc 4.0.2, if that makes a difference.
ANSWER:
The standard tool for listing symbols is nm, you can use it simply like this: nm -gD yourLib.so If you want to see symbols of a C++ library, add the "-C" option which demangle the symbols (it's far more readable demangled). nm -gDC yourLib.so If your.so file is in elf format, you have two options: Either objdump ( -C is also useful for demangling C++): $ objdump -TC libz.so
libz.so: file format elf64-x86-64
DYNAMIC SYMBOL TABLE: 0000000000002010 l d.init 0000000000000000.init 0000000000000000 DF *UND* 0000000000000000 GLIBC_2.2.5 free 0000000000000000 DF *UND* 0000000000000000 GLIBC_2.2.5 __errno_location 0000000000000000 w D *UND* 0000000000000000 _ITM_deregisterTMCloneTable Or use readelf: $ readelf -Ws libz.so Symbol table '.dynsym' contains 112 entries: Num: Value Size Type Bind Vis Ndx Name 0: 0000000000000000 0 NOTYPE LOCAL DEFAULT UND 1: 0000000000002010 0 SECTION LOCAL DEFAULT 10 2: 0000000000000000 0 FUNC GLOBAL DEFAULT UND free@GLIBC_2.2.5 (14) 3: 0000000000000000 0 FUNC GLOBAL DEFAULT UND __errno_location@GLIBC_2.2.5 (14) 4: 0000000000000000 0 NOTYPE WEAK DEFAULT UND _ITM_deregisterTMCloneTable | [
"c++",
"c",
"gcc",
"symbols",
"name-mangling"
] | 617 | 775 | 568,618 | 11 | 0 | 2008-08-29T16:57:47.920000 | 2008-08-29T17:21:08.550000 |
34,734 | 34,747 | Best Way to Reuse Code When Using Visual Studio? | I've tried two different methods of reusing code. I have a solution full of just class library projects with generic code that I reuse in almost every project I work on. When I get to work on a new project, I will reuse code from this code library in one of two ways: I have tried bringing the projects I need from this code library into my project. I have also tried compiling down to a.dll and referencing the.dll from a folder in the root of my current solution. While the second method seems easier and lighter to implement, I always find myself making small tweaks to the original code to fit it into the context of my current project. I know this is a bit of a vague question, but has anyone had success with other methods of reusing class libraries on new solutions? | In short, what you are doing is right, you want to move the common code into a class library (DLL) and then reference that in any projects that require its logic. Where you are going wrong is that you are not maintaining it. If you need to make little "tweaks", subclass your existing code and extend it, dont change it.. If there are major changes needed, then re-think the design. | Best Way to Reuse Code When Using Visual Studio? I've tried two different methods of reusing code. I have a solution full of just class library projects with generic code that I reuse in almost every project I work on. When I get to work on a new project, I will reuse code from this code library in one of two ways: I have tried bringing the projects I need from this code library into my project. I have also tried compiling down to a.dll and referencing the.dll from a folder in the root of my current solution. While the second method seems easier and lighter to implement, I always find myself making small tweaks to the original code to fit it into the context of my current project. I know this is a bit of a vague question, but has anyone had success with other methods of reusing class libraries on new solutions? | TITLE:
Best Way to Reuse Code When Using Visual Studio?
QUESTION:
I've tried two different methods of reusing code. I have a solution full of just class library projects with generic code that I reuse in almost every project I work on. When I get to work on a new project, I will reuse code from this code library in one of two ways: I have tried bringing the projects I need from this code library into my project. I have also tried compiling down to a.dll and referencing the.dll from a folder in the root of my current solution. While the second method seems easier and lighter to implement, I always find myself making small tweaks to the original code to fit it into the context of my current project. I know this is a bit of a vague question, but has anyone had success with other methods of reusing class libraries on new solutions?
ANSWER:
In short, what you are doing is right, you want to move the common code into a class library (DLL) and then reference that in any projects that require its logic. Where you are going wrong is that you are not maintaining it. If you need to make little "tweaks", subclass your existing code and extend it, dont change it.. If there are major changes needed, then re-think the design. | [
".net",
"visual-studio"
] | 5 | 8 | 5,946 | 8 | 0 | 2008-08-29T16:58:01.617000 | 2008-08-29T17:02:11.480000 |
34,735 | 35,126 | Using a rotary encoder with AVR Micro controller | I'm having trouble getting a rotary encoder to work properly with AVR micro controllers. The encoder is a mechanical ALPS encoder, and I'm using Atmega168. Clarification I have tried using an External Interrupt to listen to the pins, but it seems like it is too slow. When Pin A goes high, the interrupt procedure starts and then checks if Pin B is high. The idea is that if Pin B is high the moment Pin A went high, then it is rotating counter clock-wise. If Pin B is low, then it is rotating clock-wise. But it seems like the AVR takes too long to check Pin B, so it is always read as high. I've also tried to create a program that simply blocks until Pin B or Pin A changes. But it might be that there is too much noise when the encoder is rotated, because this does not work either. My last attempt was to have a timer which stores the last 8 values in a buffer and checks if it is going from low to high. This did not work either. I have tried scoping the encoder, and it seems to use between 2 and 4ms from the first Pin changes till the other Pin changes. | I have a webpage about rotary encoders and how to use them, which you might find useful. Unfortunately without more information I can't troubleshoot your particular problem. Which microcontroller pins are connected to the encoder, and what is the code you're currently using to decode the pulses? Ok, you're dealing with a few different issues, the first issue is that this is a mechanical encoder, so you have to deal with switch noise (bounce, chatter). The data sheet indicates that it may take up to 3mS for the parts to stop bouncing and creating false outputs. You need to create a debounce routine. The simplest of which is to continuously check to see if A goes high. If it does, start a timer and check it again in 3 ms. If it's still high, then you can check B - if it's not high then you ignore the spurious pulse and continue looking for A high. When you check B, you look at it, start a timer for 3 ms, and then look at B again. If it was the same both times, then you can use that value - if it changes within 3 ms then you have to do it again (read B, wait 3 ms, then read it again and see if it matches). The atmega is fast enough that you shouldn't have to worry about these checks going slowly, unless you're also running a slow clock speed. Once you deal with the mechanical noise, then you want to look at a proper gray code routine - the algorithm you're following won't work unless you also decrement if A is high when B goes low. Generally people store the last value of the two inputs, and then compare it to the new value of the two inputs and use a small function to increment or decrement based on that. (Check out the heading "high resolution reading" on the website I mentioned above for the table). I combine the two readings into a four bit number and use a simple array to tell me whether I increment or decrement the counter, but there are solutions that are even more advanced, and optimize for code size, speed, or ease of code maintenance. | Using a rotary encoder with AVR Micro controller I'm having trouble getting a rotary encoder to work properly with AVR micro controllers. The encoder is a mechanical ALPS encoder, and I'm using Atmega168. Clarification I have tried using an External Interrupt to listen to the pins, but it seems like it is too slow. When Pin A goes high, the interrupt procedure starts and then checks if Pin B is high. The idea is that if Pin B is high the moment Pin A went high, then it is rotating counter clock-wise. If Pin B is low, then it is rotating clock-wise. But it seems like the AVR takes too long to check Pin B, so it is always read as high. I've also tried to create a program that simply blocks until Pin B or Pin A changes. But it might be that there is too much noise when the encoder is rotated, because this does not work either. My last attempt was to have a timer which stores the last 8 values in a buffer and checks if it is going from low to high. This did not work either. I have tried scoping the encoder, and it seems to use between 2 and 4ms from the first Pin changes till the other Pin changes. | TITLE:
Using a rotary encoder with AVR Micro controller
QUESTION:
I'm having trouble getting a rotary encoder to work properly with AVR micro controllers. The encoder is a mechanical ALPS encoder, and I'm using Atmega168. Clarification I have tried using an External Interrupt to listen to the pins, but it seems like it is too slow. When Pin A goes high, the interrupt procedure starts and then checks if Pin B is high. The idea is that if Pin B is high the moment Pin A went high, then it is rotating counter clock-wise. If Pin B is low, then it is rotating clock-wise. But it seems like the AVR takes too long to check Pin B, so it is always read as high. I've also tried to create a program that simply blocks until Pin B or Pin A changes. But it might be that there is too much noise when the encoder is rotated, because this does not work either. My last attempt was to have a timer which stores the last 8 values in a buffer and checks if it is going from low to high. This did not work either. I have tried scoping the encoder, and it seems to use between 2 and 4ms from the first Pin changes till the other Pin changes.
ANSWER:
I have a webpage about rotary encoders and how to use them, which you might find useful. Unfortunately without more information I can't troubleshoot your particular problem. Which microcontroller pins are connected to the encoder, and what is the code you're currently using to decode the pulses? Ok, you're dealing with a few different issues, the first issue is that this is a mechanical encoder, so you have to deal with switch noise (bounce, chatter). The data sheet indicates that it may take up to 3mS for the parts to stop bouncing and creating false outputs. You need to create a debounce routine. The simplest of which is to continuously check to see if A goes high. If it does, start a timer and check it again in 3 ms. If it's still high, then you can check B - if it's not high then you ignore the spurious pulse and continue looking for A high. When you check B, you look at it, start a timer for 3 ms, and then look at B again. If it was the same both times, then you can use that value - if it changes within 3 ms then you have to do it again (read B, wait 3 ms, then read it again and see if it matches). The atmega is fast enough that you shouldn't have to worry about these checks going slowly, unless you're also running a slow clock speed. Once you deal with the mechanical noise, then you want to look at a proper gray code routine - the algorithm you're following won't work unless you also decrement if A is high when B goes low. Generally people store the last value of the two inputs, and then compare it to the new value of the two inputs and use a small function to increment or decrement based on that. (Check out the heading "high resolution reading" on the website I mentioned above for the table). I combine the two readings into a four bit number and use a simple array to tell me whether I increment or decrement the counter, but there are solutions that are even more advanced, and optimize for code size, speed, or ease of code maintenance. | [
"microcontroller",
"avr",
"encoder",
"atmega"
] | 5 | 10 | 32,156 | 5 | 0 | 2008-08-29T16:58:02.083000 | 2008-08-29T19:37:37.503000 |
34,768 | 34,810 | Setting a form's action in .net 3.5 SP1 causes errors when compiled | I have recently installed.net 3.5 SP1. When I deployed a compiled web site that contained a form with its action set: I received this error. Method not found: 'Void System.Web.UI.HtmlControls.HtmlForm.set_Action(System.String)'. If a fellow developer who has not installed SP1 deploys the compiled site it works fine. Does anyone know of any solutions for this? | .NET 3.5 SP1 tries to use the action="" attribute (.NET 3.5 RTM did not). So, when you deploy, your code is attempting to set the HtmlForm.Action property and failing, as the System.Web.dll on the deploy target is RTM and does not have a setter on the property. | Setting a form's action in .net 3.5 SP1 causes errors when compiled I have recently installed.net 3.5 SP1. When I deployed a compiled web site that contained a form with its action set: I received this error. Method not found: 'Void System.Web.UI.HtmlControls.HtmlForm.set_Action(System.String)'. If a fellow developer who has not installed SP1 deploys the compiled site it works fine. Does anyone know of any solutions for this? | TITLE:
Setting a form's action in .net 3.5 SP1 causes errors when compiled
QUESTION:
I have recently installed.net 3.5 SP1. When I deployed a compiled web site that contained a form with its action set: I received this error. Method not found: 'Void System.Web.UI.HtmlControls.HtmlForm.set_Action(System.String)'. If a fellow developer who has not installed SP1 deploys the compiled site it works fine. Does anyone know of any solutions for this?
ANSWER:
.NET 3.5 SP1 tries to use the action="" attribute (.NET 3.5 RTM did not). So, when you deploy, your code is attempting to set the HtmlForm.Action property and failing, as the System.Web.dll on the deploy target is RTM and does not have a setter on the property. | [
"asp.net",
".net-3.5"
] | 8 | 6 | 3,902 | 6 | 0 | 2008-08-29T17:11:40.007000 | 2008-08-29T17:30:23.690000 |
34,781 | 34,792 | How do you build a ratings implementation? | We have need for a "rating" system in a project we are working on, similar to the one in SO. However, in ours there are multiple entities that need to be "tagged" with a vote up (only up, never down, like an increment). Sometimes we will need to show all of the entities in order of what is rated highest, regardless of entity type, basically mixing the result sets, I guess. What data structures / algorithms do you use to implement this so that is flexible and still scalable? | Since reddit's ranking algorithm rocks, it makes very much sense to have a look at it, if not copy it: Given the time the entry was posted A and the time of 7:46:43 a.m. December 8, 2005 B we have t s as their difference in seconds: t s = A - B and x as the difference between the number of up votes U and the number of down votes D: x = U - D Where y = 1 if x > 0 y = 0 if x = 0 y = -1 if x < 0 and z as the maximal value of the absolute value of x and 1: z = |x| if |x| >= 1 z = 1 if |x| < 1 we have the rating as a function ƒ(t s, y, z): ƒ(t s, y, z) = log 10 z + (y • t s )/45000 | How do you build a ratings implementation? We have need for a "rating" system in a project we are working on, similar to the one in SO. However, in ours there are multiple entities that need to be "tagged" with a vote up (only up, never down, like an increment). Sometimes we will need to show all of the entities in order of what is rated highest, regardless of entity type, basically mixing the result sets, I guess. What data structures / algorithms do you use to implement this so that is flexible and still scalable? | TITLE:
How do you build a ratings implementation?
QUESTION:
We have need for a "rating" system in a project we are working on, similar to the one in SO. However, in ours there are multiple entities that need to be "tagged" with a vote up (only up, never down, like an increment). Sometimes we will need to show all of the entities in order of what is rated highest, regardless of entity type, basically mixing the result sets, I guess. What data structures / algorithms do you use to implement this so that is flexible and still scalable?
ANSWER:
Since reddit's ranking algorithm rocks, it makes very much sense to have a look at it, if not copy it: Given the time the entry was posted A and the time of 7:46:43 a.m. December 8, 2005 B we have t s as their difference in seconds: t s = A - B and x as the difference between the number of up votes U and the number of down votes D: x = U - D Where y = 1 if x > 0 y = 0 if x = 0 y = -1 if x < 0 and z as the maximal value of the absolute value of x and 1: z = |x| if |x| >= 1 z = 1 if |x| < 1 we have the rating as a function ƒ(t s, y, z): ƒ(t s, y, z) = log 10 z + (y • t s )/45000 | [
"algorithm",
"database-design",
"architecture",
"data-structures"
] | 6 | 6 | 408 | 1 | 0 | 2008-08-29T17:16:59.667000 | 2008-08-29T17:20:34.947000 |
34,784 | 744,333 | Mercurial .hgignore for Visual Studio 2008 projects | What is a good setup for.hgignore file when working with Visual Studio 2008? I mostly develop on my own, only occasionly I clone the repository for somebody else to work on it. I'm thinking about obj folders,.suo,.sln,.user files etc.. Can they just be included or are there file I shouldn't include? Thanks! p.s.: at the moment I do the following: ignore all.pdb files and all obj folders. # regexp syntax. syntax: glob *.pdb
syntax: regexp /obj/ | Here's my standard.hgignore file for use with VS2008 that was originally modified from a Git ignore file: # Ignore file for Visual Studio 2008
# use glob syntax syntax: glob
# Ignore Visual Studio 2008 files *.obj *.exe *.pdb *.user *.aps *.pch *.vspscc *_i.c *_p.c *.ncb *.suo *.tlb *.tlh *.bak *.cache *.ilk *.log *.lib *.sbr *.scc [Bb]in [Dd]ebug*/ obj/ [Rr]elease*/ _ReSharper*/ [Tt]est[Rr]esult* [Bb]uild[Ll]og.* *.[Pp]ublish.xml | Mercurial .hgignore for Visual Studio 2008 projects What is a good setup for.hgignore file when working with Visual Studio 2008? I mostly develop on my own, only occasionly I clone the repository for somebody else to work on it. I'm thinking about obj folders,.suo,.sln,.user files etc.. Can they just be included or are there file I shouldn't include? Thanks! p.s.: at the moment I do the following: ignore all.pdb files and all obj folders. # regexp syntax. syntax: glob *.pdb
syntax: regexp /obj/ | TITLE:
Mercurial .hgignore for Visual Studio 2008 projects
QUESTION:
What is a good setup for.hgignore file when working with Visual Studio 2008? I mostly develop on my own, only occasionly I clone the repository for somebody else to work on it. I'm thinking about obj folders,.suo,.sln,.user files etc.. Can they just be included or are there file I shouldn't include? Thanks! p.s.: at the moment I do the following: ignore all.pdb files and all obj folders. # regexp syntax. syntax: glob *.pdb
syntax: regexp /obj/
ANSWER:
Here's my standard.hgignore file for use with VS2008 that was originally modified from a Git ignore file: # Ignore file for Visual Studio 2008
# use glob syntax syntax: glob
# Ignore Visual Studio 2008 files *.obj *.exe *.pdb *.user *.aps *.pch *.vspscc *_i.c *_p.c *.ncb *.suo *.tlb *.tlh *.bak *.cache *.ilk *.log *.lib *.sbr *.scc [Bb]in [Dd]ebug*/ obj/ [Rr]elease*/ _ReSharper*/ [Tt]est[Rr]esult* [Bb]uild[Ll]og.* *.[Pp]ublish.xml | [
"visual-studio",
"visual-studio-2008",
"mercurial",
"hgignore"
] | 166 | 209 | 25,421 | 7 | 0 | 2008-08-29T17:17:40.507000 | 2009-04-13T15:54:11.263000 |
34,790 | 34,855 | duplicating jQuery datepicker | The datepicker function only works on the first input box that is created. I'm trying to duplicate a datepicker by cloning the div that is containing it. click input-text date time picker To initialize the datepicker, according to the jQuery UI documentation I only have to do $('#example').datepicker(); and it does work, but only on the first datepicker that is created. The code to duplicate the div is the following: $("a#dupMe").click(function(event){ event.preventDefault(); i++; var a = $("#template").clone(true).insertBefore("#template").hide().fadeIn(1000); a.find("input#txt").attr('value', i); a.find("input#example").datepicker(); }); The strangest thing is that on the document.ready I have: $('#template #example').datepicker(); $("#template #txt").click(function() { alert($(this).val()); }); and if I click on the #txt it always works. | I'd recommend just using a common class name as well. However, if you're against this for some reason, you could also write a function to create date pickers for all text boxes in your template div (to be called after each duplication). Something like: function makeDatePickers() { $("#template input[type=text]").datepicker(); } | duplicating jQuery datepicker The datepicker function only works on the first input box that is created. I'm trying to duplicate a datepicker by cloning the div that is containing it. click input-text date time picker To initialize the datepicker, according to the jQuery UI documentation I only have to do $('#example').datepicker(); and it does work, but only on the first datepicker that is created. The code to duplicate the div is the following: $("a#dupMe").click(function(event){ event.preventDefault(); i++; var a = $("#template").clone(true).insertBefore("#template").hide().fadeIn(1000); a.find("input#txt").attr('value', i); a.find("input#example").datepicker(); }); The strangest thing is that on the document.ready I have: $('#template #example').datepicker(); $("#template #txt").click(function() { alert($(this).val()); }); and if I click on the #txt it always works. | TITLE:
duplicating jQuery datepicker
QUESTION:
The datepicker function only works on the first input box that is created. I'm trying to duplicate a datepicker by cloning the div that is containing it. click input-text date time picker To initialize the datepicker, according to the jQuery UI documentation I only have to do $('#example').datepicker(); and it does work, but only on the first datepicker that is created. The code to duplicate the div is the following: $("a#dupMe").click(function(event){ event.preventDefault(); i++; var a = $("#template").clone(true).insertBefore("#template").hide().fadeIn(1000); a.find("input#txt").attr('value', i); a.find("input#example").datepicker(); }); The strangest thing is that on the document.ready I have: $('#template #example').datepicker(); $("#template #txt").click(function() { alert($(this).val()); }); and if I click on the #txt it always works.
ANSWER:
I'd recommend just using a common class name as well. However, if you're against this for some reason, you could also write a function to create date pickers for all text boxes in your template div (to be called after each duplication). Something like: function makeDatePickers() { $("#template input[type=text]").datepicker(); } | [
"javascript",
"jquery"
] | 15 | 7 | 9,568 | 4 | 0 | 2008-08-29T17:19:25.823000 | 2008-08-29T17:51:03.890000 |
34,798 | 403,473 | Entire Page refreshes even though gridview is in an update panel | I have a gridview that is within an updatepanel for a modal popup I have on a page. The issue is that the entire page refreshes every time I click an imagebutton that is within my gridview. This causes my entire page to load and since I have grayed out the rest of the page so that the user cannot click on it this is very annoying. Does any one know what I am missing. Edit: I entered a better solution at the bottom | Several months later this problem was fixed. The project I was working in was a previous v1.1 which was converted with 2.0. However, in the web.config this line remained: When it was commented out all of the bugs that we seemed to have with the ajax control toolkit disappeared | Entire Page refreshes even though gridview is in an update panel I have a gridview that is within an updatepanel for a modal popup I have on a page. The issue is that the entire page refreshes every time I click an imagebutton that is within my gridview. This causes my entire page to load and since I have grayed out the rest of the page so that the user cannot click on it this is very annoying. Does any one know what I am missing. Edit: I entered a better solution at the bottom | TITLE:
Entire Page refreshes even though gridview is in an update panel
QUESTION:
I have a gridview that is within an updatepanel for a modal popup I have on a page. The issue is that the entire page refreshes every time I click an imagebutton that is within my gridview. This causes my entire page to load and since I have grayed out the rest of the page so that the user cannot click on it this is very annoying. Does any one know what I am missing. Edit: I entered a better solution at the bottom
ANSWER:
Several months later this problem was fixed. The project I was working in was a previous v1.1 which was converted with 2.0. However, in the web.config this line remained: When it was commented out all of the bugs that we seemed to have with the ajax control toolkit disappeared | [
"asp.net",
"gridview",
"asp.net-ajax",
"updatepanel"
] | 2 | 1 | 6,809 | 11 | 0 | 2008-08-29T17:21:32.153000 | 2008-12-31T16:58:15.890000 |
34,802 | 34,885 | ValidationRule To Enforce Unique Name | I'm trying to write a custom WPF ValidationRule to enforce that a certain property is unique within the context of a given collection. For example: I am editing a collection of custom objects bound to a ListView and I need to ensure that the Name property of each object in the collection is unique. Does anyone know how to do this? | First, I'd create a simple DependencyObject class to hold your collection: class YourCollectionType: DependencyObject {
[PROPERTY DEPENDENCY OF ObservableCollection NAMED: BoundList]
} Then, on your ValidationRule-derived class, create a property: YourCollectionType ListToCheck { get; set; } Then, in the XAML, do this: Then in your validation, look at ListToCheck's BoundList property's collection for the item that you're validating against. If it's in there, obviously return a false validation result. If it's not, return true. | ValidationRule To Enforce Unique Name I'm trying to write a custom WPF ValidationRule to enforce that a certain property is unique within the context of a given collection. For example: I am editing a collection of custom objects bound to a ListView and I need to ensure that the Name property of each object in the collection is unique. Does anyone know how to do this? | TITLE:
ValidationRule To Enforce Unique Name
QUESTION:
I'm trying to write a custom WPF ValidationRule to enforce that a certain property is unique within the context of a given collection. For example: I am editing a collection of custom objects bound to a ListView and I need to ensure that the Name property of each object in the collection is unique. Does anyone know how to do this?
ANSWER:
First, I'd create a simple DependencyObject class to hold your collection: class YourCollectionType: DependencyObject {
[PROPERTY DEPENDENCY OF ObservableCollection NAMED: BoundList]
} Then, on your ValidationRule-derived class, create a property: YourCollectionType ListToCheck { get; set; } Then, in the XAML, do this: Then in your validation, look at ListToCheck's BoundList property's collection for the item that you're validating against. If it's in there, obviously return a false validation result. If it's not, return true. | [
"wpf",
"validation",
"data-binding"
] | 1 | 2 | 1,983 | 2 | 0 | 2008-08-29T17:22:59.747000 | 2008-08-29T18:03:51.427000 |
34,806 | 34,832 | Class design decision | I have a little dilemma that maybe you can help me sort out. I've been working today in modifying ASP.NET's Membership to add a level of indirection. Basically, ASP.NET's Membership supports Users and Roles, leaving all authorization rules to be based on whether a user belongs to a Role or not. What I need to do is add the concept of Function, where a user will belong to a role (or roles) and the role will have one or more functions associated with them, allowing us to authorize a specific action based on if the user belongs to a role which has a function assigned. Having said that, my problem has nothing to do with it, it's a generic class design issue. I want to provide an abstract method in my base RoleProvider class to create the function (and persist it), but I want to make it optional to save a description for that function, so I need to create my CreateFunction method with an overload, one signature accepting the name, and the other accepting the name and the description. I can think of the following scenarios: Create both signatures with the abstract modifier. This has the problem that the implementer may not respect the best practice that says that one overload should call the other one with the parameters normalized, and the logic should only be in the final one (the one with all the parameters). Besides, it's not nice to require both methods to be implemented by the developer. Create the first like virtual, and the second like abstract. Call the second from the first, allow the implementer to override the behavior. It has the same problem, the implementer could make "bad decisions" when overriding it. Same as before, but do not allow the first to be overriden (remove the virtual modifier). The problem here is that the implementer has to be aware that the method could be called with a null description and has to handle that situation. I think the best option is the third one... How is this scenario handled in general? When you design an abstract class and it contains overloaded methods. It isn't that uncommon I think... | I feel the best combination of DRYness and forcing the contract is as follows (in pseudocode): class Base { public final constructor(name) { constructor(name, null) end
public abstract constructor(name, description); } or, alternatively: class Base { public abstract constructor(name);
public final constructor(name, description) { constructor(name) this.set_description(description) }
private final set_description(description) {... } } There's a rule in Java that supports this decision: "never call non-final methods from a constructor." | Class design decision I have a little dilemma that maybe you can help me sort out. I've been working today in modifying ASP.NET's Membership to add a level of indirection. Basically, ASP.NET's Membership supports Users and Roles, leaving all authorization rules to be based on whether a user belongs to a Role or not. What I need to do is add the concept of Function, where a user will belong to a role (or roles) and the role will have one or more functions associated with them, allowing us to authorize a specific action based on if the user belongs to a role which has a function assigned. Having said that, my problem has nothing to do with it, it's a generic class design issue. I want to provide an abstract method in my base RoleProvider class to create the function (and persist it), but I want to make it optional to save a description for that function, so I need to create my CreateFunction method with an overload, one signature accepting the name, and the other accepting the name and the description. I can think of the following scenarios: Create both signatures with the abstract modifier. This has the problem that the implementer may not respect the best practice that says that one overload should call the other one with the parameters normalized, and the logic should only be in the final one (the one with all the parameters). Besides, it's not nice to require both methods to be implemented by the developer. Create the first like virtual, and the second like abstract. Call the second from the first, allow the implementer to override the behavior. It has the same problem, the implementer could make "bad decisions" when overriding it. Same as before, but do not allow the first to be overriden (remove the virtual modifier). The problem here is that the implementer has to be aware that the method could be called with a null description and has to handle that situation. I think the best option is the third one... How is this scenario handled in general? When you design an abstract class and it contains overloaded methods. It isn't that uncommon I think... | TITLE:
Class design decision
QUESTION:
I have a little dilemma that maybe you can help me sort out. I've been working today in modifying ASP.NET's Membership to add a level of indirection. Basically, ASP.NET's Membership supports Users and Roles, leaving all authorization rules to be based on whether a user belongs to a Role or not. What I need to do is add the concept of Function, where a user will belong to a role (or roles) and the role will have one or more functions associated with them, allowing us to authorize a specific action based on if the user belongs to a role which has a function assigned. Having said that, my problem has nothing to do with it, it's a generic class design issue. I want to provide an abstract method in my base RoleProvider class to create the function (and persist it), but I want to make it optional to save a description for that function, so I need to create my CreateFunction method with an overload, one signature accepting the name, and the other accepting the name and the description. I can think of the following scenarios: Create both signatures with the abstract modifier. This has the problem that the implementer may not respect the best practice that says that one overload should call the other one with the parameters normalized, and the logic should only be in the final one (the one with all the parameters). Besides, it's not nice to require both methods to be implemented by the developer. Create the first like virtual, and the second like abstract. Call the second from the first, allow the implementer to override the behavior. It has the same problem, the implementer could make "bad decisions" when overriding it. Same as before, but do not allow the first to be overriden (remove the virtual modifier). The problem here is that the implementer has to be aware that the method could be called with a null description and has to handle that situation. I think the best option is the third one... How is this scenario handled in general? When you design an abstract class and it contains overloaded methods. It isn't that uncommon I think...
ANSWER:
I feel the best combination of DRYness and forcing the contract is as follows (in pseudocode): class Base { public final constructor(name) { constructor(name, null) end
public abstract constructor(name, description); } or, alternatively: class Base { public abstract constructor(name);
public final constructor(name, description) { constructor(name) this.set_description(description) }
private final set_description(description) {... } } There's a rule in Java that supports this decision: "never call non-final methods from a constructor." | [
"inheritance",
"asp.net-membership",
"oop"
] | 1 | 1 | 248 | 2 | 0 | 2008-08-29T17:29:38.060000 | 2008-08-29T17:41:16.940000 |
34,809 | 34,882 | What is the best way to tell if an object is modified? | I have an object that is mapped to a cookie as a serialized base-64 string. I only want to write out a new cookie if there are changes made to the object stored in the cookie on server-side. What I want to do is get a hash code when the object is pulled from the cookie/initialized and compare the original hash code to the hash code that exists just before I send the cookie header off to the client to ensure I don't have to re-serialize/send the cookie unless changes were made. I was going to override the.NET's Object.GetHashCode() method, but I wasn't sure that this is the best way to go about checking if an object is modified. Are there any other ways I can check if an object is modified, or should I override the GetHashCode() method. Update I decided to accept @rmbarnes's answer as it had an interesting solution to the problem, and because I decided to use his advice at the end of his post and not check for modification. I'd still be interested to hear any other solutions anyone may have to my scenario however. | At the end of the object's constructor you could serialize the object to a base 64 string just like the cookie stores it, and store this in a member variable. When you want to check if the cookie needs recreating, re - serialize the object and compare this new base 64 string against the one stored in a member variable. If it has changed, reset the cookie with the new value. Watch out for the gotcha - don't include the member variable storing the base 64 serialization in the serialization itself. I presume your language uses something like a sleep() function (is how PHP does it) to serialize itself, so just make sure the member is not included in that function. This will always work because you are comparing the exact value you'd be saving in the cookie, and wouldn't need to override GetHashCode() which sounds like it could have nasty consequences. All that said I'd probably just drop the test and always reset the cookie, can't be that much overhead in it when compared to doing the change check, and far less likelyhood of bugs. | What is the best way to tell if an object is modified? I have an object that is mapped to a cookie as a serialized base-64 string. I only want to write out a new cookie if there are changes made to the object stored in the cookie on server-side. What I want to do is get a hash code when the object is pulled from the cookie/initialized and compare the original hash code to the hash code that exists just before I send the cookie header off to the client to ensure I don't have to re-serialize/send the cookie unless changes were made. I was going to override the.NET's Object.GetHashCode() method, but I wasn't sure that this is the best way to go about checking if an object is modified. Are there any other ways I can check if an object is modified, or should I override the GetHashCode() method. Update I decided to accept @rmbarnes's answer as it had an interesting solution to the problem, and because I decided to use his advice at the end of his post and not check for modification. I'd still be interested to hear any other solutions anyone may have to my scenario however. | TITLE:
What is the best way to tell if an object is modified?
QUESTION:
I have an object that is mapped to a cookie as a serialized base-64 string. I only want to write out a new cookie if there are changes made to the object stored in the cookie on server-side. What I want to do is get a hash code when the object is pulled from the cookie/initialized and compare the original hash code to the hash code that exists just before I send the cookie header off to the client to ensure I don't have to re-serialize/send the cookie unless changes were made. I was going to override the.NET's Object.GetHashCode() method, but I wasn't sure that this is the best way to go about checking if an object is modified. Are there any other ways I can check if an object is modified, or should I override the GetHashCode() method. Update I decided to accept @rmbarnes's answer as it had an interesting solution to the problem, and because I decided to use his advice at the end of his post and not check for modification. I'd still be interested to hear any other solutions anyone may have to my scenario however.
ANSWER:
At the end of the object's constructor you could serialize the object to a base 64 string just like the cookie stores it, and store this in a member variable. When you want to check if the cookie needs recreating, re - serialize the object and compare this new base 64 string against the one stored in a member variable. If it has changed, reset the cookie with the new value. Watch out for the gotcha - don't include the member variable storing the base 64 serialization in the serialization itself. I presume your language uses something like a sleep() function (is how PHP does it) to serialize itself, so just make sure the member is not included in that function. This will always work because you are comparing the exact value you'd be saving in the cookie, and wouldn't need to override GetHashCode() which sounds like it could have nasty consequences. All that said I'd probably just drop the test and always reset the cookie, can't be that much overhead in it when compared to doing the change check, and far less likelyhood of bugs. | [
"c#",
".net"
] | 6 | 1 | 2,750 | 4 | 0 | 2008-08-29T17:30:15.407000 | 2008-08-29T18:02:04.160000 |
34,848 | 35,894 | Zend Framework: setting a Zend_Form_Element form field to be required, how do I change the validator used to ensure that the element is not blank | When using a Zend_Form, the only way to validate that an input is not left blank is to do $element->setRequired(true); If this is not set and the element is blank, it appears to me that validation is not run on the element. If I do use setRequired(), the element is automatically given the standard NotEmpty validator. The thing is that the error message with this validator sucks, "Value is empty, but a non-empty value is required". I want to change this message. At the moment I have done this by changing the Zend_Validate_NotEmpty class, but this is a bit hacky. I would ideally like to be able to use my own class (derived from Zend_Validate_NotEmpty ) to perform the not empty check. | I did it this way (ZF 1.5): $name = new Zend_Form_Element_Text('name'); $name->setLabel('Full Name: ') ->setRequired(true) ->addFilter('StripTags') ->addFilter('StringTrim') ->addValidator($MyNotEmpty); so, the addValidator() is the interesting part. The Message is set in an "Errormessage File" (to bundle all custom messages in one file): $MyNotEmpty = new Zend_Validate_NotEmpty(); $MyNotEmpty->setMessage($trans->translate('err.IS_EMPTY'),Zend_Validate_NotEmpty::IS_EMPTY); hope this helps... | Zend Framework: setting a Zend_Form_Element form field to be required, how do I change the validator used to ensure that the element is not blank When using a Zend_Form, the only way to validate that an input is not left blank is to do $element->setRequired(true); If this is not set and the element is blank, it appears to me that validation is not run on the element. If I do use setRequired(), the element is automatically given the standard NotEmpty validator. The thing is that the error message with this validator sucks, "Value is empty, but a non-empty value is required". I want to change this message. At the moment I have done this by changing the Zend_Validate_NotEmpty class, but this is a bit hacky. I would ideally like to be able to use my own class (derived from Zend_Validate_NotEmpty ) to perform the not empty check. | TITLE:
Zend Framework: setting a Zend_Form_Element form field to be required, how do I change the validator used to ensure that the element is not blank
QUESTION:
When using a Zend_Form, the only way to validate that an input is not left blank is to do $element->setRequired(true); If this is not set and the element is blank, it appears to me that validation is not run on the element. If I do use setRequired(), the element is automatically given the standard NotEmpty validator. The thing is that the error message with this validator sucks, "Value is empty, but a non-empty value is required". I want to change this message. At the moment I have done this by changing the Zend_Validate_NotEmpty class, but this is a bit hacky. I would ideally like to be able to use my own class (derived from Zend_Validate_NotEmpty ) to perform the not empty check.
ANSWER:
I did it this way (ZF 1.5): $name = new Zend_Form_Element_Text('name'); $name->setLabel('Full Name: ') ->setRequired(true) ->addFilter('StripTags') ->addFilter('StringTrim') ->addValidator($MyNotEmpty); so, the addValidator() is the interesting part. The Message is set in an "Errormessage File" (to bundle all custom messages in one file): $MyNotEmpty = new Zend_Validate_NotEmpty(); $MyNotEmpty->setMessage($trans->translate('err.IS_EMPTY'),Zend_Validate_NotEmpty::IS_EMPTY); hope this helps... | [
"php",
"zend-framework",
"validation"
] | 4 | 4 | 8,168 | 5 | 0 | 2008-08-29T17:47:46.893000 | 2008-08-30T11:26:57.207000 |
34,852 | 34,965 | NHibernate Session.Flush() Sending Update Queries When No Update Has Occurred | I have an NHibernate session. In this session, I am performing exactly 1 operation, which is to run this code to get a list: public IList GetCustomerByFirstName(string customerFirstName) { return _session.CreateCriteria(typeof(Customer)).Add(new NHibernate.Expression.EqExpression("FirstName", customerFirstName)).List (); } I am calling Session.Flush() at the end of the HttpRequest, and I get a HibernateAdoException. NHibernate is passing an update statement to the db, and causing a foreign key violation. If I don't run the flush, the request completes with no problem. The issue here is that I need the flush in place in case there is a change that occurs within other sessions, since this code is reused in other areas. Is there another configuration setting I might be missing? Here's the code from the exception: [SQL: UPDATE CUSTOMER SET first_name =?, last_name =?, strategy_code_1 =?, strategy_code_2 =?, strategy_code_3 =?, dts_import =?, account_cycle_code =?, bucket =?, collector_code =?, days_delinquent_count =?, external_status_code =?, principal_balance_amount =?, total_min_pay_due =?, current_balance =?, amount_delinquent =?, current_min_pay_due =?, bucket_1 =?, bucket_2 =?, bucket_3 =?, bucket_4 =?, bucket_5 =?, bucket_6 =?, bucket_7 =? WHERE customer_account_id =?] No parameters are showing as being passed. | I have seen this once before when one of my models was not mapped correctly (wasn't using nullable types correctly). May you please paste your model and mapping? | NHibernate Session.Flush() Sending Update Queries When No Update Has Occurred I have an NHibernate session. In this session, I am performing exactly 1 operation, which is to run this code to get a list: public IList GetCustomerByFirstName(string customerFirstName) { return _session.CreateCriteria(typeof(Customer)).Add(new NHibernate.Expression.EqExpression("FirstName", customerFirstName)).List (); } I am calling Session.Flush() at the end of the HttpRequest, and I get a HibernateAdoException. NHibernate is passing an update statement to the db, and causing a foreign key violation. If I don't run the flush, the request completes with no problem. The issue here is that I need the flush in place in case there is a change that occurs within other sessions, since this code is reused in other areas. Is there another configuration setting I might be missing? Here's the code from the exception: [SQL: UPDATE CUSTOMER SET first_name =?, last_name =?, strategy_code_1 =?, strategy_code_2 =?, strategy_code_3 =?, dts_import =?, account_cycle_code =?, bucket =?, collector_code =?, days_delinquent_count =?, external_status_code =?, principal_balance_amount =?, total_min_pay_due =?, current_balance =?, amount_delinquent =?, current_min_pay_due =?, bucket_1 =?, bucket_2 =?, bucket_3 =?, bucket_4 =?, bucket_5 =?, bucket_6 =?, bucket_7 =? WHERE customer_account_id =?] No parameters are showing as being passed. | TITLE:
NHibernate Session.Flush() Sending Update Queries When No Update Has Occurred
QUESTION:
I have an NHibernate session. In this session, I am performing exactly 1 operation, which is to run this code to get a list: public IList GetCustomerByFirstName(string customerFirstName) { return _session.CreateCriteria(typeof(Customer)).Add(new NHibernate.Expression.EqExpression("FirstName", customerFirstName)).List (); } I am calling Session.Flush() at the end of the HttpRequest, and I get a HibernateAdoException. NHibernate is passing an update statement to the db, and causing a foreign key violation. If I don't run the flush, the request completes with no problem. The issue here is that I need the flush in place in case there is a change that occurs within other sessions, since this code is reused in other areas. Is there another configuration setting I might be missing? Here's the code from the exception: [SQL: UPDATE CUSTOMER SET first_name =?, last_name =?, strategy_code_1 =?, strategy_code_2 =?, strategy_code_3 =?, dts_import =?, account_cycle_code =?, bucket =?, collector_code =?, days_delinquent_count =?, external_status_code =?, principal_balance_amount =?, total_min_pay_due =?, current_balance =?, amount_delinquent =?, current_min_pay_due =?, bucket_1 =?, bucket_2 =?, bucket_3 =?, bucket_4 =?, bucket_5 =?, bucket_6 =?, bucket_7 =? WHERE customer_account_id =?] No parameters are showing as being passed.
ANSWER:
I have seen this once before when one of my models was not mapped correctly (wasn't using nullable types correctly). May you please paste your model and mapping? | [
"c#",
".net",
"nhibernate"
] | 35 | 16 | 10,491 | 3 | 0 | 2008-08-29T17:49:31.197000 | 2008-08-29T18:35:23.207000 |
34,858 | 34,865 | How to benchmark a SQL Server Query? | I'd like to know the standard way to benchmark a SQL Sever Query, preferably I'd like to know about the tools that come with SQL Server rather than 3rd Party tools. | set showplan_text on will show you the execution plan (to see it graphically use CTRL + K (sql 2000) or CTRL + M (sql 2005 +) set statistics IO on will show you the reads set statistics time on will show you the elapsed time | How to benchmark a SQL Server Query? I'd like to know the standard way to benchmark a SQL Sever Query, preferably I'd like to know about the tools that come with SQL Server rather than 3rd Party tools. | TITLE:
How to benchmark a SQL Server Query?
QUESTION:
I'd like to know the standard way to benchmark a SQL Sever Query, preferably I'd like to know about the tools that come with SQL Server rather than 3rd Party tools.
ANSWER:
set showplan_text on will show you the execution plan (to see it graphically use CTRL + K (sql 2000) or CTRL + M (sql 2005 +) set statistics IO on will show you the reads set statistics time on will show you the elapsed time | [
"sql-server",
"database",
"benchmarking"
] | 8 | 11 | 7,458 | 3 | 0 | 2008-08-29T17:52:23.060000 | 2008-08-29T17:55:25.860000 |
34,868 | 34,869 | How do you create optional arguments in php? | In the PHP manual, to show the syntax for functions with optional parameters, they use brackets around each set of dependent optional parameter. For example, for the date() function, the manual reads: string date ( string $format [, int $timestamp = time() ] ) Where $timestamp is an optional parameter, and when left blank it defaults to the time() function's return value. How do you go about creating optional parameters like this when defining a custom function in PHP? | Much like the manual, use an equals ( = ) sign in your definition of the parameters: function dosomething($var1, $var2, $var3 = 'somevalue'){ // Rest of function here... } | How do you create optional arguments in php? In the PHP manual, to show the syntax for functions with optional parameters, they use brackets around each set of dependent optional parameter. For example, for the date() function, the manual reads: string date ( string $format [, int $timestamp = time() ] ) Where $timestamp is an optional parameter, and when left blank it defaults to the time() function's return value. How do you go about creating optional parameters like this when defining a custom function in PHP? | TITLE:
How do you create optional arguments in php?
QUESTION:
In the PHP manual, to show the syntax for functions with optional parameters, they use brackets around each set of dependent optional parameter. For example, for the date() function, the manual reads: string date ( string $format [, int $timestamp = time() ] ) Where $timestamp is an optional parameter, and when left blank it defaults to the time() function's return value. How do you go about creating optional parameters like this when defining a custom function in PHP?
ANSWER:
Much like the manual, use an equals ( = ) sign in your definition of the parameters: function dosomething($var1, $var2, $var3 = 'somevalue'){ // Rest of function here... } | [
"php"
] | 216 | 287 | 200,516 | 7 | 0 | 2008-08-29T17:57:50.847000 | 2008-08-29T17:58:50.113000 |
34,879 | 34,884 | Print out the keys and Data of a Hashtable in C# .NET 1.1 | I need debug some old code that uses a Hashtable to store response from various threads. I need a way to go through the entire Hashtable and print out both keys and the data in the Hastable. How can this be done? | foreach(string key in hashTable.Keys) { Console.WriteLine(String.Format("{0}: {1}", key, hashTable[key])); } | Print out the keys and Data of a Hashtable in C# .NET 1.1 I need debug some old code that uses a Hashtable to store response from various threads. I need a way to go through the entire Hashtable and print out both keys and the data in the Hastable. How can this be done? | TITLE:
Print out the keys and Data of a Hashtable in C# .NET 1.1
QUESTION:
I need debug some old code that uses a Hashtable to store response from various threads. I need a way to go through the entire Hashtable and print out both keys and the data in the Hastable. How can this be done?
ANSWER:
foreach(string key in hashTable.Keys) { Console.WriteLine(String.Format("{0}: {1}", key, hashTable[key])); } | [
"c#",
"hashtable",
".net-1.1"
] | 11 | 23 | 39,571 | 5 | 0 | 2008-08-29T18:01:15.240000 | 2008-08-29T18:03:37.120000 |
34,896 | 34,902 | When is it best to sanitize user input? | User equals untrustworthy. Never trust untrustworthy user's input. I get that. However, I am wondering when the best time to sanitize input is. For example, do you blindly store user input and then sanitize it whenever it is accessed/used, or do you sanitize the input immediately and then store this "cleaned" version? Maybe there are also some other approaches I haven't though of in addition to these. I am leaning more towards the first method, because any data that came from user input must still be approached cautiously, where the "cleaned" data might still unknowingly or accidentally be dangerous. Either way, what method do people think is best, and for what reasons? | I like to sanitize it as early as possible, which means the sanitizing happens when the user tries to enter in invalid data. If there's a TextBox for their age, and they type in anything other that a number, I don't let the keypress for the letter go through. Then, whatever is reading the data (often a server) I do a sanity check when I read in the data, just to make sure that nothing slips in due to a more determined user (such as hand-editing files, or even modifying packets!) Edit: Overall, sanitize early and sanitize any time you've lost sight of the data for even a second (e.g. File Save -> File Open) | When is it best to sanitize user input? User equals untrustworthy. Never trust untrustworthy user's input. I get that. However, I am wondering when the best time to sanitize input is. For example, do you blindly store user input and then sanitize it whenever it is accessed/used, or do you sanitize the input immediately and then store this "cleaned" version? Maybe there are also some other approaches I haven't though of in addition to these. I am leaning more towards the first method, because any data that came from user input must still be approached cautiously, where the "cleaned" data might still unknowingly or accidentally be dangerous. Either way, what method do people think is best, and for what reasons? | TITLE:
When is it best to sanitize user input?
QUESTION:
User equals untrustworthy. Never trust untrustworthy user's input. I get that. However, I am wondering when the best time to sanitize input is. For example, do you blindly store user input and then sanitize it whenever it is accessed/used, or do you sanitize the input immediately and then store this "cleaned" version? Maybe there are also some other approaches I haven't though of in addition to these. I am leaning more towards the first method, because any data that came from user input must still be approached cautiously, where the "cleaned" data might still unknowingly or accidentally be dangerous. Either way, what method do people think is best, and for what reasons?
ANSWER:
I like to sanitize it as early as possible, which means the sanitizing happens when the user tries to enter in invalid data. If there's a TextBox for their age, and they type in anything other that a number, I don't let the keypress for the letter go through. Then, whatever is reading the data (often a server) I do a sanity check when I read in the data, just to make sure that nothing slips in due to a more determined user (such as hand-editing files, or even modifying packets!) Edit: Overall, sanitize early and sanitize any time you've lost sight of the data for even a second (e.g. File Save -> File Open) | [
"xss",
"sql-injection",
"user-input",
"sanitization"
] | 68 | 13 | 27,579 | 14 | 0 | 2008-08-29T18:07:04.960000 | 2008-08-29T18:09:27.140000 |
34,913 | 36,678 | C# Linq Grouping | I'm experimenting with Linq and am having trouble figuring out grouping. I've gone through several tutorials but for some reason can't figure this out. As an example, say I have a table (SiteStats) with multiple website IDs that stores a count of how many visitors by type have accessed each site in total and for the past 30 days. ╔════════╦═════════════╦════════╦══════╗ ║ SiteId ║ VisitorType ║ Last30 ║ Total║ ╠════════╬═════════════╬════════╬══════╣ ║ 1 ║ 1 ║ 10 ║ 100 ║ ║ 1 ║ 2 ║ 40 ║ 140 ║ ║ 2 ║ 1 ║ 20 ║ 180 ║ ╚════════╩═════════════╩════════╩══════╝ In SQL, I can easily get the counts for SiteID 1 with the following: SELECT SiteId, SUM(Last30) AS Last30Sum FROM Sites WHERE SiteId = 1 GROUP BY SiteId and should get a row like... ╔════════╦════════════╗ ║ SiteId ║ Last30Total║ ╠════════╬════════════╣ ║ 1 ║ 50 ║ ╚════════╩════════════╝ However I'm not sure how to get this result using Linq. I've tried: var statsRecord = from ss in db.SiteStats where ss.SiteId == siteId group ss by ss.SiteId into ss select ss; but I'm not able to get back the total with something like statsRecord.Last30 Can someone please let me know where I'm going wrong? Any help is appreciated. | Actually, although Thomas' code will work, it is more succint to use a lambda expression: var totals = from s in sites group s by s.SiteID into grouped select new { SiteID = grouped.Key, Last30Sum = grouped.Sum( s => s.Last30 ) }; which uses the Sum extension method without the need for a nested LINQ operation. as per the LINQ 101 examples - http://msdn.microsoft.com/en-us/vcsharp/aa336747.aspx#sumGrouped | C# Linq Grouping I'm experimenting with Linq and am having trouble figuring out grouping. I've gone through several tutorials but for some reason can't figure this out. As an example, say I have a table (SiteStats) with multiple website IDs that stores a count of how many visitors by type have accessed each site in total and for the past 30 days. ╔════════╦═════════════╦════════╦══════╗ ║ SiteId ║ VisitorType ║ Last30 ║ Total║ ╠════════╬═════════════╬════════╬══════╣ ║ 1 ║ 1 ║ 10 ║ 100 ║ ║ 1 ║ 2 ║ 40 ║ 140 ║ ║ 2 ║ 1 ║ 20 ║ 180 ║ ╚════════╩═════════════╩════════╩══════╝ In SQL, I can easily get the counts for SiteID 1 with the following: SELECT SiteId, SUM(Last30) AS Last30Sum FROM Sites WHERE SiteId = 1 GROUP BY SiteId and should get a row like... ╔════════╦════════════╗ ║ SiteId ║ Last30Total║ ╠════════╬════════════╣ ║ 1 ║ 50 ║ ╚════════╩════════════╝ However I'm not sure how to get this result using Linq. I've tried: var statsRecord = from ss in db.SiteStats where ss.SiteId == siteId group ss by ss.SiteId into ss select ss; but I'm not able to get back the total with something like statsRecord.Last30 Can someone please let me know where I'm going wrong? Any help is appreciated. | TITLE:
C# Linq Grouping
QUESTION:
I'm experimenting with Linq and am having trouble figuring out grouping. I've gone through several tutorials but for some reason can't figure this out. As an example, say I have a table (SiteStats) with multiple website IDs that stores a count of how many visitors by type have accessed each site in total and for the past 30 days. ╔════════╦═════════════╦════════╦══════╗ ║ SiteId ║ VisitorType ║ Last30 ║ Total║ ╠════════╬═════════════╬════════╬══════╣ ║ 1 ║ 1 ║ 10 ║ 100 ║ ║ 1 ║ 2 ║ 40 ║ 140 ║ ║ 2 ║ 1 ║ 20 ║ 180 ║ ╚════════╩═════════════╩════════╩══════╝ In SQL, I can easily get the counts for SiteID 1 with the following: SELECT SiteId, SUM(Last30) AS Last30Sum FROM Sites WHERE SiteId = 1 GROUP BY SiteId and should get a row like... ╔════════╦════════════╗ ║ SiteId ║ Last30Total║ ╠════════╬════════════╣ ║ 1 ║ 50 ║ ╚════════╩════════════╝ However I'm not sure how to get this result using Linq. I've tried: var statsRecord = from ss in db.SiteStats where ss.SiteId == siteId group ss by ss.SiteId into ss select ss; but I'm not able to get back the total with something like statsRecord.Last30 Can someone please let me know where I'm going wrong? Any help is appreciated.
ANSWER:
Actually, although Thomas' code will work, it is more succint to use a lambda expression: var totals = from s in sites group s by s.SiteID into grouped select new { SiteID = grouped.Key, Last30Sum = grouped.Sum( s => s.Last30 ) }; which uses the Sum extension method without the need for a nested LINQ operation. as per the LINQ 101 examples - http://msdn.microsoft.com/en-us/vcsharp/aa336747.aspx#sumGrouped | [
"c#",
"linq"
] | 19 | 35 | 18,811 | 2 | 0 | 2008-08-29T18:11:45.400000 | 2008-08-31T07:40:23.437000 |
34,914 | 35,467 | How do you use XML::Parser with Style => 'Objects' | The manual page for XML::Parser::Style::Objects is horrible. A simple hello world style program would really be helpful. I really wanted to do something like this: (not real code of course) use XML::Parser; my $p = XML::Parser->new(Style => 'Objects', Pkg => 'MyNode'); my $tree = $p->parsefile('foo.xml'); $tree->doSomething();
MyNode::doSomething() { my $self = shift; print "This is a normal node"; for $kid ($self->Kids) { $kid->doSomething(); } }
MyNode::special::doSomething() { my $self = shift; print "This is a special node"; } | In all cases here is actual code that runs... doesn't mean much but produces output and hopefully can get you started... use XML::Parser;
package MyNode::inner; sub doSomething { my $self = shift; print "This is an inner node containing: "; print $self->{Kids}->[0]->{Text}; print "\n"; } package MyNode::Characters; sub doSomething {} package MyNode::foo; sub doSomething { my $self = shift; print "This is an external node\n"; for $kid (@ { $self->{Kids} }) { $kid->doSomething(); } }
package main;
my $p = XML::Parser->new(Style => 'Objects', Pkg => 'MyNode'); my $tree = $p->parsefile('foo.xml'); for (@$tree) { $_->doSomething(); } with foo.xml some text something else which outputs >perl -w "tree.pl" This is an external node This is an inner node containing: some text This is an inner node containing: something else Hope that helps. | How do you use XML::Parser with Style => 'Objects' The manual page for XML::Parser::Style::Objects is horrible. A simple hello world style program would really be helpful. I really wanted to do something like this: (not real code of course) use XML::Parser; my $p = XML::Parser->new(Style => 'Objects', Pkg => 'MyNode'); my $tree = $p->parsefile('foo.xml'); $tree->doSomething();
MyNode::doSomething() { my $self = shift; print "This is a normal node"; for $kid ($self->Kids) { $kid->doSomething(); } }
MyNode::special::doSomething() { my $self = shift; print "This is a special node"; } | TITLE:
How do you use XML::Parser with Style => 'Objects'
QUESTION:
The manual page for XML::Parser::Style::Objects is horrible. A simple hello world style program would really be helpful. I really wanted to do something like this: (not real code of course) use XML::Parser; my $p = XML::Parser->new(Style => 'Objects', Pkg => 'MyNode'); my $tree = $p->parsefile('foo.xml'); $tree->doSomething();
MyNode::doSomething() { my $self = shift; print "This is a normal node"; for $kid ($self->Kids) { $kid->doSomething(); } }
MyNode::special::doSomething() { my $self = shift; print "This is a special node"; }
ANSWER:
In all cases here is actual code that runs... doesn't mean much but produces output and hopefully can get you started... use XML::Parser;
package MyNode::inner; sub doSomething { my $self = shift; print "This is an inner node containing: "; print $self->{Kids}->[0]->{Text}; print "\n"; } package MyNode::Characters; sub doSomething {} package MyNode::foo; sub doSomething { my $self = shift; print "This is an external node\n"; for $kid (@ { $self->{Kids} }) { $kid->doSomething(); } }
package main;
my $p = XML::Parser->new(Style => 'Objects', Pkg => 'MyNode'); my $tree = $p->parsefile('foo.xml'); for (@$tree) { $_->doSomething(); } with foo.xml some text something else which outputs >perl -w "tree.pl" This is an external node This is an inner node containing: some text This is an inner node containing: something else Hope that helps. | [
"xml",
"perl"
] | 3 | 1 | 3,621 | 2 | 0 | 2008-08-29T18:12:01.453000 | 2008-08-29T23:29:17.917000 |
34,916 | 1,056,092 | Scaffolding in pylons | Is there anything similar to rails' scaffolding for pylons? I've been poking around google, but only found this thing called dbsprockets, which is fine, although probably way too much for my needs. What I really need is a basic CRUD that is based on the SQLAlchemy model. | The question is super old, but hell: http://code.google.com/p/formalchemy/ Gives you basic crud out of the box, customizable to do even relatively complex things easily, and gives you a drop-in Pylons admin app too (written and customizable with the same api, no magic). | Scaffolding in pylons Is there anything similar to rails' scaffolding for pylons? I've been poking around google, but only found this thing called dbsprockets, which is fine, although probably way too much for my needs. What I really need is a basic CRUD that is based on the SQLAlchemy model. | TITLE:
Scaffolding in pylons
QUESTION:
Is there anything similar to rails' scaffolding for pylons? I've been poking around google, but only found this thing called dbsprockets, which is fine, although probably way too much for my needs. What I really need is a basic CRUD that is based on the SQLAlchemy model.
ANSWER:
The question is super old, but hell: http://code.google.com/p/formalchemy/ Gives you basic crud out of the box, customizable to do even relatively complex things easily, and gives you a drop-in Pylons admin app too (written and customizable with the same api, no magic). | [
"python",
"pylons"
] | 10 | 7 | 1,802 | 3 | 0 | 2008-08-29T18:12:30.517000 | 2009-06-29T00:02:20.330000 |
34,920 | 34,933 | How do I lock a file in Perl? | What is the best way to create a lock on a file in Perl? Is it best to flock on the file or to create a lock file to place a lock on and check for a lock on the lock file? | If you end up using flock, here's some code to do it: use Fcntl ':flock'; # Import LOCK_* constants
# We will use this file path in error messages and function calls. # Don't type it out more than once in your code. Use a variable. my $file = '/path/to/some/file';
# Open the file for appending. Note the file path is quoted # in the error message. This helps debug situations where you # have a stray space at the start or end of the path. open(my $fh, '>>', $file) or die "Could not open '$file' - $!";
# Get exclusive lock (will block until it does) flock($fh, LOCK_EX) or die "Could not lock '$file' - $!";
# Do something with the file here...
# Do NOT use flock() to unlock the file if you wrote to the # file in the "do something" section above. This could create # a race condition. The close() call below will unlock the # file for you, but only after writing any buffered data.
# In a world of buffered i/o, some or all of your data may not # be written until close() completes. Always, always, ALWAYS # check the return value of close() if you wrote to the file! close($fh) or die "Could not write '$file' - $!"; Some useful links: PerlMonks file locking tutorial (somewhat old) flock() documentation In response to your added question, I'd say either place the lock on the file or create a file that you call 'lock' whenever the file is locked and delete it when it is no longer locked (and then make sure your programs obey those semantics). | How do I lock a file in Perl? What is the best way to create a lock on a file in Perl? Is it best to flock on the file or to create a lock file to place a lock on and check for a lock on the lock file? | TITLE:
How do I lock a file in Perl?
QUESTION:
What is the best way to create a lock on a file in Perl? Is it best to flock on the file or to create a lock file to place a lock on and check for a lock on the lock file?
ANSWER:
If you end up using flock, here's some code to do it: use Fcntl ':flock'; # Import LOCK_* constants
# We will use this file path in error messages and function calls. # Don't type it out more than once in your code. Use a variable. my $file = '/path/to/some/file';
# Open the file for appending. Note the file path is quoted # in the error message. This helps debug situations where you # have a stray space at the start or end of the path. open(my $fh, '>>', $file) or die "Could not open '$file' - $!";
# Get exclusive lock (will block until it does) flock($fh, LOCK_EX) or die "Could not lock '$file' - $!";
# Do something with the file here...
# Do NOT use flock() to unlock the file if you wrote to the # file in the "do something" section above. This could create # a race condition. The close() call below will unlock the # file for you, but only after writing any buffered data.
# In a world of buffered i/o, some or all of your data may not # be written until close() completes. Always, always, ALWAYS # check the return value of close() if you wrote to the file! close($fh) or die "Could not write '$file' - $!"; Some useful links: PerlMonks file locking tutorial (somewhat old) flock() documentation In response to your added question, I'd say either place the lock on the file or create a file that you call 'lock' whenever the file is locked and delete it when it is no longer locked (and then make sure your programs obey those semantics). | [
"perl",
"file",
"locking"
] | 29 | 32 | 31,301 | 14 | 0 | 2008-08-29T18:13:21.420000 | 2008-08-29T18:18:40.487000 |
34,924 | 34,971 | 3.1 or 5.1 audio in Flash | Is it possible to do 3.1 or 5.1 audio using Flash? We're starting a project here for an interactive kiosk, and we've been told to use Flash. However, we also have a requirement to support either 3.1 or 5.1 audio (where 5.1 is the most wanted feature). I haven't done any high-tech audio stuff using Flash, so I was wondering if anyone knew if it was possible to do? Thanks. | A quick google search gave me this forum http://board.flashkit.com/board/showthread.php?t=715062 where they state that Flash is unable to handle 5.1 audio and the alternative is to use another application that can communicate with Flash to handle the audio side of things. I also found this blog entry from Summit Projects http://summitprojectsflashblog.wordpress.com/2008/08/07/wave-theory-in-actionscript-3-part-4/ where they go into great detail about byte handling and processing audio samples. I'm not sure if they are using their own actionscript libraries for this, or if they are using Adobe's libraries. I'm not too up to speed on the audio side of Flash with respects to surround sound. I think your two options might have to be either using a separate application to run your audio(which may be less stressful) or maybe getting in touch with the Summit people if you are as lost as I am over some of the concepts they touch on, heh. Good luck! | 3.1 or 5.1 audio in Flash Is it possible to do 3.1 or 5.1 audio using Flash? We're starting a project here for an interactive kiosk, and we've been told to use Flash. However, we also have a requirement to support either 3.1 or 5.1 audio (where 5.1 is the most wanted feature). I haven't done any high-tech audio stuff using Flash, so I was wondering if anyone knew if it was possible to do? Thanks. | TITLE:
3.1 or 5.1 audio in Flash
QUESTION:
Is it possible to do 3.1 or 5.1 audio using Flash? We're starting a project here for an interactive kiosk, and we've been told to use Flash. However, we also have a requirement to support either 3.1 or 5.1 audio (where 5.1 is the most wanted feature). I haven't done any high-tech audio stuff using Flash, so I was wondering if anyone knew if it was possible to do? Thanks.
ANSWER:
A quick google search gave me this forum http://board.flashkit.com/board/showthread.php?t=715062 where they state that Flash is unable to handle 5.1 audio and the alternative is to use another application that can communicate with Flash to handle the audio side of things. I also found this blog entry from Summit Projects http://summitprojectsflashblog.wordpress.com/2008/08/07/wave-theory-in-actionscript-3-part-4/ where they go into great detail about byte handling and processing audio samples. I'm not sure if they are using their own actionscript libraries for this, or if they are using Adobe's libraries. I'm not too up to speed on the audio side of Flash with respects to surround sound. I think your two options might have to be either using a separate application to run your audio(which may be less stressful) or maybe getting in touch with the Summit people if you are as lost as I am over some of the concepts they touch on, heh. Good luck! | [
"flash",
"audio"
] | 2 | 2 | 2,172 | 3 | 0 | 2008-08-29T18:14:44.740000 | 2008-08-29T18:36:45.530000 |
34,925 | 35,223 | XmlSerializer changes in .NET 3.5 SP1 | I've seen quite a few posts on changes in.NET 3.5 SP1, but stumbled into one that I've yet to see documentation for yesterday. I had code working just fine on my machine, from VS, msbuild command line, everything, but it failed on the build server (running.NET 3.5 RTM). [XmlRoot("foo")] public class Foo { static void Main() { XmlSerializer serializer = new XmlSerializer(typeof(Foo));
string xml = @" "; using (StringReader sr = new StringReader(xml)) { Foo foo = serializer.Deserialize(sr) as Foo; } }
[XmlAttribute("name")] public string Name { get; set; }
public Foo Bar { get; private set; } } In SP1, the above code runs just fine. In RTM, you get an InvalidOperationException: Unable to generate a temporary class (result=1). error CS0200: Property or indexer 'ConsoleApplication2.Foo.Bar' cannot be assign to -- it is read only Of course, all that's needed to make it run under RTM is adding [XmlIgnore] to the Bar property. My google fu is apparently not up to finding documentation of these kinds of changes. Is there a change list anywhere that lists this change (and similar under-the-hood changes that might jump up and shout "gotcha")? Is this a bug or a feature? EDIT: In SP1, if I added a element, or set [XmlElement] for the Bar property, it won't get deserialized. It doesn't fail pre-SP1 when it tries to deserialize--it throws an exception when the XmlSerializer is constructed. This makes me lean more toward it being a bug, especially if I set an [XmlElement] attribute for Foo.Bar. If it's unable to do what I ask it to do, it should be throwing an exception instead of silently ignoring Foo.Bar. Other invalid combinations/settings of XML serialization attributes result in an exception. EDIT: Thank you, TonyB, I'd not known about setting the temp files location. For those that come across similar issues in the future, you do need an additional config flag: Even with setting an [XmlElement] attribute on the Bar property, no mention was made of it in the generated serialization assembly--which fairly firmly puts this in the realm of a silently swallowed error (aka, a bug). Either that or the designers have decided [XmlIgnore] is no longer necessary for properties that can't be set--and you'd expect to see that in release notes, change lists, or the XmlIgnoreAttribute documentation. | In SP1 does the foo.Bar property get properly deserialized? In pre SP1 you wouldn't be able to deserialize the object because the set method of the Bar property is private so the XmlSerializer doesn't have a way to set that value. I'm not sure how SP1 is pulling it off. You could try adding this to your web.config/app.config That will put the class generated by the XmlSerializer into c:\foo so you can see what it is doing in SP1 vs RTM | XmlSerializer changes in .NET 3.5 SP1 I've seen quite a few posts on changes in.NET 3.5 SP1, but stumbled into one that I've yet to see documentation for yesterday. I had code working just fine on my machine, from VS, msbuild command line, everything, but it failed on the build server (running.NET 3.5 RTM). [XmlRoot("foo")] public class Foo { static void Main() { XmlSerializer serializer = new XmlSerializer(typeof(Foo));
string xml = @" "; using (StringReader sr = new StringReader(xml)) { Foo foo = serializer.Deserialize(sr) as Foo; } }
[XmlAttribute("name")] public string Name { get; set; }
public Foo Bar { get; private set; } } In SP1, the above code runs just fine. In RTM, you get an InvalidOperationException: Unable to generate a temporary class (result=1). error CS0200: Property or indexer 'ConsoleApplication2.Foo.Bar' cannot be assign to -- it is read only Of course, all that's needed to make it run under RTM is adding [XmlIgnore] to the Bar property. My google fu is apparently not up to finding documentation of these kinds of changes. Is there a change list anywhere that lists this change (and similar under-the-hood changes that might jump up and shout "gotcha")? Is this a bug or a feature? EDIT: In SP1, if I added a element, or set [XmlElement] for the Bar property, it won't get deserialized. It doesn't fail pre-SP1 when it tries to deserialize--it throws an exception when the XmlSerializer is constructed. This makes me lean more toward it being a bug, especially if I set an [XmlElement] attribute for Foo.Bar. If it's unable to do what I ask it to do, it should be throwing an exception instead of silently ignoring Foo.Bar. Other invalid combinations/settings of XML serialization attributes result in an exception. EDIT: Thank you, TonyB, I'd not known about setting the temp files location. For those that come across similar issues in the future, you do need an additional config flag: Even with setting an [XmlElement] attribute on the Bar property, no mention was made of it in the generated serialization assembly--which fairly firmly puts this in the realm of a silently swallowed error (aka, a bug). Either that or the designers have decided [XmlIgnore] is no longer necessary for properties that can't be set--and you'd expect to see that in release notes, change lists, or the XmlIgnoreAttribute documentation. | TITLE:
XmlSerializer changes in .NET 3.5 SP1
QUESTION:
I've seen quite a few posts on changes in.NET 3.5 SP1, but stumbled into one that I've yet to see documentation for yesterday. I had code working just fine on my machine, from VS, msbuild command line, everything, but it failed on the build server (running.NET 3.5 RTM). [XmlRoot("foo")] public class Foo { static void Main() { XmlSerializer serializer = new XmlSerializer(typeof(Foo));
string xml = @" "; using (StringReader sr = new StringReader(xml)) { Foo foo = serializer.Deserialize(sr) as Foo; } }
[XmlAttribute("name")] public string Name { get; set; }
public Foo Bar { get; private set; } } In SP1, the above code runs just fine. In RTM, you get an InvalidOperationException: Unable to generate a temporary class (result=1). error CS0200: Property or indexer 'ConsoleApplication2.Foo.Bar' cannot be assign to -- it is read only Of course, all that's needed to make it run under RTM is adding [XmlIgnore] to the Bar property. My google fu is apparently not up to finding documentation of these kinds of changes. Is there a change list anywhere that lists this change (and similar under-the-hood changes that might jump up and shout "gotcha")? Is this a bug or a feature? EDIT: In SP1, if I added a element, or set [XmlElement] for the Bar property, it won't get deserialized. It doesn't fail pre-SP1 when it tries to deserialize--it throws an exception when the XmlSerializer is constructed. This makes me lean more toward it being a bug, especially if I set an [XmlElement] attribute for Foo.Bar. If it's unable to do what I ask it to do, it should be throwing an exception instead of silently ignoring Foo.Bar. Other invalid combinations/settings of XML serialization attributes result in an exception. EDIT: Thank you, TonyB, I'd not known about setting the temp files location. For those that come across similar issues in the future, you do need an additional config flag: Even with setting an [XmlElement] attribute on the Bar property, no mention was made of it in the generated serialization assembly--which fairly firmly puts this in the realm of a silently swallowed error (aka, a bug). Either that or the designers have decided [XmlIgnore] is no longer necessary for properties that can't be set--and you'd expect to see that in release notes, change lists, or the XmlIgnoreAttribute documentation.
ANSWER:
In SP1 does the foo.Bar property get properly deserialized? In pre SP1 you wouldn't be able to deserialize the object because the set method of the Bar property is private so the XmlSerializer doesn't have a way to set that value. I'm not sure how SP1 is pulling it off. You could try adding this to your web.config/app.config That will put the class generated by the XmlSerializer into c:\foo so you can see what it is doing in SP1 vs RTM | [
"xml",
"serialization",
".net-3.5"
] | 5 | 4 | 4,832 | 2 | 0 | 2008-08-29T18:15:04.567000 | 2008-08-29T20:20:59.180000 |
34,926 | 35,012 | Strip HTML from string in SSRS 2005 (VB.NET) | my SSRS DataSet returns a field with HTML, e.g. blah blah blah. how do i strip all the HTML tags? has to be done with inline VB.NET Changing the data in the table is not an option. Solution found... = System.Text.RegularExpressions.Regex.Replace(StringWithHTMLtoStrip, "<[^>]+>","") | Thanx to Daniel, but I needed it to be done inline... here's the solution: = System.Text.RegularExpressions.Regex.Replace(StringWithHTMLtoStrip, "<[^>]+>","") Here are the links: http://weblogs.asp.net/rosherove/archive/2003/05/13/6963.aspx http://msdn.microsoft.com/en-us/library/ms157328.aspx | Strip HTML from string in SSRS 2005 (VB.NET) my SSRS DataSet returns a field with HTML, e.g. blah blah blah. how do i strip all the HTML tags? has to be done with inline VB.NET Changing the data in the table is not an option. Solution found... = System.Text.RegularExpressions.Regex.Replace(StringWithHTMLtoStrip, "<[^>]+>","") | TITLE:
Strip HTML from string in SSRS 2005 (VB.NET)
QUESTION:
my SSRS DataSet returns a field with HTML, e.g. blah blah blah. how do i strip all the HTML tags? has to be done with inline VB.NET Changing the data in the table is not an option. Solution found... = System.Text.RegularExpressions.Regex.Replace(StringWithHTMLtoStrip, "<[^>]+>","")
ANSWER:
Thanx to Daniel, but I needed it to be done inline... here's the solution: = System.Text.RegularExpressions.Regex.Replace(StringWithHTMLtoStrip, "<[^>]+>","") Here are the links: http://weblogs.asp.net/rosherove/archive/2003/05/13/6963.aspx http://msdn.microsoft.com/en-us/library/ms157328.aspx | [
"vb.net",
"reporting-services"
] | 11 | 14 | 11,335 | 5 | 0 | 2008-08-29T18:16:14.250000 | 2008-08-29T18:50:57.727000 |
34,938 | 34,954 | if statement condition optimisation | I have an if statement with two conditions (separated by an OR operator), one of the conditions covers +70% of situations and takes far less time to process/execute than the second condition, so in the interests of speed I only want the second condition to be processed if the first condition evaluates to false. if I order the conditions so that the first condition (the quicker one) appears in the if statement first - on the occasions where this condition is met and evaluates true is the second condition even processed? if ( (condition1) | (condition2) ){ // do this } or would I need to nest two if statements to only check the second condition if the first evaluates to false? if (condition1){ // do this }else if (condition2){ // do this } I am working in PHP, however, I assume that this may be language-agnostic. | For C, C++, C#, Java and other.NET languages boolean expressions are optimised so that as soon as enough is known nothing else is evaluated. An old trick for doing obfuscated code was to use this to create if statements, such as: a || b(); if "a" is true, "b()" would never be evaluated, so we can rewrite it into: if(!a) b(); and similarly: a && b(); would become if(a) b(); Please note that this is only valid for the || and && operator. The two operators | and & is bitwise or, and and, respectively, and are therefore not "optimised". EDIT: As mentioned by others, trying to optimise code using short circuit logic is very rarely well spent time. First go for clarity, both because it is easier to read and understand. Also, if you try to be too clever a simple reordering of the terms could lead to wildly different behaviour without any apparent reason. Second, go for optimisation, but only after timing and profiling. Way too many developer do premature optimisation without profiling. Most of the time it's completely useless. | if statement condition optimisation I have an if statement with two conditions (separated by an OR operator), one of the conditions covers +70% of situations and takes far less time to process/execute than the second condition, so in the interests of speed I only want the second condition to be processed if the first condition evaluates to false. if I order the conditions so that the first condition (the quicker one) appears in the if statement first - on the occasions where this condition is met and evaluates true is the second condition even processed? if ( (condition1) | (condition2) ){ // do this } or would I need to nest two if statements to only check the second condition if the first evaluates to false? if (condition1){ // do this }else if (condition2){ // do this } I am working in PHP, however, I assume that this may be language-agnostic. | TITLE:
if statement condition optimisation
QUESTION:
I have an if statement with two conditions (separated by an OR operator), one of the conditions covers +70% of situations and takes far less time to process/execute than the second condition, so in the interests of speed I only want the second condition to be processed if the first condition evaluates to false. if I order the conditions so that the first condition (the quicker one) appears in the if statement first - on the occasions where this condition is met and evaluates true is the second condition even processed? if ( (condition1) | (condition2) ){ // do this } or would I need to nest two if statements to only check the second condition if the first evaluates to false? if (condition1){ // do this }else if (condition2){ // do this } I am working in PHP, however, I assume that this may be language-agnostic.
ANSWER:
For C, C++, C#, Java and other.NET languages boolean expressions are optimised so that as soon as enough is known nothing else is evaluated. An old trick for doing obfuscated code was to use this to create if statements, such as: a || b(); if "a" is true, "b()" would never be evaluated, so we can rewrite it into: if(!a) b(); and similarly: a && b(); would become if(a) b(); Please note that this is only valid for the || and && operator. The two operators | and & is bitwise or, and and, respectively, and are therefore not "optimised". EDIT: As mentioned by others, trying to optimise code using short circuit logic is very rarely well spent time. First go for clarity, both because it is easier to read and understand. Also, if you try to be too clever a simple reordering of the terms could lead to wildly different behaviour without any apparent reason. Second, go for optimisation, but only after timing and profiling. Way too many developer do premature optimisation without profiling. Most of the time it's completely useless. | [
"php",
"language-agnostic",
"conditional-statements"
] | 5 | 9 | 9,550 | 11 | 0 | 2008-08-29T18:21:17.593000 | 2008-08-29T18:27:35.003000 |
34,955 | 41,043 | Best practices for debugging linking errors | When building projects in C++, I've found debugging linking errors to be tricky, especially when picking up other people's code. What strategies do people use for debugging and fixing linking errors? | Not sure what your level of expertise is, but here are the basics. Below is a linker error from VS 2005 - yes, it's a giant mess if you're not familiar with it. ByteComparator.obj: error LNK2019: unresolved external symbol "int __cdecl does_not_exist(void)" (?does_not_exist@@YAHXZ) referenced in function "void __cdecl TextScan(struct FileTextStats &,char const *,char const *,bool,bool,__int64)" (?TextScan@@YAXAAUFileTextStats@@PBD1_N2_J@Z) There are a couple of points to focus on: "ByteComparator.obj" - Look for a ByteComparator.cpp file, this is the source of the linker problem "int __cdecl does_not_exist(void)" - This is the symbol it couldn't find, in this case a function named does_not_exist() At this point, in many cases the fastest way to resolution is to search the code base for this function and find where the implementation is. Once you know where the function is implemented you just have to make sure the two places get linked together. If you're using VS2005, you would use the "Project Dependencies..." right-click menu. If you're using gcc, you would look in your makefiles for the executable generation step (gcc called with a bunch of.o files) and add the missing.o file. In a second scenario, you may be missing an "external" dependency, which you don't have code for. The Win32 libraries are often times implemented in static libraries that you have to link to. In this case, go to MSDN or "Microsoft Google" and search for the API. At the bottom of the API description the library name is given. Add this to your project properties "Configuration Properties->Linker->Input->Additional Dependencies" list. For example, the function timeGetTime()'s page on MSDN tells you to use Winmm.lib at the bottom of the page. | Best practices for debugging linking errors When building projects in C++, I've found debugging linking errors to be tricky, especially when picking up other people's code. What strategies do people use for debugging and fixing linking errors? | TITLE:
Best practices for debugging linking errors
QUESTION:
When building projects in C++, I've found debugging linking errors to be tricky, especially when picking up other people's code. What strategies do people use for debugging and fixing linking errors?
ANSWER:
Not sure what your level of expertise is, but here are the basics. Below is a linker error from VS 2005 - yes, it's a giant mess if you're not familiar with it. ByteComparator.obj: error LNK2019: unresolved external symbol "int __cdecl does_not_exist(void)" (?does_not_exist@@YAHXZ) referenced in function "void __cdecl TextScan(struct FileTextStats &,char const *,char const *,bool,bool,__int64)" (?TextScan@@YAXAAUFileTextStats@@PBD1_N2_J@Z) There are a couple of points to focus on: "ByteComparator.obj" - Look for a ByteComparator.cpp file, this is the source of the linker problem "int __cdecl does_not_exist(void)" - This is the symbol it couldn't find, in this case a function named does_not_exist() At this point, in many cases the fastest way to resolution is to search the code base for this function and find where the implementation is. Once you know where the function is implemented you just have to make sure the two places get linked together. If you're using VS2005, you would use the "Project Dependencies..." right-click menu. If you're using gcc, you would look in your makefiles for the executable generation step (gcc called with a bunch of.o files) and add the missing.o file. In a second scenario, you may be missing an "external" dependency, which you don't have code for. The Win32 libraries are often times implemented in static libraries that you have to link to. In this case, go to MSDN or "Microsoft Google" and search for the API. At the bottom of the API description the library name is given. Add this to your project properties "Configuration Properties->Linker->Input->Additional Dependencies" list. For example, the function timeGetTime()'s page on MSDN tells you to use Winmm.lib at the bottom of the page. | [
"c++",
"visual-studio",
"gcc",
"linker",
"compilation"
] | 51 | 25 | 29,209 | 3 | 0 | 2008-08-29T18:27:44.147000 | 2008-09-03T02:06:30.437000 |
34,973 | 35,176 | Tools for finding memory corruption in managed C++ code | I have a.NET application, which is using an open source C++ compression library for compressing images. We are accessing the C++ library via managed C++. I'm seeing heap corruption during compression. A call to _CrtIsValidHeapPointer is finding an error on a call to free() when cleaning up after compression. Are there tools such as Purify to help diagnosis this problem and what is causing the heap corruption when working in a combination of managed and unmanaged code? I do have the exception caught in the debugger, but it would be nice to have other tools to help find the solution to the problem. | In native code, if the corruption always occurs in the same place in memory, you can use a data breakpoint to break the debugger when that memory is changed. Unfortunately, you cannot set a data breakpoint in the managed C++ environment, presumably because the GC could move the object in memory. Not sure if this helps, but hopefully it leads you off in the right direction. | Tools for finding memory corruption in managed C++ code I have a.NET application, which is using an open source C++ compression library for compressing images. We are accessing the C++ library via managed C++. I'm seeing heap corruption during compression. A call to _CrtIsValidHeapPointer is finding an error on a call to free() when cleaning up after compression. Are there tools such as Purify to help diagnosis this problem and what is causing the heap corruption when working in a combination of managed and unmanaged code? I do have the exception caught in the debugger, but it would be nice to have other tools to help find the solution to the problem. | TITLE:
Tools for finding memory corruption in managed C++ code
QUESTION:
I have a.NET application, which is using an open source C++ compression library for compressing images. We are accessing the C++ library via managed C++. I'm seeing heap corruption during compression. A call to _CrtIsValidHeapPointer is finding an error on a call to free() when cleaning up after compression. Are there tools such as Purify to help diagnosis this problem and what is causing the heap corruption when working in a combination of managed and unmanaged code? I do have the exception caught in the debugger, but it would be nice to have other tools to help find the solution to the problem.
ANSWER:
In native code, if the corruption always occurs in the same place in memory, you can use a data breakpoint to break the debugger when that memory is changed. Unfortunately, you cannot set a data breakpoint in the managed C++ environment, presumably because the GC could move the object in memory. Not sure if this helps, but hopefully it leads you off in the right direction. | [
".net",
"managed-c++"
] | 2 | 1 | 1,632 | 3 | 0 | 2008-08-29T18:37:02.080000 | 2008-08-29T19:58:37.720000 |
34,977 | 41,051 | Byte level length description | I have a protocol that requires a length field up to 32-bits, and it must be generated at runtime to describe how many bytes are in a given packet. The code below is kind of ugly but I am wondering if this can be refactored to be slightly more efficient or easily understandable. The problem is that the code will only generate enough bytes to describe the length of the packet, so less than 255 bytes = 1 byte of length, less than 65535 = 2 bytes of length etc... { extern char byte_stream[]; int bytes = offset_in_packet; int n = length_of_packet; /* Under 4 billion, so this can be represented in 32 bits. */ int t; /* 32-bit number used for temporary storage. */
/* These are the bytes we will break up n into. */ unsigned char first, second, third, fourth;
t = n & 0xFF000000; /* We have used AND to "mask out" the first byte of the number. */ /* The only bits which can be on in t are the first 8 bits. */ first = t >> 24; if (t) { printf("byte 1: 0x%02x\n",first ); byte_stream[bytes] = first; bytes++; write_zeros = 1; } /* Now we shift t so that it is between 0 and 255. This is the first, highest byte of n. */ t = n & 0x00FF0000; second = t >> 16; if (t || write_zeros) { printf("byte 2: 0x%02x\n", second ); byte_stream[bytes] = second; bytes++; write_zeros = 1; }
t = n & 0x0000FF00; third = t >> 8; if ( t || write_zeros) { printf("byte 3: 0x%02x\n", third ); byte_stream[bytes] = third; bytes++; write_zeros = 1; }
t = n & 0x000000FF; fourth = t; if (t || write_zeros) { printf("byte 4: 0x%02x\n", fourth); byte_stream[bytes] = fourth; bytes++; } } | Really you're only doing four calculations, so readability seems way more important here than efficiency. My approach to make something like this more readable is to Extract common code to a function Put similar calculations together to make the patterns more obvious Get rid of the intermediate variable print_zeroes and be explicit about the cases in which you output bytes even if they're zero (i.e. the preceding byte was non-zero) I've changed the random code block into a function and changed a few variables (underscores are giving me trouble in the markdown preview screen). I've also assumed that bytes is being passed in, and that whoever is passing it in will pass us a pointer so we can modify it. Here's the code: /* append byte b to stream, increment index */ /* really needs to check length of stream before appending */ void output( int i, unsigned char b, char stream[], int *index ) { printf("byte %d: 0x%02x\n", i, b); stream[(*index)++] = b; }
void answer( char bytestream[], unsigned int *bytes, unsigned int n) { /* mask out four bytes from word n */ first = (n & 0xFF000000) >> 24; second = (n & 0x00FF0000) >> 16; third = (n & 0x0000FF00) >> 8; fourth = (n & 0x000000FF) >> 0;
/* conditionally output each byte starting with the */ /* first non-zero byte */ if (first) output( 1, first, bytestream, bytes);
if (first || second) output( 2, second, bytestream, bytes);
if (first || second || third) output( 3, third, bytestream, bytes);
if (first || second || third || fourth) output( 4, fourth, bytestream, bytes); } Ever so slightly more efficient, and maybe easier to understand would be this modification to the last four if statements: if (n>0x00FFFFFF) output( 1, first, bytestream, bytes);
if (n>0x0000FFFF) output( 2, second, bytestream, bytes);
if (n>0x000000FF) output( 3, third, bytestream, bytes);
if (1) output( 4, fourth, bytestream, bytes); I agree, however, that compressing this field makes the receiving state machine overly complicated. But if you can't change the protocol, this code is much easier to read. | Byte level length description I have a protocol that requires a length field up to 32-bits, and it must be generated at runtime to describe how many bytes are in a given packet. The code below is kind of ugly but I am wondering if this can be refactored to be slightly more efficient or easily understandable. The problem is that the code will only generate enough bytes to describe the length of the packet, so less than 255 bytes = 1 byte of length, less than 65535 = 2 bytes of length etc... { extern char byte_stream[]; int bytes = offset_in_packet; int n = length_of_packet; /* Under 4 billion, so this can be represented in 32 bits. */ int t; /* 32-bit number used for temporary storage. */
/* These are the bytes we will break up n into. */ unsigned char first, second, third, fourth;
t = n & 0xFF000000; /* We have used AND to "mask out" the first byte of the number. */ /* The only bits which can be on in t are the first 8 bits. */ first = t >> 24; if (t) { printf("byte 1: 0x%02x\n",first ); byte_stream[bytes] = first; bytes++; write_zeros = 1; } /* Now we shift t so that it is between 0 and 255. This is the first, highest byte of n. */ t = n & 0x00FF0000; second = t >> 16; if (t || write_zeros) { printf("byte 2: 0x%02x\n", second ); byte_stream[bytes] = second; bytes++; write_zeros = 1; }
t = n & 0x0000FF00; third = t >> 8; if ( t || write_zeros) { printf("byte 3: 0x%02x\n", third ); byte_stream[bytes] = third; bytes++; write_zeros = 1; }
t = n & 0x000000FF; fourth = t; if (t || write_zeros) { printf("byte 4: 0x%02x\n", fourth); byte_stream[bytes] = fourth; bytes++; } } | TITLE:
Byte level length description
QUESTION:
I have a protocol that requires a length field up to 32-bits, and it must be generated at runtime to describe how many bytes are in a given packet. The code below is kind of ugly but I am wondering if this can be refactored to be slightly more efficient or easily understandable. The problem is that the code will only generate enough bytes to describe the length of the packet, so less than 255 bytes = 1 byte of length, less than 65535 = 2 bytes of length etc... { extern char byte_stream[]; int bytes = offset_in_packet; int n = length_of_packet; /* Under 4 billion, so this can be represented in 32 bits. */ int t; /* 32-bit number used for temporary storage. */
/* These are the bytes we will break up n into. */ unsigned char first, second, third, fourth;
t = n & 0xFF000000; /* We have used AND to "mask out" the first byte of the number. */ /* The only bits which can be on in t are the first 8 bits. */ first = t >> 24; if (t) { printf("byte 1: 0x%02x\n",first ); byte_stream[bytes] = first; bytes++; write_zeros = 1; } /* Now we shift t so that it is between 0 and 255. This is the first, highest byte of n. */ t = n & 0x00FF0000; second = t >> 16; if (t || write_zeros) { printf("byte 2: 0x%02x\n", second ); byte_stream[bytes] = second; bytes++; write_zeros = 1; }
t = n & 0x0000FF00; third = t >> 8; if ( t || write_zeros) { printf("byte 3: 0x%02x\n", third ); byte_stream[bytes] = third; bytes++; write_zeros = 1; }
t = n & 0x000000FF; fourth = t; if (t || write_zeros) { printf("byte 4: 0x%02x\n", fourth); byte_stream[bytes] = fourth; bytes++; } }
ANSWER:
Really you're only doing four calculations, so readability seems way more important here than efficiency. My approach to make something like this more readable is to Extract common code to a function Put similar calculations together to make the patterns more obvious Get rid of the intermediate variable print_zeroes and be explicit about the cases in which you output bytes even if they're zero (i.e. the preceding byte was non-zero) I've changed the random code block into a function and changed a few variables (underscores are giving me trouble in the markdown preview screen). I've also assumed that bytes is being passed in, and that whoever is passing it in will pass us a pointer so we can modify it. Here's the code: /* append byte b to stream, increment index */ /* really needs to check length of stream before appending */ void output( int i, unsigned char b, char stream[], int *index ) { printf("byte %d: 0x%02x\n", i, b); stream[(*index)++] = b; }
void answer( char bytestream[], unsigned int *bytes, unsigned int n) { /* mask out four bytes from word n */ first = (n & 0xFF000000) >> 24; second = (n & 0x00FF0000) >> 16; third = (n & 0x0000FF00) >> 8; fourth = (n & 0x000000FF) >> 0;
/* conditionally output each byte starting with the */ /* first non-zero byte */ if (first) output( 1, first, bytestream, bytes);
if (first || second) output( 2, second, bytestream, bytes);
if (first || second || third) output( 3, third, bytestream, bytes);
if (first || second || third || fourth) output( 4, fourth, bytestream, bytes); } Ever so slightly more efficient, and maybe easier to understand would be this modification to the last four if statements: if (n>0x00FFFFFF) output( 1, first, bytestream, bytes);
if (n>0x0000FFFF) output( 2, second, bytestream, bytes);
if (n>0x000000FF) output( 3, third, bytestream, bytes);
if (1) output( 4, fourth, bytestream, bytes); I agree, however, that compressing this field makes the receiving state machine overly complicated. But if you can't change the protocol, this code is much easier to read. | [
"c",
"protocols"
] | 2 | 0 | 752 | 4 | 0 | 2008-08-29T18:38:42.357000 | 2008-09-03T02:14:08.080000 |
34,981 | 34,998 | Scrum: Resistance is (not) futile | I'm the second dev and a recent hire here at a PHP/MySQL shop. I was hired mostly due to my experience in wrangling some sort of process out of a chaotic mess. At least, that's what I did at my last company.;) Since I've been here (a few months now), I've brought on board my boss, my product manager and several other key figures (But mostly chickens, if you pardon the Scrum-based stereotyping). I've also helped bring in some visibility to the development cycle of a major product that has been lagging for over a year. People are loving it! However, my coworker (the only other dev here for now) is not into it. She prefers to close her door and focus on her work and be left alone. Me? I'm into the whole Agile approach of collaboration, cooperation and openness. Without her input, I started the Scrum practices (daily scrums, burndown charts and other things I've found that worked for me and my previous teams (ala H. Kniberg's cool wall chart). During our daily stand up she slinks by and ignores us as if we actually weren't standing right outside her door (we are actually). It's pretty amazing. I've never seen such resistance. Question... how do I get her onboard? Peer pressure is not working. Thanks from fellow Scrum-borg, beaudetious | While Scrum other agile methodologies like it embody a lot of good practices, sometimes giving it a name and making it (as many bloggers have commented on) a "religion" that must be adopted in the workplace is rather offputting to a lot of people, including myself. It depends on what your options and commitments are, but I know I'd be a lot more keen on accepting ideas because they are good ideas, not because they are a bandwagon. Try implementing/drawing her in to the practices one at a time, by showing her how they can improve her life and workflow as well. Programmers love cool things that help them get stuff done. They hate being preached at or being asked to board what they see as a bandwagon. Present it as the former rather than the latter. (It goes without saying, make sure it actually IS the former) Edit: another question I've never actually worked for a place that used a specific agile methodology, though I'm pretty happy where I'm at now in that we incorporate a lot of agile practices without the hype and the dogma (best of both worlds, IMHO). But I was just reading about Scrum and, is a system like that even beneficial for a 2 person team? Scrum does add a certain amount of overhead to a project, it seems, and that might outweigh the benefits when you have a very small team where communication and planning is already easy. | Scrum: Resistance is (not) futile I'm the second dev and a recent hire here at a PHP/MySQL shop. I was hired mostly due to my experience in wrangling some sort of process out of a chaotic mess. At least, that's what I did at my last company.;) Since I've been here (a few months now), I've brought on board my boss, my product manager and several other key figures (But mostly chickens, if you pardon the Scrum-based stereotyping). I've also helped bring in some visibility to the development cycle of a major product that has been lagging for over a year. People are loving it! However, my coworker (the only other dev here for now) is not into it. She prefers to close her door and focus on her work and be left alone. Me? I'm into the whole Agile approach of collaboration, cooperation and openness. Without her input, I started the Scrum practices (daily scrums, burndown charts and other things I've found that worked for me and my previous teams (ala H. Kniberg's cool wall chart). During our daily stand up she slinks by and ignores us as if we actually weren't standing right outside her door (we are actually). It's pretty amazing. I've never seen such resistance. Question... how do I get her onboard? Peer pressure is not working. Thanks from fellow Scrum-borg, beaudetious | TITLE:
Scrum: Resistance is (not) futile
QUESTION:
I'm the second dev and a recent hire here at a PHP/MySQL shop. I was hired mostly due to my experience in wrangling some sort of process out of a chaotic mess. At least, that's what I did at my last company.;) Since I've been here (a few months now), I've brought on board my boss, my product manager and several other key figures (But mostly chickens, if you pardon the Scrum-based stereotyping). I've also helped bring in some visibility to the development cycle of a major product that has been lagging for over a year. People are loving it! However, my coworker (the only other dev here for now) is not into it. She prefers to close her door and focus on her work and be left alone. Me? I'm into the whole Agile approach of collaboration, cooperation and openness. Without her input, I started the Scrum practices (daily scrums, burndown charts and other things I've found that worked for me and my previous teams (ala H. Kniberg's cool wall chart). During our daily stand up she slinks by and ignores us as if we actually weren't standing right outside her door (we are actually). It's pretty amazing. I've never seen such resistance. Question... how do I get her onboard? Peer pressure is not working. Thanks from fellow Scrum-borg, beaudetious
ANSWER:
While Scrum other agile methodologies like it embody a lot of good practices, sometimes giving it a name and making it (as many bloggers have commented on) a "religion" that must be adopted in the workplace is rather offputting to a lot of people, including myself. It depends on what your options and commitments are, but I know I'd be a lot more keen on accepting ideas because they are good ideas, not because they are a bandwagon. Try implementing/drawing her in to the practices one at a time, by showing her how they can improve her life and workflow as well. Programmers love cool things that help them get stuff done. They hate being preached at or being asked to board what they see as a bandwagon. Present it as the former rather than the latter. (It goes without saying, make sure it actually IS the former) Edit: another question I've never actually worked for a place that used a specific agile methodology, though I'm pretty happy where I'm at now in that we incorporate a lot of agile practices without the hype and the dogma (best of both worlds, IMHO). But I was just reading about Scrum and, is a system like that even beneficial for a 2 person team? Scrum does add a certain amount of overhead to a project, it seems, and that might outweigh the benefits when you have a very small team where communication and planning is already easy. | [
"agile",
"scrum"
] | 7 | 14 | 1,749 | 7 | 0 | 2008-08-29T18:39:24.320000 | 2008-08-29T18:46:28.297000 |
34,988 | 219,897 | How to transform a WebService call that is using behaviours? | We have some really old code that calls WebServices using behaviours (webservice.htc), and we are having some strange problems... since they've been deprecated a long time ago, I want to change the call. What's the correct way of doing it? It's ASP.NET 1.1 | You should be able to generate a proxy class using wsdl.exe. Then just use the web service as you normally would. | How to transform a WebService call that is using behaviours? We have some really old code that calls WebServices using behaviours (webservice.htc), and we are having some strange problems... since they've been deprecated a long time ago, I want to change the call. What's the correct way of doing it? It's ASP.NET 1.1 | TITLE:
How to transform a WebService call that is using behaviours?
QUESTION:
We have some really old code that calls WebServices using behaviours (webservice.htc), and we are having some strange problems... since they've been deprecated a long time ago, I want to change the call. What's the correct way of doing it? It's ASP.NET 1.1
ANSWER:
You should be able to generate a proxy class using wsdl.exe. Then just use the web service as you normally would. | [
"c#",
"javascript",
"web-services",
"asp.net-1.1",
"behavior"
] | 6 | 3 | 260 | 2 | 0 | 2008-08-29T18:41:42.630000 | 2008-10-20T21:02:05.013000 |
35,002 | 35,666 | Does C# have a way of giving me an immutable Dictionary? | Is there anything built into the core C# libraries that can give me an immutable Dictionary? Something along the lines of Java's: Collections.unmodifiableMap(myMap); And just to clarify, I am not looking to stop the keys / values themselves from being changed, just the structure of the Dictionary. I want something that fails fast and loud if any of IDictionary's mutator methods are called ( Add, Remove, Clear ). | No, but a wrapper is rather trivial: public class ReadOnlyDictionary: IDictionary { IDictionary _dict;
public ReadOnlyDictionary(IDictionary backingDict) { _dict = backingDict; }
public void Add(TKey key, TValue value) { throw new InvalidOperationException(); }
public bool ContainsKey(TKey key) { return _dict.ContainsKey(key); }
public ICollection Keys { get { return _dict.Keys; } }
public bool Remove(TKey key) { throw new InvalidOperationException(); }
public bool TryGetValue(TKey key, out TValue value) { return _dict.TryGetValue(key, out value); }
public ICollection Values { get { return _dict.Values; } }
public TValue this[TKey key] { get { return _dict[key]; } set { throw new InvalidOperationException(); } }
public void Add(KeyValuePair item) { throw new InvalidOperationException(); }
public void Clear() { throw new InvalidOperationException(); }
public bool Contains(KeyValuePair item) { return _dict.Contains(item); }
public void CopyTo(KeyValuePair [] array, int arrayIndex) { _dict.CopyTo(array, arrayIndex); }
public int Count { get { return _dict.Count; } }
public bool IsReadOnly { get { return true; } }
public bool Remove(KeyValuePair item) { throw new InvalidOperationException(); }
public IEnumerator > GetEnumerator() { return _dict.GetEnumerator(); }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return ((System.Collections.IEnumerable)_dict).GetEnumerator(); } } Obviously, you can change the this[] setter above if you want to allow modifying values. | Does C# have a way of giving me an immutable Dictionary? Is there anything built into the core C# libraries that can give me an immutable Dictionary? Something along the lines of Java's: Collections.unmodifiableMap(myMap); And just to clarify, I am not looking to stop the keys / values themselves from being changed, just the structure of the Dictionary. I want something that fails fast and loud if any of IDictionary's mutator methods are called ( Add, Remove, Clear ). | TITLE:
Does C# have a way of giving me an immutable Dictionary?
QUESTION:
Is there anything built into the core C# libraries that can give me an immutable Dictionary? Something along the lines of Java's: Collections.unmodifiableMap(myMap); And just to clarify, I am not looking to stop the keys / values themselves from being changed, just the structure of the Dictionary. I want something that fails fast and loud if any of IDictionary's mutator methods are called ( Add, Remove, Clear ).
ANSWER:
No, but a wrapper is rather trivial: public class ReadOnlyDictionary: IDictionary { IDictionary _dict;
public ReadOnlyDictionary(IDictionary backingDict) { _dict = backingDict; }
public void Add(TKey key, TValue value) { throw new InvalidOperationException(); }
public bool ContainsKey(TKey key) { return _dict.ContainsKey(key); }
public ICollection Keys { get { return _dict.Keys; } }
public bool Remove(TKey key) { throw new InvalidOperationException(); }
public bool TryGetValue(TKey key, out TValue value) { return _dict.TryGetValue(key, out value); }
public ICollection Values { get { return _dict.Values; } }
public TValue this[TKey key] { get { return _dict[key]; } set { throw new InvalidOperationException(); } }
public void Add(KeyValuePair item) { throw new InvalidOperationException(); }
public void Clear() { throw new InvalidOperationException(); }
public bool Contains(KeyValuePair item) { return _dict.Contains(item); }
public void CopyTo(KeyValuePair [] array, int arrayIndex) { _dict.CopyTo(array, arrayIndex); }
public int Count { get { return _dict.Count; } }
public bool IsReadOnly { get { return true; } }
public bool Remove(KeyValuePair item) { throw new InvalidOperationException(); }
public IEnumerator > GetEnumerator() { return _dict.GetEnumerator(); }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return ((System.Collections.IEnumerable)_dict).GetEnumerator(); } } Obviously, you can change the this[] setter above if you want to allow modifying values. | [
"c#",
"java",
".net",
"collections",
"dictionary"
] | 75 | 52 | 26,641 | 14 | 0 | 2008-08-29T18:47:23.117000 | 2008-08-30T03:56:02.440000 |
35,007 | 38,410 | How to expose a collection property? | Every time I create an object that has a collection property I go back and forth on the best way to do it? public property with a getter that returns a reference to private variable explicit get_ObjList and set_ObjList methods that return and create new or cloned objects every time explicit get_ObjList that returns an IEnumerator and a set_ObjList that takes IEnumerator Does it make a difference if the collection is an array (i.e., objList.Clone()) versus a List? If returning the actual collection as a reference is so bad because it creates dependencies, then why return any property as a reference? Anytime you expose an child object as a reference the internals of that child can be changed without the parent "knowing" unless the child has a property changed event. Is there a risk for memory leaks? And, don't options 2 and 3 break serialization? Is this a catch 22 or do you have to implement custom serialization anytime you have a collection property? The generic ReadOnlyCollection seems like a nice compromise for general use. It wraps an IList and restricts access to it. Maybe this helps with memory leaks and serialization. However it still has enumeration concerns Maybe it just depends. If you don't care that the collection is modified, then just expose it as a public accessor over a private variable per #1. If you don't want other programs to modify the collection then #2 and/or #3 is better. Implicit in the question is why should one method be used over another and what are the ramifications on security, memory, serialization, etc.? | How you expose a collection depends entirely on how users are intended to interact with it. 1) If users will be adding and removing items from an object's collection, then a simple get-only collection property is best (option #1 from the original question): private readonly Collection myCollection_ = new...; public Collection MyCollection { get { return this.myCollection_; } } This strategy is used for the Items collections on the WindowsForms and WPF ItemsControl controls, where users add and remove items they want the control to display. These controls publish the actual collection and use callbacks or event listeners to keep track of items. WPF also exposes some settable collections to allow users to display a collection of items they control, such as the ItemsSource property on ItemsControl (option #3 from the original question). However, this is not a common use case. 2) If users will only be reading data maintained by the object, then you can use a readonly collection, as Quibblesome suggested: private readonly List myPrivateCollection_ = new...; private ReadOnlyCollection myPrivateCollectionView_; public ReadOnlyCollection MyCollection { get { if( this.myPrivateCollectionView_ == null ) { /* lazily initialize view */ } return this.myPrivateCollectionView_; } } Note that ReadOnlyCollection provides a live view of the underlying collection, so you only need to create the view once. If the internal collection does not implement IList, or if you want to restrict access to more advanced users, you can instead wrap access to the collection through an enumerator: public IEnumerable MyCollection { get { foreach( T item in this.myPrivateCollection_ ) yield return item; } } This approach is simple to implement and also provides access to all the members without exposing the internal collection. However, it does require that the collection remain unmodfied, as the BCL collection classes will throw an exception if you try to enumerate a collection after it has been modified. If the underlying collection is likely to change, you can either create a light wrapper that will enumerate the collection safely, or return a copy of the collection. 3) Finally, if you need to expose arrays rather than higher-level collections, then you should return a copy of the array to prevent users from modifying it (option #2 from the orginal question): private T[] myArray_; public T[] GetMyArray( ) { T[] copy = new T[this.myArray_.Length]; this.myArray_.CopyTo( copy, 0 ); return copy; // Note: if you are using LINQ, calling the 'ToArray( )' // extension method will create a copy for you. } You should not expose the underlying array through a property, as you will not be able to tell when users modify it. To allow modifying the array, you can either add a corresponding SetMyArray( T[] array ) method, or use a custom indexer: public T this[int index] { get { return this.myArray_[index]; } set { // TODO: validate new value; raise change event; etc. this.myArray_[index] = value; } } (of course, by implementing a custom indexer, you will be duplicating the work of the BCL classes:) | How to expose a collection property? Every time I create an object that has a collection property I go back and forth on the best way to do it? public property with a getter that returns a reference to private variable explicit get_ObjList and set_ObjList methods that return and create new or cloned objects every time explicit get_ObjList that returns an IEnumerator and a set_ObjList that takes IEnumerator Does it make a difference if the collection is an array (i.e., objList.Clone()) versus a List? If returning the actual collection as a reference is so bad because it creates dependencies, then why return any property as a reference? Anytime you expose an child object as a reference the internals of that child can be changed without the parent "knowing" unless the child has a property changed event. Is there a risk for memory leaks? And, don't options 2 and 3 break serialization? Is this a catch 22 or do you have to implement custom serialization anytime you have a collection property? The generic ReadOnlyCollection seems like a nice compromise for general use. It wraps an IList and restricts access to it. Maybe this helps with memory leaks and serialization. However it still has enumeration concerns Maybe it just depends. If you don't care that the collection is modified, then just expose it as a public accessor over a private variable per #1. If you don't want other programs to modify the collection then #2 and/or #3 is better. Implicit in the question is why should one method be used over another and what are the ramifications on security, memory, serialization, etc.? | TITLE:
How to expose a collection property?
QUESTION:
Every time I create an object that has a collection property I go back and forth on the best way to do it? public property with a getter that returns a reference to private variable explicit get_ObjList and set_ObjList methods that return and create new or cloned objects every time explicit get_ObjList that returns an IEnumerator and a set_ObjList that takes IEnumerator Does it make a difference if the collection is an array (i.e., objList.Clone()) versus a List? If returning the actual collection as a reference is so bad because it creates dependencies, then why return any property as a reference? Anytime you expose an child object as a reference the internals of that child can be changed without the parent "knowing" unless the child has a property changed event. Is there a risk for memory leaks? And, don't options 2 and 3 break serialization? Is this a catch 22 or do you have to implement custom serialization anytime you have a collection property? The generic ReadOnlyCollection seems like a nice compromise for general use. It wraps an IList and restricts access to it. Maybe this helps with memory leaks and serialization. However it still has enumeration concerns Maybe it just depends. If you don't care that the collection is modified, then just expose it as a public accessor over a private variable per #1. If you don't want other programs to modify the collection then #2 and/or #3 is better. Implicit in the question is why should one method be used over another and what are the ramifications on security, memory, serialization, etc.?
ANSWER:
How you expose a collection depends entirely on how users are intended to interact with it. 1) If users will be adding and removing items from an object's collection, then a simple get-only collection property is best (option #1 from the original question): private readonly Collection myCollection_ = new...; public Collection MyCollection { get { return this.myCollection_; } } This strategy is used for the Items collections on the WindowsForms and WPF ItemsControl controls, where users add and remove items they want the control to display. These controls publish the actual collection and use callbacks or event listeners to keep track of items. WPF also exposes some settable collections to allow users to display a collection of items they control, such as the ItemsSource property on ItemsControl (option #3 from the original question). However, this is not a common use case. 2) If users will only be reading data maintained by the object, then you can use a readonly collection, as Quibblesome suggested: private readonly List myPrivateCollection_ = new...; private ReadOnlyCollection myPrivateCollectionView_; public ReadOnlyCollection MyCollection { get { if( this.myPrivateCollectionView_ == null ) { /* lazily initialize view */ } return this.myPrivateCollectionView_; } } Note that ReadOnlyCollection provides a live view of the underlying collection, so you only need to create the view once. If the internal collection does not implement IList, or if you want to restrict access to more advanced users, you can instead wrap access to the collection through an enumerator: public IEnumerable MyCollection { get { foreach( T item in this.myPrivateCollection_ ) yield return item; } } This approach is simple to implement and also provides access to all the members without exposing the internal collection. However, it does require that the collection remain unmodfied, as the BCL collection classes will throw an exception if you try to enumerate a collection after it has been modified. If the underlying collection is likely to change, you can either create a light wrapper that will enumerate the collection safely, or return a copy of the collection. 3) Finally, if you need to expose arrays rather than higher-level collections, then you should return a copy of the array to prevent users from modifying it (option #2 from the orginal question): private T[] myArray_; public T[] GetMyArray( ) { T[] copy = new T[this.myArray_.Length]; this.myArray_.CopyTo( copy, 0 ); return copy; // Note: if you are using LINQ, calling the 'ToArray( )' // extension method will create a copy for you. } You should not expose the underlying array through a property, as you will not be able to tell when users modify it. To allow modifying the array, you can either add a corresponding SetMyArray( T[] array ) method, or use a custom indexer: public T this[int index] { get { return this.myArray_[index]; } set { // TODO: validate new value; raise change event; etc. this.myArray_[index] = value; } } (of course, by implementing a custom indexer, you will be duplicating the work of the BCL classes:) | [
"c#",
".net",
"architecture"
] | 49 | 57 | 24,917 | 7 | 0 | 2008-08-29T18:48:17.390000 | 2008-09-01T20:46:35.923000 |
35,011 | 35,057 | Register Multiple Assemblies to the GAC in Vista | I've got a whole directory of dll's I need to register to the GAC. I'd like to avoid registering each file explicitly- but it appears that gacutil has no "register directory" option. Anyone have a fast/simple solution? | GACUTIL doesn't register DLLs -- not in the "COM" sense. Unlike in COM, GACUTIL copies the file to an opaque directory under %SYSTEMROOT%\assembly and that's where they run from. It wouldn't make sense to ask GACUTIL "register a folder" (not that you can do that with RegSvr32 either). You can use a batch FOR command such as: FOR %a IN (C:\MyFolderWithAssemblies\*.dll) DO GACUTIL /i %a If you place that in a batch file, you must replace %a with %%a | Register Multiple Assemblies to the GAC in Vista I've got a whole directory of dll's I need to register to the GAC. I'd like to avoid registering each file explicitly- but it appears that gacutil has no "register directory" option. Anyone have a fast/simple solution? | TITLE:
Register Multiple Assemblies to the GAC in Vista
QUESTION:
I've got a whole directory of dll's I need to register to the GAC. I'd like to avoid registering each file explicitly- but it appears that gacutil has no "register directory" option. Anyone have a fast/simple solution?
ANSWER:
GACUTIL doesn't register DLLs -- not in the "COM" sense. Unlike in COM, GACUTIL copies the file to an opaque directory under %SYSTEMROOT%\assembly and that's where they run from. It wouldn't make sense to ask GACUTIL "register a folder" (not that you can do that with RegSvr32 either). You can use a batch FOR command such as: FOR %a IN (C:\MyFolderWithAssemblies\*.dll) DO GACUTIL /i %a If you place that in a batch file, you must replace %a with %%a | [
".net",
"gac",
"gacutil"
] | 21 | 38 | 13,143 | 4 | 0 | 2008-08-29T18:50:51.360000 | 2008-08-29T19:05:44.880000 |
35,017 | 35,051 | File database suggestion with support for multiple concurrent users | I need a database that could be stored network drive and would allow multiple users (up to 20) to use it without any server software. I'm considering MS Access or Berkeley DB. Can you share your experience with file databases? Which one did you use, did you have any problems with it? | I would suggest SQLite because the entire database is stored in a single file, and it quite safely handles multiple users accessing it at the same time. There are several different libraries that you can use for your client application and there is no server software needed. One of the strengths is that it mimics SQL servers so closely that if you need to convert from using a database file to a full-fledged SQL Server, most of your queries in your client won't need to change. You'll just need to migrate the data over to the new server database (which I wouldn't be surprised if there are programs to convert SQLite databases to MySQL databases, for example.) | File database suggestion with support for multiple concurrent users I need a database that could be stored network drive and would allow multiple users (up to 20) to use it without any server software. I'm considering MS Access or Berkeley DB. Can you share your experience with file databases? Which one did you use, did you have any problems with it? | TITLE:
File database suggestion with support for multiple concurrent users
QUESTION:
I need a database that could be stored network drive and would allow multiple users (up to 20) to use it without any server software. I'm considering MS Access or Berkeley DB. Can you share your experience with file databases? Which one did you use, did you have any problems with it?
ANSWER:
I would suggest SQLite because the entire database is stored in a single file, and it quite safely handles multiple users accessing it at the same time. There are several different libraries that you can use for your client application and there is no server software needed. One of the strengths is that it mimics SQL servers so closely that if you need to convert from using a database file to a full-fledged SQL Server, most of your queries in your client won't need to change. You'll just need to migrate the data over to the new server database (which I wouldn't be surprised if there are programs to convert SQLite databases to MySQL databases, for example.) | [
"database",
"ms-access",
"concurrency",
"berkeley-db"
] | 2 | 5 | 2,351 | 9 | 0 | 2008-08-29T18:52:54.397000 | 2008-08-29T19:03:04.717000 |
35,026 | 35,038 | SQL Server, convert a named instance to default instance? | I need to convert a named instance of SQL server 2005, to a default instance. Is there a way to do this without a reinstall? The problem is, 2 out of 6 of the developers, installed with a named instance. So its becoming a pain changing connection strings for the other 4 of us. I am looking for the path of least resistance to getting these 2 back on to our teams standard setup. Each has expressed that this is going to be, too much trouble and that it will take away from their development time. I assumed that it would take some time to resolve, in the best interest of all involved, I tried combing through configuration apps installed and didn't see anything, so I figured someone with more knowledge of the inner workings would be here. | As far as I know, no. One reason is the folder structure on the hard drive; they will have a name like MSSQL10.[instancename] | SQL Server, convert a named instance to default instance? I need to convert a named instance of SQL server 2005, to a default instance. Is there a way to do this without a reinstall? The problem is, 2 out of 6 of the developers, installed with a named instance. So its becoming a pain changing connection strings for the other 4 of us. I am looking for the path of least resistance to getting these 2 back on to our teams standard setup. Each has expressed that this is going to be, too much trouble and that it will take away from their development time. I assumed that it would take some time to resolve, in the best interest of all involved, I tried combing through configuration apps installed and didn't see anything, so I figured someone with more knowledge of the inner workings would be here. | TITLE:
SQL Server, convert a named instance to default instance?
QUESTION:
I need to convert a named instance of SQL server 2005, to a default instance. Is there a way to do this without a reinstall? The problem is, 2 out of 6 of the developers, installed with a named instance. So its becoming a pain changing connection strings for the other 4 of us. I am looking for the path of least resistance to getting these 2 back on to our teams standard setup. Each has expressed that this is going to be, too much trouble and that it will take away from their development time. I assumed that it would take some time to resolve, in the best interest of all involved, I tried combing through configuration apps installed and didn't see anything, so I figured someone with more knowledge of the inner workings would be here.
ANSWER:
As far as I know, no. One reason is the folder structure on the hard drive; they will have a name like MSSQL10.[instancename] | [
"sql-server",
"sql-server-2005",
"named-instance"
] | 154 | 21 | 118,650 | 7 | 0 | 2008-08-29T18:55:35.123000 | 2008-08-29T18:59:18.953000 |
35,037 | 35,052 | How to convert complex filename into HTML link? | I have a directory with PDF files that I need to create an index for. It is a PHP page with a list of links: filename The filenames can be complicated: LVD 2-1133 - Ändring av dumpningslina (1984-11-20).pdf What is the correct way to link to this file on a Linux/Apache server? Is there a PHP function to do this conversion? | You can use rawurlencode() to convert a string according to the RFC 1738 spec. This function replaces all non-alphanumeric characters by their associated code. The difference with urlencode() is that spaces are encoded as plus signs. You'll probably want to use the last one. This technique is called Percent or URL encoding. See Wikipedia for more details. | How to convert complex filename into HTML link? I have a directory with PDF files that I need to create an index for. It is a PHP page with a list of links: filename The filenames can be complicated: LVD 2-1133 - Ändring av dumpningslina (1984-11-20).pdf What is the correct way to link to this file on a Linux/Apache server? Is there a PHP function to do this conversion? | TITLE:
How to convert complex filename into HTML link?
QUESTION:
I have a directory with PDF files that I need to create an index for. It is a PHP page with a list of links: filename The filenames can be complicated: LVD 2-1133 - Ändring av dumpningslina (1984-11-20).pdf What is the correct way to link to this file on a Linux/Apache server? Is there a PHP function to do this conversion?
ANSWER:
You can use rawurlencode() to convert a string according to the RFC 1738 spec. This function replaces all non-alphanumeric characters by their associated code. The difference with urlencode() is that spaces are encoded as plus signs. You'll probably want to use the last one. This technique is called Percent or URL encoding. See Wikipedia for more details. | [
"php",
"html"
] | 1 | 3 | 2,447 | 5 | 0 | 2008-08-29T18:58:55.583000 | 2008-08-29T19:03:17.617000 |
35,050 | 35,054 | Comparison of Javascript libraries | After the suggestion to use a library for my ajax needs I am going to use one, the problem is that there are so many and I've no idea how to even begin telling them apart. Thus, can anybody A) Give a rundown of the differences or B) Point me (and others like me) somewhere that has such a list. Failing that plan C is to go with whichever gets mentioned the most here. | To answer B: Comparison of JavaScript frameworks EDIT: Although everyone and their mom is apparently riding the jQuery bandwagon (I use MochiKit ), there are many libraries which provide the same functionality - the problem set which most libraries solve (async client-server communication, DOM manipulation, etc.) is the same, and there are few that don't have what you will need to get the job done. The important thing to determine for yourself is whether or not a library will fit your particular style and sensibilities. Wide-spread ignorance about how JavaScript, the language, actually works, coupled with the negative press resulting thereby, coupled with the now-immense popularity of jQuery leads most people down that road. Thankfully, it isn't a bad road to be on as there are a lot of travellers to keep you company when the abstractions leak and you need help. You probably can't go wrong choosing jQuery. | Comparison of Javascript libraries After the suggestion to use a library for my ajax needs I am going to use one, the problem is that there are so many and I've no idea how to even begin telling them apart. Thus, can anybody A) Give a rundown of the differences or B) Point me (and others like me) somewhere that has such a list. Failing that plan C is to go with whichever gets mentioned the most here. | TITLE:
Comparison of Javascript libraries
QUESTION:
After the suggestion to use a library for my ajax needs I am going to use one, the problem is that there are so many and I've no idea how to even begin telling them apart. Thus, can anybody A) Give a rundown of the differences or B) Point me (and others like me) somewhere that has such a list. Failing that plan C is to go with whichever gets mentioned the most here.
ANSWER:
To answer B: Comparison of JavaScript frameworks EDIT: Although everyone and their mom is apparently riding the jQuery bandwagon (I use MochiKit ), there are many libraries which provide the same functionality - the problem set which most libraries solve (async client-server communication, DOM manipulation, etc.) is the same, and there are few that don't have what you will need to get the job done. The important thing to determine for yourself is whether or not a library will fit your particular style and sensibilities. Wide-spread ignorance about how JavaScript, the language, actually works, coupled with the negative press resulting thereby, coupled with the now-immense popularity of jQuery leads most people down that road. Thankfully, it isn't a bad road to be on as there are a lot of travellers to keep you company when the abstractions leak and you need help. You probably can't go wrong choosing jQuery. | [
"javascript",
"comparison"
] | 4 | 10 | 5,613 | 11 | 0 | 2008-08-29T19:03:01.347000 | 2008-08-29T19:04:05.667000 |
35,070 | 35,162 | programmatically merge .reg file into win32 registry | What's the best way to programmatically merge a.reg file into the registry? This is for unit testing; the.reg file is a test artifact which will be added then removed at the start and end of testing. Or, if there's a better way to unit test against the registry... | It is possible to remove registry keys using a.reg file, although I'm not sure how well it's documented. Here's how: REGEDIT4
[-HKEY_CURRENT_USER\Software\ ] The - in front of the key name tells Regedit that you want to remove the key. To run this silently, type: regedit /s "myfile.reg" | programmatically merge .reg file into win32 registry What's the best way to programmatically merge a.reg file into the registry? This is for unit testing; the.reg file is a test artifact which will be added then removed at the start and end of testing. Or, if there's a better way to unit test against the registry... | TITLE:
programmatically merge .reg file into win32 registry
QUESTION:
What's the best way to programmatically merge a.reg file into the registry? This is for unit testing; the.reg file is a test artifact which will be added then removed at the start and end of testing. Or, if there's a better way to unit test against the registry...
ANSWER:
It is possible to remove registry keys using a.reg file, although I'm not sure how well it's documented. Here's how: REGEDIT4
[-HKEY_CURRENT_USER\Software\ ] The - in front of the key name tells Regedit that you want to remove the key. To run this silently, type: regedit /s "myfile.reg" | [
"unit-testing",
"registry"
] | 6 | 9 | 4,602 | 5 | 0 | 2008-08-29T19:09:47.353000 | 2008-08-29T19:53:11.507000 |
35,076 | 35,100 | Strategy for identifying unused tables in SQL Server 2000? | I'm working with a SQL Server 2000 database that likely has a few dozen tables that are no longer accessed. I'd like to clear out the data that we no longer need to be maintaining, but I'm not sure how to identify which tables to remove. The database is shared by several different applications, so I can't be 100% confident that reviewing these will give me a complete list of the objects that are used. What I'd like to do, if it's possible, is to get a list of tables that haven't been accessed at all for some period of time. No reads, no writes. How should I approach this? | MSSQL2000 won't give you that kind of information. But a way you can identify what tables ARE used (and then deduce which ones are not) is to use the SQL Profiler, to save all the queries that go to a certain database. Configure the profiler to record the results to a new table, and then check the queries saved there to find all the tables (and views, sps, etc) that are used by your applications. Another way I think you might check if there's any "writes" is to add a new timestamp column to every table, and a trigger that updates that column every time there's an update or an insert. But keep in mind that if your apps do queries of the type select * from... then they will receive a new column and that might cause you some problems. | Strategy for identifying unused tables in SQL Server 2000? I'm working with a SQL Server 2000 database that likely has a few dozen tables that are no longer accessed. I'd like to clear out the data that we no longer need to be maintaining, but I'm not sure how to identify which tables to remove. The database is shared by several different applications, so I can't be 100% confident that reviewing these will give me a complete list of the objects that are used. What I'd like to do, if it's possible, is to get a list of tables that haven't been accessed at all for some period of time. No reads, no writes. How should I approach this? | TITLE:
Strategy for identifying unused tables in SQL Server 2000?
QUESTION:
I'm working with a SQL Server 2000 database that likely has a few dozen tables that are no longer accessed. I'd like to clear out the data that we no longer need to be maintaining, but I'm not sure how to identify which tables to remove. The database is shared by several different applications, so I can't be 100% confident that reviewing these will give me a complete list of the objects that are used. What I'd like to do, if it's possible, is to get a list of tables that haven't been accessed at all for some period of time. No reads, no writes. How should I approach this?
ANSWER:
MSSQL2000 won't give you that kind of information. But a way you can identify what tables ARE used (and then deduce which ones are not) is to use the SQL Profiler, to save all the queries that go to a certain database. Configure the profiler to record the results to a new table, and then check the queries saved there to find all the tables (and views, sps, etc) that are used by your applications. Another way I think you might check if there's any "writes" is to add a new timestamp column to every table, and a trigger that updates that column every time there's an update or an insert. But keep in mind that if your apps do queries of the type select * from... then they will receive a new column and that might cause you some problems. | [
"sql",
"database",
"sql-server-2000"
] | 2 | 5 | 1,526 | 6 | 0 | 2008-08-29T19:13:14.350000 | 2008-08-29T19:25:05.553000 |
35,102 | 35,139 | What is the role of the buried-buffer-list frame parameter in Emacs | In emacs, I've read the following code snippet in simple.el: (frame-parameter frame 'buried-buffer-list) What is the exact meaning of the 'buried-buffer-list parameter? What it is used for? | The result of M-x describe function RET frame-parameter is: frame-parameter is a built-in function. (frame-parameter FRAME PARAMETER) Return FRAME's value for parameter PARAMETER. If FRAME is nil, describe the currently selected frame. Also, have a look in the Elisp info manual for the node called "Frame/Frame Parameters". There isn't a specific reference to 'buried-buffer-list that I could find. You might be able to get the value of it by evaluating: (cdr (frame-parameter FRAME 'buffer-list)) since a "buried buffer" is just a buffer that's been pushed to the back of the list of buffers for a particular frame. See the documentation for bury-buffer: bury-buffer is an interactive compiled Lisp function in `window.el'. (bury-buffer &optional BUFFER-OR-NAME) Put BUFFER-OR-NAME at the end of the list of all buffers. There it is the least likely candidate for `other-buffer' to return; thus, the least likely buffer for C-x b to select by default. You can specify a buffer name as BUFFER-OR-NAME, or an actual buffer object. If BUFFER-OR-NAME is nil or omitted, bury the current buffer. Also, if BUFFER-OR-NAME is nil or omitted, remove the current buffer from the selected window if it is displayed there. | What is the role of the buried-buffer-list frame parameter in Emacs In emacs, I've read the following code snippet in simple.el: (frame-parameter frame 'buried-buffer-list) What is the exact meaning of the 'buried-buffer-list parameter? What it is used for? | TITLE:
What is the role of the buried-buffer-list frame parameter in Emacs
QUESTION:
In emacs, I've read the following code snippet in simple.el: (frame-parameter frame 'buried-buffer-list) What is the exact meaning of the 'buried-buffer-list parameter? What it is used for?
ANSWER:
The result of M-x describe function RET frame-parameter is: frame-parameter is a built-in function. (frame-parameter FRAME PARAMETER) Return FRAME's value for parameter PARAMETER. If FRAME is nil, describe the currently selected frame. Also, have a look in the Elisp info manual for the node called "Frame/Frame Parameters". There isn't a specific reference to 'buried-buffer-list that I could find. You might be able to get the value of it by evaluating: (cdr (frame-parameter FRAME 'buffer-list)) since a "buried buffer" is just a buffer that's been pushed to the back of the list of buffers for a particular frame. See the documentation for bury-buffer: bury-buffer is an interactive compiled Lisp function in `window.el'. (bury-buffer &optional BUFFER-OR-NAME) Put BUFFER-OR-NAME at the end of the list of all buffers. There it is the least likely candidate for `other-buffer' to return; thus, the least likely buffer for C-x b to select by default. You can specify a buffer name as BUFFER-OR-NAME, or an actual buffer object. If BUFFER-OR-NAME is nil or omitted, bury the current buffer. Also, if BUFFER-OR-NAME is nil or omitted, remove the current buffer from the selected window if it is displayed there. | [
"emacs",
"elisp"
] | 5 | 1 | 408 | 2 | 0 | 2008-08-29T19:27:17.980000 | 2008-08-29T19:42:56.773000 |
35,103 | 35,116 | How do I store information in my executable in .Net | I'd like to bind a configuration file to my executable. I'd like to do this by storing an MD5 hash of the file inside the executable. This should keep anyone but the executable from modifying the file. Essentially if someone modifies this file outside of the program the program should fail to load it again. EDIT: The program processes credit card information so being able to change the configuration in any way could be a potential security risk. This software will be distributed to a large number of clients. Ideally client should have a configuration that is tied directly to the executable. This will hopefully keep a hacker from being able to get a fake configuration into place. The configuration still needs to be editable though so compiling an individual copy for each customer is not an option. It's important that this be dynamic. So that I can tie the hash to the configuration file as the configuration changes. | A better solution is to store the MD5 in the configuration file. But instead of the MD5 being just of the configuration file, also include some secret "key" value, like a fixed guid, in the MD5. write(MD5(SecretKey + ConfigFileText)); Then you simply remove that MD5 and rehash the file (including your secret key). If the MD5's are the same, then no-one modified it. This prevents someone from modifying it and re-applying the MD5 since they don't know your secret key. Keep in mind this is a fairly weak solution (as is the one you are suggesting) as they could easily track into your program to find the key or where the MD5 is stored. A better solution would be to use a public key system and sign the configuration file. Again that is weak since that would require the private key to be stored on their local machine. Pretty much anything that is contained on their local PC can be bypassed with enough effort. If you REALLY want to store the information in your executable (which I would discourage) then you can just try appending it at the end of the EXE. That is usually safe. Modifying executable programs is virus like behavior and most operating system security will try to stop you too. If your program is in the Program Files directory, and your configuration file is in the Application Data directory, and the user is logged in as a non-administrator (in XP or Vista), then you will be unable to update the EXE. Update: I don't care if you are using Asymmetric encryption, RSA or Quantum cryptography, if you are storing your keys on the user's computer (which you must do unless you route it all through a web service) then the user can find your keys, even if it means inspecting the registers on the CPU at run time! You are only buying yourself a moderate level of security, so stick with something that is simple. To prevent modification the solution I suggested is the best. To prevent reading then encrypt it, and if you are storing your key locally then use AES Rijndael. Update: The FixedGUID / SecretKey could alternatively be generated at install time and stored somewhere "secret" in the registry. Or you could generate it every time you use it from hardware configuration. Then you are getting more complicated. How you want to do this to allow for moderate levels of hardware changes would be to take 6 different signatures, and hash your configuration file 6 times - once with each. Combine each one with a 2nd secret value, like the GUID mentioned above (either global or generated at install). Then when you check you verify each hash separately. As long as they have 3 out of 6 (or whatever your tolerance is) then you accept it. Next time you write it you hash it with the new hardware configuration. This allows them to slowly swap out hardware over time and get a whole new system... Maybe that is a weakness. It all comes down to your tolerance. There are variations based on tighter tolerances. UPDATE: For a Credit Card system you might want to consider some real security. You should retain the services of a security and cryptography consultant. More information needs to be exchanged. They need to analyze your specific needs and risks. Also, if you want security with.NET you need to first start with a really good.NET obfuscator ( just Google it ). A.NET assembly is way to easy to disassemble and get at the source code and read all your secrets. Not to sound a like a broken record, but anything that depends on the security of your user's system is fundamentally flawed from the beginning. | How do I store information in my executable in .Net I'd like to bind a configuration file to my executable. I'd like to do this by storing an MD5 hash of the file inside the executable. This should keep anyone but the executable from modifying the file. Essentially if someone modifies this file outside of the program the program should fail to load it again. EDIT: The program processes credit card information so being able to change the configuration in any way could be a potential security risk. This software will be distributed to a large number of clients. Ideally client should have a configuration that is tied directly to the executable. This will hopefully keep a hacker from being able to get a fake configuration into place. The configuration still needs to be editable though so compiling an individual copy for each customer is not an option. It's important that this be dynamic. So that I can tie the hash to the configuration file as the configuration changes. | TITLE:
How do I store information in my executable in .Net
QUESTION:
I'd like to bind a configuration file to my executable. I'd like to do this by storing an MD5 hash of the file inside the executable. This should keep anyone but the executable from modifying the file. Essentially if someone modifies this file outside of the program the program should fail to load it again. EDIT: The program processes credit card information so being able to change the configuration in any way could be a potential security risk. This software will be distributed to a large number of clients. Ideally client should have a configuration that is tied directly to the executable. This will hopefully keep a hacker from being able to get a fake configuration into place. The configuration still needs to be editable though so compiling an individual copy for each customer is not an option. It's important that this be dynamic. So that I can tie the hash to the configuration file as the configuration changes.
ANSWER:
A better solution is to store the MD5 in the configuration file. But instead of the MD5 being just of the configuration file, also include some secret "key" value, like a fixed guid, in the MD5. write(MD5(SecretKey + ConfigFileText)); Then you simply remove that MD5 and rehash the file (including your secret key). If the MD5's are the same, then no-one modified it. This prevents someone from modifying it and re-applying the MD5 since they don't know your secret key. Keep in mind this is a fairly weak solution (as is the one you are suggesting) as they could easily track into your program to find the key or where the MD5 is stored. A better solution would be to use a public key system and sign the configuration file. Again that is weak since that would require the private key to be stored on their local machine. Pretty much anything that is contained on their local PC can be bypassed with enough effort. If you REALLY want to store the information in your executable (which I would discourage) then you can just try appending it at the end of the EXE. That is usually safe. Modifying executable programs is virus like behavior and most operating system security will try to stop you too. If your program is in the Program Files directory, and your configuration file is in the Application Data directory, and the user is logged in as a non-administrator (in XP or Vista), then you will be unable to update the EXE. Update: I don't care if you are using Asymmetric encryption, RSA or Quantum cryptography, if you are storing your keys on the user's computer (which you must do unless you route it all through a web service) then the user can find your keys, even if it means inspecting the registers on the CPU at run time! You are only buying yourself a moderate level of security, so stick with something that is simple. To prevent modification the solution I suggested is the best. To prevent reading then encrypt it, and if you are storing your key locally then use AES Rijndael. Update: The FixedGUID / SecretKey could alternatively be generated at install time and stored somewhere "secret" in the registry. Or you could generate it every time you use it from hardware configuration. Then you are getting more complicated. How you want to do this to allow for moderate levels of hardware changes would be to take 6 different signatures, and hash your configuration file 6 times - once with each. Combine each one with a 2nd secret value, like the GUID mentioned above (either global or generated at install). Then when you check you verify each hash separately. As long as they have 3 out of 6 (or whatever your tolerance is) then you accept it. Next time you write it you hash it with the new hardware configuration. This allows them to slowly swap out hardware over time and get a whole new system... Maybe that is a weakness. It all comes down to your tolerance. There are variations based on tighter tolerances. UPDATE: For a Credit Card system you might want to consider some real security. You should retain the services of a security and cryptography consultant. More information needs to be exchanged. They need to analyze your specific needs and risks. Also, if you want security with.NET you need to first start with a really good.NET obfuscator ( just Google it ). A.NET assembly is way to easy to disassemble and get at the source code and read all your secrets. Not to sound a like a broken record, but anything that depends on the security of your user's system is fundamentally flawed from the beginning. | [
"c#",
".net"
] | 10 | 12 | 1,404 | 4 | 0 | 2008-08-29T19:27:18.667000 | 2008-08-29T19:34:07.573000 |
35,106 | 35,125 | Is there a built in way in .Net AJAX to manually serialize an object to a JSON string? | I've found ScriptingJsonSerializationSection but I'm not sure how to use it. I could write a function to convert the object to a JSON string manually, but since.Net can do it on the fly with the and attributes so there must be a built-in way that I'm missing. PS: using Asp.Net 2.0 and VB.Net - I put this in the tags but I think people missed it. | This should do the trick Dim jsonSerialiser As New System.Web.Script.Serialization.JavaScriptSerializer Dim jsonString as String = jsonSerialiser.Serialize(yourObject) | Is there a built in way in .Net AJAX to manually serialize an object to a JSON string? I've found ScriptingJsonSerializationSection but I'm not sure how to use it. I could write a function to convert the object to a JSON string manually, but since.Net can do it on the fly with the and attributes so there must be a built-in way that I'm missing. PS: using Asp.Net 2.0 and VB.Net - I put this in the tags but I think people missed it. | TITLE:
Is there a built in way in .Net AJAX to manually serialize an object to a JSON string?
QUESTION:
I've found ScriptingJsonSerializationSection but I'm not sure how to use it. I could write a function to convert the object to a JSON string manually, but since.Net can do it on the fly with the and attributes so there must be a built-in way that I'm missing. PS: using Asp.Net 2.0 and VB.Net - I put this in the tags but I think people missed it.
ANSWER:
This should do the trick Dim jsonSerialiser As New System.Web.Script.Serialization.JavaScriptSerializer Dim jsonString as String = jsonSerialiser.Serialize(yourObject) | [
"asp.net",
"vb.net",
"json",
"serialization",
".net-2.0"
] | 11 | 11 | 1,958 | 6 | 0 | 2008-08-29T19:28:50.583000 | 2008-08-29T19:37:28.363000 |
35,120 | 35,705 | Image processing in Silverlight 2 | Is it possible to do image processing in silverlight 2.0? What I want to do is take an image, crop it, and then send the new cropped image up to the server. I know I can fake it by clipping the image, but that only effects the rendering of the image. I want to create a new image. After further research I have answered my own question. Answer: No. Since all apis would be in System.Windows.Media.Imaging and that namespace does not have the appropriate classes in Silverlight I'm going to use fjcore. http://code.google.com/p/fjcore/ Thanks Jonas | Well, you can actually do local image processing in Silverlight 2... But there are no built in classes to help you. But you can load any image into a byte array, and start manipulating it, or implement your own image encoder. Joe Stegman got lots of great information about "editable images" in Silverlight over at http://blogs.msdn.com/jstegman/. He does things like applying filters to images, generating mandlebrots and more. This blog discuss a JPEG Silverilght Encoder (FJCore) you can use to resize and recompress photos client size: http://fluxcapacity.net/2008/07/14/fjcore-to-the-rescue/ Another tool is "Fluxify" which lets you resize and upload photos using Silverilght 2. Can be found over at http://fluxtools.net/ So yes, client side image processing can definetly be done in Silverilght 2. Happy hacking! | Image processing in Silverlight 2 Is it possible to do image processing in silverlight 2.0? What I want to do is take an image, crop it, and then send the new cropped image up to the server. I know I can fake it by clipping the image, but that only effects the rendering of the image. I want to create a new image. After further research I have answered my own question. Answer: No. Since all apis would be in System.Windows.Media.Imaging and that namespace does not have the appropriate classes in Silverlight I'm going to use fjcore. http://code.google.com/p/fjcore/ Thanks Jonas | TITLE:
Image processing in Silverlight 2
QUESTION:
Is it possible to do image processing in silverlight 2.0? What I want to do is take an image, crop it, and then send the new cropped image up to the server. I know I can fake it by clipping the image, but that only effects the rendering of the image. I want to create a new image. After further research I have answered my own question. Answer: No. Since all apis would be in System.Windows.Media.Imaging and that namespace does not have the appropriate classes in Silverlight I'm going to use fjcore. http://code.google.com/p/fjcore/ Thanks Jonas
ANSWER:
Well, you can actually do local image processing in Silverlight 2... But there are no built in classes to help you. But you can load any image into a byte array, and start manipulating it, or implement your own image encoder. Joe Stegman got lots of great information about "editable images" in Silverlight over at http://blogs.msdn.com/jstegman/. He does things like applying filters to images, generating mandlebrots and more. This blog discuss a JPEG Silverilght Encoder (FJCore) you can use to resize and recompress photos client size: http://fluxcapacity.net/2008/07/14/fjcore-to-the-rescue/ Another tool is "Fluxify" which lets you resize and upload photos using Silverilght 2. Can be found over at http://fluxtools.net/ So yes, client side image processing can definetly be done in Silverilght 2. Happy hacking! | [
"silverlight"
] | 4 | 3 | 4,493 | 3 | 0 | 2008-08-29T19:35:44.327000 | 2008-08-30T05:38:50.477000 |
35,123 | 159,454 | Prevent SWT ScrolledComposite from eating part of it's children | What did I do wrong? Here is an excerpt from my code: public void createPartControl(Composite parent) { parent.setLayout(new FillLayout()); ScrolledComposite scrollBox = new ScrolledComposite(parent, SWT.V_SCROLL); scrollBox.setExpandHorizontal(true); mParent = new Composite(scrollBox, SWT.NONE); scrollBox.setContent(mParent); FormLayout layout = new FormLayout(); mParent.setLayout(layout); // Adds a bunch of controls here mParent.layout(); mParent.setSize(mParent.computeSize(SWT.DEFAULT, SWT.DEFAULT, true)); }...but it clips the last button: bigbrother82: That didn't work. SCdF: I tried your suggestion, and now the scrollbars are gone. I need to work some more on that. | This is a common hurdle when using ScrolledComposite. When it gets so small that the scroll bar must be shown, the client control has to shrink horizontally to make room for the scroll bar. This has the side effect of making some labels wrap lines, which moved the following controls farther down, which increased the minimum height needed by the content composite. You need to listen for width changes on the content composite ( mParent ), compute the minimum height again given the new content width, and call setMinHeight() on the scrolled composite with new height. public void createPartControl(Composite parent) { parent.setLayout(new FillLayout()); ScrolledComposite scrollBox = new ScrolledComposite(parent, SWT.V_SCROLL); scrollBox.setExpandHorizontal(true); scrollBox.setExpandVertical(true);
// Using 0 here ensures the horizontal scroll bar will never appear. If // you want the horizontal bar to appear at some threshold (say 100 // pixels) then send that value instead. scrollBox.setMinWidth(0);
mParent = new Composite(scrollBox, SWT.NONE);
FormLayout layout = new FormLayout(); mParent.setLayout(layout);
// Adds a bunch of controls here
mParent.addListener(SWT.Resize, new Listener() { int width = -1; public void handleEvent(Event e) { int newWidth = mParent.getSize().x; if (newWidth!= width) { scrollBox.setMinHeight(mParent.computeSize(newWidth, SWT.DEFAULT).y); width = newWidth; } } }
// Wait until here to set content pane. This way the resize listener will // fire when the scrolled composite first resizes mParent, which in turn // computes the minimum height and calls setMinHeight() scrollBox.setContent(mParent); } In listening for size changes, note that we ignore any resize events where the width stays the same. This is because changes in the height of the content do not affect the minimum height of the content, as long as the width is the same. | Prevent SWT ScrolledComposite from eating part of it's children What did I do wrong? Here is an excerpt from my code: public void createPartControl(Composite parent) { parent.setLayout(new FillLayout()); ScrolledComposite scrollBox = new ScrolledComposite(parent, SWT.V_SCROLL); scrollBox.setExpandHorizontal(true); mParent = new Composite(scrollBox, SWT.NONE); scrollBox.setContent(mParent); FormLayout layout = new FormLayout(); mParent.setLayout(layout); // Adds a bunch of controls here mParent.layout(); mParent.setSize(mParent.computeSize(SWT.DEFAULT, SWT.DEFAULT, true)); }...but it clips the last button: bigbrother82: That didn't work. SCdF: I tried your suggestion, and now the scrollbars are gone. I need to work some more on that. | TITLE:
Prevent SWT ScrolledComposite from eating part of it's children
QUESTION:
What did I do wrong? Here is an excerpt from my code: public void createPartControl(Composite parent) { parent.setLayout(new FillLayout()); ScrolledComposite scrollBox = new ScrolledComposite(parent, SWT.V_SCROLL); scrollBox.setExpandHorizontal(true); mParent = new Composite(scrollBox, SWT.NONE); scrollBox.setContent(mParent); FormLayout layout = new FormLayout(); mParent.setLayout(layout); // Adds a bunch of controls here mParent.layout(); mParent.setSize(mParent.computeSize(SWT.DEFAULT, SWT.DEFAULT, true)); }...but it clips the last button: bigbrother82: That didn't work. SCdF: I tried your suggestion, and now the scrollbars are gone. I need to work some more on that.
ANSWER:
This is a common hurdle when using ScrolledComposite. When it gets so small that the scroll bar must be shown, the client control has to shrink horizontally to make room for the scroll bar. This has the side effect of making some labels wrap lines, which moved the following controls farther down, which increased the minimum height needed by the content composite. You need to listen for width changes on the content composite ( mParent ), compute the minimum height again given the new content width, and call setMinHeight() on the scrolled composite with new height. public void createPartControl(Composite parent) { parent.setLayout(new FillLayout()); ScrolledComposite scrollBox = new ScrolledComposite(parent, SWT.V_SCROLL); scrollBox.setExpandHorizontal(true); scrollBox.setExpandVertical(true);
// Using 0 here ensures the horizontal scroll bar will never appear. If // you want the horizontal bar to appear at some threshold (say 100 // pixels) then send that value instead. scrollBox.setMinWidth(0);
mParent = new Composite(scrollBox, SWT.NONE);
FormLayout layout = new FormLayout(); mParent.setLayout(layout);
// Adds a bunch of controls here
mParent.addListener(SWT.Resize, new Listener() { int width = -1; public void handleEvent(Event e) { int newWidth = mParent.getSize().x; if (newWidth!= width) { scrollBox.setMinHeight(mParent.computeSize(newWidth, SWT.DEFAULT).y); width = newWidth; } } }
// Wait until here to set content pane. This way the resize listener will // fire when the scrolled composite first resizes mParent, which in turn // computes the minimum height and calls setMinHeight() scrollBox.setContent(mParent); } In listening for size changes, note that we ignore any resize events where the width stays the same. This is because changes in the height of the content do not affect the minimum height of the content, as long as the width is the same. | [
"java",
"eclipse",
"swt",
"rcp"
] | 13 | 13 | 11,969 | 4 | 0 | 2008-08-29T19:36:33.920000 | 2008-10-01T20:03:37.207000 |
35,167 | 35,172 | Is there a way to perform a circular bit shift in C#? | I know that the following is true int i = 17; //binary 10001 int j = i << 1; //decimal 34, binary 100010 But, if you shift too far, the bits fall off the end. Where this happens is a matter of the size of integer you are working with. Is there a way to perform a shift so that the bits rotate around to the other side? I'm looking for a single operation, not a for loop. | If you know the size of type, you could do something like: uint i = 17; uint j = i << 1 | i >> 31;... which would perform a circular shift of a 32 bit value. As a generalization to circular shift left n bits, on a b bit variable: /*some unsigned numeric type*/ input = 17; var result = input << n | input >> (b - n); @The comment, it appears that C# does treat the high bit of signed values differently. I found some info on this here. I also changed the example to use a uint. | Is there a way to perform a circular bit shift in C#? I know that the following is true int i = 17; //binary 10001 int j = i << 1; //decimal 34, binary 100010 But, if you shift too far, the bits fall off the end. Where this happens is a matter of the size of integer you are working with. Is there a way to perform a shift so that the bits rotate around to the other side? I'm looking for a single operation, not a for loop. | TITLE:
Is there a way to perform a circular bit shift in C#?
QUESTION:
I know that the following is true int i = 17; //binary 10001 int j = i << 1; //decimal 34, binary 100010 But, if you shift too far, the bits fall off the end. Where this happens is a matter of the size of integer you are working with. Is there a way to perform a shift so that the bits rotate around to the other side? I'm looking for a single operation, not a for loop.
ANSWER:
If you know the size of type, you could do something like: uint i = 17; uint j = i << 1 | i >> 31;... which would perform a circular shift of a 32 bit value. As a generalization to circular shift left n bits, on a b bit variable: /*some unsigned numeric type*/ input = 17; var result = input << n | input >> (b - n); @The comment, it appears that C# does treat the high bit of signed values differently. I found some info on this here. I also changed the example to use a uint. | [
"c#",
"bit-manipulation"
] | 43 | 56 | 27,272 | 5 | 0 | 2008-08-29T19:54:43.047000 | 2008-08-29T19:57:17.847000 |
35,170 | 35,193 | Verilog automatic task | What does it mean if a task is declared with the automatic keyword in Verilog? task automatic do_things; input [31:0] number_of_things; reg [31:0] tmp_thing; begin //... end endtask; Note: This question is mostly because I'm curious if there are any hardware programmers on the site.:) | It means that the task is re-entrant - items declared within the task are dynamically allocated rather than shared between different invocations of the task. You see - some of us do Verilog... (ugh) | Verilog automatic task What does it mean if a task is declared with the automatic keyword in Verilog? task automatic do_things; input [31:0] number_of_things; reg [31:0] tmp_thing; begin //... end endtask; Note: This question is mostly because I'm curious if there are any hardware programmers on the site.:) | TITLE:
Verilog automatic task
QUESTION:
What does it mean if a task is declared with the automatic keyword in Verilog? task automatic do_things; input [31:0] number_of_things; reg [31:0] tmp_thing; begin //... end endtask; Note: This question is mostly because I'm curious if there are any hardware programmers on the site.:)
ANSWER:
It means that the task is re-entrant - items declared within the task are dynamically allocated rather than shared between different invocations of the task. You see - some of us do Verilog... (ugh) | [
"verilog"
] | 21 | 22 | 46,590 | 6 | 0 | 2008-08-29T19:56:47.427000 | 2008-08-29T20:07:49.990000 |
35,185 | 35,271 | Finding a single number in a list | What would be the best algorithm for finding a number that occurs only once in a list which has all other numbers occurring exactly twice. So, in the list of integers (lets take it as an array) each integer repeats exactly twice, except one. To find that one, what is the best algorithm. | The fastest (O(n)) and most memory efficient (O(1)) way is with the XOR operation. In C: int arr[] = {3, 2, 5, 2, 1, 5, 3};
int num = 0, i;
for (i=0; i < 7; i++) num ^= arr[i];
printf("%i\n", num); This prints "1", which is the only one that occurs once. This works because the first time you hit a number it marks the num variable with itself, and the second time it unmarks num with itself (more or less). The only one that remains unmarked is your non-duplicate. | Finding a single number in a list What would be the best algorithm for finding a number that occurs only once in a list which has all other numbers occurring exactly twice. So, in the list of integers (lets take it as an array) each integer repeats exactly twice, except one. To find that one, what is the best algorithm. | TITLE:
Finding a single number in a list
QUESTION:
What would be the best algorithm for finding a number that occurs only once in a list which has all other numbers occurring exactly twice. So, in the list of integers (lets take it as an array) each integer repeats exactly twice, except one. To find that one, what is the best algorithm.
ANSWER:
The fastest (O(n)) and most memory efficient (O(1)) way is with the XOR operation. In C: int arr[] = {3, 2, 5, 2, 1, 5, 3};
int num = 0, i;
for (i=0; i < 7; i++) num ^= arr[i];
printf("%i\n", num); This prints "1", which is the only one that occurs once. This works because the first time you hit a number it marks the num variable with itself, and the second time it unmarks num with itself (more or less). The only one that remains unmarked is your non-duplicate. | [
"algorithm",
"puzzle"
] | 40 | 140 | 24,236 | 11 | 0 | 2008-08-29T20:03:58.063000 | 2008-08-29T20:43:57.017000 |
35,186 | 35,210 | How do I fix a NoSuchMethodError? | I'm getting a NoSuchMethodError error when running my Java program. What's wrong and how do I fix it? | Without any more information it is difficult to pinpoint the problem, but the root cause is that you most likely have compiled a class against a different version of the class that is missing a method, than the one you are using when running it. Look at the stack trace... If the exception appears when calling a method on an object in a library, you are most likely using separate versions of the library when compiling and running. Make sure you have the right version both places. If the exception appears when calling a method on objects instantiated by classes you made, then your build process seems to be faulty. Make sure the class files that you are actually running are updated when you compile. | How do I fix a NoSuchMethodError? I'm getting a NoSuchMethodError error when running my Java program. What's wrong and how do I fix it? | TITLE:
How do I fix a NoSuchMethodError?
QUESTION:
I'm getting a NoSuchMethodError error when running my Java program. What's wrong and how do I fix it?
ANSWER:
Without any more information it is difficult to pinpoint the problem, but the root cause is that you most likely have compiled a class against a different version of the class that is missing a method, than the one you are using when running it. Look at the stack trace... If the exception appears when calling a method on an object in a library, you are most likely using separate versions of the library when compiling and running. Make sure you have the right version both places. If the exception appears when calling a method on objects instantiated by classes you made, then your build process seems to be faulty. Make sure the class files that you are actually running are updated when you compile. | [
"java",
"nosuchmethoderror"
] | 235 | 283 | 566,753 | 33 | 0 | 2008-08-29T20:04:27.643000 | 2008-08-29T20:14:56.353000 |
35,191 | 36,771 | Error using Team Foundation Server merge function | When merging two code branches in Team Foundation Server I get the following error: The given key was not present in the dictionary. Some files are checked out and show up in "Pending Changes", but no changes are actually made. I have a workaround: Attempt to merge (fails with error) Get latest from trunk Undo all pending changes with "merge, edit" or "merge" Merge Again (works this time) Any ideas on what's causing this error? Edit after answer: Seems like a bug. And it's extremely repeatable. Every single merge does it. I'll send a bug report to MS and see what happens. | Sounds like a bug. If you can replicate this, I recommend you contact Microsoft Support or use the Microsoft Connect bug reporting web site. I did not find any mention of this in a preliminary search. | Error using Team Foundation Server merge function When merging two code branches in Team Foundation Server I get the following error: The given key was not present in the dictionary. Some files are checked out and show up in "Pending Changes", but no changes are actually made. I have a workaround: Attempt to merge (fails with error) Get latest from trunk Undo all pending changes with "merge, edit" or "merge" Merge Again (works this time) Any ideas on what's causing this error? Edit after answer: Seems like a bug. And it's extremely repeatable. Every single merge does it. I'll send a bug report to MS and see what happens. | TITLE:
Error using Team Foundation Server merge function
QUESTION:
When merging two code branches in Team Foundation Server I get the following error: The given key was not present in the dictionary. Some files are checked out and show up in "Pending Changes", but no changes are actually made. I have a workaround: Attempt to merge (fails with error) Get latest from trunk Undo all pending changes with "merge, edit" or "merge" Merge Again (works this time) Any ideas on what's causing this error? Edit after answer: Seems like a bug. And it's extremely repeatable. Every single merge does it. I'll send a bug report to MS and see what happens.
ANSWER:
Sounds like a bug. If you can replicate this, I recommend you contact Microsoft Support or use the Microsoft Connect bug reporting web site. I did not find any mention of this in a preliminary search. | [
"tfs",
"merge"
] | 0 | 1 | 764 | 1 | 0 | 2008-08-29T20:07:31.300000 | 2008-08-31T11:10:29.563000 |
35,194 | 35,221 | Working in Visual Studio (2005 or 2008) on a networked drive | Have you guys had any experiences (positive or negative) by placing your source code/solution on a network drive for Visual Studio 2005 or 2008? Please note I am not referring to placing your actual source control system on that drive, but rather your working folder. Thanks | It works just fine. I have worked with source code from my "home" folder on many different systems (NFS, Samba, AD) and never had any problems. The only drawback is that you might experience somewhat longer compile times if your network is slow or there is much traffic on the network. Under normal circumstances this is not an issue though, since source code files are usually small and will be cached by the operating system anyway. | Working in Visual Studio (2005 or 2008) on a networked drive Have you guys had any experiences (positive or negative) by placing your source code/solution on a network drive for Visual Studio 2005 or 2008? Please note I am not referring to placing your actual source control system on that drive, but rather your working folder. Thanks | TITLE:
Working in Visual Studio (2005 or 2008) on a networked drive
QUESTION:
Have you guys had any experiences (positive or negative) by placing your source code/solution on a network drive for Visual Studio 2005 or 2008? Please note I am not referring to placing your actual source control system on that drive, but rather your working folder. Thanks
ANSWER:
It works just fine. I have worked with source code from my "home" folder on many different systems (NFS, Samba, AD) and never had any problems. The only drawback is that you might experience somewhat longer compile times if your network is slow or there is much traffic on the network. Under normal circumstances this is not an issue though, since source code files are usually small and will be cached by the operating system anyway. | [
"visual-studio-2008",
"visual-studio-2005"
] | 0 | 1 | 303 | 2 | 0 | 2008-08-29T20:08:23.373000 | 2008-08-29T20:20:44.093000 |
35,208 | 35,226 | requiredfield validator is preventing another form from submitting | I have a page with many forms in panels and usercontrols, and a requiredfield validator I just added to one form is preventing all of my other forms from submitting. what's the rule that I'm not following? | Are you using ValidationGroups? Try assigning each control with a validation group as well as the validator that you want to use. Something like: Note, if a button doesn't specify a validation group it will validate all controls that aren't assigned to a validation group. | requiredfield validator is preventing another form from submitting I have a page with many forms in panels and usercontrols, and a requiredfield validator I just added to one form is preventing all of my other forms from submitting. what's the rule that I'm not following? | TITLE:
requiredfield validator is preventing another form from submitting
QUESTION:
I have a page with many forms in panels and usercontrols, and a requiredfield validator I just added to one form is preventing all of my other forms from submitting. what's the rule that I'm not following?
ANSWER:
Are you using ValidationGroups? Try assigning each control with a validation group as well as the validator that you want to use. Something like: Note, if a button doesn't specify a validation group it will validate all controls that aren't assigned to a validation group. | [
"asp.net"
] | 1 | 5 | 460 | 2 | 0 | 2008-08-29T20:14:19.210000 | 2008-08-29T20:21:58.707000 |
35,211 | 37,315 | Identify an event via a Linq Expression tree | The compiler usually chokes when an event doesn't appear beside a += or a -=, so I'm not sure if this is possible. I want to be able to identify an event by using an Expression tree, so I can create an event watcher for a test. The syntax would look something like this: using(var foo = new EventWatcher(target, x => x.MyEventToWatch) { // act here } // throws on Dispose() if MyEventToWatch hasn't fired My questions are twofold: Will the compiler choke? And if so, any suggestions on how to prevent this? How can I parse the Expression object from the constructor in order to attach to the MyEventToWatch event of target? | Edit: As Curt has pointed out, my implementation is rather flawed in that it can only be used from within the class that declares the event:) Instead of " x => x.MyEvent " returning the event, it was returning the backing field, which is only accessble by the class. Since expressions cannot contain assignment statements, a modified expression like " ( x, h ) => x.MyEvent += h " cannot be used to retrieve the event, so reflection would need to be used instead. A correct implementation would need to use reflection to retrieve the EventInfo for the event (which, unfortunatley, will not be strongly typed). Otherwise, the only updates that need to be made are to store the reflected EventInfo, and use the AddEventHandler / RemoveEventHandler methods to register the listener (instead of the manual Delegate Combine / Remove calls and field sets). The rest of the implementation should not need to be changed. Good luck:) Note: This is demonstration-quality code that makes several assumptions about the format of the accessor. Proper error checking, handling of static events, etc, is left as an exercise to the reader;) public sealed class EventWatcher: IDisposable { private readonly object target_; private readonly string eventName_; private readonly FieldInfo eventField_; private readonly Delegate listener_; private bool eventWasRaised_;
public static EventWatcher Create ( T target, Expression > accessor ) { return new EventWatcher( target, accessor ); }
private EventWatcher( object target, LambdaExpression accessor ) { this.target_ = target;
// Retrieve event definition from expression. var eventAccessor = accessor.Body as MemberExpression; this.eventField_ = eventAccessor.Member as FieldInfo; this.eventName_ = this.eventField_.Name;
// Create our event listener and add it to the declaring object's event field. this.listener_ = CreateEventListenerDelegate( this.eventField_.FieldType ); var currentEventList = this.eventField_.GetValue( this.target_ ) as Delegate; var newEventList = Delegate.Combine( currentEventList, this.listener_ ); this.eventField_.SetValue( this.target_, newEventList ); }
public void SetEventWasRaised( ) { this.eventWasRaised_ = true; }
private Delegate CreateEventListenerDelegate( Type eventType ) { // Create the event listener's body, setting the 'eventWasRaised_' field. var setMethod = typeof( EventWatcher ).GetMethod( "SetEventWasRaised" ); var body = Expression.Call( Expression.Constant( this ), setMethod );
// Get the event delegate's parameters from its 'Invoke' method. var invokeMethod = eventType.GetMethod( "Invoke" ); var parameters = invokeMethod.GetParameters( ).Select( ( p ) => Expression.Parameter( p.ParameterType, p.Name ) );
// Create the listener. var listener = Expression.Lambda( eventType, body, parameters ); return listener.Compile( ); }
void IDisposable.Dispose( ) { // Remove the event listener. var currentEventList = this.eventField_.GetValue( this.target_ ) as Delegate; var newEventList = Delegate.Remove( currentEventList, this.listener_ ); this.eventField_.SetValue( this.target_, newEventList );
// Ensure event was raised. if(!this.eventWasRaised_ ) throw new InvalidOperationException( "Event was not raised: " + this.eventName_ ); } } Usage is slightly different from that suggested, in order to take advantage of type inference: try { using( EventWatcher.Create( o, x => x.MyEvent ) ) { //o.RaiseEvent( ); // Uncomment for test to succeed. } Console.WriteLine( "Event raised successfully" ); } catch( InvalidOperationException ex ) { Console.WriteLine( ex.Message ); } | Identify an event via a Linq Expression tree The compiler usually chokes when an event doesn't appear beside a += or a -=, so I'm not sure if this is possible. I want to be able to identify an event by using an Expression tree, so I can create an event watcher for a test. The syntax would look something like this: using(var foo = new EventWatcher(target, x => x.MyEventToWatch) { // act here } // throws on Dispose() if MyEventToWatch hasn't fired My questions are twofold: Will the compiler choke? And if so, any suggestions on how to prevent this? How can I parse the Expression object from the constructor in order to attach to the MyEventToWatch event of target? | TITLE:
Identify an event via a Linq Expression tree
QUESTION:
The compiler usually chokes when an event doesn't appear beside a += or a -=, so I'm not sure if this is possible. I want to be able to identify an event by using an Expression tree, so I can create an event watcher for a test. The syntax would look something like this: using(var foo = new EventWatcher(target, x => x.MyEventToWatch) { // act here } // throws on Dispose() if MyEventToWatch hasn't fired My questions are twofold: Will the compiler choke? And if so, any suggestions on how to prevent this? How can I parse the Expression object from the constructor in order to attach to the MyEventToWatch event of target?
ANSWER:
Edit: As Curt has pointed out, my implementation is rather flawed in that it can only be used from within the class that declares the event:) Instead of " x => x.MyEvent " returning the event, it was returning the backing field, which is only accessble by the class. Since expressions cannot contain assignment statements, a modified expression like " ( x, h ) => x.MyEvent += h " cannot be used to retrieve the event, so reflection would need to be used instead. A correct implementation would need to use reflection to retrieve the EventInfo for the event (which, unfortunatley, will not be strongly typed). Otherwise, the only updates that need to be made are to store the reflected EventInfo, and use the AddEventHandler / RemoveEventHandler methods to register the listener (instead of the manual Delegate Combine / Remove calls and field sets). The rest of the implementation should not need to be changed. Good luck:) Note: This is demonstration-quality code that makes several assumptions about the format of the accessor. Proper error checking, handling of static events, etc, is left as an exercise to the reader;) public sealed class EventWatcher: IDisposable { private readonly object target_; private readonly string eventName_; private readonly FieldInfo eventField_; private readonly Delegate listener_; private bool eventWasRaised_;
public static EventWatcher Create ( T target, Expression > accessor ) { return new EventWatcher( target, accessor ); }
private EventWatcher( object target, LambdaExpression accessor ) { this.target_ = target;
// Retrieve event definition from expression. var eventAccessor = accessor.Body as MemberExpression; this.eventField_ = eventAccessor.Member as FieldInfo; this.eventName_ = this.eventField_.Name;
// Create our event listener and add it to the declaring object's event field. this.listener_ = CreateEventListenerDelegate( this.eventField_.FieldType ); var currentEventList = this.eventField_.GetValue( this.target_ ) as Delegate; var newEventList = Delegate.Combine( currentEventList, this.listener_ ); this.eventField_.SetValue( this.target_, newEventList ); }
public void SetEventWasRaised( ) { this.eventWasRaised_ = true; }
private Delegate CreateEventListenerDelegate( Type eventType ) { // Create the event listener's body, setting the 'eventWasRaised_' field. var setMethod = typeof( EventWatcher ).GetMethod( "SetEventWasRaised" ); var body = Expression.Call( Expression.Constant( this ), setMethod );
// Get the event delegate's parameters from its 'Invoke' method. var invokeMethod = eventType.GetMethod( "Invoke" ); var parameters = invokeMethod.GetParameters( ).Select( ( p ) => Expression.Parameter( p.ParameterType, p.Name ) );
// Create the listener. var listener = Expression.Lambda( eventType, body, parameters ); return listener.Compile( ); }
void IDisposable.Dispose( ) { // Remove the event listener. var currentEventList = this.eventField_.GetValue( this.target_ ) as Delegate; var newEventList = Delegate.Remove( currentEventList, this.listener_ ); this.eventField_.SetValue( this.target_, newEventList );
// Ensure event was raised. if(!this.eventWasRaised_ ) throw new InvalidOperationException( "Event was not raised: " + this.eventName_ ); } } Usage is slightly different from that suggested, in order to take advantage of type inference: try { using( EventWatcher.Create( o, x => x.MyEvent ) ) { //o.RaiseEvent( ); // Uncomment for test to succeed. } Console.WriteLine( "Event raised successfully" ); } catch( InvalidOperationException ex ) { Console.WriteLine( ex.Message ); } | [
"c#",
"linq",
"expression-trees"
] | 9 | 4 | 3,577 | 4 | 0 | 2008-08-29T20:15:50.580000 | 2008-09-01T00:47:10.193000 |
35,219 | 38,231 | Optimizing/Customizing Sharepoint Search Crawling | With SharePoint Server 2007, there is also a Search Feature and a Crawler. However, the Crawler is somewhat limited in that it only supports Basic Auth when crawling external sites and that there is no way to tell it to ignore no-index,no-follow attributes. Now, there is a site i'd like to index, unfortunately this site uses it's own Authentication System, and it uses no-index,no-follow on the pages. As I control that site, i can remove the Attributes, but it's a PITA to do so. Also, it does not solve the Authentication issue. So I just wonder if it's possible to extend Sharepoint's Crawler somehow? | The limitation of MOSS crawling sites with different forms authentication should have been addressed in MOSS SP1.: http://www.microsoft.com/downloads/details.aspx?FamilyID=ad59175c-ad6a-4027-8c2f-db25322f791b&displaylang=en Here's a link to a post which describes how to get the hotfix for pre-SP1 MOSS to enable the crawling of sites with forms authentication: http://blogs.microsoft.co.il/blogs/adir_ron/archive/2007/10/11/moss-search-for-sso-form-based-authentication-sites.aspx Hope that helps! | Optimizing/Customizing Sharepoint Search Crawling With SharePoint Server 2007, there is also a Search Feature and a Crawler. However, the Crawler is somewhat limited in that it only supports Basic Auth when crawling external sites and that there is no way to tell it to ignore no-index,no-follow attributes. Now, there is a site i'd like to index, unfortunately this site uses it's own Authentication System, and it uses no-index,no-follow on the pages. As I control that site, i can remove the Attributes, but it's a PITA to do so. Also, it does not solve the Authentication issue. So I just wonder if it's possible to extend Sharepoint's Crawler somehow? | TITLE:
Optimizing/Customizing Sharepoint Search Crawling
QUESTION:
With SharePoint Server 2007, there is also a Search Feature and a Crawler. However, the Crawler is somewhat limited in that it only supports Basic Auth when crawling external sites and that there is no way to tell it to ignore no-index,no-follow attributes. Now, there is a site i'd like to index, unfortunately this site uses it's own Authentication System, and it uses no-index,no-follow on the pages. As I control that site, i can remove the Attributes, but it's a PITA to do so. Also, it does not solve the Authentication issue. So I just wonder if it's possible to extend Sharepoint's Crawler somehow?
ANSWER:
The limitation of MOSS crawling sites with different forms authentication should have been addressed in MOSS SP1.: http://www.microsoft.com/downloads/details.aspx?FamilyID=ad59175c-ad6a-4027-8c2f-db25322f791b&displaylang=en Here's a link to a post which describes how to get the hotfix for pre-SP1 MOSS to enable the crawling of sites with forms authentication: http://blogs.microsoft.co.il/blogs/adir_ron/archive/2007/10/11/moss-search-for-sso-form-based-authentication-sites.aspx Hope that helps! | [
"c#",
".net",
"sharepoint"
] | 6 | 3 | 1,034 | 1 | 0 | 2008-08-29T20:19:31.677000 | 2008-09-01T18:09:03.400000 |
35,224 | 35,883 | Flex ComboBox, default value and dataproviders | I have a Flex ComboBox that gets populated by a dataprovider all is well... I would now like to add a default " -- select a item --" option at the 0 index, how can I do this and still use a dataprovider? I have not seen any examples of such, but I can't imagine this being hard... | If you don't need the default item to be selectable you can use the prompt property of ComboBox and set the selectedIndex to -1. That will show the string you set propmt to as the selected value until the user chooses another. It will not appear in the list of options, however. | Flex ComboBox, default value and dataproviders I have a Flex ComboBox that gets populated by a dataprovider all is well... I would now like to add a default " -- select a item --" option at the 0 index, how can I do this and still use a dataprovider? I have not seen any examples of such, but I can't imagine this being hard... | TITLE:
Flex ComboBox, default value and dataproviders
QUESTION:
I have a Flex ComboBox that gets populated by a dataprovider all is well... I would now like to add a default " -- select a item --" option at the 0 index, how can I do this and still use a dataprovider? I have not seen any examples of such, but I can't imagine this being hard...
ANSWER:
If you don't need the default item to be selectable you can use the prompt property of ComboBox and set the selectedIndex to -1. That will show the string you set propmt to as the selected value until the user chooses another. It will not appear in the list of options, however. | [
"apache-flex",
"data-binding",
"combobox"
] | 14 | 36 | 31,009 | 4 | 0 | 2008-08-29T20:21:13.827000 | 2008-08-30T11:07:33.947000 |
35,232 | 1,157,405 | Would building an application using a Sql Server Database File (mdf) be a terrible idea? | I'm working on a side project that would be a simple web application to maintain a list of classes and their upcoming schedules. I would really like to use Linq to SQL for this project, but unfortunately the server environment I'm developing for only has MySql available. I've dabbled briefly with Subsonic but it just doesn't get the job done. The database requirements for this application aren't that great, though, so I'm curious if using an MDF file in App_Data would be a workable solution. Otherwise, it appears I'm going to have to hand-code sql queries which I want to avoid at all costs. | I've long since completed the project which prompted this question, but recently I've had another project come along with very minor data requirements, so I spent some more time experimenting with this. I had assumed that Sql Server Express required licensing fees to deploy, but this is not in fact the case. According to Microsoft's website, you are free to use it with certain restrictions: Maximum database size: 4 GB Maximum memory used: 1 GB Maximum CPUs used: 1 (complete procs, not cores) Sql Server Compact is a bad idea for web applications because it requires a hack to make it work, and it isn't built for the concurrent access you'd need for the web. But if your application can fit within the modest limitations of Sql Server Express, it works pretty well. And since it speaks regular T-SQL like its larger siblings, you can use Linq to SQL with it. I hear that Linq to Sql support is now in the Mono trunk for the 2.6 release, so L2S' tight-coupling to Sql Server will likely be a moot point in the near future. I will either end up porting my code to use Mono's superior Linq to Sql implementation on the db of my choice, or go another route entirely (SubSonic has improved by leaps and bounds since I last tried it). But for the time being, Sql Server Express is a valid choice for very small database-driven apps. | Would building an application using a Sql Server Database File (mdf) be a terrible idea? I'm working on a side project that would be a simple web application to maintain a list of classes and their upcoming schedules. I would really like to use Linq to SQL for this project, but unfortunately the server environment I'm developing for only has MySql available. I've dabbled briefly with Subsonic but it just doesn't get the job done. The database requirements for this application aren't that great, though, so I'm curious if using an MDF file in App_Data would be a workable solution. Otherwise, it appears I'm going to have to hand-code sql queries which I want to avoid at all costs. | TITLE:
Would building an application using a Sql Server Database File (mdf) be a terrible idea?
QUESTION:
I'm working on a side project that would be a simple web application to maintain a list of classes and their upcoming schedules. I would really like to use Linq to SQL for this project, but unfortunately the server environment I'm developing for only has MySql available. I've dabbled briefly with Subsonic but it just doesn't get the job done. The database requirements for this application aren't that great, though, so I'm curious if using an MDF file in App_Data would be a workable solution. Otherwise, it appears I'm going to have to hand-code sql queries which I want to avoid at all costs.
ANSWER:
I've long since completed the project which prompted this question, but recently I've had another project come along with very minor data requirements, so I spent some more time experimenting with this. I had assumed that Sql Server Express required licensing fees to deploy, but this is not in fact the case. According to Microsoft's website, you are free to use it with certain restrictions: Maximum database size: 4 GB Maximum memory used: 1 GB Maximum CPUs used: 1 (complete procs, not cores) Sql Server Compact is a bad idea for web applications because it requires a hack to make it work, and it isn't built for the concurrent access you'd need for the web. But if your application can fit within the modest limitations of Sql Server Express, it works pretty well. And since it speaks regular T-SQL like its larger siblings, you can use Linq to SQL with it. I hear that Linq to Sql support is now in the Mono trunk for the 2.6 release, so L2S' tight-coupling to Sql Server will likely be a moot point in the near future. I will either end up porting my code to use Mono's superior Linq to Sql implementation on the db of my choice, or go another route entirely (SubSonic has improved by leaps and bounds since I last tried it). But for the time being, Sql Server Express is a valid choice for very small database-driven apps. | [
"asp.net",
"sql",
"mysql",
"sql-server"
] | 2 | 2 | 1,914 | 10 | 0 | 2008-08-29T20:26:39.743000 | 2009-07-21T05:12:15.687000 |
35,233 | 35,262 | Rewrite or repair? | I'm sure you have all been there, you take on a project where there is a creaky old code base which is barely fit for purpose and you have to make the decision to either re-write it from scratch or repair what already exists. Conventional wisdom tends to suggest that you should never attempt a re-write from scratch as the risk of failure is very high. So what did you do when faced with this problem, how did you make the decision and how did it turn out? | It really depends on how bad it is. If it's a small system, and you fully understand it, then a rewrite is not crazy. On the other hand, if it's a giant legacy monster with ten million lines of undocumented mystery code, then you're really going to have a hard time with a full rewrite. Points to consider: If it looks good to the user, they won't care what kind of spaghetti mess it is for you. On the other hand, if it's bad for them too, then it's easier to get agreement (and patience). If you do rewrite, try to do it one part at a time. A messy, disorganized codebase may make this difficult (i.e, replacing just one part requires a rewrite of large icebergs of dependency code), but if possible, this makes it a lot easier to gradually do the rewrite and get feedback from users along the way. I would really hesitate to take on a giant rewrite project for a large system without being able to release the new edition one part at a time. | Rewrite or repair? I'm sure you have all been there, you take on a project where there is a creaky old code base which is barely fit for purpose and you have to make the decision to either re-write it from scratch or repair what already exists. Conventional wisdom tends to suggest that you should never attempt a re-write from scratch as the risk of failure is very high. So what did you do when faced with this problem, how did you make the decision and how did it turn out? | TITLE:
Rewrite or repair?
QUESTION:
I'm sure you have all been there, you take on a project where there is a creaky old code base which is barely fit for purpose and you have to make the decision to either re-write it from scratch or repair what already exists. Conventional wisdom tends to suggest that you should never attempt a re-write from scratch as the risk of failure is very high. So what did you do when faced with this problem, how did you make the decision and how did it turn out?
ANSWER:
It really depends on how bad it is. If it's a small system, and you fully understand it, then a rewrite is not crazy. On the other hand, if it's a giant legacy monster with ten million lines of undocumented mystery code, then you're really going to have a hard time with a full rewrite. Points to consider: If it looks good to the user, they won't care what kind of spaghetti mess it is for you. On the other hand, if it's bad for them too, then it's easier to get agreement (and patience). If you do rewrite, try to do it one part at a time. A messy, disorganized codebase may make this difficult (i.e, replacing just one part requires a rewrite of large icebergs of dependency code), but if possible, this makes it a lot easier to gradually do the rewrite and get feedback from users along the way. I would really hesitate to take on a giant rewrite project for a large system without being able to release the new edition one part at a time. | [
"refactoring",
"url-rewriting"
] | 13 | 11 | 1,646 | 11 | 0 | 2008-08-29T20:27:11.160000 | 2008-08-29T20:39:23.800000 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.