content
stringlengths
86
88.9k
title
stringlengths
0
150
question
stringlengths
1
35.8k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
30
130
Q: In Tomcat how can my servlet determine what connectors are configured? In Tomcat 5.5 the server.xml can have many connectors, typically port only 8080, but for my application a user might configure their servlet.xml to also have other ports open (say 8081-8088). I would like for my servlet to figure out what socket connections ports will be vaild (During the Servlet.init() tomcat has not yet started the connectors.) I could find and parse the server.xml myself (grotty), I could look at the thread names (after tomcat starts up - but how would I know when a good time to do that is? ) But I would prefer a solution that can execute in my servlet.init() and determine what will be the valid port range. Any ideas? A solution can be tightly bound to Tomcat for my application that's ok. A: In Tomcat 6.0 it should be something like: org.apache.catalina.ServerFactory.getServer().getServices to get the services. After that you might use Service.findConnectors which returns a Connector which finally has the method Connector.getPort See the JavaDocs for the details. A: Why? If you need during page generation for a image or css file URL, what's wrong with ServletRequest.getLocalPort() or, better yet, HttpServletRequest.getContextPath() for the whole shebang? A: Whatever you are about to do - I'd not go down the tomcat specific road. If you really need to locate different ports, configure them to your webapp through the usual configuration means - e.g. specifying values. You'd not have any automatic discovery, but also it won't break on tomcats next update. More specifically, I'd say that I believe you've asked the wrong question. E.g. you have your requirement, opted for one solution and asked for how to implement this solution. I believe you'd get better answers if you stated your first hand requirement and asked for a solution for this.
In Tomcat how can my servlet determine what connectors are configured?
In Tomcat 5.5 the server.xml can have many connectors, typically port only 8080, but for my application a user might configure their servlet.xml to also have other ports open (say 8081-8088). I would like for my servlet to figure out what socket connections ports will be vaild (During the Servlet.init() tomcat has not yet started the connectors.) I could find and parse the server.xml myself (grotty), I could look at the thread names (after tomcat starts up - but how would I know when a good time to do that is? ) But I would prefer a solution that can execute in my servlet.init() and determine what will be the valid port range. Any ideas? A solution can be tightly bound to Tomcat for my application that's ok.
[ "In Tomcat 6.0 it should be something like:\norg.apache.catalina.ServerFactory.getServer().getServices \n\nto get the services. After that you might use \nService.findConnectors\n\nwhich returns a Connector which finally has the method\nConnector.getPort\n\nSee the JavaDocs for the details.\n", "Why?\nIf you need during page generation for a image or css file URL, what's wrong with ServletRequest.getLocalPort() or, better yet, HttpServletRequest.getContextPath() for the whole shebang?\n", "Whatever you are about to do - I'd not go down the tomcat specific road.\nIf you really need to locate different ports, configure them to your webapp through the usual configuration means - e.g. specifying values. You'd not have any automatic discovery, but also it won't break on tomcats next update.\nMore specifically, I'd say that I believe you've asked the wrong question. E.g. you have your requirement, opted for one solution and asked for how to implement this solution. I believe you'd get better answers if you stated your first hand requirement and asked for a solution for this.\n" ]
[ 4, 0, 0 ]
[]
[]
[ "tomcat" ]
stackoverflow_0000065530_tomcat.txt
Q: When to enable/disable Viewstate I generaly disable viewstate for my ASP.net controls unless I explicitly know I am going to require view state for them. I have found that this can significantly reduce the page size of the HTML generated. Is this good practice? When should be enabled or disabled? A: Yes it is a very good idea. One could argue that it should have been disabled by default by Microsoft, just like caching. To see how bad Viewstate is in terms of size increased you can use a tool called Viewstate Analyzer. This is particularly useful when you have an existing application developed with Viewstate enabled. Another good reason to disable Viewstate is that it is really hard to disable at a later stage, when you have loads of components depending on it. A: I think it's good practice. Many ASP.NET devs are unaware that their viewstates add tremendous baggage to the HTML that's being sent to their users' browsers. A: You may find the information contained in the "ASP.NET State Management Recommendations" article on MSDN useful for making your decision. Generally in ASP.NET 2.0 and above disabling the ViewState is less destructive due to the introduction of the Control State for storing informaton required for raising events etc. A: It's a good practice. Unless you use ViewState values on postbacks, or they are required by some complex control itself it's good idea to save on ViewState as part of what will be sent to the client. A: Definately a good idea, nothing worse that a page which a developer is binding a dataGrid in the Page_Load every time but also submitting the viewstate! It's also a really good idea if you are planning on using the UpdatePanel from the AJAX Extensions, it means you're submitting less during the UpdatePanel request. (Don't flame for saying that an UpdatePanel can be good :P) A: _Viewstate can unnecessarily increase the number of bytes that need to be transferred. So unless the data is going to be used the next time , it's a good idea to switch it off.
When to enable/disable Viewstate
I generaly disable viewstate for my ASP.net controls unless I explicitly know I am going to require view state for them. I have found that this can significantly reduce the page size of the HTML generated. Is this good practice? When should be enabled or disabled?
[ "Yes it is a very good idea. One could argue that it should have been disabled by default by Microsoft, just like caching.\nTo see how bad Viewstate is in terms of size increased you can use a tool called Viewstate Analyzer. This is particularly useful when you have an existing application developed with Viewstate enabled.\nAnother good reason to disable Viewstate is that it is really hard to disable at a later stage, when you have loads of components depending on it.\n", "I think it's good practice. Many ASP.NET devs are unaware that their viewstates add tremendous baggage to the HTML that's being sent to their users' browsers.\n", "You may find the information contained in the \"ASP.NET State Management Recommendations\" article on MSDN useful for making your decision.\nGenerally in ASP.NET 2.0 and above disabling the ViewState is less destructive due to the introduction of the Control State for storing informaton required for raising events etc.\n", "It's a good practice. Unless you use ViewState values on postbacks, or they are required by some complex control itself it's good idea to save on ViewState as part of what will be sent to the client.\n", "Definately a good idea, nothing worse that a page which a developer is binding a dataGrid in the Page_Load every time but also submitting the viewstate!\nIt's also a really good idea if you are planning on using the UpdatePanel from the AJAX Extensions, it means you're submitting less during the UpdatePanel request.\n(Don't flame for saying that an UpdatePanel can be good :P)\n", "_Viewstate can unnecessarily increase the number of bytes that need to be transferred. \nSo unless the data is going to be used the next time , it's a good idea to switch it off.\n" ]
[ 20, 6, 5, 4, 2, 0 ]
[]
[]
[ "asp.net", "web_user_controls" ]
stackoverflow_0000113479_asp.net_web_user_controls.txt
Q: What is the best Linux distribution for Vmware server? In terms of Webserver and low package size installation. A: To be honest, the best distro for VMWare is the one the admin has the most experience with. With the GUI stuff all disabled I've not found any difference in performance between RedHat, Centos and Ubuntu when running VMWare. Picking the distro that you can adminster easiest will save you hassle. If you already have a few linux systems using the same flavour makes the admins job a lot easier. A: It is not clear to me if you are asking about the distro for the Vmware host, or for the guest operating system that will be your web server. I generally really like Debian or Debian based distributions. But as far as Vmware is concerned Centos or anything really should work. If you are looking at setting up many vms on this server you might want to look at using the bare-metal hypervisor product that has been released as a free product. (Vmware ESX)
What is the best Linux distribution for Vmware server?
In terms of Webserver and low package size installation.
[ "To be honest, the best distro for VMWare is the one the admin has the most experience with. With the GUI stuff all disabled I've not found any difference in performance between RedHat, Centos and Ubuntu when running VMWare.\nPicking the distro that you can adminster easiest will save you hassle. If you already have a few linux systems using the same flavour makes the admins job a lot easier.\n", "It is not clear to me if you are asking about the distro for the Vmware host, or for the guest operating system that will be your web server.\nI generally really like Debian or Debian based distributions. But as far as Vmware is concerned Centos or anything really should work.\nIf you are looking at setting up many vms on this server you might want to look at using the bare-metal hypervisor product that has been released as a free product. (Vmware ESX)\n" ]
[ 3, 0 ]
[]
[]
[ "linux" ]
stackoverflow_0000113561_linux.txt
Q: ASP.NET Custom Controls and "Dynamic" Event Model OK, I am not sure if the title it completely accurate, open to suggestions! I am in the process of creating an ASP.NET custom control, this is something that is still relatively new to me, so please bear with me. I am thinking about the event model. Since we are not using Web Controls there are no events being fired from buttons, rather I am manually calling __doPostBack with the appropriate arguments. However this can obviously mean that there are a lot of postbacks occuring when say, selecting options (which render differently when selected). In time, I will need to make this more Ajax-y and responsive, so I will need to change the event binding to call local Javascript. So, I was thinking I should be able to toggle the "mode" of the control, it can either use postback and handlle itself, or you can specify the Javascript function names to call instead of the doPostBack. What are your thoughts on this? Am I approaching the raising of the events from the control in the wrong way? (totally open to suggestions here!) How would you approach a similar problem? Edit - To Clarify I am creating a custom rendered control (i.e. inherits from WebControl). We are not using existnig Web Controls since we want complete control over the rendered output. AFAIK the only way to get a server side event to occur from a custom rendered control is to call doPostBack from the rendered elements (please correct if wrong!). ASP.NET MVC is not an option. A: Very odd. You're using ASP.NET server controls and custom controls, but you're not using web controls? And you're calling __doPostBack manually? Do you like to do things the hard way? If I was still using the server control model rather than MVC, I would slap ASP.NET Ajax controls on that sucker and call it a day. What you're doing is like putting a blower on a model T. It may be fun and interesting, but after you're done with all the hard work, what do you really have? A: I have been doing some more digging on this, and came across how to inject Javascript in to the client when required. This will obviously play a huge part in making the controls more responsive and less round-trips to the server. For example: RegisterClientScriptBlock. Look forward to playing with this more, feel free to get invovled people!
ASP.NET Custom Controls and "Dynamic" Event Model
OK, I am not sure if the title it completely accurate, open to suggestions! I am in the process of creating an ASP.NET custom control, this is something that is still relatively new to me, so please bear with me. I am thinking about the event model. Since we are not using Web Controls there are no events being fired from buttons, rather I am manually calling __doPostBack with the appropriate arguments. However this can obviously mean that there are a lot of postbacks occuring when say, selecting options (which render differently when selected). In time, I will need to make this more Ajax-y and responsive, so I will need to change the event binding to call local Javascript. So, I was thinking I should be able to toggle the "mode" of the control, it can either use postback and handlle itself, or you can specify the Javascript function names to call instead of the doPostBack. What are your thoughts on this? Am I approaching the raising of the events from the control in the wrong way? (totally open to suggestions here!) How would you approach a similar problem? Edit - To Clarify I am creating a custom rendered control (i.e. inherits from WebControl). We are not using existnig Web Controls since we want complete control over the rendered output. AFAIK the only way to get a server side event to occur from a custom rendered control is to call doPostBack from the rendered elements (please correct if wrong!). ASP.NET MVC is not an option.
[ "Very odd. You're using ASP.NET server controls and custom controls, but you're not using web controls? And you're calling __doPostBack manually?\nDo you like to do things the hard way?\nIf I was still using the server control model rather than MVC, I would slap ASP.NET Ajax controls on that sucker and call it a day. What you're doing is like putting a blower on a model T. It may be fun and interesting, but after you're done with all the hard work, what do you really have?\n", "I have been doing some more digging on this, and came across how to inject Javascript in to the client when required. This will obviously play a huge part in making the controls more responsive and less round-trips to the server.\nFor example: RegisterClientScriptBlock.\nLook forward to playing with this more, feel free to get invovled people!\n" ]
[ 1, 1 ]
[]
[]
[ "asp.net", "custom_server_controls", "events" ]
stackoverflow_0000058827_asp.net_custom_server_controls_events.txt
Q: PHP performance considerations? I'm building a PHP site, but for now the only PHP I'm using is a half-dozen or so includes on certain pages. (I will probably use some database queries eventually.) Are simple include() statements a concern for speed or scaling, as opposed to static HTML? What kinds of things tend to cause a site to bog down? A: Certainly include() is slower than static pages. However, with modern systems you're not likely to see this as a bottleneck for a long time - if ever. The benefits of using includes to keep common parts of your site up to date outweigh the tiny performance hit, in my opinion (having different navigation on one page because you forgot to update it leads to a bad user experience, and thus bad feelings about your site/company/whatever). Using caching will really not help either - caching code is going to be slower than just an include(). The only time caching will benefit you is if you're doing computationally-intensive calculations (very rare, on web pages), or grabbing data from a database. A: Sounds like you are participating in a bit of premature optimization. If the application is not built, while performance concerns are good to be aware of, your primary concern should be getting the app written. Includes are a fact of life. Don't worry about number, worry about keeping your code well organized (PEAR folder structure is a lovely thing, if you don't know what I'm talking about look at the structure of the Zend Framework class files). Focus on getting the application written with a reasonable amount of abstraction. Group all of your DB calls into a class (or classes) so that you minimize code duplication (KISS principles and all) and when it comes time to refactor and optimize your queries they are centrally located. Also get started on some unit testing to prevent regression. Once the application is up and running, don't ask us what is faster or better since it depends on each application what your bottleneck will be. It may turn out that even though you have lots of includes, your loops are eating up your time, or whatever. Use XDebug and profile your code once its up and running. Look for the segments of code that are eating up a disproportionate amount of time then refactor. If you focus too much now on the performance hit between include and include_once you'll end up chasing a ghost when those curl requests running in sync are eating your breakfast. Though in the mean time, the best suggestions are look through the php.net manual and make sure if there's a built in function doing something you are trying to do, use it! PHP's C-based extensions will always be faster than any PHP code that you could write, and you'll be surprised how much of what you are trying to do is done already. But again, I cannot stress this enough, premature optimization is BAD!!! Just get your application up off the ground with good levels of abstraction, profile it, then fix what actually is eating up your time rather than fixing what you think might eat up your time. A: Strictly speaking, straight HTML will always serve faster than a server-side approach since the server doesn't have to do any interpretation of the code. To answer the bigger question, there are a number of things that will cause your site to bog down; there's just no specific threshold for when your code is causing the problem vs. PHP. (keep in mind that many of Yahoo's sites are PHP-driven, so don't think that PHP can't scale). One thing I've noticed is that the PHP-driven sites that are the slowest are the ones that include more than is necessary to display a specific page. OSCommerce (oscommerce.com) is one of the most popular PHP-driven shopping carts. It has a bad habit, however, of including all of their core functionality (just in case it's needed) on every single page. So even if you don't need to display an 'info box', the function is loaded. On the other hand, there are many PHP frameworks out there (such as CakePHP, Symfony, and CodeIgniter) that take a 'load it as you need it' approach. I would advise the following: Don't include more functionality than you need for a specific page Keep base functions separate (use an MVC approach when possible) Use require_once instead of include if you think you'll have nested includes (e.g. page A includes file B which includes file C). This will avoid including the same file more than once. It will also stop the process if a file can't be found; thus helping your troubleshooting process ;) Cache static pages as HTML if possible - to avoid having to reparse when things don't change A: Nah includes are fine, nothing to worry about there. You might want to think about tweaking your caching headers a bit at some point, but unless you're getting significant hits it should be no problem. Assuming this is all static data, you could even consider converting the whole site to static HTML (easiest way: write a script that grabs every page via the webserver and dumps it out in a matching dir structure) Most web applications are limited by the speed of their database (or whatever their external storage is, but 9/10 times that'll be a database), the application code is rarely cause for concern, and it doesn't sound like you're doing anything you need to worry about yet. A: Before you make any long-lasting decisions about how to structure the code for your site, I would recommend that you do some reading on the Model-View-Controller design pattern. While there are others this one appears to be gaining a great deal of ground in web development circles and certainly will be around for a while. You might want to take a look at some of the other design patterns suggested by Martin Fowler in his Patterns of Enterprise Application Architecture before making any final decisions about what sort of design will best fit your needs. Depending on the size and scope of your project, you may want to go with a ready-made framework for PHP like Zend Framework or PHP On Trax or you may decide to build your own solution. Specifically regarding the rendering of HTML content I would strongly recommend that you use some form of templating in order to keep your business logic separate from your display logic. I've found that this one simple rule in my development has saved me hours of work when one or the other needed to be changed. I've used http://www.smarty.net/">Smarty and I know that most of the frameworks out there either have a template system of their own or provide a plug-in architecture that allows you to use your own preferred method. As you look at possible solutions, I would recommend that you look for one that is capable of creating cached versions. Lastly, if you're concerned about speed on the back-end then I would highly recommend that you look at ways to minimize your calls your back-end data store (whether it be a database or just system files). Try to avoid loading and rendering too much content (say a large report stored in a table that contains hundreds of records) all at once. If possible look for ways to make the user interface load smaller bits of data at a time. And if you're specifically concerned about the actual load time of your html content and its CSS, Javascript or other dependencies I would recommend that you review these suggestions from the guys at Yahoo!. A: To add on what JayTee mentioned - loading functionality when you need it. If you're not using any of the frameworks that do this automatically, you might want to look into the __autoload() functionality that was introduced in PHP5 - basically, your own logic can be invoked when you instantiate a particular class if it's not already loaded. This gives you a chance to include() a file that defines that class on-demand. A: The biggest thing you can do to speed up your application is to use an Opcode cache, like APC. There's an excellent list and description available on Wikipedia. As far as simple includes are concerned, be careful not to include too many files on each request as the disk I/O can cause your application not to scale well. A few dozen includes should be fine, but it's generally a good idea to package your most commonly included files into a single script so you only have one include. The cost in memory of having a few classes here and there you don't need loaded will be better than the cost of disk I/O for including hundreds of smaller files.
PHP performance considerations?
I'm building a PHP site, but for now the only PHP I'm using is a half-dozen or so includes on certain pages. (I will probably use some database queries eventually.) Are simple include() statements a concern for speed or scaling, as opposed to static HTML? What kinds of things tend to cause a site to bog down?
[ "Certainly include() is slower than static pages. However, with modern systems you're not likely to see this as a bottleneck for a long time - if ever. The benefits of using includes to keep common parts of your site up to date outweigh the tiny performance hit, in my opinion (having different navigation on one page because you forgot to update it leads to a bad user experience, and thus bad feelings about your site/company/whatever).\nUsing caching will really not help either - caching code is going to be slower than just an include(). The only time caching will benefit you is if you're doing computationally-intensive calculations (very rare, on web pages), or grabbing data from a database.\n", "Sounds like you are participating in a bit of premature optimization. If the application is not built, while performance concerns are good to be aware of, your primary concern should be getting the app written.\nIncludes are a fact of life. Don't worry about number, worry about keeping your code well organized (PEAR folder structure is a lovely thing, if you don't know what I'm talking about look at the structure of the Zend Framework class files).\nFocus on getting the application written with a reasonable amount of abstraction. Group all of your DB calls into a class (or classes) so that you minimize code duplication (KISS principles and all) and when it comes time to refactor and optimize your queries they are centrally located. Also get started on some unit testing to prevent regression.\nOnce the application is up and running, don't ask us what is faster or better since it depends on each application what your bottleneck will be. It may turn out that even though you have lots of includes, your loops are eating up your time, or whatever. Use XDebug and profile your code once its up and running. Look for the segments of code that are eating up a disproportionate amount of time then refactor. If you focus too much now on the performance hit between include and include_once you'll end up chasing a ghost when those curl requests running in sync are eating your breakfast.\nThough in the mean time, the best suggestions are look through the php.net manual and make sure if there's a built in function doing something you are trying to do, use it! PHP's C-based extensions will always be faster than any PHP code that you could write, and you'll be surprised how much of what you are trying to do is done already.\nBut again, I cannot stress this enough, premature optimization is BAD!!! Just get your application up off the ground with good levels of abstraction, profile it, then fix what actually is eating up your time rather than fixing what you think might eat up your time.\n", "Strictly speaking, straight HTML will always serve faster than a server-side approach since the server doesn't have to do any interpretation of the code.\nTo answer the bigger question, there are a number of things that will cause your site to bog down; there's just no specific threshold for when your code is causing the problem vs. PHP. (keep in mind that many of Yahoo's sites are PHP-driven, so don't think that PHP can't scale).\nOne thing I've noticed is that the PHP-driven sites that are the slowest are the ones that include more than is necessary to display a specific page. OSCommerce (oscommerce.com) is one of the most popular PHP-driven shopping carts. It has a bad habit, however, of including all of their core functionality (just in case it's needed) on every single page. So even if you don't need to display an 'info box', the function is loaded.\nOn the other hand, there are many PHP frameworks out there (such as CakePHP, Symfony, and CodeIgniter) that take a 'load it as you need it' approach.\nI would advise the following:\n\nDon't include more functionality than you need for a specific page\nKeep base functions separate (use an MVC approach when possible)\nUse require_once instead of include if you think you'll have nested includes (e.g. page A includes file B which includes file C). This will avoid including the same file more than once. It will also stop the process if a file can't be found; thus helping your troubleshooting process ;)\nCache static pages as HTML if possible - to avoid having to reparse when things don't change\n\n", "Nah includes are fine, nothing to worry about there. \nYou might want to think about tweaking your caching headers a bit at some point, but unless you're getting significant hits it should be no problem. Assuming this is all static data, you could even consider converting the whole site to static HTML (easiest way: write a script that grabs every page via the webserver and dumps it out in a matching dir structure)\nMost web applications are limited by the speed of their database (or whatever their external storage is, but 9/10 times that'll be a database), the application code is rarely cause for concern, and it doesn't sound like you're doing anything you need to worry about yet.\n", "Before you make any long-lasting decisions about how to structure the code for your site, I would recommend that you do some reading on the Model-View-Controller design pattern. While there are others this one appears to be gaining a great deal of ground in web development circles and certainly will be around for a while. You might want to take a look at some of the other design patterns suggested by Martin Fowler in his Patterns of Enterprise Application Architecture before making any final decisions about what sort of design will best fit your needs. \nDepending on the size and scope of your project, you may want to go with a ready-made framework for PHP like Zend Framework or PHP On Trax or you may decide to build your own solution. \nSpecifically regarding the rendering of HTML content I would strongly recommend that you use some form of templating in order to keep your business logic separate from your display logic. I've found that this one simple rule in my development has saved me hours of work when one or the other needed to be changed. I've used http://www.smarty.net/\">Smarty and I know that most of the frameworks out there either have a template system of their own or provide a plug-in architecture that allows you to use your own preferred method. As you look at possible solutions, I would recommend that you look for one that is capable of creating cached versions.\nLastly, if you're concerned about speed on the back-end then I would highly recommend that you look at ways to minimize your calls your back-end data store (whether it be a database or just system files). Try to avoid loading and rendering too much content (say a large report stored in a table that contains hundreds of records) all at once. If possible look for ways to make the user interface load smaller bits of data at a time. \nAnd if you're specifically concerned about the actual load time of your html content and its CSS, Javascript or other dependencies I would recommend that you review these suggestions from the guys at Yahoo!.\n", "To add on what JayTee mentioned - loading functionality when you need it. If you're not using any of the frameworks that do this automatically, you might want to look into the __autoload() functionality that was introduced in PHP5 - basically, your own logic can be invoked when you instantiate a particular class if it's not already loaded. This gives you a chance to include() a file that defines that class on-demand. \n", "The biggest thing you can do to speed up your application is to use an Opcode cache, like APC. There's an excellent list and description available on Wikipedia.\nAs far as simple includes are concerned, be careful not to include too many files on each request as the disk I/O can cause your application not to scale well. A few dozen includes should be fine, but it's generally a good idea to package your most commonly included files into a single script so you only have one include. The cost in memory of having a few classes here and there you don't need loaded will be better than the cost of disk I/O for including hundreds of smaller files.\n" ]
[ 5, 4, 3, 2, 1, 0, 0 ]
[]
[]
[ "performance", "php", "scalability" ]
stackoverflow_0000112786_performance_php_scalability.txt
Q: Limiting a group of checkboxes to a certain amount of checks I have a group of checkboxes that I only want to allow a set amount to be checked at any one time. If the newly checked checkbox pushes the count over the limit, I'd like the oldest checkbox to be automatically unchecked. The group of checkboxes all use the same event handler shown below. I have achieved the functionality with a Queue, but it's pretty messy when I have to remove an item from the middle of the queue and I think there's a more elegant way. I especially don't like converting the queue to a list just to call one method before I convert the list back to a queue. Is there a better way to do this? Is it a good idea to unhook are rehook the event handlers like I did. Here's the code. private Queue<CheckBox> favAttributesLimiter - new Queue<CheckBox>(); private const int MaxFavoredAttributes = 5; private void favoredAttributes_CheckedChanged(object sender, EventArgs e) { CheckBox cb = (CheckBox)sender; if (cb.Checked) { if (favAttributesLimiter.Count == MaxFavoredAttributes) { CheckBox oldest = favAttributesLimiter.Dequeue(); oldest.CheckedChanged -= favoredAttributes_CheckedChanged; oldest.Checked = false; oldest.CheckedChanged += new EventHandler(favoredAttributes_CheckedChanged); } favAttributesLimiter.Enqueue(cb); } else // cb.Checked == false { if (favAttributesLimiter.Contains(cb)) { var list = favAttributesLimiter.ToList(); list.Remove(cb); favAttributesLimiter=new Queue<CheckBox>(list); } } } Edit: Chakrit answered my actual question with a better replacement for Queue(Of T). However, the argument that my idea of unchecking boxes was actually a bad idea was quite convincing. I'm leaving Chakrit's answer as accepted, but I've voted up the other answers because they're offering a more consistent and usable solution in the eyes of the user. A: Just in case you haven't thought of it this way around. For a usability point of view, presumably you have some text saying something like "click no more than 4 check boxes". In which case, why not simply keep a count of the number of checked boxes, and prevent any changes to the 5th box (until of course there are only 3 check boxes). A: One thing to ask yourself is: do you really want to implement this type of behavior with checkboxes? Checkboxes already have a well-understood behavior from a user point of view, and having a seemingly random box become unchecked when a new one is checked will likely be very confusing or maybe even frustrating for the average user. Maybe consider something like a listbox with add/remove buttons, where the design of the list gives the user a visual cue that there is a max of (say) four items. As a reference, I'm thinking something along the lines of the toolbar customizing dialog in IE. Perhaps not the answer you were looking for, but something to consider. A: I think you are looking for a LinkedList. Use AddLast instead of Enqueue and RemoveFirst instead of Dequeue and for removing something in the middle, just use a normal Remove. A: What I've done before is have a multicolumn selection menu like this:            <----> choices:selected choice-1-empty box- choice-2-empty box- choice-3-empty box- choice-4-empty box-                   Then people could highlight a "choice-1" and hit the right button. Suddenly the second column would be populated by the items in the first. Then you can disable the arrow after 3 choices have been added, and pop up a message saying, "You may only select three choices." This makes far more sense compared to other options. It would be far easier for the user. A: Is it a good idea to unhook are rehook the event handlers like I did. That depends. Is it Windows Forms? Windows Forms run on top of the WinAPI which mean that event handler is really just a function called by the message dispatch loop in the main thread. As such the functions do not need to be re-entrant and it is "safe". But, you must do your error handling and catch any exceptions like failed allocations within your event handler or your application will terminate. A: If you ask a user to pick form a list of options and limit the number of choices it is likely that the first choice is there primary choice. e.g. Pick two, you will never have any of what you don't choose: Money Power Sex Excitement Gadgets Army of Coders. Was your first choice you primary choice? If you want to use check boxes, simply disable all the unchecked ones when the the second one is checked.
Limiting a group of checkboxes to a certain amount of checks
I have a group of checkboxes that I only want to allow a set amount to be checked at any one time. If the newly checked checkbox pushes the count over the limit, I'd like the oldest checkbox to be automatically unchecked. The group of checkboxes all use the same event handler shown below. I have achieved the functionality with a Queue, but it's pretty messy when I have to remove an item from the middle of the queue and I think there's a more elegant way. I especially don't like converting the queue to a list just to call one method before I convert the list back to a queue. Is there a better way to do this? Is it a good idea to unhook are rehook the event handlers like I did. Here's the code. private Queue<CheckBox> favAttributesLimiter - new Queue<CheckBox>(); private const int MaxFavoredAttributes = 5; private void favoredAttributes_CheckedChanged(object sender, EventArgs e) { CheckBox cb = (CheckBox)sender; if (cb.Checked) { if (favAttributesLimiter.Count == MaxFavoredAttributes) { CheckBox oldest = favAttributesLimiter.Dequeue(); oldest.CheckedChanged -= favoredAttributes_CheckedChanged; oldest.Checked = false; oldest.CheckedChanged += new EventHandler(favoredAttributes_CheckedChanged); } favAttributesLimiter.Enqueue(cb); } else // cb.Checked == false { if (favAttributesLimiter.Contains(cb)) { var list = favAttributesLimiter.ToList(); list.Remove(cb); favAttributesLimiter=new Queue<CheckBox>(list); } } } Edit: Chakrit answered my actual question with a better replacement for Queue(Of T). However, the argument that my idea of unchecking boxes was actually a bad idea was quite convincing. I'm leaving Chakrit's answer as accepted, but I've voted up the other answers because they're offering a more consistent and usable solution in the eyes of the user.
[ "Just in case you haven't thought of it this way around. \nFor a usability point of view, presumably you have some text saying something like \"click no more than 4 check boxes\".\nIn which case, why not simply keep a count of the number of checked boxes, and prevent any changes to the 5th box (until of course there are only 3 check boxes). \n", "One thing to ask yourself is: do you really want to implement this type of behavior with checkboxes? Checkboxes already have a well-understood behavior from a user point of view, and having a seemingly random box become unchecked when a new one is checked will likely be very confusing or maybe even frustrating for the average user.\nMaybe consider something like a listbox with add/remove buttons, where the design of the list gives the user a visual cue that there is a max of (say) four items. As a reference, I'm thinking something along the lines of the toolbar customizing dialog in IE.\nPerhaps not the answer you were looking for, but something to consider.\n", "I think you are looking for a LinkedList.\nUse AddLast instead of Enqueue and RemoveFirst instead of Dequeue and for removing something in the middle, just use a normal Remove.\n", "What I've done before is have a multicolumn selection menu like this: \n           <---->\n\n\nchoices:selected\nchoice-1-empty box-\nchoice-2-empty box-\nchoice-3-empty box-\nchoice-4-empty box-\n                 \n\n\n\nThen people could highlight a \"choice-1\" and hit the right button. Suddenly the second column would be populated by the items in the first. Then you can disable the arrow after 3 choices have been added, and pop up a message saying, \"You may only select three choices.\" This makes far more sense compared to other options. It would be far easier for the user.\n", "\nIs it a good idea to unhook are rehook\n the event handlers like I did.\n\nThat depends.\nIs it Windows Forms? Windows Forms run on top of the WinAPI which mean that event handler is really just a function called by the message dispatch loop in the main thread. As such the functions do not need to be re-entrant and it is \"safe\".\nBut, you must do your error handling and catch any exceptions like failed allocations within your event handler or your application will terminate.\n", "If you ask a user to pick form a list of options and limit the number of choices it is likely that the first choice is there primary choice.\ne.g. Pick two, you will never have any of what you don't choose:\n\nMoney\nPower\nSex\nExcitement\nGadgets\nArmy of Coders.\n\nWas your first choice you primary choice?\nIf you want to use check boxes, simply disable all the unchecked ones when the the second one is checked.\n" ]
[ 4, 3, 2, 1, 1, 0 ]
[]
[]
[ ".net", "user_interface", "winforms" ]
stackoverflow_0000110385_.net_user_interface_winforms.txt
Q: Beginning TDD - Challenges? Solutions? Recommendations? OK, I know there have already been questions about getting started with TDD.. However, I guess I kind of know the general concensus is to just do it , However, I seem to have the following problems getting my head into the game: When working with collections, do will still test for obvious add/remove/inserts successful, even when based on Generics etc where we kind of "know" its going to work? Some tests seem to take forever to implement.. Such as when working with string output, is there a "better" way to go about this sort of thing? (e.g. test the object model before parsing, break parsing down into small ops and test there) In my mind you should always test the "end result" but that can vary wildly and be tedious to set up. I don't have a testing framework to use (work wont pay for one) so I can "practice" more. Are there any good ones that are free for commercial use? (at the moment I am using good 'ol Debug.Assert :) Probably the biggest.. Sometimes I don't know what to expect NOT to happen.. I mean, you get your green light but I am always concerned that I may be missing a test.. Do you dig deeper to try and break the code, or leave it be and wait for it all fall over later (which will cost more).. So basically what I am looking for here is not a " just do it " but more " I did this, had problems with this, solved them by this ".. The personal experience :) A: First, it is alright and normal to feel frustrated when you first start trying to use TDD in your coding style. Just don't get discouraged and quit, you will need to give it some time. It is a major paradigm shift in how we think about solving a problem in code. I like to think of it like when we switched from procedural to object oriented programming. Secondly, I feel that test driven development is first and foremost a design activity that is used to flesh out the design of a component by creating a test that first describes the API it is going to expose and how you are going to consume it's functionality. The test will help shape and mold the System Under Test until you have been able to encapsulate enough functionality to satisfy whatever tasks you happen to be working on. Taking the above paragraph in mind, let's look at your questions: If I am using a collection in my system under test, then I will setup an expectation to make sure that the code was called to insert the item and then assert the count of the collection. I don't necessarily test the Add method on my internal list. I just make sure it was called when the method that adds the item is called. I do this by adding a mocking framework into the mix, with my testing framework. Testing strings as output can be tedious. You cannot account for every outcome. You can only test what you expect based on the functionality of the system under test. You should always break your tests down to the smallest element that it is testing. Which means you will have a lot of tests, but tests that are small and fast and only test what they should, nothing else. There are a lot of open source testing frameworks to choose from. I am not going to argue which is best. Just find one you like and start using it. MbUnit nUnit xUnit All you can do is setup your tests to account for what you want to happen. If a scenario comes up that introduces a bug in your functionality, at least you have a test around the functionality to add that scenario into the test and then change your functionality until the test passes. One way to find where we may have missed a test is to use code coverage. I introduced you to the mocking term in the answer for question one. When you introduce mocking into your arsenal for TDD, it dramatically makes testing easier to abstract away the parts that are not part of the system under test. Here are some resources on the mocking frameworks out there are: Moq: Open Source RhinoMocks: Open Source TypeMock: Commercial Product NSubstitute: Open Source One way to help in using TDD, besides reading about the process, is to watch people do it. I recommend in watching the screen casts by JP Boodhoo on DNRTV. Check these out: Jean Paul Boodhoo on Test Driven Development Part 1 Jean Paul Boodhoo on Test Driven Development Part 2 Jean Paul Boodhoo on Demystifying Design Patterns Part 1 Jean Paul Boodhoo on Demystifying Design Patterns Part 2 Jean Paul Boodhoo on Demystifying Design Patterns Part 3 Jean Paul Boodhoo on Demystifying Design Patterns Part 4 Jean Paul Boodhoo on Demystifying Design Patterns Part 5 OK, these will help you see how the terms I introduced are used. It will also introduce another tool called Resharper and how it can facilitate the TDD process. I couldn't recommend this tool enough when doing TDD. Seems like you are learning the process and you are just finding some of the problems that have already been solved with using other tools. I think I would be doing an injustice to the community, if I didn't update this by adding Kent Beck's new series on Test Driven Development on Pragmatic Programmer. A: From my own experience: Only test your own code, not the underlying framework's code. So if you're using a generic list then there's no need to test Add, Remove etc. There is no 2. Look over there! Monkeys!!! NUnit is the way to go. You definitely can't test every outcome. I test for what I expect to happen, and then test a few edge cases where I expect to get exceptions or invalid responses. If a bug comes up down the track because of something you forgot to test, the first thing you should do (before trying to fix the bug) is write a test to prove that the bug exists. A: My take on this is following: +1 for not testing framework code, but you may still need to test classes derived from framework classes. If some class/method is cumbersome to test it may be strong indication that something is wrong with desing. I try to follow "1 class - 1 responsibility, 1 method - 1 action" principle. That way you will be able to test complex methods much easier by doing that in smaller portions. +1 for xUnit. For Java you may also consider TestNG. TDD is not single event it is a process. So do not try to envision everything from the beginning, but make sure that every bug found in code is actually covered by test once discovered. A: I think the most important thing with (and actually one of the great outcomes of, in a somewhat recursive manner) TDD is successful management of dependencies. You have to make sure that modules are tested in isolation with no elaborate setup needed. For example, if you're testing a component that eventually sends an email, make the email sender a dependency so that you can mock it in your tests. This leads to a second point - mocks are your friends. Get familiarized with mocking frameworks and the style of tests they promote (behavioral, as opposed to the classic state based), and the design choices they encourage (The "Tell, don't ask" principle). A: I found that the principles illustrated in the Three Index Cards to Easily Remember the Essence of TDD is a good guide. Anyway, to answer your questions You don't have to test something you "know" is going to work, unless you wrote it. You didn't write generics, Microsoft did ;) If you need to do so much for your test, maybe your object/method is doing too much as well. Download TestDriven.NET to immediately start unit testing on your Visual Studio, (except if it's an Express edition) Just test the correct thing that will happen. You don't need to test everything that can go wrong: you have to wait for your tests to fail for that. Seriously, just do it, dude. :) A: I am no expert at TDD, by any means, but here is my view: If it is completely trivial (getters/setters etc) do not test it, unless you don't have confidence in the code for some reason. If it is a quite simple, but non-trivial method, test it. The test is probably easy to write anyway. When it comes to what to expect not to happen, I would say that if a certain potential problem is the responsibility of the class you are testing, you need to test that it handles it correctly. If it is not the current class' responsibility, don't test it. The xUnit testing frameworks are often free to use, so if you are a .Net guy, check out NUnit, and if Java is your thing check out JUnit. A: The above advice is good, and if you want a list of free frameworks you have to look no farther than the xUnit Frameworks List on Wikipedia. Hope this helps :) A: In my opinion (your mileage may vary): 1- If you didn't write it don't test it. If you wrote it and you don't have a test for it it doesn't exist. 3- As everyone's said, xUnit's free and great. 2 & 4- Deciding exactly what to test is one of those things you can debate about with yourself forever. I try to draw this line using the principles of design by contract. Check out 'Object Oriented Software Construction" or "The Pragmatic Programmer" for details on it. A: Keep tests short, "atomic". Test the smallest assumption in each test. Make each TestMethod independent, for integration tests I even create a new database for each method. If you need to build some data for each test use an "Init" method. Use mocks to isolate the class your testing from it's dependencies. I always think "what's the minimum amount of code I need to write to prove this works for all cases ?" A: Over the last year I have become more and more convinced of the benefits of TDD. The things that I have learned along the way: 1) dependency injection is your friend. I'm not talking about inversion of control containers and frameworks to assemble plugin architectures, just passing dependencies into the constructor of the object under test. This pays back huge dividends in the testability of your code. 2) I set out with the passion / zealotry of the convert and grabbed a mocking framework and set about using mocks for everything I could. This led to brittle tests that required lots of painful set up and would fall over as soon as I started any refactoring. Use the correct kind of test double. Fakes where you just need to honour an interface, stubs to feed data back to the object under test, mock only where you care about interaction. 3) Test should be small. Aim for one assertion or interaction being tested in each test. I try to do this and mostly I'm there. This is about robustness of test code and also about the amount of complexity in a test when you need to revisit it later. The biggest problem I have had with TDD has been working with a specification from a standards body and a third party implementation of that standard that was the de-facto standard. I coded lots of really nice unit tests to the letter of the specification only to find that the implementation on the other side of the fence saw the standard as more of an advisory document. They played quite loose with it. The only way to fix this was to test with the implementation as well as the unit tests and refactor the tests and code as necessary. The real problem was the belief on my part that as long as I had code and unit tests all was good. Not so. You need to be building actual outputs and performing functional testing at the same time as you are unit testing. Small pieces of benefit all the way through the process - into users or stakeholders hands. A: Just as an addition to this, I thought I would say I have put a blog post up on my thoughts on getting started with testing (following this discussion and my own research), since it may be useful to people viewing this thread. "TDD – Getting Started with Test-Driven Development" - I have got some great feedback so far and would really appreciate any more that you guys have to offer. I hope this helps! :)
Beginning TDD - Challenges? Solutions? Recommendations?
OK, I know there have already been questions about getting started with TDD.. However, I guess I kind of know the general concensus is to just do it , However, I seem to have the following problems getting my head into the game: When working with collections, do will still test for obvious add/remove/inserts successful, even when based on Generics etc where we kind of "know" its going to work? Some tests seem to take forever to implement.. Such as when working with string output, is there a "better" way to go about this sort of thing? (e.g. test the object model before parsing, break parsing down into small ops and test there) In my mind you should always test the "end result" but that can vary wildly and be tedious to set up. I don't have a testing framework to use (work wont pay for one) so I can "practice" more. Are there any good ones that are free for commercial use? (at the moment I am using good 'ol Debug.Assert :) Probably the biggest.. Sometimes I don't know what to expect NOT to happen.. I mean, you get your green light but I am always concerned that I may be missing a test.. Do you dig deeper to try and break the code, or leave it be and wait for it all fall over later (which will cost more).. So basically what I am looking for here is not a " just do it " but more " I did this, had problems with this, solved them by this ".. The personal experience :)
[ "First, it is alright and normal to feel frustrated when you first start trying to use TDD in your coding style. Just don't get discouraged and quit, you will need to give it some time. It is a major paradigm shift in how we think about solving a problem in code. I like to think of it like when we switched from procedural to object oriented programming.\nSecondly, I feel that test driven development is first and foremost a design activity that is used to flesh out the design of a component by creating a test that first describes the API it is going to expose and how you are going to consume it's functionality. The test will help shape and mold the System Under Test until you have been able to encapsulate enough functionality to satisfy whatever tasks you happen to be working on.\nTaking the above paragraph in mind, let's look at your questions:\n\nIf I am using a collection in my system under test, then I will setup an expectation to make sure that the code was called to insert the item and then assert the count of the collection. I don't necessarily test the Add method on my internal list. I just make sure it was called when the method that adds the item is called. I do this by adding a mocking framework into the mix, with my testing framework.\nTesting strings as output can be tedious. You cannot account for every outcome. You can only test what you expect based on the functionality of the system under test. You should always break your tests down to the smallest element that it is testing. Which means you will have a lot of tests, but tests that are small and fast and only test what they should, nothing else.\nThere are a lot of open source testing frameworks to choose from. I am not going to argue which is best. Just find one you like and start using it.\n\n\nMbUnit\nnUnit\nxUnit\n\nAll you can do is setup your tests to account for what you want to happen. If a scenario comes up that introduces a bug in your functionality, at least you have a test around the functionality to add that scenario into the test and then change your functionality until the test passes. One way to find where we may have missed a test is to use code coverage.\n\nI introduced you to the mocking term in the answer for question one. When you introduce mocking into your arsenal for TDD, it dramatically makes testing easier to abstract away the parts that are not part of the system under test. Here are some resources on the mocking frameworks out there are:\n\nMoq: Open Source\nRhinoMocks: Open Source\nTypeMock: Commercial Product\nNSubstitute: Open Source\n\nOne way to help in using TDD, besides reading about the process, is to watch people do it. I recommend in watching the screen casts by JP Boodhoo on DNRTV. Check these out:\n\nJean Paul Boodhoo on Test Driven Development Part 1\nJean Paul Boodhoo on Test Driven Development Part 2\nJean Paul Boodhoo on Demystifying Design Patterns Part 1\nJean Paul Boodhoo on Demystifying Design Patterns Part 2\nJean Paul Boodhoo on Demystifying Design Patterns Part 3\nJean Paul Boodhoo on Demystifying Design Patterns Part 4\nJean Paul Boodhoo on Demystifying Design Patterns Part 5\n\nOK, these will help you see how the terms I introduced are used. It will also introduce another tool called Resharper and how it can facilitate the TDD process. I couldn't recommend this tool enough when doing TDD. Seems like you are learning the process and you are just finding some of the problems that have already been solved with using other tools.\nI think I would be doing an injustice to the community, if I didn't update this by adding Kent Beck's new series on Test Driven Development on Pragmatic Programmer.\n", "From my own experience:\n\nOnly test your own code, not the underlying framework's code. So if you're using a generic list then there's no need to test Add, Remove etc.\nThere is no 2. Look over there! Monkeys!!!\nNUnit is the way to go.\nYou definitely can't test every outcome. I test for what I expect to happen, and then test a few edge cases where I expect to get exceptions or invalid responses. If a bug comes up down the track because of something you forgot to test, the first thing you should do (before trying to fix the bug) is write a test to prove that the bug exists.\n\n", "My take on this is following:\n\n+1 for not testing framework code, but you may still need to test classes derived from framework classes.\nIf some class/method is cumbersome to test it may be strong indication that something is wrong with desing. I try to follow \"1 class - 1 responsibility, 1 method - 1 action\" principle. That way you will be able to test complex methods much easier by doing that in smaller portions.\n+1 for xUnit. For Java you may also consider TestNG.\nTDD is not single event it is a process. So do not try to envision everything from the beginning, but make sure that every bug found in code is actually covered by test once discovered.\n\n", "I think the most important thing with (and actually one of the great outcomes of, in a somewhat recursive manner) TDD is successful management of dependencies. You have to make sure that modules are tested in isolation with no elaborate setup needed. For example, if you're testing a component that eventually sends an email, make the email sender a dependency so that you can mock it in your tests.\nThis leads to a second point - mocks are your friends. Get familiarized with mocking frameworks and the style of tests they promote (behavioral, as opposed to the classic state based), and the design choices they encourage (The \"Tell, don't ask\" principle).\n", "I found that the principles illustrated in the Three Index Cards to Easily Remember the Essence of TDD is a good guide.\nAnyway, to answer your questions\n\nYou don't have to test something you \"know\" is going to work, unless you wrote it. You didn't write generics, Microsoft did ;)\nIf you need to do so much for your test, maybe your object/method is doing too much as well.\nDownload TestDriven.NET to immediately start unit testing on your Visual Studio, (except if it's an Express edition)\nJust test the correct thing that will happen. You don't need to test everything that can go wrong: you have to wait for your tests to fail for that.\n\nSeriously, just do it, dude. :)\n", "I am no expert at TDD, by any means, but here is my view:\n\nIf it is completely trivial (getters/setters etc) do not test it, unless you don't have confidence in the code for some reason.\nIf it is a quite simple, but non-trivial method, test it. The test is probably easy to write anyway.\nWhen it comes to what to expect not to happen, I would say that if a certain potential problem is the responsibility of the class you are testing, you need to test that it handles it correctly. If it is not the current class' responsibility, don't test it.\n\nThe xUnit testing frameworks are often free to use, so if you are a .Net guy, check out NUnit, and if Java is your thing check out JUnit.\n", "The above advice is good, and if you want a list of free frameworks you have to look no farther than the xUnit Frameworks List on Wikipedia. Hope this helps :)\n", "In my opinion (your mileage may vary):\n1- If you didn't write it don't test it. If you wrote it and you don't have a test for it it doesn't exist. \n3- As everyone's said, xUnit's free and great.\n2 & 4- Deciding exactly what to test is one of those things you can debate about with yourself forever. I try to draw this line using the principles of design by contract. Check out 'Object Oriented Software Construction\" or \"The Pragmatic Programmer\" for details on it.\n", "Keep tests short, \"atomic\". Test the smallest assumption in each test. Make each TestMethod independent, for integration tests I even create a new database for each method. If you need to build some data for each test use an \"Init\" method. Use mocks to isolate the class your testing from it's dependencies. \nI always think \"what's the minimum amount of code I need to write to prove this works for all cases ?\"\n", "Over the last year I have become more and more convinced of the benefits of TDD.\nThe things that I have learned along the way: \n1) dependency injection is your friend. I'm not talking about inversion of control containers and frameworks to assemble plugin architectures, just passing dependencies into the constructor of the object under test. This pays back huge dividends in the testability of your code.\n2) I set out with the passion / zealotry of the convert and grabbed a mocking framework and set about using mocks for everything I could. This led to brittle tests that required lots of painful set up and would fall over as soon as I started any refactoring. Use the correct kind of test double. Fakes where you just need to honour an interface, stubs to feed data back to the object under test, mock only where you care about interaction.\n3) Test should be small. Aim for one assertion or interaction being tested in each test. I try to do this and mostly I'm there. This is about robustness of test code and also about the amount of complexity in a test when you need to revisit it later.\nThe biggest problem I have had with TDD has been working with a specification from a standards body and a third party implementation of that standard that was the de-facto standard. I coded lots of really nice unit tests to the letter of the specification only to find that the implementation on the other side of the fence saw the standard as more of an advisory document. They played quite loose with it. The only way to fix this was to test with the implementation as well as the unit tests and refactor the tests and code as necessary. The real problem was the belief on my part that as long as I had code and unit tests all was good. Not so. You need to be building actual outputs and performing functional testing at the same time as you are unit testing. Small pieces of benefit all the way through the process - into users or stakeholders hands.\n", "Just as an addition to this, I thought I would say I have put a blog post up on my thoughts on getting started with testing (following this discussion and my own research), since it may be useful to people viewing this thread.\n\"TDD – Getting Started with Test-Driven Development\" - I have got some great feedback so far and would really appreciate any more that you guys have to offer.\nI hope this helps! :)\n" ]
[ 50, 6, 2, 2, 2, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "language_agnostic", "tdd", "unit_testing" ]
stackoverflow_0000024965_language_agnostic_tdd_unit_testing.txt
Q: How not to repeat yourself across projects and/or languages I'm working on several distinct but related projects in different programming languages. Some of these projects need to parse filenames written by other projects, and expect a certain filename pattern. This pattern is now hardcoded in several places and in several languages, making it a maintenance bomb. It is fairly easy to define this pattern exactly once in a given project, but what are the techniques for defining it once and for all for all projects and for all languages in use? A: Creating a Domain Specific Language, then compile that into the code for each of the target languages that you are using would be the best solution (and most elegant). Its not difficult to make a DSL - wither embed it in something (like inside Ruby since its the 'in' thing right now, or another language like LISP/Haskell...), or create a grammar from scratch (use Antlr?). It seems like the project is large, then this path is worth your while. A: I'd store the pattern in a simple text file and, depending on a particular project: Embed it in the source at build time (preprocessing) If the above is not an option, treat it as a config file read at runtime Edit: I assume the pattern is something no more complicated than a regex, otherwise I'd go with the DSL solution from another answer. A: You could use a common script, process or web service for generating the file names (depending on your set-up). A: I don't know which languages you are speaking about but most of languages can use external dynamic libraries dlls/shared objects and export common functionality from this library. For example you implement function get file name in simple c lib and use acrros rest of languages. Another option will be to create common code dynamically as part of the build process for each language this should not be to complex. I will suggest using dynamic link approach if feasible (you did not give enough information to determine this),since maintaining this solution will be much easier then maintaining code generation for different languages. A: Put the pattern in a database - the easiest and comfortable way could be using XML database. This database will be accessible by all the projects and they will read the pattern from there
How not to repeat yourself across projects and/or languages
I'm working on several distinct but related projects in different programming languages. Some of these projects need to parse filenames written by other projects, and expect a certain filename pattern. This pattern is now hardcoded in several places and in several languages, making it a maintenance bomb. It is fairly easy to define this pattern exactly once in a given project, but what are the techniques for defining it once and for all for all projects and for all languages in use?
[ "Creating a Domain Specific Language, then compile that into the code for each of the target languages that you are using would be the best solution (and most elegant). \nIts not difficult to make a DSL - wither embed it in something (like inside Ruby since its the 'in' thing right now, or another language like LISP/Haskell...), or create a grammar from scratch (use Antlr?). It seems like the project is large, then this path is worth your while. \n", "I'd store the pattern in a simple text file and, depending on a particular project:\n\nEmbed it in the source at build time (preprocessing)\nIf the above is not an option, treat it as a config file read at runtime\n\nEdit: I assume the pattern is something no more complicated than a regex, otherwise I'd go with the DSL solution from another answer.\n", "You could use a common script, process or web service for generating the file names (depending on your set-up).\n", "I don't know which languages you are speaking about but most of languages can use external dynamic libraries dlls/shared objects and export common functionality from this library. \nFor example you implement function get file name in simple c lib and use acrros rest of languages.\nAnother option will be to create common code dynamically as part of the build process for each language this should not be to complex.\nI will suggest using dynamic link approach if feasible (you did not give enough information to determine this),since maintaining this solution will be much easier then maintaining code generation for different languages. \n", "Put the pattern in a database - the easiest and comfortable way could be using XML database. This database will be accessible by all the projects and they will read the pattern from there\n" ]
[ 1, 1, 1, 1, 0 ]
[]
[]
[ "dry", "maintainability" ]
stackoverflow_0000113696_dry_maintainability.txt
Q: In MATLAB, can a class method act as a uicontrol callback without being public? In MATLAB 2008a, is there a way to allow a class method to act as a uicontrol callback function without having to make the method public? Conceptually, the method should not be public because it should never be called by a user of the class. It should only be called as a result of a UI event triggering a callback. However, if I set the method's access to private or protected, the callback doesn't work. My class is derived from hgsetget and is defined using the 2008a classdef syntax. The uicontrol code looks something like: methods (Access = public) function this = MyClass(args) this.someClassProperty = uicontrol(property1, value1, ... , 'Callback', ... {@(src, event)myCallbackMethod(this, src, event)}); % the rest of the class constructor code end end The callback code looks like: methods (Access = private) % This doesn't work because it's private % It works just fine if I make it public instead, but that's wrong conceptually. function myCallbackMethod(this, src, event) % do something end end A: Storing the function handle of the callback as a private property seems to workaround the problem. Try this: classdef MyClass properties handle; end properties (Access=private) callback; end methods function this = MyClass(args) this.callback = @myCallbackMethod; this.handle = uicontrol('Callback', ... {@(src, event)myCallbackMethod(this, src, event)}); end end methods (Access = private) function myCallbackMethod(this, src, event) disp('Hello world!'); end end end
In MATLAB, can a class method act as a uicontrol callback without being public?
In MATLAB 2008a, is there a way to allow a class method to act as a uicontrol callback function without having to make the method public? Conceptually, the method should not be public because it should never be called by a user of the class. It should only be called as a result of a UI event triggering a callback. However, if I set the method's access to private or protected, the callback doesn't work. My class is derived from hgsetget and is defined using the 2008a classdef syntax. The uicontrol code looks something like: methods (Access = public) function this = MyClass(args) this.someClassProperty = uicontrol(property1, value1, ... , 'Callback', ... {@(src, event)myCallbackMethod(this, src, event)}); % the rest of the class constructor code end end The callback code looks like: methods (Access = private) % This doesn't work because it's private % It works just fine if I make it public instead, but that's wrong conceptually. function myCallbackMethod(this, src, event) % do something end end
[ "Storing the function handle of the callback as a private property seems to workaround the problem. Try this:\nclassdef MyClass\n properties\n handle;\n end\n\n properties (Access=private)\n callback;\n end\n\n methods\n function this = MyClass(args)\n this.callback = @myCallbackMethod;\n this.handle = uicontrol('Callback', ...\n {@(src, event)myCallbackMethod(this, src, event)});\n end\n end\n\n methods (Access = private)\n function myCallbackMethod(this, src, event)\n disp('Hello world!');\n end\n end\nend\n\n" ]
[ 8 ]
[]
[]
[ "access_control", "callback", "matlab", "oop", "user_interface" ]
stackoverflow_0000106086_access_control_callback_matlab_oop_user_interface.txt
Q: How do I run a script when ip-address changes (most likely using a dhclient hook) on a (Ubuntu) Linux machine? I have a script which contacts a few sources and tell them "the IP-address XXX.XXX.XXX.XXX is my current one". My test web server has a dynamic IP-address through DHCP and amongst other things it needs to update a DDNS entry when its IP-address changes. However it's not the only thing it does, so I will need to run my own custom script. I suspect that this is possible by a attaching the script to be run for a given dhclient hook. However I still need to know which hook I should use, and how. A: I would recommend to put the script into dhclient-exit-hooks.d. Because you should just change the DDNS entry, if the address change has been finished. However, I am not sure if dhclient-exit-hooks are called, if assigning an address fails. Edit: The man pages (man dhclient-script) says, that the exit-hooks script will get the exit code in a shell variable (exit_status). So you could check it.
How do I run a script when ip-address changes (most likely using a dhclient hook) on a (Ubuntu) Linux machine?
I have a script which contacts a few sources and tell them "the IP-address XXX.XXX.XXX.XXX is my current one". My test web server has a dynamic IP-address through DHCP and amongst other things it needs to update a DDNS entry when its IP-address changes. However it's not the only thing it does, so I will need to run my own custom script. I suspect that this is possible by a attaching the script to be run for a given dhclient hook. However I still need to know which hook I should use, and how.
[ "I would recommend to put the script into dhclient-exit-hooks.d. Because you should just change the DDNS entry, if the address change has been finished. However, I am not sure if dhclient-exit-hooks are called, if assigning an address fails. \nEdit: The man pages (man dhclient-script) says, that the exit-hooks script will get the exit code in a shell variable (exit_status). So you could check it. \n" ]
[ 5 ]
[]
[]
[ "dhcp", "hook", "linux", "unix" ]
stackoverflow_0000113730_dhcp_hook_linux_unix.txt
Q: Running xinc on OpenBSD's Apache Server Has anyone been able to get xinc to run correctly under OpenBSD's chrooted default Apache? I'd like to keep our development server running fully chrooted just like our Production server so that we make sure our code runs just fine chrooted. A: Have you posted the issue on the Xinc bug tracker? Xinc itself should run fine as it runs both as a daemon and as a web app. As you alluded to, the issue may be that the daemon is not running in a chroot'ed environment where as the web interface is, leading to either side not grabbing the files. A: @dragonmantank In Xinc's case, I hope you used PEAR to install it. pear list-files xinc/Xinc This should do it, and show you where your Xinc install put its files. So even though Xinc is "just" one big PHP script, it's still spread out into rc scripts and all those other things which are necessary to make an application run. I'm sure you don't need to add all paths listed there, but probably some in order to make it run. Aside from Xinc itself, I think it also needs phpUnit and a bunch of other PEAR libs to run, so what I'd propose is this: pear config-get php_dir And then you need to add that path (like Henrik suggested) to the chroot environment. A: Having never used xinc myself, I can only hint as to how I usually get to chrooting apps. First step would be to gather information on everything the app needs to run; this I usually accomplish by running systrace(1) and ldd(1) to find out what is needed to run the software. Go through the output of systrace -A -d. <app> ldd <app> and make sure that everything the app touches and needs (quite a lot of apps touch stuff it doesn't actually need) is available in the chroot environment. You might need to tweak configs and environment variables a bit. Also, if there is an option to have the app log to syslog, I usually do that and create a syslog socket (see the -a option of syslogd(8)) in order to decrease the places the app needs write access to. What I just described is a generic way to make just about any program run in a chroot environment (however, if you need to import half the userland and some suid commands, you might want to just not do chroot :). For apps running under Apache (I'm sure you're aware that the OpenBSD httpd(8) is slightly different) you have the option (once the program has started; any dynamic libraries still needs to be present in the jail) of using apache to access the files, allowing the use of httpd.conf to import resources in the chroot environment without actually copying them. Also useful (if slightly outdated) is this link, outlining some gotchas in chrooted PHP on OpenBSD. A: First step would be to gather information on everything the app needs to run; this I usually accomplish by running systrace(1) and ldd(1) to find out what is needed to run the software. I'll give this a try. The big issue I've found with xinc is that while it is a PHP application, it wants to know application installation paths (yet it still spreads stuff into other folders) and runs some PHP scripts in daemon mode (those scripts being the hardest to get running). So, for example, I told it to install to /var/www/xinc and then made a symlink of /var/www/var/www/xinc -> /var/www/xinc and it partially worked. I got the GUI to come up bit it refused to recognize any projects that I had set up. I think the biggest problem is that part of it is running a chroot and the other half is running outside. If all else fails I'm going to just have to build something as we program inside chrooted environments since our production is chrooted. We've run into issues where we code outside of a chroot and then have to back track to find what we need to make it work inside a chroot.
Running xinc on OpenBSD's Apache Server
Has anyone been able to get xinc to run correctly under OpenBSD's chrooted default Apache? I'd like to keep our development server running fully chrooted just like our Production server so that we make sure our code runs just fine chrooted.
[ "Have you posted the issue on the Xinc bug tracker? Xinc itself should run fine as it runs both as a daemon and as a web app. As you alluded to, the issue may be that the daemon is not running in a chroot'ed environment where as the web interface is, leading to either side not grabbing the files.\n", "@dragonmantank\nIn Xinc's case, I hope you used PEAR to install it.\npear list-files xinc/Xinc\n\nThis should do it, and show you where your Xinc install put its files. So even though Xinc is \"just\" one big PHP script, it's still spread out into rc scripts and all those other things which are necessary to make an application run. I'm sure you don't need to add all paths listed there, but probably some in order to make it run.\nAside from Xinc itself, I think it also needs phpUnit and a bunch of other PEAR libs to run, so what I'd propose is this:\npear config-get php_dir\n\nAnd then you need to add that path (like Henrik suggested) to the chroot environment.\n", "Having never used xinc myself, I can only hint as to how I usually get to chrooting apps.\nFirst step would be to gather information on everything the app needs to run; this I usually accomplish by running systrace(1) and ldd(1) to find out what is needed to run the software.\nGo through the output of\nsystrace -A -d. <app>\nldd <app>\n\nand make sure that everything the app touches and needs (quite a lot of apps touch stuff it doesn't actually need) is available in the chroot environment. You might need to tweak configs and environment variables a bit. Also, if there is an option to have the app log to syslog, I usually do that and create a syslog socket (see the -a option of syslogd(8)) in order to decrease the places the app needs write access to.\nWhat I just described is a generic way to make just about any program run in a chroot environment (however, if you need to import half the userland and some suid commands, you might want to just not do chroot :). For apps running under Apache (I'm sure you're aware that the OpenBSD httpd(8) is slightly different) you have the option (once the program has started; any dynamic libraries still needs to be present in the jail) of using apache to access the files, allowing the use of httpd.conf to import resources in the chroot environment without actually copying them.\nAlso useful (if slightly outdated) is this link, outlining some gotchas in chrooted PHP on OpenBSD.\n", "\nFirst step would be to gather information on everything the app needs to run; this I usually accomplish by running systrace(1) and ldd(1) to find out what is needed to run the software.\n\nI'll give this a try. The big issue I've found with xinc is that while it is a PHP application, it wants to know application installation paths (yet it still spreads stuff into other folders) and runs some PHP scripts in daemon mode (those scripts being the hardest to get running). So, for example, I told it to install to /var/www/xinc and then made a symlink of\n/var/www/var/www/xinc -> /var/www/xinc\nand it partially worked. I got the GUI to come up bit it refused to recognize any projects that I had set up. I think the biggest problem is that part of it is running a chroot and the other half is running outside. \nIf all else fails I'm going to just have to build something as we program inside chrooted environments since our production is chrooted. We've run into issues where we code outside of a chroot and then have to back track to find what we need to make it work inside a chroot.\n" ]
[ 4, 2, 1, 1 ]
[]
[]
[ "continuous_integration", "openbsd", "php", "xinc" ]
stackoverflow_0000009455_continuous_integration_openbsd_php_xinc.txt
Q: How do you re-attach a subversion local copy to a different remote? Our subversion repository has been moved to a new host, and we have old applications that connect to that host. We CANNOT add an alias for the new server with the old name, how can we re-connect our checked out clients to the new repository? A: Example: svn switch --relocate \ http://svn.example.com/path/to/repository/path/within/repository \ http://svnnew.example.com/new/repository/path/within/repository One thing which is to remember, lets assume you checked out the project "path/within/repository" then you have to go to the root of your working copy, and execute the above command. it is NOT enough just to use the repository root (as in svn switch --relocate http://svn.example.com/path/to/repository/ http://svnnew.example.com/new/repository/), because that wouldn't work. A: Look up the svn switch command. In particular, the --relocate option is what you want. A: SVN command line - see svn switch TortoiseSVN - see relocate dialog
How do you re-attach a subversion local copy to a different remote?
Our subversion repository has been moved to a new host, and we have old applications that connect to that host. We CANNOT add an alias for the new server with the old name, how can we re-connect our checked out clients to the new repository?
[ "Example:\nsvn switch --relocate \\\n http://svn.example.com/path/to/repository/path/within/repository \\\n http://svnnew.example.com/new/repository/path/within/repository\n\nOne thing which is to remember, lets assume you checked out the project \"path/within/repository\" then you have to go to the root of your working copy, and execute the above command. it is NOT enough just to use the repository root (as in svn switch --relocate http://svn.example.com/path/to/repository/ http://svnnew.example.com/new/repository/), because that wouldn't work.\n", "Look up the svn switch command. In particular, the --relocate option is what you want.\n", "SVN command line - see svn switch\nTortoiseSVN - see relocate dialog\n" ]
[ 17, 8, 1 ]
[]
[]
[ "svn" ]
stackoverflow_0000112770_svn.txt
Q: What are pros and cons of Msmqdistributor service of Enterprise Library? We are using EntLib Logging Application Block. And also it turned out that we should use msmq for logging because of performance. Now we are trying to use Msmqdistributor service to log those messages in the queue. What are pros and cons of Msmqdistributor service of Enterprise Library? Please share your experience. A: The main drawback is going to be the Microsoft Message Queue (MSMQ) itself. MSMQ has been around for awhile and it is a pretty cool tool. It does however lack utilities. Because of the way that data is stored in the queue, most people end up needing to write some helper utilities for debugging and manually manipulating the queue. Some other things to consider: Queue size - if too many items get put in the queue, and aren't removed in a timely manner the server can stall. Purpose - MSMQ is designed for multi-step transactions (such as billing), you mention you are going to use it for logging. If the log is just for debugging, Then a DB table or a flat file or sending errors to a bug tracker will serve you better. If you need complicated logging and are using MSMQ to send the information to a different copmuter, then you will find MSMQ more useful.
What are pros and cons of Msmqdistributor service of Enterprise Library?
We are using EntLib Logging Application Block. And also it turned out that we should use msmq for logging because of performance. Now we are trying to use Msmqdistributor service to log those messages in the queue. What are pros and cons of Msmqdistributor service of Enterprise Library? Please share your experience.
[ "The main drawback is going to be the Microsoft Message Queue (MSMQ) itself. MSMQ has been around for awhile and it is a pretty cool tool. It does however lack utilities. Because of the way that data is stored in the queue, most people end up needing to write some helper utilities for debugging and manually manipulating the queue. Some other things to consider:\n\nQueue size - if too many items get put in the queue, and aren't removed in a timely manner the server can stall.\nPurpose - MSMQ is designed for multi-step transactions (such as billing), you mention you are going to use it for logging. If the log is just for debugging, Then a DB table or a flat file or sending errors to a bug tracker will serve you better. If you need complicated logging and are using MSMQ to send the information to a different copmuter, then you will find MSMQ more useful.\n\n" ]
[ 4 ]
[]
[]
[ "enterprise_library" ]
stackoverflow_0000103033_enterprise_library.txt
Q: Conflicting desires in Database Design, with fields of two similar functions Okay, so I'm making a table right now for "Box Items". Now, a Box Item, depending on what it's being used for/the status of the item, may end up being related to a "Shipping" box or a "Returns" box. A Box Item may be defective:if it is, a flag will be set in the Box Item's row (IsDefective), and the Box Item will be put in a "Returns" box (with other items to be returned to that vendor). Otherwise, the Box Item will eventually be put into a "Shipping" box (with other items to be shipped). (Note that Shipping and Returns boxes have their own tables: there's not one common table for all boxes... though maybe I should consider doing that if possible as a third possibility?) Maybe I'm just not thinking clearly today, but I started questioning what should be done in this situation. My gut tells me that I should have a separate field for each possible relation, even if only one of the relations can happen at any given time, which would make the schema for Box Items look like: BoxItemID Description IsDefective ShippingBoxID ReturnBoxID etc... This would make the relations clear, but it seems wasteful (since only one of the relations will be used at any time). So then I thought I could have just one field for the BoxID, and determine which BoxID it's referring to (a Shipping or a Returns Box ID) based on the IsDefective field: BoxItemID Description IsDefective BoxID etc... This seems less wasteful, but doesn't sit right with me. The relation isn't obvious. So, I put it to you, database gurus of Stackoverflow. What would you do in this situation? EDIT: Thank you everyone for your input! It's given me a lot to think about. For one, I'm going to use an ORM next time I start a project like this. =) For two, since I'm not right now, I'll bite the four bytes and use two fields. Thanks everyone again! A: I'm with Psychotic Venom and mattlant. Going the polymorphic route (having to figure out which table your foreign key points to based on the contents of another field) is going to be a pain. Coding the constraints for that maybe tough (I'm not sure most databases would support that natively, I think you'd have to use a trigger). Do items ever move between the tables? Sticking with two tables with identical definitions where one is for returns and one is for shipping may be the easiest route. If you want to stick with the definition you first proposed (with the two separate fields) is perfectly reasonable. "Premature optimization is the root of all evil" and all that. While it seems wasteful, remember what you're storing. Since they are IDs they are probably just integers, maybe 4 bytes. Wasting four bytes per record is basically nothing. In fact, due to padding to put things on even addresses or other such things it may be "free" to put that extra field in there. It all depends on the DB design. Unless you have a very good reason to go the polymorphic route (like you're on an embedded system with little memory or you have to replicate across some really slow 9600bps link) it probably won't be worth the headaches you can end up with. Having to write all those special cases into your queries can get annoying. Quick example: doing a join between two tables where if you want to join is based on if the isDefective flag is set is going to be a pain. Being able to just use one of the two columns alone is probably enough of a hassle you may save, at least for me. A: What you're talking about is polymorphic relations. A single ID that can reference multiple other tables. There are several frameworks that support this, however, it is (potentially) bad for database integrity (that could be a whole other discussion whether or not your database or your application should maintain referential integrity). What about this? BoxItem: BoxItemID, Description, IsDefective Box: BoxID, Description BoxItemMap: BoxID, BoxItemID, BoxItemType Then you can have BoxItemType be an enumeration, or an integer where you define constants in your application as "Return" or "Shipping" as the type of box. A: I would consider making a single table for the boxes and the box type be a column of the box table. This would simplify the relationships and make it easy to still query for box type. So the box item only has one foreign key to the boxId. A: I'd use what Hibernate calls Table-per-subclass, so my DB would wind up with 3 tables for Boxes: Box, ShippingBox, and ReturnBox. The FK in BoxItem would point to Box. A: Agree about the polymorphic discussion above, although it has potential to be used poorly, it is still a viable solution. Basically you have a base table called box. Then you have two other tables, shipping box and return box. Those two add any extra fields that are special to them. they are related to box with a 1:1 fk.Boz base table has the common fields of all box types. You relate BoxItem with the box table. The way you you get the proper box type is by doing a query that joins the child box with the root box based on the key. The record that has in both the base box and the child box is of that type. You just have to be careful like mentioned that when you create a box type that it is done correctly. BUt thats what testing is for. The code to add them only needs ot written once. Or use an ORM. Almost all ORM's support this strategy. A: I'd probably go with: BoxTable: box_id, box_descrip, box_status_id ... 1, Lovely Box, 1 2, Borked box, 2 3, Ugly Box, 3 4, Flammable Box, 4 BoxStatus: box_status_id, box_status_name, box_type_id, .... 1,Shippable, 1 2,Return, 2 3,Ugly, 2 4,Dangerous,3 BoxType: box_type_id, box_type_name, ... 1, Shipping box, ... 2, Return box, .... 3, Hazmat box, ... That way the Box Status defines the box type, and it's flexible if you need to expand into a few more status levels or box types later on. A: I'd go with just a single BoxItems table with IsDefective, ShippingBoxID, the shipping-box-related fields, ReturnBoxID and the return-box-related fields. Some fields will always be NULL for each record. This is a very simple and self-evident design that the next developer is unlikely to be confused by. In theory this design is inefficient because of the guaranteed empty fields for each row. In practice, databases tend to have a minimum required storage size for each row anyway, so (unless the number of fields is huge) this design is as efficient as possible anyway, and much easier to code to.
Conflicting desires in Database Design, with fields of two similar functions
Okay, so I'm making a table right now for "Box Items". Now, a Box Item, depending on what it's being used for/the status of the item, may end up being related to a "Shipping" box or a "Returns" box. A Box Item may be defective:if it is, a flag will be set in the Box Item's row (IsDefective), and the Box Item will be put in a "Returns" box (with other items to be returned to that vendor). Otherwise, the Box Item will eventually be put into a "Shipping" box (with other items to be shipped). (Note that Shipping and Returns boxes have their own tables: there's not one common table for all boxes... though maybe I should consider doing that if possible as a third possibility?) Maybe I'm just not thinking clearly today, but I started questioning what should be done in this situation. My gut tells me that I should have a separate field for each possible relation, even if only one of the relations can happen at any given time, which would make the schema for Box Items look like: BoxItemID Description IsDefective ShippingBoxID ReturnBoxID etc... This would make the relations clear, but it seems wasteful (since only one of the relations will be used at any time). So then I thought I could have just one field for the BoxID, and determine which BoxID it's referring to (a Shipping or a Returns Box ID) based on the IsDefective field: BoxItemID Description IsDefective BoxID etc... This seems less wasteful, but doesn't sit right with me. The relation isn't obvious. So, I put it to you, database gurus of Stackoverflow. What would you do in this situation? EDIT: Thank you everyone for your input! It's given me a lot to think about. For one, I'm going to use an ORM next time I start a project like this. =) For two, since I'm not right now, I'll bite the four bytes and use two fields. Thanks everyone again!
[ "I'm with Psychotic Venom and mattlant.\nGoing the polymorphic route (having to figure out which table your foreign key points to based on the contents of another field) is going to be a pain. Coding the constraints for that maybe tough (I'm not sure most databases would support that natively, I think you'd have to use a trigger).\nDo items ever move between the tables? Sticking with two tables with identical definitions where one is for returns and one is for shipping may be the easiest route. If you want to stick with the definition you first proposed (with the two separate fields) is perfectly reasonable. \n\"Premature optimization is the root of all evil\" and all that. While it seems wasteful, remember what you're storing. Since they are IDs they are probably just integers, maybe 4 bytes. Wasting four bytes per record is basically nothing. In fact, due to padding to put things on even addresses or other such things it may be \"free\" to put that extra field in there. It all depends on the DB design.\nUnless you have a very good reason to go the polymorphic route (like you're on an embedded system with little memory or you have to replicate across some really slow 9600bps link) it probably won't be worth the headaches you can end up with. Having to write all those special cases into your queries can get annoying.\nQuick example: doing a join between two tables where if you want to join is based on if the isDefective flag is set is going to be a pain. Being able to just use one of the two columns alone is probably enough of a hassle you may save, at least for me.\n", "What you're talking about is polymorphic relations. A single ID that can reference multiple other tables. There are several frameworks that support this, however, it is (potentially) bad for database integrity (that could be a whole other discussion whether or not your database or your application should maintain referential integrity).\nWhat about this?\nBoxItem:\nBoxItemID, Description, IsDefective\n\nBox:\nBoxID, Description\n\nBoxItemMap:\nBoxID, BoxItemID, BoxItemType\n\nThen you can have BoxItemType be an enumeration, or an integer where you define constants in your application as \"Return\" or \"Shipping\" as the type of box.\n", "I would consider making a single table for the boxes and the box type be a column of the box table. This would simplify the relationships and make it easy to still query for box type. So the box item only has one foreign key to the boxId.\n", "I'd use what Hibernate calls Table-per-subclass, so my DB would wind up with 3 tables for Boxes: Box, ShippingBox, and ReturnBox. The FK in BoxItem would point to Box.\n", "Agree about the polymorphic discussion above, although it has potential to be used poorly, it is still a viable solution.\nBasically you have a base table called box. Then you have two other tables, shipping box and return box. Those two add any extra fields that are special to them. they are related to box with a 1:1 fk.Boz base table has the common fields of all box types.\nYou relate BoxItem with the box table. The way you you get the proper box type is by doing a query that joins the child box with the root box based on the key. The record that has in both the base box and the child box is of that type.\nYou just have to be careful like mentioned that when you create a box type that it is done correctly. BUt thats what testing is for. The code to add them only needs ot written once. Or use an ORM.\nAlmost all ORM's support this strategy.\n", "I'd probably go with:\nBoxTable:\nbox_id, box_descrip, box_status_id ...\n 1, Lovely Box, 1\n 2, Borked box, 2\n 3, Ugly Box, 3\n 4, Flammable Box, 4\n\n BoxStatus:\n box_status_id, box_status_name, box_type_id, ....\n 1,Shippable, 1\n 2,Return, 2\n 3,Ugly, 2\n 4,Dangerous,3\n\n BoxType:\n box_type_id, box_type_name, ...\n 1, Shipping box, ...\n 2, Return box, ....\n 3, Hazmat box, ...\n\nThat way the Box Status defines the box type, and it's flexible if you need to expand into a few more status levels or box types later on.\n", "I'd go with just a single BoxItems table with IsDefective, ShippingBoxID, the shipping-box-related fields, ReturnBoxID and the return-box-related fields. Some fields will always be NULL for each record.\nThis is a very simple and self-evident design that the next developer is unlikely to be confused by. In theory this design is inefficient because of the guaranteed empty fields for each row. In practice, databases tend to have a minimum required storage size for each row anyway, so (unless the number of fields is huge) this design is as efficient as possible anyway, and much easier to code to.\n" ]
[ 2, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "database", "database_design", "database_relations", "normalizing" ]
stackoverflow_0000112780_database_database_design_database_relations_normalizing.txt
Q: How do you find media resources for game-dev? I've been wondering, as a lone game developer, or to say a part of team which has only got programmers and people who like to play games... How do I manage the void created by lack of artists (sprites/tiles/animations) in such a situation??? What do you do in that case? and suppose I am a student, with no money to hire artists, is there a place where I can get these resources legally & free ? A: Recently I needed some free-as-in-speech sound samples, and found freesounds.org where all sound samples are under a CC license. Not quite sure where I would go for images/textures though. A: Have you tried to attract a game playing artist to join your effort? Lot's of people play games (even artists). The idea of collaborating on a game may be enough incentive, particulary if they get credit in the game, and samples for a portfolio. A: For images there is also several sites like freespace pointed out for instance http://commons.wikimedia.org/ another great resource for getting artwork/images for your projects is to reach out to art schools or other locations that you know artists frequent and permit them to sign or get credit for any creation you use. A: For a hobbyist, the simplest answer is that you shouldn't worry about your game's art. You can get by fine with only programmer's art. After you've created a working gameplay prototype, only then should you look for artists. For an independent developer, you would need cash to hire artists. There's no getting around this. Just think of it this way: you get what you pay for. Fun trivia: the most popular programmer's art is Kirby. The developers were using a pink fluffy sprite as placeholder's art until the the creator, Masahiro Sakurai, decided that the art fits the game and should stay.
How do you find media resources for game-dev?
I've been wondering, as a lone game developer, or to say a part of team which has only got programmers and people who like to play games... How do I manage the void created by lack of artists (sprites/tiles/animations) in such a situation??? What do you do in that case? and suppose I am a student, with no money to hire artists, is there a place where I can get these resources legally & free ?
[ "Recently I needed some free-as-in-speech sound samples, and found freesounds.org where all sound samples are under a CC license. Not quite sure where I would go for images/textures though.\n", "Have you tried to attract a game playing artist to join your effort? \nLot's of people play games (even artists). The idea of collaborating on a game may be enough incentive, particulary if they get credit in the game, and samples for a portfolio.\n", "For images there is also several sites like freespace pointed out for instance http://commons.wikimedia.org/ another great resource for getting artwork/images for your projects is to reach out to art schools or other locations that you know artists frequent and permit them to sign or get credit for any creation you use. \n", "For a hobbyist, the simplest answer is that you shouldn't worry about your game's art. You can get by fine with only programmer's art.\nAfter you've created a working gameplay prototype, only then should you look for artists.\nFor an independent developer, you would need cash to hire artists. There's no getting around this. Just think of it this way: you get what you pay for.\nFun trivia: the most popular programmer's art is Kirby. The developers were using a pink fluffy sprite as placeholder's art until the the creator, Masahiro Sakurai, decided that the art fits the game and should stay.\n" ]
[ 1, 1, 1, 1 ]
[]
[]
[ "media", "resources" ]
stackoverflow_0000110279_media_resources.txt
Q: Java User Interface Specification Java supplies standard User Interface guidelines for applications built using Java Swing. The basic guidelines are good, but I really feel the look and feel is really boring and outdated. Is anyone aware of a publicly available Java User Interface Guide that has better look & feel guidelines than the Sun provided guidelines? A: You have many LNF (Look And Feel) displayed here but they have not exactly a 'Java User Guide' Provided. However MigLayout does follow closely the main User Interface standards that exist out there (including some obcure points of button order): For instance the OK and Cancel buttons have different order on Windows and Mac OS X. While other layout managers use factories and button builders for this, it is inherently supported by MigLayout by just tagging the buttons. One just tags the OK button with "ok" and the Cancel button with "cancel" and they will end up in the correct order for the platform the application is running on, if they are put in the same grid cell. Example on Mac: (source: miglayout.com) A: the apple developer guide has a human computer interface guide - http://developer.apple.com/documentation/UserExperience/Conceptual/AppleHIGuidelines/XHIGIntro/chapter_1_section_1.html#//apple_ref/doc/uid/TP30000894-TP6 . Even though its targeted at the mac platform, you could learn something from it - its the reason why so many mac apps are pleasant to use, as well as aesthetically pleasing! A: Along the line of Chii's answer, I would recommend taking a look at the Windows Vista User Experience Guidelines for general tips on making user interfaces. Although the name ("Windows Vista User Experience Guidelines") and source (Microsoft) may suggest that it only contains Windows-centric tips and advice, it does offer good general tips and directions that can be used when designing interfaces for non-Windows applications as well. The Design Principles sections address some points to keep in mind when designing an effective user interface. For example, bullet three of How to Design a Great User Experience says: Don't be all things to all people Your program is going to be more successful by delighting its target users than attempting to satisfy everyone. These are the kinds of tips that apply to designing user interfaces on any platform. Of course, there are also Windows-specific guidelines as well. I believe one of the biggest reasons why look and feel of Swing applications seems "boring" and "outdated" is due to the platform-independent nature of Java. In order for the graphical user interfaces to work on several different platforms, Java needs to have facilities to adapt the user interface to the different host operating systems. For example, various platforms have various sizes for windows, buttons, and other visual components, so absolute positioning does not work too well. To combat that problem, Swing uses Layout Managers which (generally) use relative positioning to place the visual components on the screen. Despite these "limitations" of building graphical user interfaces for Java, I think that using tips from guidelines that are provided by non-Sun sources and non-Java-specific sources can still be a good source of information in designing and implementing an user interface that is effective. After all, designing an user interface is less about programming languages and more about human-machine interaction. A: I don't think there are any other complete guidelines. But if you are not talking about the spacing/positioning of components (I don't think that part of Look And Feel Design Guidelines is outdated), but only about the look and feel good starting points are singlabx / swingx: http://swinglabs.org http://swinglabs.org/docs/presentations/2007/DesktopMatters/FilthyRichClients.pdf http://parleys.com/display/PARLEYS/Home#slide=1;talk=7643;title=Filthy%20Rich%20Clients and JGoodies: http://www.jgoodies.com/articles/index.html http://www.jgoodies.com/articles/efficient%20swing%20design.pdf
Java User Interface Specification
Java supplies standard User Interface guidelines for applications built using Java Swing. The basic guidelines are good, but I really feel the look and feel is really boring and outdated. Is anyone aware of a publicly available Java User Interface Guide that has better look & feel guidelines than the Sun provided guidelines?
[ "You have many LNF (Look And Feel) displayed here but they have not exactly a 'Java User Guide' Provided.\nHowever MigLayout does follow closely the main User Interface standards that exist out there (including some obcure points of button order):\n\nFor instance the OK and Cancel buttons have different order on Windows and Mac OS X.\n While other layout managers use factories and button builders for this, it is inherently supported by MigLayout by just tagging the buttons.\n One just tags the OK button with \"ok\" and the Cancel button with \"cancel\" and they will end up in the correct order for the platform the application is running on, if they are put in the same grid cell.\n\nExample on Mac: \n\n(source: miglayout.com) \n", "the apple developer guide has a human computer interface guide - http://developer.apple.com/documentation/UserExperience/Conceptual/AppleHIGuidelines/XHIGIntro/chapter_1_section_1.html#//apple_ref/doc/uid/TP30000894-TP6 . \nEven though its targeted at the mac platform, you could learn something from it - its the reason why so many mac apps are pleasant to use, as well as aesthetically pleasing!\n", "Along the line of Chii's answer, I would recommend taking a look at the Windows Vista User Experience Guidelines for general tips on making user interfaces.\nAlthough the name (\"Windows Vista User Experience Guidelines\") and source (Microsoft) may suggest that it only contains Windows-centric tips and advice, it does offer good general tips and directions that can be used when designing interfaces for non-Windows applications as well. \nThe Design Principles sections address some points to keep in mind when designing an effective user interface. For example, bullet three of How to Design a Great User Experience says:\n\nDon't be all things to all people Your\n program is going to be more successful\n by delighting its target users than\n attempting to satisfy everyone.\n\nThese are the kinds of tips that apply to designing user interfaces on any platform. Of course, there are also Windows-specific guidelines as well.\nI believe one of the biggest reasons why look and feel of Swing applications seems \"boring\" and \"outdated\" is due to the platform-independent nature of Java. In order for the graphical user interfaces to work on several different platforms, Java needs to have facilities to adapt the user interface to the different host operating systems.\nFor example, various platforms have various sizes for windows, buttons, and other visual components, so absolute positioning does not work too well. To combat that problem, Swing uses Layout Managers which (generally) use relative positioning to place the visual components on the screen.\nDespite these \"limitations\" of building graphical user interfaces for Java, I think that using tips from guidelines that are provided by non-Sun sources and non-Java-specific sources can still be a good source of information in designing and implementing an user interface that is effective. After all, designing an user interface is less about programming languages and more about human-machine interaction.\n", "I don't think there are any other complete guidelines. But if you are not talking about the spacing/positioning of components (I don't think that part of Look And Feel Design Guidelines is outdated), but only about the look and feel good starting points are singlabx / swingx:\nhttp://swinglabs.org\nhttp://swinglabs.org/docs/presentations/2007/DesktopMatters/FilthyRichClients.pdf\nhttp://parleys.com/display/PARLEYS/Home#slide=1;talk=7643;title=Filthy%20Rich%20Clients\nand JGoodies:\nhttp://www.jgoodies.com/articles/index.html\nhttp://www.jgoodies.com/articles/efficient%20swing%20design.pdf\n" ]
[ 3, 3, 3, 1 ]
[]
[]
[ "java", "swing", "user_interface" ]
stackoverflow_0000113464_java_swing_user_interface.txt
Q: VisualStudio using BootCamp/VMWare on OS X Just bought a 2.4GHz Intel Core 2 Duo iMac with 2GB of memory and a 320GB hard drive. I plan on doing some .net development on it using a BootCamp/VMWare combo since VMWare grants access to the bootcamp partition. What is a recommended size for a BootCamp partition and how much memory should I give VMWare? Any pitfalls to watch out for? What is your current configuration? A: I use VMWare Fusion 2.0 on my MacBook Pro and I wouldn't have it any other way. I'd strongly recommend getting a min of 4gb RAM is you're going to run Windows + VS 2008 in virtualisation. I have a 2gb RAM for my VM and you do notice a bit of chugging, particularly when you are compiling a large solution, or when running lots of apps at once. I strongly recommend VMWare over Parallels as VMWare supports 2 virtual CPU's (I think it's up to 4 virtual CPU's in v2). I'd recommend around a 30gb disk for your VM and I don't recommend BootCamp unless you want to play games on it. Why? It's a lot easier to have a really large virtual disk which is not using it all where as BootCamp will take the space. Also a complete virtual disk is easier to backup/ snapshot/ restore. A: While this doesn't address your question directly, I wouldn't recommend running VS 2008 and all of the supporting tools on anything less than 2GB of RAM. A: I have a 2.4 GHz Intel Core Duo Macbook Pro with 4 GB of RAM. I do some .NET development using VM Fusion/XP/Visual Studio 2005, and have allocated 1 GB of RAM for the virtual machine. It works fine for me, and I have been happy with its performance and responsiveness. The only real annoyance for me is that by default some of the function keys trigger Mac events, and can't be used as keyboard shortcuts for step over/into/continue debugging functions. For example, F10 triggers the expose function. However, as @Crash points out, the mac keyboard shortcuts can be disabled in the vmware preferences. This works like a charm - thanks for the tip! @Soeren Kuklau: Thanks for your suggestion, but I don't think I was clear about my problem. I've already configured the "use standard function keys" option. What I was referring to is that by default, F10 and F11 trigger expose actions. And that's my real annoyance: to use keyboard shortcuts for debugging, you have to change default settings. A: The only real annoyance for me is the some of the function keys trigger Mac events, and can't be used as keyboard shortcuts for step over/into/continue debugging functions. Enable System Preference → Keyboard & Mouse → Keyboard → Use all F1, F2, etc. keys as standard function keys. A: The only real annoyance for me is the some of the function keys trigger Mac events, and can't be used as keyboard shortcuts for step over/into/continue debugging functions. I use VmWare Fusion 2.0 on my MBP with Vista x64. There's an option in virtual machine configuration to let you disable mac-specific-keys. Once i disabled it, i can use F10 and F11 in Visual Studio 2008 without any problems and as soon as i switch back to mac os they act as set in System Preferences (in my case, they behave as standard function keys). What is a recommended size for a BootCamp partition and how much memory should I give VMWare? Any pitfalls to watch out for? What is your current configuration? I have a MBP 15", with 4GB of RAM. I use VmWare Fusion 2.0 with Vista x64. I configured the virtual drive to use 40GB (i only installed Vista, Visual Studio 2008 Pro (c#+web dev), MSDN and Microsoft Access 2007. I set 2GB of ram to be used by vm and one cpu. I mostly use Vista in windowed-mode and i can switch back to Leopard very smoothly and vs 2008 experience is really great. A: I ran windows Xp on a mac (AMD 2.4 GHz) and i alloted 1.5GB and it was fairly slow, but it was a file based disk. I agree with the above that you need the ram, especially with vista. I dont think 2GB base is anough for mac and vmware with vista. For the partition, give at least 40 Gb for os + software and whatveer else extra you need for data. If you can create an extra physical partitioon for the pagefile, that would help too. A: You might also find the suggestions here helpful - elements of this were covered on Stack Overflow a few weeks ago. Personally I'd say don't bother trying to give the VM more than 2Gb of ram (I've had mixed results giving it more than 1, but your mileage may vary, and my experience is all with VMware Fusion 1). Certainly I'd echo the comments above about not going with Bootcamp, too.
VisualStudio using BootCamp/VMWare on OS X
Just bought a 2.4GHz Intel Core 2 Duo iMac with 2GB of memory and a 320GB hard drive. I plan on doing some .net development on it using a BootCamp/VMWare combo since VMWare grants access to the bootcamp partition. What is a recommended size for a BootCamp partition and how much memory should I give VMWare? Any pitfalls to watch out for? What is your current configuration?
[ "I use VMWare Fusion 2.0 on my MacBook Pro and I wouldn't have it any other way.\nI'd strongly recommend getting a min of 4gb RAM is you're going to run Windows + VS 2008 in virtualisation.\nI have a 2gb RAM for my VM and you do notice a bit of chugging, particularly when you are compiling a large solution, or when running lots of apps at once.\nI strongly recommend VMWare over Parallels as VMWare supports 2 virtual CPU's (I think it's up to 4 virtual CPU's in v2).\nI'd recommend around a 30gb disk for your VM and I don't recommend BootCamp unless you want to play games on it.\nWhy? It's a lot easier to have a really large virtual disk which is not using it all where as BootCamp will take the space. Also a complete virtual disk is easier to backup/ snapshot/ restore.\n", "While this doesn't address your question directly, I wouldn't recommend running VS 2008 and all of the supporting tools on anything less than 2GB of RAM.\n", "I have a 2.4 GHz Intel Core Duo Macbook Pro with 4 GB of RAM. I do some .NET development using VM Fusion/XP/Visual Studio 2005, and have allocated 1 GB of RAM for the virtual machine. It works fine for me, and I have been happy with its performance and responsiveness.\nThe only real annoyance for me is that by default some of the function keys trigger Mac events, and can't be used as keyboard shortcuts for step over/into/continue debugging functions. For example, F10 triggers the expose function. However, as @Crash points out, the mac keyboard shortcuts can be disabled in the vmware preferences. This works like a charm - thanks for the tip!\n@Soeren Kuklau: Thanks for your suggestion, but I don't think I was clear about my problem. I've already configured the \"use standard function keys\" option. What I was referring to is that by default, F10 and F11 trigger expose actions. And that's my real annoyance: to use keyboard shortcuts for debugging, you have to change default settings.\n", "\nThe only real annoyance for me is the some of the function keys trigger Mac events, and can't be used as keyboard shortcuts for step over/into/continue debugging functions.\n\nEnable System Preference → Keyboard & Mouse → Keyboard → Use all F1, F2, etc. keys as standard function keys.\n", "\nThe only real annoyance for me is the some of the function keys trigger Mac events, and can't be used as keyboard shortcuts for step over/into/continue debugging functions.\n\nI use VmWare Fusion 2.0 on my MBP with Vista x64. There's an option in virtual machine configuration to let you disable mac-specific-keys. Once i disabled it, i can use F10 and F11 in Visual Studio 2008 without any problems and as soon as i switch back to mac os they act as set in System Preferences (in my case, they behave as standard function keys).\n\nWhat is a recommended size for a BootCamp partition and how much memory should I give VMWare? Any pitfalls to watch out for? What is your current configuration?\n\nI have a MBP 15\", with 4GB of RAM. I use VmWare Fusion 2.0 with Vista x64. I configured the virtual drive to use 40GB (i only installed Vista, Visual Studio 2008 Pro (c#+web dev), MSDN and Microsoft Access 2007. I set 2GB of ram to be used by vm and one cpu.\nI mostly use Vista in windowed-mode and i can switch back to Leopard very smoothly and vs 2008 experience is really great.\n", "I ran windows Xp on a mac (AMD 2.4 GHz) and i alloted 1.5GB and it was fairly slow, but it was a file based disk. I agree with the above that you need the ram, especially with vista. I dont think 2GB base is anough for mac and vmware with vista.\nFor the partition, give at least 40 Gb for os + software and whatveer else extra you need for data. If you can create an extra physical partitioon for the pagefile, that would help too.\n", "You might also find the suggestions here helpful - elements of this were covered on Stack Overflow a few weeks ago.\nPersonally I'd say don't bother trying to give the VM more than 2Gb of ram (I've had mixed results giving it more than 1, but your mileage may vary, and my experience is all with VMware Fusion 1). Certainly I'd echo the comments above about not going with Bootcamp, too.\n" ]
[ 3, 1, 1, 1, 1, 0, 0 ]
[]
[]
[ ".net", "configuration", "macos", "visual_studio", "vmware" ]
stackoverflow_0000110030_.net_configuration_macos_visual_studio_vmware.txt
Q: Set operation in .NET C# I'm working on a something related to roughset right now. The project uses alot of sets operation and manipulation. I've been using string operations as a stop gap measure for set operation. It has worked fine until we need to process some ungodly amount of data ( 500,000 records with about 40+ columns each ) through the algorithm. I know that there is no set data structure in .net 2.0(2.0 was the latest when I started the project) I want to know if there is any library that offer fast set operation in .net c# or if 3.5 has added native set data structure. Thanks . A: .NET 3.5 already has a native set data type: HashSet. You might also want to look at HashSet and LINQ set operators for the operations. In .NET 1.0, there was a third party Set data type: Iesi.Collections which was extended with .NET 2.0 generics with Iesi.Collections.Generic. You might want to try and look at all of them to see which one would benefit you the most. :) A: LINQ supports some set operations. See LINQ 101 page for examples. Also there is a class HashSet (.NET 3.5) Here is Microsoft guidelines for set operations in .NET: HashSet and LINQ Set Operations List of set operations supported by HasSet class: HashSet Collection Type A: Update: This is for .Net 2.0. For .Net 3.5, refer posts by aku, Jon.. This is a good reference for efficiently representing sets in .Net. A: It may be worth taking a look at C5, it's a generic collection library for .NET which includes sets. Note that I haven't looked into it much, but it seems to be a pretty fantastic collection library. A: Try HashSet in .NET 3.5. This page from a member of the .NET BCL team has some good information on the intent of HashSet A: I have been abusing the Dictionary class in .NET 2.0 as a set: private object dummy = "ok"; public void Add(object el) { dict[el] = dummy; } public bool Contains(object el) { return dict.ContainsKey(el); } A: You can use Linq to Objects in C# 3.0. A: You ever think about sing F#? This seems like a job for a functional programming language. A: You should take a look at C5 Generic Collection Library. This library is a systematic approach to fix holes in .NET class library by providing missing structures, as well as replacing existing ones with set of well designed interfaces and generic classes. Among others, there is HashSet<T> - generic Set class based on linear hashing.
Set operation in .NET C#
I'm working on a something related to roughset right now. The project uses alot of sets operation and manipulation. I've been using string operations as a stop gap measure for set operation. It has worked fine until we need to process some ungodly amount of data ( 500,000 records with about 40+ columns each ) through the algorithm. I know that there is no set data structure in .net 2.0(2.0 was the latest when I started the project) I want to know if there is any library that offer fast set operation in .net c# or if 3.5 has added native set data structure. Thanks .
[ ".NET 3.5 already has a native set data type: HashSet. You might also want to look at HashSet and LINQ set operators for the operations.\nIn .NET 1.0, there was a third party Set data type: Iesi.Collections which was extended with .NET 2.0 generics with Iesi.Collections.Generic.\nYou might want to try and look at all of them to see which one would benefit you the most. :)\n", "LINQ supports some set operations. See LINQ 101 page for examples.\nAlso there is a class HashSet (.NET 3.5)\n\nHere is Microsoft guidelines for set operations in .NET:\nHashSet and LINQ Set Operations\nList of set operations supported by HasSet class:\nHashSet Collection Type\n", "Update: This is for .Net 2.0. For .Net 3.5, refer posts by aku, Jon..\nThis is a good reference for efficiently representing sets in .Net.\n", "It may be worth taking a look at C5, it's a generic collection library for .NET which includes sets.\nNote that I haven't looked into it much, but it seems to be a pretty fantastic collection library.\n", "Try HashSet in .NET 3.5.\nThis page from a member of the .NET BCL team has some good information on the intent of HashSet\n", "I have been abusing the Dictionary class in .NET 2.0 as a set:\nprivate object dummy = \"ok\";\n\npublic void Add(object el) {\n dict[el] = dummy;\n}\n\npublic bool Contains(object el) {\n return dict.ContainsKey(el);\n}\n\n", "You can use Linq to Objects in C# 3.0.\n", "You ever think about sing F#? This seems like a job for a functional programming language.\n", "You should take a look at C5 Generic Collection Library. This library is a systematic approach to fix holes in .NET class library by providing missing structures, as well as replacing existing ones with set of well designed interfaces and generic classes.\nAmong others, there is HashSet<T> - generic Set class based on linear hashing. \n" ]
[ 11, 5, 2, 2, 1, 1, 0, 0, 0 ]
[]
[]
[ ".net", "c#", "data_structures", "set" ]
stackoverflow_0000113173_.net_c#_data_structures_set.txt
Q: Class library with support for several persistence strategies I am developing a C++ class library containing domain model classes, and I would like to add support for instantiating these classes from various persistence mechanisms, i.e. databases and file. The user of the class library should be given an interface(?) against which to program a class that can transfer the data from/to the persistence mechanism. I know of the Data Access Object pattern which seems to work for Java, but I'm not exactly sure how to apply it to C++. Are there other solutions? A: Boost Serialization provides some pretty useful stuff for working with serializing C++ types, but how well it will match the interface you desire I don't know. It supports both intrusive and non-intrusive designs, so is pretty flexible. A: C++ supports multiple inheritance so you can have a generic persistence API and inherit a persistence mechanism. This would still have to use introspection to get out the class metadata, but you would still have this issue with any persistence layer. Alternatively you could do something similar but use the metadata to drive a code generator that fills in the 'Getters' and 'Setters' for the persistence layer. Any persistence layer will typically use one or the other approach, so your problem is hooking the loading mechanism into the persistence layer. I think this makes your problem little different from a single persistence layer but tackling it from the other direction. Rather than building domain classes onto a persistence framework you are providing a set of domain classes with the hooks for a persistence framework that third parties can plug their data access mechanism into. I think that once you provide access to class metadata and callbacks the perisistence mechanism is relatively straightforward. Look at the metadata components of any convenient C++ O/R mapping framework and understand how they work. Encapsulate this with an API in one of the base classes of your domain classes and provide a generic getter/setter API for instantiation or persisting. The rest is up to the person implementing the persistence layer. Edit: I can't think of a C++ library with the type of pluggable persistence mechanism you're describing, but I did something in Python that could have had this type of facility added. The particular implementation used facilities in Python with no direct C++ equivalent, although the basic principle could probably be adapted to work with C++. In Python, you can intercept accesses to instance variables by overriding __getattr()__ and __setattr()__. The persistence mechanism actually maintained its own data cache behind the scenes. When the functionality was mixed into the class (done through multiple inheritance), it overrode the default system behaviour for member accessing and checked whether the attribute being queried matched anything in its dictionary. Where this happened, the call was redirected to get or set an item in the data cache. The cache had metadata of its own. It was aware of relationships between entities within its data model, and knew which attribute names to intercept to access data. The way this worked separated it from the database access layer and could (at least in theory) have allowed the persistence mechanism to be used with different drivers. There is no inherent reason that you couldn't have (for example) built a driver that serialised it out to an XML file. Making something like this work in C++ would be a bit more fiddly, and it may not be possible to make the object cache access as transparent as it was with this system. You would probably be best with an explicit protocol that loads and flushes the object's state to the cache. The code to this would be quite amenable to generation from the cache metadata, but this would have to be done at compile time. You may be able to do something with templates or by overriding the -> operator to make the access protocol more transparent, but this is probably more trouble than it's worth. A: I would avoid serialization, IMHO, we implemented this for one of our applications in MFC back in 1995, we were smart enough to use independent object versioning, and file versioning, but you end up with a lot of old messy code around after time. Imagine certain scenarios, deprecating classes, deprecating members, etc, each presents a new problem. Now we use compreseds "XML type" streams, we can add new data and maintain backward compatibility. Reading and writing the file is abstracted from mapping the data to the objects, we can now switch file formats, add importers/exporters without modification to our core business objects. That being said some developers love serialization, my own encounters is that switching code base, platforms, languages, toolkits all bring along a lot of problems, reading and writing your data should not be one of them. Additionally using a standard data format, with some proprietary key, means its a lot easier to work with 3rd parties. A: You might like to look at boost serialization. Not having used it I can't say whether to recommend it or not. Boost libraries are typically high quality.
Class library with support for several persistence strategies
I am developing a C++ class library containing domain model classes, and I would like to add support for instantiating these classes from various persistence mechanisms, i.e. databases and file. The user of the class library should be given an interface(?) against which to program a class that can transfer the data from/to the persistence mechanism. I know of the Data Access Object pattern which seems to work for Java, but I'm not exactly sure how to apply it to C++. Are there other solutions?
[ "Boost Serialization provides some pretty useful stuff for working with serializing C++ types, but how well it will match the interface you desire I don't know. It supports both intrusive and non-intrusive designs, so is pretty flexible.\n", "C++ supports multiple inheritance so you can have a generic persistence API and inherit a persistence mechanism. This would still have to use introspection to get out the class metadata, but you would still have this issue with any persistence layer.\nAlternatively you could do something similar but use the metadata to drive a code generator that fills in the 'Getters' and 'Setters' for the persistence layer.\nAny persistence layer will typically use one or the other approach, so your problem is hooking the loading mechanism into the persistence layer. I think this makes your problem little different from a single persistence layer but tackling it from the other direction. Rather than building domain classes onto a persistence framework you are providing a set of domain classes with the hooks for a persistence framework that third parties can plug their data access mechanism into.\nI think that once you provide access to class metadata and callbacks the perisistence mechanism is relatively straightforward. Look at the metadata components of any convenient C++ O/R mapping framework and understand how they work. Encapsulate this with an API in one of the base classes of your domain classes and provide a generic getter/setter API for instantiation or persisting. The rest is up to the person implementing the persistence layer.\nEdit: I can't think of a C++ library with the type of pluggable persistence mechanism you're describing, but I did something in Python that could have had this type of facility added. The particular implementation used facilities in Python with no direct C++ equivalent, although the basic principle could probably be adapted to work with C++.\nIn Python, you can intercept accesses to instance variables by overriding __getattr()__ and __setattr()__. The persistence mechanism actually maintained its own data cache behind the scenes. When the functionality was mixed into the class (done through multiple inheritance), it overrode the default system behaviour for member accessing and checked whether the attribute being queried matched anything in its dictionary. Where this happened, the call was redirected to get or set an item in the data cache.\nThe cache had metadata of its own. It was aware of relationships between entities within its data model, and knew which attribute names to intercept to access data. The way this worked separated it from the database access layer and could (at least in theory) have allowed the persistence mechanism to be used with different drivers. There is no inherent reason that you couldn't have (for example) built a driver that serialised it out to an XML file.\nMaking something like this work in C++ would be a bit more fiddly, and it may not be possible to make the object cache access as transparent as it was with this system. You would probably be best with an explicit protocol that loads and flushes the object's state to the cache. The code to this would be quite amenable to generation from the cache metadata, but this would have to be done at compile time. You may be able to do something with templates or by overriding the -> operator to make the access protocol more transparent, but this is probably more trouble than it's worth.\n", "I would avoid serialization, IMHO, we implemented this for one of our applications in MFC back in 1995, we were smart enough to use independent object versioning, and file versioning, but you end up with a lot of old messy code around after time.\nImagine certain scenarios, deprecating classes, deprecating members, etc, each presents a new problem. Now we use compreseds \"XML type\" streams, we can add new data and maintain backward compatibility.\nReading and writing the file is abstracted from mapping the data to the objects, we can now switch file formats, add importers/exporters without modification to our core business objects.\nThat being said some developers love serialization, my own encounters is that switching code base, platforms, languages, toolkits all bring along a lot of problems, reading and writing your data should not be one of them.\nAdditionally using a standard data format, with some proprietary key, means its a lot easier to work with 3rd parties.\n", "You might like to look at boost serialization. Not having used it I can't say whether to recommend it or not. Boost libraries are typically high quality.\n" ]
[ 1, 1, 1, 0 ]
[]
[]
[ "c++", "design_patterns", "persistence" ]
stackoverflow_0000113818_c++_design_patterns_persistence.txt
Q: Finding Cell Range With Excel Macros I have an many embedded objects (shapes) in a worksheet and the icons is displayed inside a cell. How do I know the Cell range in which the shape object is displayed. Example: When I select a B2 and then select the object(shape) in the B17, and I query on the Cell.Address it shows B2 - how do I get the cell address as B17? thanks A: You can use the Shape properties .TopLeftCell and .BottomRightCell to return the extents of the rectangular range that the shape overlaps. In your example, YourShape.TopLeftCell.Address should return $B$17
Finding Cell Range With Excel Macros
I have an many embedded objects (shapes) in a worksheet and the icons is displayed inside a cell. How do I know the Cell range in which the shape object is displayed. Example: When I select a B2 and then select the object(shape) in the B17, and I query on the Cell.Address it shows B2 - how do I get the cell address as B17? thanks
[ "You can use the Shape properties .TopLeftCell and .BottomRightCell to return the extents of the rectangular range that the shape overlaps.\nIn your example, YourShape.TopLeftCell.Address should return $B$17\n" ]
[ 4 ]
[]
[]
[ "excel", "vba" ]
stackoverflow_0000113983_excel_vba.txt
Q: How do I get the current size of a matrix stack in OpenGL? How do I get the current size of a matrix stack (GL_MODELVIEW, GL_PROJECTION, GL_TEXTURE) in OpenGL? I want this so that I can do some error checking to ensure that in certain parts of the code I can check that the matrix stacks have been left in the original condition. A: Try: GLint depth; glGetIntegerv (GL_MODELVIEW_STACK_DEPTH, &depth); The enums for the other stacks are: GL_MODELVIEW_STACK_DEPTH GL_PROJECTION_STACK_DEPTH GL_TEXTURE_STACK_DEPTH If you use multi-texturing, you have more than one texture matrix stack to query. To do so, set the current texture-unit via glActiveTexture();.
How do I get the current size of a matrix stack in OpenGL?
How do I get the current size of a matrix stack (GL_MODELVIEW, GL_PROJECTION, GL_TEXTURE) in OpenGL? I want this so that I can do some error checking to ensure that in certain parts of the code I can check that the matrix stacks have been left in the original condition.
[ "Try:\n GLint depth;\n glGetIntegerv (GL_MODELVIEW_STACK_DEPTH, &depth);\n\nThe enums for the other stacks are:\n GL_MODELVIEW_STACK_DEPTH \n GL_PROJECTION_STACK_DEPTH \n GL_TEXTURE_STACK_DEPTH \n\nIf you use multi-texturing, you have more than one texture matrix stack to query. To do so, set the current texture-unit via glActiveTexture();.\n" ]
[ 15 ]
[]
[]
[ "c", "graphics", "matrix", "opengl" ]
stackoverflow_0000114011_c_graphics_matrix_opengl.txt
Q: Variable height items in Win32 TreeView using NM_CUSTOMDRAW Is it possible for items in a WIn32 TreeView control to have variable heights when using NM_CUSTOMDRAW? Right now, I can successfully select variable sized fonts in the dc in NM_CUSTOMDRAW, but the item texts get clipped. A: You need to set the height of each item using the iIntegral member of the TVITEMEX structure that you specify when you insert the item.
Variable height items in Win32 TreeView using NM_CUSTOMDRAW
Is it possible for items in a WIn32 TreeView control to have variable heights when using NM_CUSTOMDRAW? Right now, I can successfully select variable sized fonts in the dc in NM_CUSTOMDRAW, but the item texts get clipped.
[ "You need to set the height of each item using the iIntegral member of the TVITEMEX structure that you specify when you insert the item.\n" ]
[ 1 ]
[]
[]
[ "treeview", "winapi" ]
stackoverflow_0000114005_treeview_winapi.txt
Q: What is the fastest way (in theory at least) to sort a heap? A heap is a list where the following applies: l[i] <= l[2*i] && l[i] <= [2*i+1] for 0 <= i < len(list) I'm looking for in-place sorting. A: Just use heap-sort. It is in-place. That would be the most natural choice. You can as well just use your heap as it and sort it with some other algorithm. Afterwards you re-build your heap from the sorted list. Quicksort is a good candidate because you can be sure it won't run in the worst-case O(n²) order simply because your heap is already pre-sorted. That may be faster if your compare-function is expensive. Heap-sort tend to evaluate the compare-function quite often. A: Well you are half way through a Heap Sort already, by having your data in a heap. You just need to implement the second part of the heap sort algorithm. This should be faster than using quicksort on the heap array. If you are feeling brave you could have a go at implementing smoothsort, which is faster than heapsort for nearly-sorted data. A: Sorting a heap in-place kind of sounds like a job for Heap Sort. I assume memory is constrained, an embedded app, perhaps? A: Since you already have a heap, couldn't you just use the second phase of the heap sort? It works in place and should be nice and efficient. A: For in-place sorting, the fastest way follows. Beware of off-by-one errors in my code. Note that this method gives a reversed sorted list which needs to be unreversed in the final step. If you use a max-heap, this problem goes away. The general idea is a neat one: swap the smallest element (at index 0) with the last element in the heap, bubble that element down until the heap property is restored, shrink the size of the heap by one and repeat. This isn't the absolute fastest way for non-in-place sorting as David Mackay demonstrates here - you can do better by putting an element more likely to be the smallest at the top of the heap instead of one from the bottom row. Time complexity is T(n.log n) worst case - n iterations with possibly log n (the height of the heap) goes through the while loop. for (int k=len(l)-1;k>0;k--){ swap( l, 0, k ); while (i*2 < k) { int left = i*2; int right = l*2 + 1; int swapidx = i; if ( l[left] < l[right] ) { if (l[i] > l[left]) { swapidx = left; } } else { if (l[i] > l[right]) { swapidx = right; } } if (swapidx == i) { // Found right place in the heap, break. break; } swap( l, i, swapidx ); i = swapidx; }} // Now reverse the list in linear time: int s = 0; int e = len(l)-1; while (e > s) { swap( l, s, e ); s++; e--: }
What is the fastest way (in theory at least) to sort a heap?
A heap is a list where the following applies: l[i] <= l[2*i] && l[i] <= [2*i+1] for 0 <= i < len(list) I'm looking for in-place sorting.
[ "Just use heap-sort. It is in-place. That would be the most natural choice.\nYou can as well just use your heap as it and sort it with some other algorithm. Afterwards you re-build your heap from the sorted list. Quicksort is a good candidate because you can be sure it won't run in the worst-case O(n²) order simply because your heap is already pre-sorted.\nThat may be faster if your compare-function is expensive. Heap-sort tend to evaluate the compare-function quite often.\n", "Well you are half way through a Heap Sort already, by having your data in a heap. You just need to implement the second part of the heap sort algorithm. This should be faster than using quicksort on the heap array.\nIf you are feeling brave you could have a go at implementing smoothsort, which is faster than heapsort for nearly-sorted data.\n", "Sorting a heap in-place kind of sounds like a job for Heap Sort.\nI assume memory is constrained, an embedded app, perhaps?\n", "Since you already have a heap, couldn't you just use the second phase of the heap sort? It works in place and should be nice and efficient.\n", "For in-place sorting, the fastest way follows. Beware of off-by-one errors in my code. Note that this method gives a reversed sorted list which needs to be unreversed in the final step. If you use a max-heap, this problem goes away. \nThe general idea is a neat one: swap the smallest element (at index 0) with the last element in the heap, bubble that element down until the heap property is restored, shrink the size of the heap by one and repeat. \nThis isn't the absolute fastest way for non-in-place sorting as David Mackay demonstrates here - you can do better by putting an element more likely to be the smallest at the top of the heap instead of one from the bottom row.\nTime complexity is T(n.log n) worst case - n iterations with possibly log n (the height of the heap) goes through the while loop.\nfor (int k=len(l)-1;k>0;k--){\nswap( l, 0, k );\nwhile (i*2 < k)\n {\nint left = i*2;\nint right = l*2 + 1;\nint swapidx = i;\nif ( l[left] < l[right] )\n {\n if (l[i] > l[left])\n {\n swapidx = left;\n }\n }\nelse\n {\n if (l[i] > l[right])\n {\n swapidx = right;\n }\n }\n\nif (swapidx == i)\n {\n // Found right place in the heap, break.\n break;\n }\nswap( l, i, swapidx );\ni = swapidx;\n }}\n\n// Now reverse the list in linear time:\nint s = 0; \nint e = len(l)-1;\nwhile (e > s)\n {\n swap( l, s, e );\n s++; e--:\n }\n\n" ]
[ 2, 1, 0, 0, 0 ]
[ "Read the items off the top of the heap one by one. Basically what you have then is heap sort.\n" ]
[ -1 ]
[ "heap", "sorting" ]
stackoverflow_0000113991_heap_sorting.txt
Q: What does "Optimize Code" option really do in Visual Studio? Name of the option tells something but what Visual Studio/compiler really do and what are the real consequences? Edit: If you search google you can find this address, but that is not really I am looking for. I wonder the real things happening. For example why do the loops get less time, etc. A: Without optimizations the compiler produces very dumb code - each command is compiled in a very straightforward manner, so that it does the intended thing. The Debug builds have optimizations disabled by default, because without the optimizations the produced executable matches the source code in a straightforward manner. Variables kept in registers Once you turn on the optimizations, the compiler applies many different techniques to make the code run faster while still doing the same thing. The most obvious difference between optimized and unoptimized builds in Visual C++ is the fact the variable values are kept in registers as long as possible in optimized builds, while without optimizations they are always stored into the memory. This affects not only the code speed, but it also affects debugging. As a result of this optimization the debugger cannot reliably obtain a variable value as you are stepping through the code. Other optimizations There are multiple other optimizations applied by the compiler, as described in /O Options (Optimize Code) MSDN docs. For a general description of various optimizations techniques see Wikipedia Compiler Optimization article. A: From Paul Vick's blog: It removes any NOP instructions that we would otherwise emit to assist in debugging. When optimizations are off (and debugging information is turned on), the compiler will emit NOP instructions for lines that don't have any actual IL associated with them but which you might want to put a breakpoint on. The most common example of something like this would be the “End If“ of an “If” statement - there's no actual IL emitted for an End If, so we don't emit a NOP the debugger won't let you set a breakpoint on it. Turning on optimizations forces the compiler not to emit the NOPs. We do a simple basic block analysis of the generated IL to remove any dead code blocks. That is, we break apart each method into blocks of IL separated by branch instructions. By doing a quick analysis of how the blocks interrelate, we can identify any blocks that have no branches into them. Thus, we can figure out code blocks that will never be executed and can be omitted, making the assembly slightly smaller. We also do some minor branch optimizations at this point as well - for example, if you GoTo another GoTo statement, we just optimize the first GoTo to jump to the second GoTo's target. We emit a DebuggableAttribute with IsJITOptimizerDisabled set to False. Basically, this allows the run-time JIT to optimize the code how it sees fit, including reordering and inlining code. This will produce more efficient and smaller code, but it means that trying to debug the code can be very challenging (as anyone who's tried it will tell you). The actual list of what the JIT optimizations are is something that I don't know - maybe someone like Chris Brumme will chime in at some point on this. The long and the short of it is that the optimization switch enables optimizations that might make setting breakpoints and stepping through your code harder. A: The short answer is: use -Ox and let the compiler do its job. The long answer: the effect of different kind of optimizations is impossible to predict accurately. Sometimes optimizing for fast code will actually yield smaller code than when optimizing for size. If you really want to get the last 0.01% of performance (speedwise or sizewise), you have to benchmark different combination of options. Also, recent versions of Visual Studio have options for more advanced optimizations such as link-time optimization and profile-guided optimization.
What does "Optimize Code" option really do in Visual Studio?
Name of the option tells something but what Visual Studio/compiler really do and what are the real consequences? Edit: If you search google you can find this address, but that is not really I am looking for. I wonder the real things happening. For example why do the loops get less time, etc.
[ "Without optimizations the compiler produces very dumb code - each command is compiled in a very straightforward manner, so that it does the intended thing. The Debug builds have optimizations disabled by default, because without the optimizations the produced executable matches the source code in a straightforward manner.\nVariables kept in registers\nOnce you turn on the optimizations, the compiler applies many different techniques to make the code run faster while still doing the same thing. The most obvious difference between optimized and unoptimized builds in Visual C++ is the fact the variable values are kept in registers as long as possible in optimized builds, while without optimizations they are always stored into the memory. This affects not only the code speed, but it also affects debugging. As a result of this optimization the debugger cannot reliably obtain a variable value as you are stepping through the code.\nOther optimizations\nThere are multiple other optimizations applied by the compiler, as described in /O Options (Optimize Code) MSDN docs. For a general description of various optimizations techniques see Wikipedia Compiler Optimization article.\n", "From Paul Vick's blog:\n\nIt removes any NOP instructions that we would otherwise emit to assist in debugging. When optimizations are off (and debugging information is turned on), the compiler will emit NOP instructions for lines that don't have any actual IL associated with them but which you might want to put a breakpoint on. The most common example of something like this would be the “End If“ of an “If” statement - there's no actual IL emitted for an End If, so we don't emit a NOP the debugger won't let you set a breakpoint on it. Turning on optimizations forces the compiler not to emit the NOPs.\nWe do a simple basic block analysis of the generated IL to remove any dead code blocks. That is, we break apart each method into blocks of IL separated by branch instructions. By doing a quick analysis of how the blocks interrelate, we can identify any blocks that have no branches into them. Thus, we can figure out code blocks that will never be executed and can be omitted, making the assembly slightly smaller. We also do some minor branch optimizations at this point as well - for example, if you GoTo another GoTo statement, we just optimize the first GoTo to jump to the second GoTo's target.\nWe emit a DebuggableAttribute with IsJITOptimizerDisabled set to False. Basically, this allows the run-time JIT to optimize the code how it sees fit, including reordering and inlining code. This will produce more efficient and smaller code, but it means that trying to debug the code can be very challenging (as anyone who's tried it will tell you). The actual list of what the JIT optimizations are is something that I don't know - maybe someone like Chris Brumme will chime in at some point on this.\nThe long and the short of it is that the optimization switch enables optimizations that might make setting breakpoints and stepping through your code harder.\n\n", "The short answer is: use -Ox and let the compiler do its job.\nThe long answer: the effect of different kind of optimizations is impossible to predict accurately. Sometimes optimizing for fast code will actually yield smaller code than when optimizing for size. If you really want to get the last 0.01% of performance (speedwise or sizewise), you have to benchmark different combination of options.\nAlso, recent versions of Visual Studio have options for more advanced optimizations such as link-time optimization and profile-guided optimization.\n" ]
[ 66, 18, 2 ]
[]
[]
[ "optimization", "visual_studio" ]
stackoverflow_0000113866_optimization_visual_studio.txt
Q: ASP.NET MVC Preview 5 - Html.Image helper has moved namespace We've just updated ASP.NET from Preview 3 to Preview 5 and we've run into a problem with the Html.Image HtmlHelper in our aspx pages. It seems that Html.Image has moved from System.Web.Mvc into Microsoft.Web.Mvc, and the only way we've found to access the helper now is to add an import statement to every .aspx page that uses it. All the other helpers can be accessed with using System.Web.Mvc; in the C# codebehind of a view master page, but this one seems to need an <@Import Namespace="Microsoft.Web.Mvc"> in every .aspx page. Does anyone know of a way around this? A: You can add the namespace to pages in System.Web in you web config. <pages validateRequest="false"> <namespaces> <add namespace="Microsoft.Web.Mvc"/> </namespaces> </pages>
ASP.NET MVC Preview 5 - Html.Image helper has moved namespace
We've just updated ASP.NET from Preview 3 to Preview 5 and we've run into a problem with the Html.Image HtmlHelper in our aspx pages. It seems that Html.Image has moved from System.Web.Mvc into Microsoft.Web.Mvc, and the only way we've found to access the helper now is to add an import statement to every .aspx page that uses it. All the other helpers can be accessed with using System.Web.Mvc; in the C# codebehind of a view master page, but this one seems to need an <@Import Namespace="Microsoft.Web.Mvc"> in every .aspx page. Does anyone know of a way around this?
[ "You can add the namespace to pages in System.Web in you web config.\n<pages validateRequest=\"false\">\n <namespaces>\n <add namespace=\"Microsoft.Web.Mvc\"/> \n </namespaces>\n</pages>\n\n" ]
[ 10 ]
[]
[]
[ "asp.net_mvc", "html_helper", "web_config" ]
stackoverflow_0000114108_asp.net_mvc_html_helper_web_config.txt
Q: Exception handling Can you please clarify the folowing query? I am not sure if the way I am trying to code is correct. Kindly advise me if I am moving in the right/wrong direction. I am trying to develop an automation framework using QuickTest Professional, a testing tool. There is an Excel sheet from which the data is being taken for execution based on the ID's stored in an array from another Excel sheet (The same ID is available in both Excel sheets). I'm trying to handle the exeptional cases through a function call. This function will capture the screenshot of the page error occured and then exit the entire loop. I need a scenario where execution continues for the next ID stored in the array, and this needs to be handled from the function call. A: Well, it sounds like you already have the answer.. You just need to handle the expection that occurs when reading in the data within the main loop and make it stop there.. Now, I have not done VBScript for a LONG time so, to pseudo it: While Not EndOfExcelSheet ReadDataFromExcel(); If errOccurred Then TakeScreenPrint(); 'NOTE: We have caught the error and requested the screen print 'is taken, but we have NOT bubbled the exception up! End While A: It's hard to answer your question based on what you wrote, but the first thing that comes to my mind is to add a boolean parameter to your exception-handling function (let's call it ExceptionHandler). Say, if the parameter (let's call it ExitLoop) is true, you wll exit from the "entire loop", otherwise, continue. Now, it might be too tedius to change that for old calls to the function (calls without the new parameter) -- I'm not sure if VB supports function overloading. If this is the case, you can rename your ExceptionHandler to ExceptionHandler2, add the new parameter (ExitLoop) and logic to it and create a (now new) function ExceptionHandler that calls ExceptionHandler2 with its parameters plus true for ExitLoop. Hope it helps.
Exception handling
Can you please clarify the folowing query? I am not sure if the way I am trying to code is correct. Kindly advise me if I am moving in the right/wrong direction. I am trying to develop an automation framework using QuickTest Professional, a testing tool. There is an Excel sheet from which the data is being taken for execution based on the ID's stored in an array from another Excel sheet (The same ID is available in both Excel sheets). I'm trying to handle the exeptional cases through a function call. This function will capture the screenshot of the page error occured and then exit the entire loop. I need a scenario where execution continues for the next ID stored in the array, and this needs to be handled from the function call.
[ "Well, it sounds like you already have the answer.. You just need to handle the expection that occurs when reading in the data within the main loop and make it stop there..\nNow, I have not done VBScript for a LONG time so, to pseudo it:\nWhile Not EndOfExcelSheet\n ReadDataFromExcel();\n If errOccurred Then TakeScreenPrint();\n 'NOTE: We have caught the error and requested the screen print\n 'is taken, but we have NOT bubbled the exception up!\nEnd While\n\n", "It's hard to answer your question based on what you wrote, but the first thing that comes to my mind is to add a boolean parameter to your exception-handling function (let's call it ExceptionHandler). Say, if the parameter (let's call it ExitLoop) is true, you wll exit from the \"entire loop\", otherwise, continue. Now, it might be too tedius to change that for old calls to the function (calls without the new parameter) -- I'm not sure if VB supports function overloading. If this is the case, you can rename your ExceptionHandler to ExceptionHandler2, add the new parameter (ExitLoop) and logic to it and create a (now new) function ExceptionHandler that calls ExceptionHandler2 with its parameters plus true for ExitLoop.\nHope it helps.\n" ]
[ 1, 0 ]
[]
[]
[ "vbscript" ]
stackoverflow_0000114054_vbscript.txt
Q: Miktex on Windows Vista I have some problems with Miktex installed on Windows Vista Business SP1/32 bit. I use miktex 2.7, ghostscript, and texniccenter 1 beta 7.50. When I compile a document with the following profiles: Latex=>DVI, Latex=>PDF everything works fine; the system crashes when I compile with profiles Latex=>PS and Latex=>PS=>PDF. The error is reported into a window that states: "Dvi-to-Postscript converter has stopped working". What can I do? I need Latex=>PS=>PDF to include my images into the final PDF. Thanks in advance, Yet another LaTeX user A: If everything you need is images, you could still compile directly to PDF. You only need to have an image in PNG or JPG format, and use the following code: %in the document preamble \usepackage{graphicx} %in the document, in the place where you want to put your image \includegraphics{image_filename_without_extension} When the image is a PNG or JPG file (there are some more, I don't remember which ones ATM), you can compile the file with pdfLaTeX, but not with the normal LaTeX (i.e. you can produce a PDF, but not DVI or PS). Of course normally, if everything works fine, it's nice to have one copy of the image in EPS, and another in, say, PNG -- this way you can compile easily both to PDF, and to PS. Hope that helps. A: Thanks for reply. I have solved the problem: the dvi crashed because I have installed Miktex with the User Account Control enabled. I have disabled it, reinstalled and now it's working (with UAC still disabled).
Miktex on Windows Vista
I have some problems with Miktex installed on Windows Vista Business SP1/32 bit. I use miktex 2.7, ghostscript, and texniccenter 1 beta 7.50. When I compile a document with the following profiles: Latex=>DVI, Latex=>PDF everything works fine; the system crashes when I compile with profiles Latex=>PS and Latex=>PS=>PDF. The error is reported into a window that states: "Dvi-to-Postscript converter has stopped working". What can I do? I need Latex=>PS=>PDF to include my images into the final PDF. Thanks in advance, Yet another LaTeX user
[ "If everything you need is images, you could still compile directly to PDF. You only need to have an image in PNG or JPG format, and use the following code:\n%in the document preamble\n\\usepackage{graphicx}\n\n%in the document, in the place where you want to put your image\n\\includegraphics{image_filename_without_extension}\n\nWhen the image is a PNG or JPG file (there are some more, I don't remember which ones ATM), you can compile the file with pdfLaTeX, but not with the normal LaTeX (i.e. you can produce a PDF, but not DVI or PS).\nOf course normally, if everything works fine, it's nice to have one copy of the image in EPS, and another in, say, PNG -- this way you can compile easily both to PDF, and to PS.\nHope that helps.\n", "Thanks for reply. I have solved the problem: the dvi crashed because I have installed Miktex with the User Account Control enabled. I have disabled it, reinstalled and now it's working (with UAC still disabled). \n" ]
[ 1, 0 ]
[]
[]
[ "crash", "miktex", "windows_vista" ]
stackoverflow_0000111405_crash_miktex_windows_vista.txt
Q: Best mock framework that can do both WebForms and MVC? I'm getting into more of a TDD workflow, and have a mix of MVC and asp.net Web Forms apps. MOQ is recommended for MVC. I've used Rhino for Web Forms. Does anyone have a best practice for having 1 framework mock for both? A: This is sort of a silly question, but I prefer Rhino Mocks as it represents a more complete understanding of mocks vs. stubs. Look deep into TypeMock before committing to the price. Also, there is no recommended mocking framework for ASP.NET MVC. Finally - I'd suggest you stick to one mocking framework in your project (and even in your team) - the differences, while not huge, can lead to confusion that is unwarranted on such a "polishing-the-rock" decision. By that I mean the decision should not be a long one, just pick what works and get on with creating value. A: Rhino's latest release includes much of the sweet sweet 3.5 love that MoQ has. I'm a fan of MoQ, so that's what I'm using. But I also have Rhino, in case it does something that MoQ doesn't do. TL;DR: MoQ it baby. A: TypeMock is insanely powerful. When I needed to unit test a web forms app that wasn't designed for testability TypeMock saved my life. But when I take the time to pick an architectural pattern (MVC) or design one that allows for Mockability (you know, public virtualize state changing methods) I use Moq. It is so simple to use and so simple to teach others. TypeMock's record replay syntax still confuses me, but it saved me plenty of time in a tight release schedule. Moq's API is almost self explanatory which is an amazing achievement given the mock library history. A: I would just go ahead and use my favourite framework for both. I don't think there's any reason that I would choose one framework for web forms and another for MVC. A far bigger problem is how I would unit test my web forms pages at all, since it's notoriously hard to seperate the page from the rest of the HttpRequest stack. My favourite is Moq. I've also used TypeMock. It costs money, but it's really powerful - it lets you mock concrete classes and constructors, so you could potentially mock things like HttpContext or HttpRequest. A: Look into Ivonna for faking HTTPContext and traditional webforms. http://sm-art.biz/Ivonna.aspx
Best mock framework that can do both WebForms and MVC?
I'm getting into more of a TDD workflow, and have a mix of MVC and asp.net Web Forms apps. MOQ is recommended for MVC. I've used Rhino for Web Forms. Does anyone have a best practice for having 1 framework mock for both?
[ "This is sort of a silly question, but I prefer Rhino Mocks as it represents a more complete understanding of mocks vs. stubs.\nLook deep into TypeMock before committing to the price.\nAlso, there is no recommended mocking framework for ASP.NET MVC.\nFinally - I'd suggest you stick to one mocking framework in your project (and even in your team) - the differences, while not huge, can lead to confusion that is unwarranted on such a \"polishing-the-rock\" decision. By that I mean the decision should not be a long one, just pick what works and get on with creating value. \n", "Rhino's latest release includes much of the sweet sweet 3.5 love that MoQ has. I'm a fan of MoQ, so that's what I'm using. But I also have Rhino, in case it does something that MoQ doesn't do.\nTL;DR: MoQ it baby.\n", "TypeMock is insanely powerful. When I needed to unit test a web forms app that wasn't designed for testability TypeMock saved my life.\nBut when I take the time to pick an architectural pattern (MVC) or design one that allows for Mockability (you know, public virtualize state changing methods) I use Moq. It is so simple to use and so simple to teach others.\nTypeMock's record replay syntax still confuses me, but it saved me plenty of time in a tight release schedule. Moq's API is almost self explanatory which is an amazing achievement given the mock library history.\n", "I would just go ahead and use my favourite framework for both. I don't think there's any reason that I would choose one framework for web forms and another for MVC. A far bigger problem is how I would unit test my web forms pages at all, since it's notoriously hard to seperate the page from the rest of the HttpRequest stack.\nMy favourite is Moq. I've also used TypeMock. It costs money, but it's really powerful - it lets you mock concrete classes and constructors, so you could potentially mock things like HttpContext or HttpRequest.\n", "Look into Ivonna for faking HTTPContext and traditional webforms.\nhttp://sm-art.biz/Ivonna.aspx\n" ]
[ 2, 1, 1, 0, 0 ]
[]
[]
[ "asp.net", "asp.net_mvc", "c#", "testing" ]
stackoverflow_0000010098_asp.net_asp.net_mvc_c#_testing.txt
Q: Property Grid Object failing on combo box selection but OK when combobox scrolled or double clicked I have a Property Grid in C#, loading up a 'PropertyAdapter' object (a basic wrapper around one of my objects displaying relevant properties with the appropriate tags) I have a TypeConverter on one of the properties (DataType, that returns an enumeration of possible values) as I want to limit the values available to the property grid to Decimal and Integer, with the 2 methods as follows public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { return new StandardValuesCollection(new List<Constants.DataTypes>() { Constants.DataTypes.Decimal, Constants.DataTypes.Integer }); } This is displaying just as I want it on the property grid, and when I double click the property field in the property grid, it happily switches between Integer and Decimal. Similarily I can use the mouse wheel to scroll through the options in the property filed's combobox. If I however use the property field as a Combo Box and select a value from the drop-down, I get the standard property grid error box with the error: Object of type 'System.String' cannot be converted to type 'Pelion.PM3.Utils.Constants+DataTypes'. I am assuming I can use the Converter overrides in the Type converter to trap these and convert them to an Enum of DataTypes, but why would the property grid fail when I select from the drop-down instead of double clicking or 'mouseewheeling' on the drop down? A: When selected from the combo box drop down, the value is returned as string. I am not sure why that is, but I've seen in happen before. I think that basically double clicking or scrolling the mousewheel changes values from the value collection, while selecting from the drop down is like editing the field value as a string. Then, you have the convert the value from a string to the enum value.
Property Grid Object failing on combo box selection but OK when combobox scrolled or double clicked
I have a Property Grid in C#, loading up a 'PropertyAdapter' object (a basic wrapper around one of my objects displaying relevant properties with the appropriate tags) I have a TypeConverter on one of the properties (DataType, that returns an enumeration of possible values) as I want to limit the values available to the property grid to Decimal and Integer, with the 2 methods as follows public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { return new StandardValuesCollection(new List<Constants.DataTypes>() { Constants.DataTypes.Decimal, Constants.DataTypes.Integer }); } This is displaying just as I want it on the property grid, and when I double click the property field in the property grid, it happily switches between Integer and Decimal. Similarily I can use the mouse wheel to scroll through the options in the property filed's combobox. If I however use the property field as a Combo Box and select a value from the drop-down, I get the standard property grid error box with the error: Object of type 'System.String' cannot be converted to type 'Pelion.PM3.Utils.Constants+DataTypes'. I am assuming I can use the Converter overrides in the Type converter to trap these and convert them to an Enum of DataTypes, but why would the property grid fail when I select from the drop-down instead of double clicking or 'mouseewheeling' on the drop down?
[ "When selected from the combo box drop down, the value is returned as string. I am not sure why that is, but I've seen in happen before. I think that basically double clicking or scrolling the mousewheel changes values from the value collection, while selecting from the drop down is like editing the field value as a string. Then, you have the convert the value from a string to the enum value.\n" ]
[ 3 ]
[]
[]
[ "c#", "propertygrid", "winforms" ]
stackoverflow_0000113644_c#_propertygrid_winforms.txt
Q: C++ Binary operators order of precedence In what order are the following parameters tested (in C++)? if (a || b && c) { } I've just seen this code in our application and I hate it, I want to add some brackets to just clarify the ordering. But I don't want to add the brackets until I know I'm adding them in the right place. Edit: Accepted Answer & Follow Up This link has more information, but it's not totally clear what it means. It seems || and && are the same precedence, and in that case, they are evaluated left-to-right. http://msdn.microsoft.com/en-us/library/126fe14k.aspx A: [http://www.cppreference.com/wiki/operator_precedence] (Found by googling "C++ operator precedence") That page tells us that &&, in group 13, has higher precedence than || in group 14, so the expression is equivalent to a || (b && c). Unfortunately, the wikipedia article [http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence] disagrees with this, but since I have the C89 standard on my desk and it agrees with the first site, I'm going to revise the wikipedia article. A: From here: a || (b && c) This is the default precedence. A: && (boolean AND) has higher precedence than || (boolean OR). Therefore the following are identical: a || b && c a || (b && c) A good mnemonic rule is to remember that AND is like multiplication and OR is like addition. If we replace AND with * and OR with +, we get a more familiar equivalent: a + b * c a + (b * c) Actually, in Boolean logic, AND and OR act similar to these arithmetic operators: a b a AND b a * b a OR b a + b --------------------------------------- 0 0 0 0 0 0 0 1 0 0 1 1 1 0 0 0 1 1 1 1 1 1 1 1 (2 really, but we pretend it's 1) A: To answer the follow-up: obviously the table at MSDN is botched, perhaps by somebody unable to do a decent HTML table (or using a Microsoft tool to generate it!). I suppose it should look more like the Wikipedia table referenced by Rodrigo, where we have clear sub-sections. But clearly the accepted answer is right, somehow we have same priority with && and || than with * and +, for example. The snippet you gave is clear and unambiguous for me, but I suppose adding parentheses wouldn't hurt either.
C++ Binary operators order of precedence
In what order are the following parameters tested (in C++)? if (a || b && c) { } I've just seen this code in our application and I hate it, I want to add some brackets to just clarify the ordering. But I don't want to add the brackets until I know I'm adding them in the right place. Edit: Accepted Answer & Follow Up This link has more information, but it's not totally clear what it means. It seems || and && are the same precedence, and in that case, they are evaluated left-to-right. http://msdn.microsoft.com/en-us/library/126fe14k.aspx
[ "[http://www.cppreference.com/wiki/operator_precedence] (Found by googling \"C++ operator precedence\")\nThat page tells us that &&, in group 13, has higher precedence than || in group 14, so the expression is equivalent to a || (b && c).\nUnfortunately, the wikipedia article [http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence] disagrees with this, but since I have the C89 standard on my desk and it agrees with the first site, I'm going to revise the wikipedia article.\n", "From here:\na || (b && c)\n\nThis is the default precedence.\n", "&& (boolean AND) has higher precedence than || (boolean OR). Therefore the following are identical:\na || b && c\na || (b && c)\n\nA good mnemonic rule is to remember that AND is like multiplication and OR is like addition. If we replace AND with * and OR with +, we get a more familiar equivalent:\na + b * c\na + (b * c)\n\nActually, in Boolean logic, AND and OR act similar to these arithmetic operators:\n\na b a AND b a * b a OR b a + b\n---------------------------------------\n0 0 0 0 0 0\n0 1 0 0 1 1\n1 0 0 0 1 1\n1 1 1 1 1 1 (2 really, but we pretend it's 1)\n\n", "To answer the follow-up: obviously the table at MSDN is botched, perhaps by somebody unable to do a decent HTML table (or using a Microsoft tool to generate it!).\nI suppose it should look more like the Wikipedia table referenced by Rodrigo, where we have clear sub-sections.\nBut clearly the accepted answer is right, somehow we have same priority with && and || than with * and +, for example.\nThe snippet you gave is clear and unambiguous for me, but I suppose adding parentheses wouldn't hurt either.\n" ]
[ 7, 4, 2, 0 ]
[ "I'm not sure but it should be easy for you to find out.\nJust create a small program with a statement that prints out the truth value of:\n(true || false && true)\nIf the result is true, then the || has higher precedence than &&, if it is falase, it's the other way around.\n" ]
[ -2 ]
[ "binary_operators", "c++" ]
stackoverflow_0000113992_binary_operators_c++.txt
Q: How does a XAML definition get turned into an object instance? XAML allows you to specify an attribute value using a string that contains curly braces. Here is an example that creates a Binding instance and assigns it to the Text property of the TextBox element. <TextBox Text="{Binding ElementName=Foo, Path=Bar}"/> I want to extend XAML so that the developer could enter this as valid... <TextBox Text="{MyCustomObject Field1=Foo, Field2=Bar}"/> This would create an instance of my class and set the Field1/Field2 properties as appropriate. Is this possible? If so how do you do it? If this is possible I have a followup question. Can I take a string "{Binding ElementName=Foo, Path=Bar}" and ask the framework to process it and return the Binding instance it specified? This must be done somewhere already to make the above XAML work and so there must be a way to ask for the same thing to be processed. A: The Binding class is a Markup Extension. You can write your own by deriving from System.Windows.Markup.MarkupExtension. ElementName and Path are simply properties on the Binding object. As for the followup you can create a new Binding in code by instantiating the Binding object. I do not know of a way to process a string through. A: take a look at markupextensions http://blogs.msdn.com/wpfsdk/archive/2007/03/22/blogpost-text-creatingasimplecustommarkupextension.aspx
How does a XAML definition get turned into an object instance?
XAML allows you to specify an attribute value using a string that contains curly braces. Here is an example that creates a Binding instance and assigns it to the Text property of the TextBox element. <TextBox Text="{Binding ElementName=Foo, Path=Bar}"/> I want to extend XAML so that the developer could enter this as valid... <TextBox Text="{MyCustomObject Field1=Foo, Field2=Bar}"/> This would create an instance of my class and set the Field1/Field2 properties as appropriate. Is this possible? If so how do you do it? If this is possible I have a followup question. Can I take a string "{Binding ElementName=Foo, Path=Bar}" and ask the framework to process it and return the Binding instance it specified? This must be done somewhere already to make the above XAML work and so there must be a way to ask for the same thing to be processed.
[ "The Binding class is a Markup Extension. You can write your own by deriving from System.Windows.Markup.MarkupExtension.\nElementName and Path are simply properties on the Binding object.\nAs for the followup you can create a new Binding in code by instantiating the Binding object. I do not know of a way to process a string through.\n", "take a look at markupextensions\nhttp://blogs.msdn.com/wpfsdk/archive/2007/03/22/blogpost-text-creatingasimplecustommarkupextension.aspx\n" ]
[ 2, 1 ]
[]
[]
[ "wpf", "xaml" ]
stackoverflow_0000114154_wpf_xaml.txt
Q: PHP: array_map on object? I'm trying to write a function that formats every (string) member/variable in an object, for example with a callback function. The variable names are unknown to me, so it must work with objects of all classes. How can I achieve something similar to array_map or array_walk with objects? A: use get_object_vars() to get an associative array of the members, and use the functions you mentioned. btw, you can also do a foreach on an object like you would on an array, which is sometimes useful as well. A: You can use get_object_vars(), but if you need more control, try using reflection. It's slower than get_object_vars() (or get_class_methods() for that matter), but it's much more powerful. A: You are looking for get_object_vars / get_class_methods (the first gets the variables, the second the method names).
PHP: array_map on object?
I'm trying to write a function that formats every (string) member/variable in an object, for example with a callback function. The variable names are unknown to me, so it must work with objects of all classes. How can I achieve something similar to array_map or array_walk with objects?
[ "use get_object_vars() to get an associative array of the members, and use the functions you mentioned.\nbtw, you can also do a foreach on an object like you would on an array, which is sometimes useful as well.\n", "You can use get_object_vars(), but if you need more control, try using reflection. It's slower than get_object_vars() (or get_class_methods() for that matter), but it's much more powerful.\n", "You are looking for get_object_vars / get_class_methods (the first gets the variables, the second the method names).\n" ]
[ 12, 1, 0 ]
[]
[]
[ "oop", "php" ]
stackoverflow_0000114229_oop_php.txt
Q: SQL: inner join on alias column Previously I have asked to strip text from a field and convert it to an int, this works successfully. But now, I would like to do an INNER JOIN on this new value. So I have this: SELECT CONVERT(int, SUBSTRING(accountingTab.id, PATINDEX('%[0-9]%', accountingTab.id), 999)) AS 'memId', userDetails.title, userDetails.lname FROM accountingTab INNER JOIN (SELECT id, title, first, last FROM memDetTab) AS userDetails ON memID = userDetails.id And then I get the Invalid Column Name memID error. How can I fix this? A: You can either repeat the whole expression or reverse your join: SELECT * FROM memDetTab JOIN (SELECT CONVERT(int, SUBSTRING(accountingTab.id, PATINDEX('%[0-9]%', accountingTab.id), 999)) AS 'memId', userDetails.title, userDetails.lname FROM accountingTab) subquery ON subquery.memID = memDetTab.ID A: Instead of memId, repeat the whole expression. A: If you have to do this, you have design problems. If you're able, I would suggest you need to refactor your table or relationships.
SQL: inner join on alias column
Previously I have asked to strip text from a field and convert it to an int, this works successfully. But now, I would like to do an INNER JOIN on this new value. So I have this: SELECT CONVERT(int, SUBSTRING(accountingTab.id, PATINDEX('%[0-9]%', accountingTab.id), 999)) AS 'memId', userDetails.title, userDetails.lname FROM accountingTab INNER JOIN (SELECT id, title, first, last FROM memDetTab) AS userDetails ON memID = userDetails.id And then I get the Invalid Column Name memID error. How can I fix this?
[ "You can either repeat the whole expression or reverse your join:\n\nSELECT *\nFROM memDetTab\n JOIN (SELECT CONVERT(int, SUBSTRING(accountingTab.id, PATINDEX('%[0-9]%', accountingTab.id), 999)) AS 'memId', userDetails.title, userDetails.lname\nFROM accountingTab) subquery\n ON subquery.memID = memDetTab.ID\n\n", "Instead of memId, repeat the whole expression.\n", "If you have to do this, you have design problems. If you're able, I would suggest you need to refactor your table or relationships.\n" ]
[ 6, 2, 0 ]
[]
[]
[ "inner_join", "sql" ]
stackoverflow_0000114242_inner_join_sql.txt
Q: PDF generation from XHTML in a LAMP environment Can anyone recommend a good server-side PDF generation tool that would work in a Linux environment. I want easy as possible, pass it a XHTML file (with images) and have it generate a PDF from the rendered source. I don't have a massive budget, but anything under $1000 should be alright. Andrew A: I sounds like FPDF might be of help... Also, the creation of PDF documents is called "PDF printing". I believe that might help you find other resources. A: You might want to take a look at FOP, which stands for Formatting Objects Processor. It can generate PDF files on linux since it is Java based. From their site: Apache FOP (Formatting Objects Processor) is a print formatter driven by XSL formatting objects (XSL-FO) and an output independent formatter. It is a Java application that reads a formatting object (FO) tree and renders the resulting pages to a specified output. Output formats currently supported include PDF, PS, PCL, AFP, XML (area tree representation), Print, AWT and PNG, and to a lesser extent, RTF and TXT. The primary output target is PDF. You can find it here A: I used HTMLDoc about 8 years ago and it did a good job of turning HTML tables with some basic formatting into a decent PDF report. There also seems to be an open source version as well. A: I did some searching, what about tbookdtd? It's downloadable here but it hasn't been active since 2005. It appears to convert the xml to Latex, into PDF. A: Have you investigated PHP's documentation? There's also PHP FAQ with a few different links. PHP primarily supports PDFlib. A: I have recently came across dompdf which I have used to convert pages created in HTML into PDF documents. It uses PHP5 (assuming using PHP does not bother you). This is also assuming that you don't want to statically create HTML files on the file system and then convert them using some kind of command-line tool? One problem I found with dompdf is that you don't get a whole lot of configuration options natively, but it is open-source and doesn't seem to be too large, so you could probably jury-rig something up pretty easily. A: If you do have a budget take a look at the following OpenEdge. I know that they did excatly what you want for us. A linux based PDF generation system. I'd ask what they can do for you. Val Cassidy is the persons name. BTW: I'm not getting anything for this and I don't even work for bespoke company anymore nor for OpenEdge ... A: You could take a look at using OpenOffice via the OpenOffice API to load your XHTML document and export a PDF version. There is a bit of a learning curve to using the OpenOffice API but it is very powerful and can be run in server mode on systems without any graphical interface. It performs well - we've used it on some internal projects.
PDF generation from XHTML in a LAMP environment
Can anyone recommend a good server-side PDF generation tool that would work in a Linux environment. I want easy as possible, pass it a XHTML file (with images) and have it generate a PDF from the rendered source. I don't have a massive budget, but anything under $1000 should be alright. Andrew
[ "I sounds like FPDF might be of help...\nAlso, the creation of PDF documents is called \"PDF printing\". I believe that might help you find other resources.\n", "You might want to take a look at FOP, which stands for Formatting Objects Processor. It can generate PDF files on linux since it is Java based. From their site:\n\nApache FOP (Formatting Objects Processor) is a print formatter driven\n by XSL formatting objects (XSL-FO) and an output independent formatter. \n It is a Java application that reads a formatting object (FO) tree\n and renders the resulting pages to a specified output. Output formats \n currently supported include PDF, PS, PCL, AFP, XML (area tree \n representation), Print, AWT and PNG, and to a lesser extent, RTF and \n TXT. The primary output target is PDF.\n\nYou can find it here\n", "I used HTMLDoc about 8 years ago and it did a good job of turning HTML tables with some basic formatting into a decent PDF report. There also seems to be an open source version as well.\n", "I did some searching, what about tbookdtd?\nIt's downloadable here but it hasn't been active since 2005. It appears to convert the xml to Latex, into PDF.\n", "Have you investigated PHP's documentation? There's also PHP FAQ with a few different links. PHP primarily supports PDFlib.\n", "I have recently came across dompdf which I have used to convert pages created in HTML into PDF documents. It uses PHP5 (assuming using PHP does not bother you). This is also assuming that you don't want to statically create HTML files on the file system and then convert them using some kind of command-line tool?\nOne problem I found with dompdf is that you don't get a whole lot of configuration options natively, but it is open-source and doesn't seem to be too large, so you could probably jury-rig something up pretty easily.\n", "If you do have a budget take a look at the following OpenEdge. I know that they did excatly what you want for us. A linux based PDF generation system.\nI'd ask what they can do for you. Val Cassidy is the persons name.\nBTW: I'm not getting anything for this and I don't even work for bespoke company anymore nor for OpenEdge ...\n", "You could take a look at using OpenOffice via the OpenOffice API to load your XHTML document and export a PDF version. There is a bit of a learning curve to using the OpenOffice API but it is very powerful and can be run in server mode on systems without any graphical interface. It performs well - we've used it on some internal projects.\n" ]
[ 1, 1, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "linux", "pdf", "pdf_generation" ]
stackoverflow_0000014911_linux_pdf_pdf_generation.txt
Q: Embedded Jetty serving static content with form authentication I try to use the Forms-Based authentication within an embedded Jetty 6.1.7 project. That's why I need to serve servlets and html (login.html) under the same context to make authentication work. I don't want to secure the hole application since different context should need different roles. The jetty javadoc states that a ContextHandlerCollection can handle different handlers for one context but I don't get it to work. My sample ignoring the authentication stuff will not work, why? ContextHandlerCollection contexts = new ContextHandlerCollection(); // serve html Context ctxADocs= new Context(contexts,"/ctxA",Context.SESSIONS); ctxADocs.setResourceBase("d:\\tmp\\ctxA"); ServletHolder ctxADocHolder= new ServletHolder(); ctxADocHolder.setInitParameter("dirAllowed", "false"); ctxADocHolder.setServlet(new DefaultServlet()); ctxADocs.addServlet(ctxADocHolder, "/"); // serve a sample servlet Context ctxA = new Context(contexts,"/ctxA",Context.SESSIONS); ctxA.addServlet(new ServletHolder(new SessionDump()), "/sda"); ctxA.addServlet(new ServletHolder(new DefaultServlet()), "/"); contexts.setHandlers(new Handler[]{ctxA, ctxADocs}); // end of snippet Any helpful thought is welcome! Thanks. Okami A: Finally I got it right, solution is to use latest jetty 6.1.12 rc2. I didn't check out what they changed - I'm just happy that it works now. A: Use the web application descriptor: Paste this in to your web.xml: <login-config> <auth-method>BASIC</auth-method> </login-config> <security-role> <role-name>MySiteRole</role-name> </security-role> <security-constraint> <display-name>ProtectEverything</display-name> <web-resource-collection> <web-resource-name>ProtectEverything</web-resource-name> <url-pattern>*.*</url-pattern> <url-pattern>/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>MySiteRole</role-name> </auth-constraint> </security-constraint> <security-constraint> <web-resource-collection> <web-resource-name>ExcludeLoginPage</web-resource-name> <url-pattern>/login.html</url-pattern> </web-resource-collection> <user-data-constraint> <transport-guarantee>NONE</transport-guarantee> </user-data-constraint> </security-constraint> Without authentication this will hide everything but the login.html.
Embedded Jetty serving static content with form authentication
I try to use the Forms-Based authentication within an embedded Jetty 6.1.7 project. That's why I need to serve servlets and html (login.html) under the same context to make authentication work. I don't want to secure the hole application since different context should need different roles. The jetty javadoc states that a ContextHandlerCollection can handle different handlers for one context but I don't get it to work. My sample ignoring the authentication stuff will not work, why? ContextHandlerCollection contexts = new ContextHandlerCollection(); // serve html Context ctxADocs= new Context(contexts,"/ctxA",Context.SESSIONS); ctxADocs.setResourceBase("d:\\tmp\\ctxA"); ServletHolder ctxADocHolder= new ServletHolder(); ctxADocHolder.setInitParameter("dirAllowed", "false"); ctxADocHolder.setServlet(new DefaultServlet()); ctxADocs.addServlet(ctxADocHolder, "/"); // serve a sample servlet Context ctxA = new Context(contexts,"/ctxA",Context.SESSIONS); ctxA.addServlet(new ServletHolder(new SessionDump()), "/sda"); ctxA.addServlet(new ServletHolder(new DefaultServlet()), "/"); contexts.setHandlers(new Handler[]{ctxA, ctxADocs}); // end of snippet Any helpful thought is welcome! Thanks. Okami
[ "Finally I got it right, solution is to use latest jetty 6.1.12 rc2.\nI didn't check out what they changed - I'm just happy that it works now.\n", "Use the web application descriptor:\nPaste this in to your web.xml:\n<login-config>\n <auth-method>BASIC</auth-method>\n</login-config>\n<security-role>\n <role-name>MySiteRole</role-name>\n</security-role>\n\n<security-constraint>\n <display-name>ProtectEverything</display-name>\n <web-resource-collection>\n <web-resource-name>ProtectEverything</web-resource-name>\n <url-pattern>*.*</url-pattern>\n <url-pattern>/*</url-pattern>\n </web-resource-collection>\n <auth-constraint>\n <role-name>MySiteRole</role-name>\n </auth-constraint>\n</security-constraint>\n\n<security-constraint>\n <web-resource-collection>\n <web-resource-name>ExcludeLoginPage</web-resource-name>\n <url-pattern>/login.html</url-pattern>\n </web-resource-collection>\n <user-data-constraint>\n <transport-guarantee>NONE</transport-guarantee>\n </user-data-constraint>\n</security-constraint>\n\nWithout authentication this will hide everything but the login.html.\n" ]
[ 3, 1 ]
[]
[]
[ "java", "jetty", "web_applications" ]
stackoverflow_0000073029_java_jetty_web_applications.txt
Q: How do I determine the value of a generic parameter on my class instance I have a marker interface defined as public interface IExtender<T> { } I have a class that implements IExtender public class UserExtender : IExtender<User> At runtime I recieve the UserExtender type as a parameter to my evaluating method public Type Evaluate(Type type) // type == typeof(UserExtender) How do I make my Evaluate method return typeof(User) based on the runtime evaluation. I am sure reflection is involved but I can't seem to crack it. (I was unsure how to word this question. I hope it is clear enough.) A: There is an example of doing what you describe in the MSDN documentation for the GetGenericTypeDefinition method. It uses the GetGenericArguments method. Type[] typeArguments = t.GetGenericArguments(); Console.WriteLine("\tList type arguments ({0}):", typeArguments.Length); foreach (Type tParam in typeArguments) { Console.WriteLine("\t\t{0}", tParam); } In your example I think you would want to replace t with this. If that doesn't work directly you may need to do something with the GetInterfaces method to enumerate the current interfaces on your type and then GetGenericArguments() from the interface type. A: I went this way based on some of the tidbits provided. It could be made more robust to handle multiple generic arguments on the interface.... but I didn't need it to ;) private static Type SafeGetSingleGenericParameter(Type type, Type interfaceType) { if (!interfaceType.IsGenericType || interfaceType.GetGenericArguments().Count() != 1) return type; foreach (Type baseInterface in type.GetInterfaces()) { if (baseInterface.IsGenericType && baseInterface.GetGenericTypeDefinition() == interfaceType.GetGenericTypeDefinition()) { return baseInterface.GetGenericArguments().Single(); } } return type; } A: I read your question completely differently than the other answers. If the evaluate signature can be changed to: public Type Evaluate<T>(IExtender<T> it) { return typeof(T); } This doesn't require the calling code to change, but does require the parameter to be of type IExtender<T>, however you can easily get at the type T : // ** compiled and tested UserExtender ue = new UserExtender(); Type t = Evaluate(ue); Certainly it's not as generic as something just taking a Type parameter, but this is a different take on the problem. Also note that there are Security Considerations for Reflection [msdn]
How do I determine the value of a generic parameter on my class instance
I have a marker interface defined as public interface IExtender<T> { } I have a class that implements IExtender public class UserExtender : IExtender<User> At runtime I recieve the UserExtender type as a parameter to my evaluating method public Type Evaluate(Type type) // type == typeof(UserExtender) How do I make my Evaluate method return typeof(User) based on the runtime evaluation. I am sure reflection is involved but I can't seem to crack it. (I was unsure how to word this question. I hope it is clear enough.)
[ "There is an example of doing what you describe in the MSDN documentation for the GetGenericTypeDefinition method. It uses the GetGenericArguments method.\nType[] typeArguments = t.GetGenericArguments();\nConsole.WriteLine(\"\\tList type arguments ({0}):\", typeArguments.Length);\nforeach (Type tParam in typeArguments)\n{\n Console.WriteLine(\"\\t\\t{0}\", tParam);\n}\n\nIn your example I think you would want to replace t with this. If that doesn't work directly you may need to do something with the GetInterfaces method to enumerate the current interfaces on your type and then GetGenericArguments() from the interface type.\n", "I went this way based on some of the tidbits provided. It could be made more robust to handle multiple generic arguments on the interface.... but I didn't need it to ;)\nprivate static Type SafeGetSingleGenericParameter(Type type, Type interfaceType)\n{\n if (!interfaceType.IsGenericType || interfaceType.GetGenericArguments().Count() != 1)\n return type;\n\n foreach (Type baseInterface in type.GetInterfaces())\n {\n if (baseInterface.IsGenericType &&\n baseInterface.GetGenericTypeDefinition() == interfaceType.GetGenericTypeDefinition())\n {\n return baseInterface.GetGenericArguments().Single();\n }\n }\n\n return type;\n}\n\n", "I read your question completely differently than the other answers. \nIf the evaluate signature can be changed to:\npublic Type Evaluate<T>(IExtender<T> it)\n{\n return typeof(T);\n}\n\nThis doesn't require the calling code to change, but does require the parameter to be of type IExtender<T>, however you can easily get at the type T :\n// ** compiled and tested \nUserExtender ue = new UserExtender();\nType t = Evaluate(ue);\n\nCertainly it's not as generic as something just taking a Type parameter, but this is a different take on the problem. Also note that there are Security Considerations for Reflection [msdn] \n" ]
[ 1, 1, 1 ]
[]
[]
[ "c#", "generics", "reflection" ]
stackoverflow_0000113384_c#_generics_reflection.txt
Q: Extending ControlCollection in VB.NET I want to extend the basic ControlCollection in VB.NET so I can just add images and text to a self-made control, and then automaticly convert them to pictureboxes and lables. So I made a class that inherits from ControlCollection, overrided the add method, and added the functionality. But when I run the example, it gives a NullReferenceException. Here is the code: Shadows Sub add(ByVal text As String) Dim LB As New Label LB.AutoSize = True LB.Text = text MyBase.Add(LB) 'Here it gives the exception. End Sub I searched on Google, and someone said that the CreateControlsInstance method needs to be overriden. So I did that, but then it gives InvalidOperationException with an innerException message of NullReferenceException. How do I to implement this? A: Why not inherit from UserControl to define a custom control that has properties like Text and Image? A: You are probably better off using just a generic collection anyways. Bieng Control Collection doesnt really do anything special for it. puclic class MyCollection : Collection<Control> A: If you're inheriting from Control.ControlCollection then you need to provide a New method in your class. Your New method must call ControlCollection's constructor (MyBase.New) and pass it a valid parent control. If you haven't done this correctly, the NullReferenceException will be thrown in the Add method. This could also be causing the InvalidOperationException in your CreateControlsInstance method The following code calls the constructor incorrectly causing the Add method to throw a NullReferenceException... Public Class MyControlCollection Inherits Control.ControlCollection Sub New() 'Bad - you need to pass a valid control instance 'to the constructor MyBase.New(Nothing) End Sub Public Shadows Sub Add(ByVal text As String) Dim LB As New Label() LB.AutoSize = True LB.Text = text 'The next line will throw a NullReferenceException MyBase.Add(LB) End Sub End Class
Extending ControlCollection in VB.NET
I want to extend the basic ControlCollection in VB.NET so I can just add images and text to a self-made control, and then automaticly convert them to pictureboxes and lables. So I made a class that inherits from ControlCollection, overrided the add method, and added the functionality. But when I run the example, it gives a NullReferenceException. Here is the code: Shadows Sub add(ByVal text As String) Dim LB As New Label LB.AutoSize = True LB.Text = text MyBase.Add(LB) 'Here it gives the exception. End Sub I searched on Google, and someone said that the CreateControlsInstance method needs to be overriden. So I did that, but then it gives InvalidOperationException with an innerException message of NullReferenceException. How do I to implement this?
[ "Why not inherit from UserControl to define a custom control that has properties like Text and Image?\n", "You are probably better off using just a generic collection anyways. Bieng Control Collection doesnt really do anything special for it.\npuclic class MyCollection : Collection<Control>\n\n", "If you're inheriting from Control.ControlCollection then you need to provide a New method in your class. Your New method must call ControlCollection's constructor (MyBase.New) and pass it a valid parent control.\nIf you haven't done this correctly, the NullReferenceException will be thrown in the Add method.\nThis could also be causing the InvalidOperationException in your CreateControlsInstance method\nThe following code calls the constructor incorrectly causing the Add method to throw a NullReferenceException...\nPublic Class MyControlCollection\n Inherits Control.ControlCollection\n\n Sub New()\n 'Bad - you need to pass a valid control instance\n 'to the constructor\n MyBase.New(Nothing)\n End Sub\n\n Public Shadows Sub Add(ByVal text As String)\n Dim LB As New Label()\n LB.AutoSize = True\n LB.Text = text\n 'The next line will throw a NullReferenceException\n MyBase.Add(LB)\n End Sub\nEnd Class\n\n" ]
[ 3, 0, 0 ]
[]
[]
[ "inheritance", "overriding", "vb.net" ]
stackoverflow_0000113873_inheritance_overriding_vb.net.txt
Q: Is there any way to use a "constant" as hash key in Perl? Is there any way to use a constant as a hash key? For example: use constant X => 1; my %x = (X => 'X'); The above code will create a hash with "X" as key and not 1 as key. Whereas, I want to use the value of constant X as key. A: use constant actually makes constant subroutines. To do what you want, you need to explicitly call the sub: use constant X => 1; my %x = ( &X => 'X'); or use constant X => 1; my %x = ( X() => 'X'); A: Another option is to not use the use constant pragma and flip to Readonly as per recommendations in the Perl Best Practices by Damian Conway. I switched a while back after realizing that constant hash ref's are just a constant reference to the hash, but don't do anything about the data inside the hash. The readonly syntax creates "normal looking" variables, but will actually enforce the constantness or readonlyness. You can use it just like you would any other variable as a key. use Readonly; Readonly my $CONSTANT => 'Some value'; $hash{$CONSTANT} = 1; A: Your problem is that => is a magic comma that automatically quotes the word in front of it. So what you wrote is equivalent to ('X', 'X'). The simplest way is to just use a comma: my %x = (X, 'X'); Or, you can add various punctuation so that you no longer have a simple word in front of the =>: my %x = ( X() => 'X' ); my %x = ( &X => 'X' ); A: Use $hash{CONSTANT()} or $hash{+CONSTANT} to prevent the bareword quoting mechanism from kicking in. From: http://perldoc.perl.org/constant.html A: Most of the other folks have answered your question well. Taken together, these create a very full explanation of the problem and recommended workarounds. The issue is that the Perl pragma "use constant" really creates a subroutine in your current package whose name is the the first argument of the pragma and whose value is the last. In Perl, once a subroutine is declared, it may be called without parens. Understanding that "constants" are simply subroutines, you can see why they are not interpolated in strings and why the "fat comma" operator "=>" which quotes the left-hand argument thinks you've handed it a string (try other built-in functions like time() and keys() sometime with the fat comma for extra fun). Luckily, you may invoke the constant using explicit punctuation like parens or the ampersand sigil. However, I've got a question for you: why are you using constants for hash keys at all? I can think of a few scenarios that might lead you in this direction: You want control over which keys can be in the hash. You want to abstract the name of the keys in case these change later In the case of number 1, constants probably won't save your hash. Instead, consider creating an Class that has public setters and getters that populate a hash visible only to the object. This is a very un-Perl like solution, but very easily to do. In the case of number 2, I'd still advocate strongly for a Class. If access to the hash is regulated through a well-defined interface, only the implementer of the class is responsible for getting the hash key names right. In which case, I wouldn't suggest using constants at all. Hope this helps and thanks for your time. A: The use constant pragma creates a subroutine prototyped to take no arguments. While it looks like a C-style constant, it's really a subroutine that returns a constant value. The => (fat comma) automatically quotes left operand if its a bareword, as does the $hash{key} notation. If your use of the constant name looks like a bareword, the quoting mechanisms will kick in and you'll get its name as the key instead of its value. To prevent this, change the usage so that it's not a bareword. For example: use constant X => 1; %hash = (X() => 1); %hash = (+X => 1); $hash{X()} = 1; $hash{+X} = 1; In initializers, you could also use the plain comma instead: %hash = (X, 1); A: => operator interprets its left side as a "string", the way qw() does. Try using my %x = ( X, 'X'); A: One way is to encapsulate X as (X): my %x ( (X) => 1 ); Another option is to do away with '=>' and use ',' instead: my %x ( X, 1 ); A: Comment @shelfoo (reputation not high enough to add comment directly there yet!) Totally agree about Perl Best Practices by Damian Conway... its highly recommended reading. However please read PBP Module Recommendation Commentary which is a useful "errata" if you plan to use PBP for an in-house style guide.
Is there any way to use a "constant" as hash key in Perl?
Is there any way to use a constant as a hash key? For example: use constant X => 1; my %x = (X => 'X'); The above code will create a hash with "X" as key and not 1 as key. Whereas, I want to use the value of constant X as key.
[ "use constant actually makes constant subroutines.\nTo do what you want, you need to explicitly call the sub:\nuse constant X => 1;\n\nmy %x = ( &X => 'X');\n\nor\nuse constant X => 1;\n\nmy %x = ( X() => 'X');\n\n", "Another option is to not use the use constant pragma and flip to Readonly as per recommendations in the Perl Best Practices by Damian Conway.\nI switched a while back after realizing that constant hash ref's are just a constant reference to the hash, but don't do anything about the data inside the hash.\nThe readonly syntax creates \"normal looking\" variables, but will actually enforce the constantness or readonlyness. You can use it just like you would any other variable as a key.\n\n\nuse Readonly;\n\nReadonly my $CONSTANT => 'Some value';\n\n$hash{$CONSTANT} = 1;\n\n\n", "Your problem is that => is a magic comma that automatically quotes the word in front of it. So what you wrote is equivalent to ('X', 'X').\nThe simplest way is to just use a comma:\nmy %x = (X, 'X');\n\nOr, you can add various punctuation so that you no longer have a simple word in front of the =>:\nmy %x = ( X() => 'X' );\nmy %x = ( &X => 'X' );\n\n", "Use $hash{CONSTANT()} or $hash{+CONSTANT} to prevent the bareword quoting mechanism from kicking in.\nFrom: http://perldoc.perl.org/constant.html\n", "Most of the other folks have answered your question well. Taken together, these create a very full explanation of the problem and recommended workarounds. The issue is that the Perl pragma \"use constant\" really creates a subroutine in your current package whose name is the the first argument of the pragma and whose value is the last.\nIn Perl, once a subroutine is declared, it may be called without parens.\nUnderstanding that \"constants\" are simply subroutines, you can see why they are not interpolated in strings and why the \"fat comma\" operator \"=>\" which quotes the left-hand argument thinks you've handed it a string (try other built-in functions like time() and keys() sometime with the fat comma for extra fun). \nLuckily, you may invoke the constant using explicit punctuation like parens or the ampersand sigil.\nHowever, I've got a question for you: why are you using constants for hash keys at all? \nI can think of a few scenarios that might lead you in this direction:\n\nYou want control over which keys can be in the hash.\nYou want to abstract the name of the keys in case these change later\n\nIn the case of number 1, constants probably won't save your hash. Instead, consider creating an Class that has public setters and getters that populate a hash visible only to the object. This is a very un-Perl like solution, but very easily to do.\nIn the case of number 2, I'd still advocate strongly for a Class. If access to the hash is regulated through a well-defined interface, only the implementer of the class is responsible for getting the hash key names right. In which case, I wouldn't suggest using constants at all.\nHope this helps and thanks for your time.\n", "The use constant pragma creates a subroutine prototyped to take no arguments. While it looks like a C-style constant, it's really a subroutine that returns a constant value.\nThe => (fat comma) automatically quotes left operand if its a bareword, as does the $hash{key} notation.\nIf your use of the constant name looks like a bareword, the quoting mechanisms will kick in and you'll get its name as the key instead of its value. To prevent this, change the usage so that it's not a bareword. For example:\nuse constant X => 1;\n%hash = (X() => 1);\n%hash = (+X => 1);\n$hash{X()} = 1;\n$hash{+X} = 1;\n\nIn initializers, you could also use the plain comma instead:\n%hash = (X, 1);\n\n", "=> operator interprets its left side as a \"string\", the way qw() does.\nTry using \nmy %x = ( X, 'X');\n\n", "One way is to encapsulate X as (X):\nmy %x ( (X) => 1 );\n\nAnother option is to do away with '=>' and use ',' instead:\nmy %x ( X, 1 );\n\n", "Comment @shelfoo (reputation not high enough to add comment directly there yet!)\nTotally agree about Perl Best Practices by Damian Conway... its highly recommended reading.\nHowever please read PBP Module Recommendation Commentary which is a useful \"errata\" if you plan to use PBP for an in-house style guide.\n" ]
[ 50, 19, 15, 10, 6, 5, 2, 2, 1 ]
[]
[]
[ "constants", "hash", "perl" ]
stackoverflow_0000096848_constants_hash_perl.txt
Q: Http Exception generated while validating viewstate I am getting the following error whenever I click on a postbacking control HttpException (0x80004005): Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster. I am not using a Web Farm or cluster server. I have even tried setting the page property EnableViewStateMac to false but it changes the error message stating The state information is invalid for this page and might be corrupted. What could possibly be wrong? A: There is an article about this here: http://blogs.msdn.com/tom/archive/2008/03/14/validation-of-viewstate-mac-failed-error.aspx . The basic problem is that Your page hasn't completed loading before You perform the postback. A few different solutions are in the article listed above: 1. Set enableEventValidation to false and viewStateEncryptionMode to Never 2. Mark the form as disabled and then enable it in script once the load is complete. 3. override the Render Event of the page to place the hidden fields for Encrypted Viewstate and Event validation on the top of the form. But the main problem is that the page load slow, which should be fixed (if possible ASAP). It can also be good to apply solution 2 above as well as there will always be trigger happy users that will click faster that the page loads no matter how fast it loads :-). /Andreas A: I have encountered the same problem with a custom build ASP.NET control which was dynamically reloaded and rebuild on every POST / GET request. Thus the page sending the POST request was not the same as the one recieving the response. If you use any custom or databound controls look closly how they behave on a POST back.
Http Exception generated while validating viewstate
I am getting the following error whenever I click on a postbacking control HttpException (0x80004005): Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster. I am not using a Web Farm or cluster server. I have even tried setting the page property EnableViewStateMac to false but it changes the error message stating The state information is invalid for this page and might be corrupted. What could possibly be wrong?
[ "There is an article about this here: http://blogs.msdn.com/tom/archive/2008/03/14/validation-of-viewstate-mac-failed-error.aspx .\nThe basic problem is that Your page hasn't completed loading before You perform the postback.\nA few different solutions are in the article listed above: \n1. Set enableEventValidation to false and viewStateEncryptionMode to Never\n2. Mark the form as disabled and then enable it in script once the load is complete.\n3. override the Render Event of the page to place the hidden fields for Encrypted Viewstate and Event validation on the top of the form.\nBut the main problem is that the page load slow, which should be fixed (if possible ASAP). It can also be good to apply solution 2 above as well as there will always be trigger happy users that will click faster that the page loads no matter how fast it loads :-).\n/Andreas\n", "I have encountered the same problem with a custom build ASP.NET control which was dynamically reloaded and rebuild on every POST / GET request. Thus the page sending the POST request was not the same as the one recieving the response.\nIf you use any custom or databound controls look closly how they behave on a POST back.\n" ]
[ 3, 0 ]
[]
[]
[ "asp.net" ]
stackoverflow_0000114266_asp.net.txt
Q: Creating Custom GnuCash Reports with Scheme Are there any resources which show how to create custom GnuCash reports? I don't know the intricacies of Scheme but I do know the basics of Lisp, based on tinkering with Emacs. Is there a site which lays out the API for GnuCash reports, ideally with a little explanation of Scheme as well? A: It appears that their wiki has some information here.
Creating Custom GnuCash Reports with Scheme
Are there any resources which show how to create custom GnuCash reports? I don't know the intricacies of Scheme but I do know the basics of Lisp, based on tinkering with Emacs. Is there a site which lays out the API for GnuCash reports, ideally with a little explanation of Scheme as well?
[ "It appears that their wiki has some information here.\n" ]
[ 7 ]
[]
[]
[ "scheme" ]
stackoverflow_0000114320_scheme.txt
Q: Wrap an executable to diagnose it's invocations I have a Windows executable (whoami) which is crashing every so often. It's called from another process to get details about the current user and domain. I'd like to know what parameters are passed when it fails. Does anyone know of an appropriate way to wrap the process and write it's command line arguments to log while still calling the process? Say the command is used like this: 'whoami.exe /all' I'd like a script to exist instead of the whoami.exe (with the same filename) which will write this invocation to log and then pass on the call to the actual process. A: You didn't note which programming language. It is not doable from a .bat file if that's what you wanted, but you can do it in any programming language. Example in C: int main(int argc, void **argv) { // dump contents of argv to some log file int i=0; for (i=0; i<argc; i++) printf("Argument #%d: %s\n", argv[i]); // run the 'real' program, giving it the rest of argv vector (1+) // for example spawn, exec or system() functions can do it return 0; // or you can do a blocking call, and pick the return value from the program } A: I don't think using a "script" will work, since the intermediate should have a .exe extension for your ploy to work. I would write a very small command line program to do this; something like the following (written in Delphi/Virtual Pascal so it will result in a Win32 executable, but any compiled language should do): program PassThrough; uses Dos; // Imports the Exec routine const PassTo = 'Original.exe'; // The program you really want to call var CommandLine: String; i: Integer; f: Text; begin CommandLine := ''; for i := 1 to ParamCount do CommandLine := CommandLine + ParamStr(i) + ' '; Assign(f,'Passthrough.log'); Append(f); Writeln(f, CommandLine); // Write a line in the log Close(f); Exec(PassTo, CommandLine); // Run the intended program end. A: Can't you just change the calling program to log the parameters it used to call the process, and the exit code? This would be way easier than trying to dig into whoami.exe A: From a batch file: echo Parameters: %* >> logfile.txt whoami.exe %* With the caveat that you can have problems if the parameters contain spaces (and you passed the in escaping with "), because the command-line parser basically de-escapes them and they should be re-escaped before passed to an other executable. A: Look for whoami.exe, BACK IT UP, replace it with your own executable and see do whatever you like with it's parameters (maybe save them in a text file). A: If you can reproduce the crash, use Process Explorer before crashed process is terminated to see its command line. http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx
Wrap an executable to diagnose it's invocations
I have a Windows executable (whoami) which is crashing every so often. It's called from another process to get details about the current user and domain. I'd like to know what parameters are passed when it fails. Does anyone know of an appropriate way to wrap the process and write it's command line arguments to log while still calling the process? Say the command is used like this: 'whoami.exe /all' I'd like a script to exist instead of the whoami.exe (with the same filename) which will write this invocation to log and then pass on the call to the actual process.
[ "You didn't note which programming language. It is not doable from a .bat file if that's what you wanted, but you can do it in any programming language. Example in C:\nint main(int argc, void **argv)\n{\n // dump contents of argv to some log file\n int i=0;\n for (i=0; i<argc; i++)\n printf(\"Argument #%d: %s\\n\", argv[i]);\n // run the 'real' program, giving it the rest of argv vector (1+)\n // for example spawn, exec or system() functions can do it\n return 0; // or you can do a blocking call, and pick the return value from the program\n}\n\n", "I don't think using a \"script\" will work, since the intermediate should have a .exe extension for your ploy to work.\nI would write a very small command line program to do this; something like the following (written in Delphi/Virtual Pascal so it will result in a Win32 executable, but any compiled language should do):\nprogram PassThrough;\n\nuses\n Dos; // Imports the Exec routine\n\nconst\n PassTo = 'Original.exe'; // The program you really want to call\n\nvar \n CommandLine: String;\n i: Integer;\n f: Text;\n\nbegin\n CommandLine := '';\n for i := 1 to ParamCount do\n CommandLine := CommandLine + ParamStr(i) + ' ';\n\n Assign(f,'Passthrough.log');\n Append(f);\n Writeln(f, CommandLine); // Write a line in the log\n Close(f);\n\n\n Exec(PassTo, CommandLine); // Run the intended program\nend.\n\n", "Can't you just change the calling program to log the parameters it used to call the process, and the exit code?\nThis would be way easier than trying to dig into whoami.exe\n", "From a batch file:\necho Parameters: %* >> logfile.txt\nwhoami.exe %*\n\nWith the caveat that you can have problems if the parameters contain spaces (and you passed the in escaping with \"), because the command-line parser basically de-escapes them and they should be re-escaped before passed to an other executable.\n", "Look for whoami.exe, BACK IT UP, replace it with your own executable and see do whatever you like with it's parameters (maybe save them in a text file).\n", "If you can reproduce the crash, use Process Explorer before crashed process is terminated to see its command line.\nhttp://technet.microsoft.com/en-us/sysinternals/bb896653.aspx\n" ]
[ 1, 1, 1, 1, 0, 0 ]
[]
[]
[ "scripting", "windows" ]
stackoverflow_0000114172_scripting_windows.txt
Q: Portable way to catch signals and report problem to the user If by some miracle a segfault occurs in our program, I want to catch the SIGSEGV and let the user (possibly a GUI client) know with a single return code that a serious problem has occurred. At the same time I would like to display information on the command line to show which signal was caught. Today our signal handler looks as follows: void catchSignal (int reason) { std :: cerr << "Caught a signal: " << reason << std::endl; exit (1); } I can hear the screams of horror with the above, as I have read from this thread that it is evil to call a non-reentrant function from a signal handler. Is there a portable way to handle the signal and provide information to users? EDIT: Or at least portable within the POSIX framework? A: This table lists all of the functions that POSIX guarantees to be async-signal-safe and so can be called from a signal handler. By using the 'write' command from this table, the following relatively "ugly" solution hopefully will do the trick: #include <csignal> #ifdef _WINDOWS_ #define _exit _Exit #else #include <unistd.h> #endif #define PRINT_SIGNAL(X) case X: \ write (STDERR_FILENO, #X ")\n" , sizeof(#X ")\n")-1); \ break; void catchSignal (int reason) { char s[] = "Caught signal: ("; write (STDERR_FILENO, s, sizeof(s) - 1); switch (reason) { // These are the handlers that we catch PRINT_SIGNAL(SIGUSR1); PRINT_SIGNAL(SIGHUP); PRINT_SIGNAL(SIGINT); PRINT_SIGNAL(SIGQUIT); PRINT_SIGNAL(SIGABRT); PRINT_SIGNAL(SIGILL); PRINT_SIGNAL(SIGFPE); PRINT_SIGNAL(SIGBUS); PRINT_SIGNAL(SIGSEGV); PRINT_SIGNAL(SIGTERM); } _Exit (1); // 'exit' is not async-signal-safe } EDIT: Building on windows. After trying to build this one windows, it appears that 'STDERR_FILENO' is not defined. From the documentation however its value appears to be '2'. #include <io.h> #define STDIO_FILENO 2 EDIT: 'exit' should not be called from the signal handler either! As pointed out by fizzer, calling _Exit in the above is a sledge hammer approach for signals such as HUP and TERM. Ideally, when these signals are caught a flag with "volatile sig_atomic_t" type can be used to notify the main program that it should exit. The following I found useful in my searches. Introduction To Unix Signals Programming Extending Traditional Signals A: FWIW, 2 is standard error on Windows also, but you're going to need some conditional compilation because their write() is called _write(). You'll also want #ifdef SIGUSR1 /* or whatever */ etc around all references to signals not guaranteed to be defined by the C standard. Also, as noted above, you don't want to handle SIGUSR1, SIGHUP, SIGINT, SIGQUIT and SIGTERM like this. A: Richard, still not enough karma to comment, so a new answer I'm afraid. These are asynchronous signals; you have no idea when they are delivered, so possibly you will be in library code which needs to complete to stay consistent. Signal handlers for these signals are therefore required to return. If you call exit(), the library will do some work post-main(), including calling functions registered with atexit() and cleaning up the standard streams. This processing may fail if, say, your signal arrived in a standard library I/O function. Therefore in C90 you are not allowed to call exit(). I see now C99 relaxes the requirement by providing a new function _Exit() in stdlib.h. _Exit() may safely be called from a handler for an asynchronous signal. _Exit() will not call atexit() functions and may omit cleaning up the standard streams at the implementation's discretion. To bk1e (commenter a few posts up) The fact that SIGSEGV is synchronous is why you can't use functions that are not designed to be reentrant. What if the function that crashed was holding a lock, and the function called by the signal handler tries to acquire the same lock? This is a possibility, but it's not 'the fact that SIGSEGV is synchronous' which is the problem. Calling non-reentrant functions from the handler is much worse with asynchronous signals for two reasons: asynchronous signal handlers are (generally) hoping to return and resume normal program execution. A handler for a synchronous signal is (generally) going to terminate anyway, so you've not lost much if you crash. in a perverse sense, you have absolute control over when a synchronous signal is delivered - it happens as you execute your defective code, and at no other time. You have no control at all over when an async signal is delivered. Unless the OP's own I/O code is ifself the cause of the defect - e.g. outputting a bad char* - his error message has a reasonable chance of succeeding. A: Write a launcher program to run your program and report abnormal exit code to the user.
Portable way to catch signals and report problem to the user
If by some miracle a segfault occurs in our program, I want to catch the SIGSEGV and let the user (possibly a GUI client) know with a single return code that a serious problem has occurred. At the same time I would like to display information on the command line to show which signal was caught. Today our signal handler looks as follows: void catchSignal (int reason) { std :: cerr << "Caught a signal: " << reason << std::endl; exit (1); } I can hear the screams of horror with the above, as I have read from this thread that it is evil to call a non-reentrant function from a signal handler. Is there a portable way to handle the signal and provide information to users? EDIT: Or at least portable within the POSIX framework?
[ "This table lists all of the functions that POSIX guarantees to be async-signal-safe and so can be called from a signal handler.\nBy using the 'write' command from this table, the following relatively \"ugly\" solution hopefully will do the trick:\n#include <csignal>\n\n#ifdef _WINDOWS_\n#define _exit _Exit\n#else\n#include <unistd.h>\n#endif\n\n#define PRINT_SIGNAL(X) case X: \\\n write (STDERR_FILENO, #X \")\\n\" , sizeof(#X \")\\n\")-1); \\\n break;\n\nvoid catchSignal (int reason) {\n char s[] = \"Caught signal: (\";\n write (STDERR_FILENO, s, sizeof(s) - 1);\n switch (reason)\n {\n // These are the handlers that we catch\n PRINT_SIGNAL(SIGUSR1);\n PRINT_SIGNAL(SIGHUP);\n PRINT_SIGNAL(SIGINT);\n PRINT_SIGNAL(SIGQUIT);\n PRINT_SIGNAL(SIGABRT);\n PRINT_SIGNAL(SIGILL);\n PRINT_SIGNAL(SIGFPE);\n PRINT_SIGNAL(SIGBUS);\n PRINT_SIGNAL(SIGSEGV);\n PRINT_SIGNAL(SIGTERM);\n }\n\n _Exit (1); // 'exit' is not async-signal-safe\n}\n\nEDIT: Building on windows.\nAfter trying to build this one windows, it appears that 'STDERR_FILENO' is not defined. From the documentation however its value appears to be '2'.\n#include <io.h>\n#define STDIO_FILENO 2\n\nEDIT: 'exit' should not be called from the signal handler either!\nAs pointed out by fizzer, calling _Exit in the above is a sledge hammer approach for signals such as HUP and TERM. Ideally, when these signals are caught a flag with \"volatile sig_atomic_t\" type can be used to notify the main program that it should exit.\nThe following I found useful in my searches.\n\nIntroduction To Unix Signals Programming \nExtending Traditional Signals\n\n", "FWIW, 2 is standard error on Windows also, but you're going to need some conditional compilation because their write() is called _write(). You'll also want \n#ifdef SIGUSR1 /* or whatever */\n\netc around all references to signals not guaranteed to be defined by the C standard.\nAlso, as noted above, you don't want to handle SIGUSR1, SIGHUP, SIGINT, SIGQUIT and SIGTERM like this.\n", "Richard, still not enough karma to comment, so a new answer I'm afraid. These are asynchronous signals; you have no idea when they are delivered, so possibly you will be in library code which needs to complete to stay consistent. Signal handlers for these signals are therefore required to return. If you call exit(), the library will do some work post-main(), including calling functions registered with atexit() and cleaning up the standard streams. This processing may fail if, say, your signal arrived in a standard library I/O function. Therefore in C90 you are not allowed to call exit(). I see now C99 relaxes the requirement by providing a new function _Exit() in stdlib.h. _Exit() may safely be called from a handler for an asynchronous signal. _Exit() will not call atexit() functions and may omit cleaning up the standard streams at the implementation's discretion.\nTo bk1e (commenter a few posts up)\nThe fact that SIGSEGV is synchronous is why you can't use functions that are not designed to be reentrant. What if the function that crashed was holding a lock, and the function called by the signal handler tries to acquire the same lock? \nThis is a possibility, but it's not 'the fact that SIGSEGV is synchronous' which is the problem. Calling non-reentrant functions from the handler is much worse with asynchronous signals for two reasons:\n\nasynchronous signal handlers are\n(generally) hoping to return and\nresume normal program execution. A\nhandler for a synchronous signal is\n(generally) going to terminate\nanyway, so you've not lost much if\nyou crash.\nin a perverse sense, you have absolute control over when a synchronous signal is delivered - it happens as you execute your defective code, and at no other time. You have no control at all over when an async signal is delivered. Unless the OP's own I/O code is ifself the cause of the defect - e.g. outputting a bad char* - his error message has a reasonable chance of succeeding.\n\n", "Write a launcher program to run your program and report abnormal exit code to the user.\n" ]
[ 12, 1, 1, 0 ]
[]
[]
[ "c", "c++", "posix", "reentrancy", "signals" ]
stackoverflow_0000103280_c_c++_posix_reentrancy_signals.txt
Q: Converting MS Access "OLE Objects" back to plain JPEGs - best way? Background: We have an old (but business-critical) SQL Server database with an MS Access ADP front-end; this was originally upsized to SQL Server from a series of Access databases. This database tracks hazardous materials for our customers, and stores a large number of images. These images are inserted from MS Access, and get put into the database as OLE Objects. The problems are: These are a pain to read out in anything except Access/Office There's a MASSIVE storage overhead - ~10GB of images takes up 600+ GB of storage space(!) My question is this: what way would you recommend to convert these bloated objects back into simple JPEGs? Once we do this we can finally migrate our front-end from Access and onto a simple web-based system, and our backup times will become manageable again! A: Take the *.bas file from here http:http://stackoverflow.com/Content/img/wmd/ul.png//www.access-im-unternehmen.de/index1.php?BeitragID=337&id=300 (unfortunately it is German). It uses the GDI+ lib from MS (included in Win standard installation) to import/export pics to/from Access OLE. Rough translation of interface: IsGDIPInstalled: Checks for installation of GDI+ InitGDIP: Init of GDI+. ShutDownGDIP: Deinit of GDI+ (importand to be used!) LoadPictureGDIP: Loads pic in StdPicture object (bmp, gif, jp(e)g, tif, png, wmf, emf and ico). ResampleGDIP: Scales pic to new dimensions and sharpens if needed. MakeThumbGDIP: Makes thumbnail and fills border with color. GetDimensionsGDIP: Get dimensions in TSize-Struktur in pixel. SavePicGDIPlus: Saves Picture objekt in file as BMP, GIF, PNG or JPG (jpg with given quality) ArrayFromPicture: Returns a byte array of picutre to put pic into OLE field of table ArrayToPicture: Creates byte array of OLE field of table containing a picture A: Here is the link again: http://www.access-im-unternehmen.de/index1.php?BeitragID=337&id=300 A: Use Access MVP Stephen Lebans ExtractInventoryOLE tool to extract the OLE objects from a table to separate files. http://www.lebans.com/oletodisk.htm According to Lebans: "Does NOT require the original application that served as the OLE server to insert the object. Supports all MS Office documents, PDF, All images inserted by MS Photo Editor, MS Paint, and Paint Shop Pro. Also supports extraction of PACKAGE class including original Filename." Also, Access 2007 stores OLE objects much more efficiently than the historical BMP formats of previous versions, so you would have a smaller storage space and be able to keep your Access app if you converted it from the 600+GB storage of SQL Server to Access 2007 accdb format. Your backup times would be manageable and you wouldn't need to spend time converting an Access front end to a web front end. A: I think the reason your database becomes so bloated, is that the JPGs are also stored as bitmaps inside the "OLE object" structure, or so I've seen, depending on the method the JPEG was inserted. This is not optimal, but: for every image in the database, I would programmatically create a dummy .doc containing just the image, then pass it through OpenOffice conversion, and extract the JPEG from the images subfolder of the produced OpenOffice document (which is a ZIP file). I would then replace the OLE documents in the database with the raw JPEG data, but then I have no way for you to plainly display them in a custom application (unless it's a web app).
Converting MS Access "OLE Objects" back to plain JPEGs - best way?
Background: We have an old (but business-critical) SQL Server database with an MS Access ADP front-end; this was originally upsized to SQL Server from a series of Access databases. This database tracks hazardous materials for our customers, and stores a large number of images. These images are inserted from MS Access, and get put into the database as OLE Objects. The problems are: These are a pain to read out in anything except Access/Office There's a MASSIVE storage overhead - ~10GB of images takes up 600+ GB of storage space(!) My question is this: what way would you recommend to convert these bloated objects back into simple JPEGs? Once we do this we can finally migrate our front-end from Access and onto a simple web-based system, and our backup times will become manageable again!
[ "Take the *.bas file from here http:http://stackoverflow.com/Content/img/wmd/ul.png//www.access-im-unternehmen.de/index1.php?BeitragID=337&id=300 (unfortunately it is German).\nIt uses the GDI+ lib from MS (included in Win standard installation) to import/export pics to/from Access OLE.\nRough translation of interface:\n\nIsGDIPInstalled: Checks for installation of GDI+\nInitGDIP: Init of GDI+.\nShutDownGDIP: Deinit of GDI+ (importand to be used!)\nLoadPictureGDIP: Loads pic in StdPicture object (bmp, gif, jp(e)g, tif, png, wmf, emf and ico).\nResampleGDIP: Scales pic to new dimensions and sharpens if needed.\nMakeThumbGDIP: Makes thumbnail and fills border with color.\nGetDimensionsGDIP: Get dimensions in TSize-Struktur in pixel.\nSavePicGDIPlus: Saves Picture objekt in file as BMP, GIF, PNG or JPG (jpg with given quality)\nArrayFromPicture: Returns a byte array of picutre to put pic into OLE field of table\nArrayToPicture: Creates byte array of OLE field of table containing a picture\n\n", "Here is the link again: http://www.access-im-unternehmen.de/index1.php?BeitragID=337&id=300\n", "Use Access MVP Stephen Lebans ExtractInventoryOLE tool to extract the OLE objects from a table to separate files. \nhttp://www.lebans.com/oletodisk.htm\nAccording to Lebans: \"Does NOT require the original application that served as the OLE server to insert the object. Supports all MS Office documents, PDF, All images inserted by MS Photo Editor, MS Paint, and Paint Shop Pro. Also supports extraction of PACKAGE class including original Filename.\"\nAlso, Access 2007 stores OLE objects much more efficiently than the historical BMP formats of previous versions, so you would have a smaller storage space and be able to keep your Access app if you converted it from the 600+GB storage of SQL Server to Access 2007 accdb format. Your backup times would be manageable and you wouldn't need to spend time converting an Access front end to a web front end.\n", "I think the reason your database becomes so bloated, is that the JPGs are also stored as bitmaps inside the \"OLE object\" structure, or so I've seen, depending on the method the JPEG was inserted.\nThis is not optimal, but: for every image in the database, I would programmatically create a dummy .doc containing just the image, then pass it through OpenOffice conversion, and extract the JPEG from the images subfolder of the produced OpenOffice document (which is a ZIP file).\nI would then replace the OLE documents in the database with the raw JPEG data, but then I have no way for you to plainly display them in a custom application (unless it's a web app).\n" ]
[ 5, 1, 1, 0 ]
[]
[]
[ "image", "ms_access" ]
stackoverflow_0000114326_image_ms_access.txt
Q: Whats the best Ribbon UI control to retro fit to a legacy MFC application build with VC2005? What experience have you had with introducing a Ribbon style control to legacy MFC applications? I know it exists in the new VC2008 Feature Pack, but changing compilers from VC2005 is a big deal for our source base and integration to our environment, Intel FORTRAN, ClearCase, many 3rd libraries. There are quiet a few different commerical implementations, most focusing on C#/VB .NET, and only a few for native C++ MFC. I have read all the usual reviews found by Google most are quiet old now, so I am interested to here from people who have actually done it, been through the pain barrier, released a legacy application with VC2005 and a Ribbon UI. We currently use a very old version of Stingray Objective Toolkit to provide our MFC extensions like customizable toolbars and docking windows etc. Any one used Prof-UIS, compared to the other commercial ones its relatively cheap, unlimited developer licensing is a 10th the cost of the others. Are there any free, open source or L-GPL'd ones available? A: In my projects I'm using the MFC Feature Pack in Visual Studio 2008, which is based on code from BCGSoft. Their BCGControlBar Library Professional Edition includes a ribbon control and is compatible with Visual Studio 2005. I'm not aware of any open source ribbon control libraries for C++, though. A: We use Codejock. It's not cheap, but I guess I've come to find that good controls usually are :-). They are fairly responsive in the tech support department (although we haven't had need to use that recently). We are buidling a whole suite of tools using these controls and have always had what we've needed, including the ability build the office 2007 style ribbon. A: Please be aware that you need a license from Microsoft to use the ribbon control in your application. They give it for free as long as you don't write a software to compete with Word or other Office software. Take a look at this link: Office UI Licensing. People are generally not happy with Microsoft for this: The evil of the Office UI ribbon license. A: We implemented a ribbon in our app due to pressure to have the latest/flashiest looking UI. It looks good, but the usability isn't good compared to using a plain toolbar! To adhere to Microsoft's License to use the ribbon, you have to stick to their guidlines on how it should be used. Eg.. only the user can change ribbon tabs, you can't do it programatically except when switching to a context tab. All these limitations mean that the ribbon only applies to applications that are definitely document-centric. If you're app isn't document-centric, don't think you can just drop a ribbon in to replace a menu/toolbar driven system without giving it a lot of thought about how everything is going to fit together.
Whats the best Ribbon UI control to retro fit to a legacy MFC application build with VC2005?
What experience have you had with introducing a Ribbon style control to legacy MFC applications? I know it exists in the new VC2008 Feature Pack, but changing compilers from VC2005 is a big deal for our source base and integration to our environment, Intel FORTRAN, ClearCase, many 3rd libraries. There are quiet a few different commerical implementations, most focusing on C#/VB .NET, and only a few for native C++ MFC. I have read all the usual reviews found by Google most are quiet old now, so I am interested to here from people who have actually done it, been through the pain barrier, released a legacy application with VC2005 and a Ribbon UI. We currently use a very old version of Stingray Objective Toolkit to provide our MFC extensions like customizable toolbars and docking windows etc. Any one used Prof-UIS, compared to the other commercial ones its relatively cheap, unlimited developer licensing is a 10th the cost of the others. Are there any free, open source or L-GPL'd ones available?
[ "In my projects I'm using the MFC Feature Pack in Visual Studio 2008, which is based on code from BCGSoft. Their BCGControlBar Library Professional Edition includes a ribbon control and is compatible with Visual Studio 2005.\nI'm not aware of any open source ribbon control libraries for C++, though.\n", "We use Codejock. It's not cheap, but I guess I've come to find that good controls usually are :-). They are fairly responsive in the tech support department (although we haven't had need to use that recently). We are buidling a whole suite of tools using these controls and have always had what we've needed, including the ability build the office 2007 style ribbon.\n", "Please be aware that you need a license from Microsoft to use the ribbon control in your application. They give it for free as long as you don't write a software to compete with Word or other Office software.\nTake a look at this link: Office UI Licensing.\nPeople are generally not happy with Microsoft for this: The evil of the Office UI ribbon license.\n", "We implemented a ribbon in our app due to pressure to have the latest/flashiest looking UI. It looks good, but the usability isn't good compared to using a plain toolbar!\nTo adhere to Microsoft's License to use the ribbon, you have to stick to their guidlines on how it should be used. Eg.. only the user can change ribbon tabs, you can't do it programatically except when switching to a context tab. All these limitations mean that the ribbon only applies to applications that are definitely document-centric. If you're app isn't document-centric, don't think you can just drop a ribbon in to replace a menu/toolbar driven system without giving it a lot of thought about how everything is going to fit together.\n" ]
[ 6, 3, 2, 1 ]
[]
[]
[ "c++", "mfc", "ribbon", "stingray", "user_interface" ]
stackoverflow_0000108047_c++_mfc_ribbon_stingray_user_interface.txt
Q: How can I unit test responses from the webapp WSGI application in Google App Engine? I'd like to unit test responses from the Google App Engine webapp.WSGIApplication, for example request the url '/' and test that the responses status code is 200, using GAEUnit. How can I do this? I'd like to use the webapp framework and GAEUnit, which runs within the App Engine sandbox (unfortunately WebTest does not work within the sandbox). A: I have added a sample application to the GAEUnit project which demonstrates how to write and execute a web test using GAEUnit. The sample includes a slightly modified version of the 'webtest' module ('import webbrowser' is commented out, as recommended by David Coffin). Here's the 'web_tests.py' file from the sample application 'test' directory: import unittest from webtest import TestApp from google.appengine.ext import webapp import index class IndexTest(unittest.TestCase): def setUp(self): self.application = webapp.WSGIApplication([('/', index.IndexHandler)], debug=True) def test_default_page(self): app = TestApp(self.application) response = app.get('/') self.assertEqual('200 OK', response.status) self.assertTrue('Hello, World!' in response) def test_page_with_param(self): app = TestApp(self.application) response = app.get('/?name=Bob') self.assertEqual('200 OK', response.status) self.assertTrue('Hello, Bob!' in response) A: Actually WebTest does work within the sandbox, as long as you comment out import webbrowser in webtest/__init__.py
How can I unit test responses from the webapp WSGI application in Google App Engine?
I'd like to unit test responses from the Google App Engine webapp.WSGIApplication, for example request the url '/' and test that the responses status code is 200, using GAEUnit. How can I do this? I'd like to use the webapp framework and GAEUnit, which runs within the App Engine sandbox (unfortunately WebTest does not work within the sandbox).
[ "I have added a sample application to the GAEUnit project which demonstrates how to write and execute a web test using GAEUnit. The sample includes a slightly modified version of the 'webtest' module ('import webbrowser' is commented out, as recommended by David Coffin).\nHere's the 'web_tests.py' file from the sample application 'test' directory:\nimport unittest\nfrom webtest import TestApp\nfrom google.appengine.ext import webapp\nimport index\n\nclass IndexTest(unittest.TestCase):\n\n def setUp(self):\n self.application = webapp.WSGIApplication([('/', index.IndexHandler)], debug=True)\n\n def test_default_page(self):\n app = TestApp(self.application)\n response = app.get('/')\n self.assertEqual('200 OK', response.status)\n self.assertTrue('Hello, World!' in response)\n\n def test_page_with_param(self):\n app = TestApp(self.application)\n response = app.get('/?name=Bob')\n self.assertEqual('200 OK', response.status)\n self.assertTrue('Hello, Bob!' in response)\n\n", "Actually WebTest does work within the sandbox, as long as you comment out \nimport webbrowser\n\nin webtest/__init__.py \n" ]
[ 13, 2 ]
[]
[]
[ "google_app_engine", "python", "unit_testing" ]
stackoverflow_0000107675_google_app_engine_python_unit_testing.txt
Q: Abusing XmlReader ReadSubtree() I need to parse a xml file which is practically an image of a really big tree structure, so I'm using the XmlReader class to populate the tree 'on the fly'. Each node is passed just the xml chunk it expects from its parent via the ReadSubtree() function. This has the advantage of not having to worry about when a node has consumed all its children. But now I'm wondering if this is actually a good idea, since there could be thousands of nodes and while reading the .NET source files I've found that a couple (and probably more) new objects are created with every ReadSubtree call, and no caching for reusable objects is made (that I'd seen). Maybe ReadSubtree() was not thought to be massively used, or maybe I'm just worrying for nothing and I just need to call GC.Collect() after parsing the file... Hope someone can shed some light on this. Thanks in advance. Update: Thanks for the nice and insightful answers. I had a deeper look at the .NET source code and I found it to be more complex than I first imagined. I've finally abandoned the idea of calling this function in this very scenario. As Stefan pointed out, the xml reader is never passed to outsiders and I can trust the code that parses the xml stream, (which is written by myself), so I'd rather force each node to be responsible for the amount of data they steal from the stream than using the not-so-thin-in-the-end ReadSubtree() function to just save a few lines of code. A: ReadSubTree() gives you an XmlReader that wraps the original XmlReader. This new reader appears to consumers as a complete document. This might be important if the code you pass the subtree to thinks it is getting a standalone xml document. For example the Depth property of the new Reader starts out at 0. It is a pretty thin wrapper, so you won't be using any more resources than you would if you used the original XmlReader directly, In the example you gave, it is rather likely that you aren't really getting much out of the subtree reader. The big advantage in your case would be that the subtree reader can't accidentally read past the subtree. Since the subtree reader isn't very expensive, that safety might be enough, though it is generally more helpful when you need the subtree to look like a document or you don't trust the code to only read its own subtree. As Will noted, you never want to call GC.Collect(). It will never improve performance. A: Making the assumption that all objects are created on the normal managed heap, and not the large object heap (ie less than 85k), there really should be no problem here, this is just what the GC was designed to deal with. I would suggest that there is also no need to call GC.Collect at the end of the process, as in almost all cases allowing the GC to schedule collections itself allows it to work in the optimal manner (see this blog post for a very detailed explanation of GC which explains this much better than I can).
Abusing XmlReader ReadSubtree()
I need to parse a xml file which is practically an image of a really big tree structure, so I'm using the XmlReader class to populate the tree 'on the fly'. Each node is passed just the xml chunk it expects from its parent via the ReadSubtree() function. This has the advantage of not having to worry about when a node has consumed all its children. But now I'm wondering if this is actually a good idea, since there could be thousands of nodes and while reading the .NET source files I've found that a couple (and probably more) new objects are created with every ReadSubtree call, and no caching for reusable objects is made (that I'd seen). Maybe ReadSubtree() was not thought to be massively used, or maybe I'm just worrying for nothing and I just need to call GC.Collect() after parsing the file... Hope someone can shed some light on this. Thanks in advance. Update: Thanks for the nice and insightful answers. I had a deeper look at the .NET source code and I found it to be more complex than I first imagined. I've finally abandoned the idea of calling this function in this very scenario. As Stefan pointed out, the xml reader is never passed to outsiders and I can trust the code that parses the xml stream, (which is written by myself), so I'd rather force each node to be responsible for the amount of data they steal from the stream than using the not-so-thin-in-the-end ReadSubtree() function to just save a few lines of code.
[ "ReadSubTree() gives you an XmlReader that wraps the original XmlReader. This new reader appears to consumers as a complete document. This might be important if the code you pass the subtree to thinks it is getting a standalone xml document. For example the Depth property of the new Reader starts out at 0. It is a pretty thin wrapper, so you won't be using any more resources than you would if you used the original XmlReader directly, In the example you gave, it is rather likely that you aren't really getting much out of the subtree reader.\nThe big advantage in your case would be that the subtree reader can't accidentally read past the subtree. Since the subtree reader isn't very expensive, that safety might be enough, though it is generally more helpful when you need the subtree to look like a document or you don't trust the code to only read its own subtree.\nAs Will noted, you never want to call GC.Collect(). It will never improve performance.\n", "Making the assumption that all objects are created on the normal managed heap, and not the large object heap (ie less than 85k), there really should be no problem here, this is just what the GC was designed to deal with. \nI would suggest that there is also no need to call GC.Collect at the end of the process, as in almost all cases allowing the GC to schedule collections itself allows it to work in the optimal manner (see this blog post for a very detailed explanation of GC which explains this much better than I can).\n" ]
[ 10, 2 ]
[]
[]
[ ".net", "xml", "xmlreader" ]
stackoverflow_0000114327_.net_xml_xmlreader.txt
Q: Updating reference to a member variable in use I got this síngleton cache object and it exposes an IEnumerable property which just returns a private IEnumerable variable. I have a static method on my singleton object that updates this member variable (that exists on the single 'Instance' instance of this cache object). Let's say some thread is currently iterating over this IEnumerable variable/property while my cache is updating. I made it so the cache is updating on a new local variable and finally setting the exposed private variable to point to this new local variable. I know i'm just updating a reference, leaving the other (old) object in memory waiting to be picked up by the GC but my problem is - i'm not 100% sure what happens once i set the new reference? Would the other thread suddenly be iterating over the new object or the old one it got passed through the IEnumerable interface? If it had been a normal reference i'd say 'no'. The calling thread would be operating on the old object, but i'm not sure if this is the case for IEnumerable as well? Here is the class stripped down: internal sealed class SektionCache : CacheBase { public static readonly SektionCache Instance = new SektionCache(); private static readonly object lockObject = new object(); private static bool isUpdating; private IEnumerable<Sektion> sektioner; static SektionCache() { UpdateCache(); } public IEnumerable<Sektion> Sektioner { get { return sektioner; } } public static void UpdateCache() { // SNIP - getting data, locking etc. Instance.sektioner = newSektioner; // SNIP } } A: Since the getter { return sektioner; } is called before the new value is put in the field, the old value is returned. Then, the loop foreach (Sektion s in cache.Sektioner) uses the value that was received when the getter was called, i.e. the old value. That value will be used throughout the foreach loop. A: The thread which is currently enumerating sektioner will continue to enumerate it even when you update the reference within the singleton. There is nothing special about objects which implement IEnumerable. You should perhaps add the volatile keyword to the sektioner field as you are not providing read-locking and multiple threads are reading/writing it. A: First of all I can't see object locking, unused lockObject variable makes me sad. IEnumerable is not special. Each thread will have it's own copy of reference to some instance of sektioner object. You can't affect other threads that way. What would happen with old version of data pointed by sektioner field largely depends on calling party. A: I think, if you want a thread safety, you should use this way: internal sealed class SektionCache : CacheBase { //public static readonly SektionCache Instance = new SektionCache(); // this template is better ( safer ) than the previous one, for thread-safe singleton patter >>> private static SektionCache defaultInstance; private static object readonly lockObject = new object(); public static SektionCach Default { get { SektionCach result = defaultInstance; if ( null == result ) { lock( lockObject ) { if ( null == result ) { defaultInstance = result = new SektionCache(); } } } return result; } } // <<< this template is better ( safer ) than the previous one //private static readonly object lockObject = new object(); //private static bool isUpdating; //private IEnumerable<Sektion> sektioner; // this declaration is enough private volatile IEnumerable<Sektion> sektioner; // no static constructor is required >>> //static SektionCache() //{ // UpdateCache(); //} // <<< no static constructor is required // I think, you can use getter and setter for reading & changing a collection public IEnumerable<Sektion> Sektioner { get { IEnumerable<Sektion> result = this.sektioner; // i don't know, if you need this functionality >>> // if ( null == result ) { result = new Sektion[0]; } // <<< i don't know, if you need this functionality return result; } set { this.sektion = value; } } //public static void UpdateCache() //{ //// SNIP - getting data, locking etc. //Instance.sektioner = newSektioner; //// SNIP //} }
Updating reference to a member variable in use
I got this síngleton cache object and it exposes an IEnumerable property which just returns a private IEnumerable variable. I have a static method on my singleton object that updates this member variable (that exists on the single 'Instance' instance of this cache object). Let's say some thread is currently iterating over this IEnumerable variable/property while my cache is updating. I made it so the cache is updating on a new local variable and finally setting the exposed private variable to point to this new local variable. I know i'm just updating a reference, leaving the other (old) object in memory waiting to be picked up by the GC but my problem is - i'm not 100% sure what happens once i set the new reference? Would the other thread suddenly be iterating over the new object or the old one it got passed through the IEnumerable interface? If it had been a normal reference i'd say 'no'. The calling thread would be operating on the old object, but i'm not sure if this is the case for IEnumerable as well? Here is the class stripped down: internal sealed class SektionCache : CacheBase { public static readonly SektionCache Instance = new SektionCache(); private static readonly object lockObject = new object(); private static bool isUpdating; private IEnumerable<Sektion> sektioner; static SektionCache() { UpdateCache(); } public IEnumerable<Sektion> Sektioner { get { return sektioner; } } public static void UpdateCache() { // SNIP - getting data, locking etc. Instance.sektioner = newSektioner; // SNIP } }
[ "Since the getter { return sektioner; } is called before the new value is put in the field, the old value is returned. Then, the loop foreach (Sektion s in cache.Sektioner) uses the value that was received when the getter was called, i.e. the old value. That value will be used throughout the foreach loop. \n", "The thread which is currently enumerating sektioner will continue to enumerate it even when you update the reference within the singleton. There is nothing special about objects which implement IEnumerable.\nYou should perhaps add the volatile keyword to the sektioner field as you are not providing read-locking and multiple threads are reading/writing it.\n", "First of all I can't see object locking, unused lockObject variable makes me sad. IEnumerable is not special. Each thread will have it's own copy of reference to some instance of sektioner object. You can't affect other threads that way. What would happen with old version of data pointed by sektioner field largely depends on calling party.\n", "I think, if you want a thread safety, you should use this way:\ninternal sealed class SektionCache : CacheBase\n{\n //public static readonly SektionCache Instance = new SektionCache();\n\n // this template is better ( safer ) than the previous one, for thread-safe singleton patter >>>\n private static SektionCache defaultInstance;\n private static object readonly lockObject = new object();\n public static SektionCach Default {\n get {\n SektionCach result = defaultInstance;\n if ( null == result ) {\n lock( lockObject ) {\n if ( null == result ) {\n defaultInstance = result = new SektionCache();\n }\n }\n }\n\n return result;\n }\n }\n // <<< this template is better ( safer ) than the previous one\n\n //private static readonly object lockObject = new object();\n //private static bool isUpdating;\n //private IEnumerable<Sektion> sektioner;\n\n // this declaration is enough\n private volatile IEnumerable<Sektion> sektioner;\n\n // no static constructor is required >>>\n //static SektionCache()\n //{\n // UpdateCache();\n //}\n // <<< no static constructor is required\n\n // I think, you can use getter and setter for reading & changing a collection\n public IEnumerable<Sektion> Sektioner {\n get {\n IEnumerable<Sektion> result = this.sektioner;\n // i don't know, if you need this functionality >>>\n // if ( null == result ) { result = new Sektion[0]; }\n // <<< i don't know, if you need this functionality\n return result;\n }\n set { this.sektion = value; }\n }\n\n //public static void UpdateCache()\n //{\n //// SNIP - getting data, locking etc.\n //Instance.sektioner = newSektioner;\n //// SNIP\n //}\n}\n\n" ]
[ 3, 1, 0, 0 ]
[]
[]
[ ".net", "c#", "singleton" ]
stackoverflow_0000114179_.net_c#_singleton.txt
Q: How can I immediately play a sound when another sound ends using XNA/XACT? This question borders between the world of the audio designer and the programmer. While this question might have to be partially answered by that domain of an audio designer, it is sure a problem for the programmer. In our project, we want to loop a sound (background music) while the game timer is greater than one minute left. When this time is hit, we wish to stop the music as authored, and then immediately continue with ending segment. I have been looking into XACT, and it seems to have support for different events. Unfortunately, the documentation is lacking, and the application is somewhat alien to me as a programmer. What I am looking to do is something along these lines (different approaches): When the music stops, I want to tie an event to play another sound immediately When a marker is triggered in the music, I want to play another sound immediately I would also like to know in my application when some of these events happen The problem is that I haven't been able to find any mechanism to auto-play sound when another sound begins and that I can't find a way to hook up with the events made in the XACT project to C#. If this can't be done (i.e. XACT/XNA lacks support for these operations), please gather your ideas on how to solve this problem with minimal cross-sound time errors. Preferably I would be able to control this as much as possible in C# with calls to XNA. A: I think I've solved it now Here's how I did it. Select the Cue which you want to change sound after it has been stopped in XACT. Set Playlist Type to Interactive. Open Cue Transitions. Select View by Destination. Select the Cue in the (stop) node visible in the tree view. In Transition Properties at the right side of the tree view, for Source and Destination: Set Source to End of Loop. Set Destiantion to Beginning. In Transition Properties at the right side of the tree view, for Transitions: Set Transition Type to Direct Concurrent Transition. Set Transitional Sound to the sound you wish to play after the looping sound has completed its loop. Close the window and test it by playing the Cue. Also test to stop it As Authored to see if the behaviour fulfilles your expectations. Implementation In code, Stop the Cue As Authored to get this behaviour. Immediate stops the cue without playing the sound outro. I hope this helps other people who might run into this problem in the future. The question and answer wasn't that much code oriented as I thought initially. Also, this applies for XNA 2.0. I don't know if there will be other options for controlling this kind of behaviour in XNA 3.0+.
How can I immediately play a sound when another sound ends using XNA/XACT?
This question borders between the world of the audio designer and the programmer. While this question might have to be partially answered by that domain of an audio designer, it is sure a problem for the programmer. In our project, we want to loop a sound (background music) while the game timer is greater than one minute left. When this time is hit, we wish to stop the music as authored, and then immediately continue with ending segment. I have been looking into XACT, and it seems to have support for different events. Unfortunately, the documentation is lacking, and the application is somewhat alien to me as a programmer. What I am looking to do is something along these lines (different approaches): When the music stops, I want to tie an event to play another sound immediately When a marker is triggered in the music, I want to play another sound immediately I would also like to know in my application when some of these events happen The problem is that I haven't been able to find any mechanism to auto-play sound when another sound begins and that I can't find a way to hook up with the events made in the XACT project to C#. If this can't be done (i.e. XACT/XNA lacks support for these operations), please gather your ideas on how to solve this problem with minimal cross-sound time errors. Preferably I would be able to control this as much as possible in C# with calls to XNA.
[ "I think I've solved it now\nHere's how I did it.\n\nSelect the Cue which you want to change sound after it has been stopped in XACT.\nSet Playlist Type to Interactive.\nOpen Cue Transitions.\nSelect View by Destination.\nSelect the Cue in the (stop) node visible in the tree view.\nIn Transition Properties at the right side of the tree view, for Source and Destination:\n\n\nSet Source to End of Loop.\nSet Destiantion to Beginning.\n\nIn Transition Properties at the right side of the tree view, for Transitions:\n\n\nSet Transition Type to Direct Concurrent Transition.\nSet Transitional Sound to the sound you wish to play after the looping sound has completed its loop.\n\n\nClose the window and test it by playing the Cue. Also test to stop it As Authored to see if the behaviour fulfilles your expectations.\n\nImplementation\nIn code, Stop the Cue As Authored to get this behaviour. Immediate stops the cue without playing the sound outro. I hope this helps other people who might run into this problem in the future. The question and answer wasn't that much code oriented as I thought initially. Also, this applies for XNA 2.0. I don't know if there will be other options for controlling this kind of behaviour in XNA 3.0+.\n" ]
[ 4 ]
[]
[]
[ "audio", "c#", "xact", "xna" ]
stackoverflow_0000113977_audio_c#_xact_xna.txt
Q: Monitor running .net apps I have some .net apps running that I need to monitor for example, then MethodA is called in App1, my monitor app should detect this. I have a lot of running apps and the solution proposed here is to recompile all those apps and include a new line in the desired methods that we want to monitor. I want to do this only if there is absolutely no way. So did anybody ever done something like this? Basically, I need to create a new app that when I click a button on it, it will tell me: MethodA was called in App1, in real time... thanks! A: There are several ways you could do this. One is to use log4Net, 'sprinkle' your methods with calls to log4Net's write methods. You can choose a variety of logging appenders (destinations) such as email or a database, but a less known tip is to download the standalone program, DebugView (SysInternals -> now Microsoft) which listens for the default messages. A: The PostSharp deliver way, how to edit compiled .net code. The editation is written in C# code which is compiled ( attributes ) or by configuration code. Thay have a mechanism, which can log ( or populate or anything else ) a method/event calling and much more. I think, this is tool, you need. A: System.Diagnostics.PerformanceCounter is a good place to start. You can create new counters that can be viewed in the Performance control panel applet. They're a little confusing at the start, but when you realize average counters need two components to calculate a percentage it gets a lot easier. A: I don't know if .NET has a matching mechanism, but Java allows you to specify an agent JAR file, namely a class that is notified/invoked when each class is loaded. Then, via instrumentation/bytecode manipulation, you could intercept such method calls. Perhaps you can replace the class loader in some way in .NET. not sure. A: Reflection is what you are looking for in .NET, but I am not sure of the implementation details behind what you want to do.
Monitor running .net apps
I have some .net apps running that I need to monitor for example, then MethodA is called in App1, my monitor app should detect this. I have a lot of running apps and the solution proposed here is to recompile all those apps and include a new line in the desired methods that we want to monitor. I want to do this only if there is absolutely no way. So did anybody ever done something like this? Basically, I need to create a new app that when I click a button on it, it will tell me: MethodA was called in App1, in real time... thanks!
[ "There are several ways you could do this. One is to use log4Net, 'sprinkle' your methods with calls to log4Net's write methods. You can choose a variety of logging appenders (destinations) such as email or a database, but a less known tip is to download the standalone program, DebugView (SysInternals -> now Microsoft) which listens for the default messages.\n", "The PostSharp deliver way, how to edit compiled .net code. The editation is written in C# code which is compiled ( attributes ) or by configuration code. Thay have a mechanism, which can log ( or populate or anything else ) a method/event calling and much more.\nI think, this is tool, you need.\n", "System.Diagnostics.PerformanceCounter is a good place to start. You can create new counters that can be viewed in the Performance control panel applet. They're a little confusing at the start, but when you realize average counters need two components to calculate a percentage it gets a lot easier.\n", "I don't know if .NET has a matching mechanism, but Java allows you to specify an agent JAR file, namely a class that is notified/invoked when each class is loaded. Then, via instrumentation/bytecode manipulation, you could intercept such method calls. Perhaps you can replace the class loader in some way in .NET. not sure.\n", "Reflection is what you are looking for in .NET, but I am not sure of the implementation details behind what you want to do.\n" ]
[ 3, 1, 0, 0, 0 ]
[]
[]
[ ".net", "monitoring" ]
stackoverflow_0000114305_.net_monitoring.txt
Q: Boost shared_ptr container question Let's say I have a container (std::vector) of pointers used by a multi-threaded application. When adding new pointers to the container, the code is protected using a critical section (boost::mutex). All well and good. The code should be able to return one of these pointers to a thread for processing, but another separate thread could choose to delete one of these pointers, which might still be in use. e.g.: thread1() { foo* p = get_pointer(); ... p->do_something(); } thread2() { foo* p = get_pointer(); ... delete p; } So thread2 could delete the pointer whilst thread1 is using it. Nasty. So instead I want to use a container of Boost shared ptrs. IIRC these pointers will be reference counted, so as long as I return shared ptrs instead of raw pointers, removing one from the container WON'T actually free it until the last use of it goes out of scope. i.e. std::vector<boost::shared_ptr<foo> > my_vec; thread1() { boost::shared_ptr<foo> sp = get_ptr[0]; ... sp->do_something(); } thread2() { boost::shared_ptr<foo> sp = get_ptr[0]; ... my_vec.erase(my_vec.begin()); } boost::shared_ptr<foo> get_ptr(int index) { lock_my_vec(); return my_vec[index]; } In the above example, if thread1 gets the pointer before thread2 calls erase, will the object pointed to still be valid? It won't actually be deleted when thread1 completes? Note that access to the global vector will be via a critical section. I think this is how shared_ptrs work but I need to be sure. A: For the threading safety of boost::shared_ptr you should check this link. It's not guarantied to be safe, but on many platforms it works. Modifying the std::vector is not safe AFAIK. A: In the above example, if thread1 gets the pointer before thread2 calls erase, will the object pointed to still be valid? It won't actually be deleted when thread1 completes? In your example, if thread1 gets the pointer before thread2, then thread2 will have to wait at the beginning of the function (because of the lock). So, yes, the object pointed to will still be valid. However, you might want to make sure that my_vec is not empty before accessing its first element. A: If in addition, you synchronize the accesses to the vector (as in your original raw pointer proposal), your usage is safe. Otherwise, you may fall foul of example 4 in the link provided by the other respondent.
Boost shared_ptr container question
Let's say I have a container (std::vector) of pointers used by a multi-threaded application. When adding new pointers to the container, the code is protected using a critical section (boost::mutex). All well and good. The code should be able to return one of these pointers to a thread for processing, but another separate thread could choose to delete one of these pointers, which might still be in use. e.g.: thread1() { foo* p = get_pointer(); ... p->do_something(); } thread2() { foo* p = get_pointer(); ... delete p; } So thread2 could delete the pointer whilst thread1 is using it. Nasty. So instead I want to use a container of Boost shared ptrs. IIRC these pointers will be reference counted, so as long as I return shared ptrs instead of raw pointers, removing one from the container WON'T actually free it until the last use of it goes out of scope. i.e. std::vector<boost::shared_ptr<foo> > my_vec; thread1() { boost::shared_ptr<foo> sp = get_ptr[0]; ... sp->do_something(); } thread2() { boost::shared_ptr<foo> sp = get_ptr[0]; ... my_vec.erase(my_vec.begin()); } boost::shared_ptr<foo> get_ptr(int index) { lock_my_vec(); return my_vec[index]; } In the above example, if thread1 gets the pointer before thread2 calls erase, will the object pointed to still be valid? It won't actually be deleted when thread1 completes? Note that access to the global vector will be via a critical section. I think this is how shared_ptrs work but I need to be sure.
[ "For the threading safety of boost::shared_ptr you should check this link. It's not guarantied to be safe, but on many platforms it works. Modifying the std::vector is not safe AFAIK.\n", "\nIn the above example, if thread1 gets the pointer before thread2 calls erase, will the object pointed to still be valid? It won't actually be deleted when thread1 completes?\n\nIn your example, if thread1 gets the pointer before thread2, then thread2 will have to wait at the beginning of the function (because of the lock). So, yes, the object pointed to will still be valid. However, you might want to make sure that my_vec is not empty before accessing its first element.\n", "If in addition, you synchronize the accesses to the vector (as in your original raw pointer proposal), your usage is safe. Otherwise, you may fall foul of example 4 in the link provided by the other respondent. \n" ]
[ 3, 1, 0 ]
[]
[]
[ "boost", "c++", "smart_pointers" ]
stackoverflow_0000114211_boost_c++_smart_pointers.txt
Q: Is there any way to inherit the existing TLD definition for particular JSP Tag? I am planning to extend the basic html input tag provided by Spring to incorporate more features into it. I did similar kind of exercise in past for Struts too. At that point of time I had to create a tld file with the attributes that I introduced plus all the attributes available in the parent tag. This is bit tiresome and repetitive so the question is that Is there anyway to inherit the existing TLD definition for particular JSP Tag? Or any shortcut? A: I don't think there is an option to inherit a TLD definition. The shortest solution, i think, will be to inherit the tag class and change the tld to your new (derived) class.
Is there any way to inherit the existing TLD definition for particular JSP Tag?
I am planning to extend the basic html input tag provided by Spring to incorporate more features into it. I did similar kind of exercise in past for Struts too. At that point of time I had to create a tld file with the attributes that I introduced plus all the attributes available in the parent tag. This is bit tiresome and repetitive so the question is that Is there anyway to inherit the existing TLD definition for particular JSP Tag? Or any shortcut?
[ "I don't think there is an option to inherit a TLD definition.\nThe shortest solution, i think, will be to inherit the tag class and change the tld to your new (derived) class.\n" ]
[ 3 ]
[]
[]
[ "jsp", "tags" ]
stackoverflow_0000113765_jsp_tags.txt
Q: Get a list of all computers on a network w/o DNS Greetings, I need a way (either via C# or in a .bat file) to get a list of all the computers on a given network. Normally, I use "net view", but this tends to work (from my understanding) only within your domain. I need the names (or at least the IP Addresses) of all computers available on my network. Being able to get all computers on a domain that isn't mine (in which case I'd use WORKGROUP, or whatever the default is) would also work. A: Nmap is good for this - use the -O option for OS fingerprinting and -oX "filename.xml" for output as xml that you can then parse from c#. A suitable commandline would be (where 192.168.0.0/24 is the subnet to scan): nmap -O -oX "filename.xml" 192.168.0.0/24 leave out the -O if you aren't interested in guessing the OS - if you just want a ping sweep use -sP, or read the docs for the myriad other options. A: To expand on what Unkwntech has said - You can also do a "broadcast" ping to avoid having to ping each IP address individually. Immediately after than you can use "arp" to examine the ARP cache and get a list of which IP addresses are on which MAC address. A: Ping everything in the rage, then you can get netbios info from the systems that respond to identify it's name. A: In one of my web app I used the NetApi32 function for network browsing. Code: http://gist.github.com/11668
Get a list of all computers on a network w/o DNS
Greetings, I need a way (either via C# or in a .bat file) to get a list of all the computers on a given network. Normally, I use "net view", but this tends to work (from my understanding) only within your domain. I need the names (or at least the IP Addresses) of all computers available on my network. Being able to get all computers on a domain that isn't mine (in which case I'd use WORKGROUP, or whatever the default is) would also work.
[ "Nmap is good for this - use the -O option for OS fingerprinting and -oX \"filename.xml\" for output as xml that you can then parse from c#.\nA suitable commandline would be (where 192.168.0.0/24 is the subnet to scan):\nnmap -O -oX \"filename.xml\" 192.168.0.0/24\n\nleave out the -O if you aren't interested in guessing the OS - if you just want a ping sweep use -sP, or read the docs for the myriad other options.\n", "To expand on what Unkwntech has said -\nYou can also do a \"broadcast\" ping to avoid having to ping each IP address individually.\nImmediately after than you can use \"arp\" to examine the ARP cache and get a list of which IP addresses are on which MAC address.\n", "Ping everything in the rage, then you can get netbios info from the systems that respond to identify it's name.\n", "In one of my web app I used the NetApi32 function for network browsing. \nCode:\nhttp://gist.github.com/11668\n" ]
[ 7, 2, 1, 1 ]
[]
[]
[ ".net", "batch_file", "c#", "networking" ]
stackoverflow_0000105676_.net_batch_file_c#_networking.txt
Q: Consequences of running a Java Class file on different JREs? What are the consequences of running a Java class file compiled in JDK 1.4.2 on JRE 1.6 or 1.5? A: The Java SE 6 Compatibility page lists the compatibility of Jave SE 6 to Java SE 5.0. Furthermore, there is a link to Incompatibilities in J2SE 5.0 (since 1.4.2) as well. By looking at the two documents, it should be possible to find out whether there are any incomapatibilities of programs written under JDK 1.4.2 and Java SE 6. In terms of the binary compatibility of the Java class files, the Java SE 6 Compatibility page has the following to say: Java SE 6 is upwards binary-compatible with J2SE 5.0 except for the incompatibilities listed below. Except for the noted incompatibilities, class files built with version 5.0 compilers will run correctly in JDK 6. So, in general, as workmad3 noted, Java class files compiled on a older JDK will still be compatible with the newest version. Furthermore, as noted by Desty, any changes to the API are generally deprecated rather than removed. From the Source Compatibilities section: Deprecated APIs are interfaces that are supported only for backwards compatibility. The javac compiler generates a warning message whenever one of these is used, unless the -nowarn command-line option is used. It is recommended that programs be modified to eliminate the use of deprecated APIs, although there are no current plans to remove such APIs entirely from the system with the exception of JVMDI and JVMPI. There is a long listing of performance improvements in the Java SE 6 Performance White Paper. A: Java classes are forward compatible , e.g. classes generated using 1.5 compiler will be loaded and executed successfully without any problems on JRE 1.6. Generally your classes genereated by today java compilers will be compatible with future JREs (for example Java7) The inverse does not hold : you can not run classes generated by 1.6 on older JREs (1.3, 1.4, etc). A: Java compilers specify source and target compliance levels. This way, you can compile for any JRE from any other higher-versioned JRE. You need to make sure to use these compliance levels because there are API differences between JREs. For example, JRE 1.5 introduced StringBuilder at the compiler level. This means any time you do: String s = "string1" + "string2"; The compiler changes it to: String s = new StringBuilder("string1").append("string2").toString(); Obviously, this will break with a NoClassDefFoundError when you attempt to construct the StringBuilder. A: Theoretically, nothing. The JVM is supposedly backwards compatible. Myself, I've never had a problem in that direction. A: Depends entirely on what parts of the java library you are using. It could be anything from 'absolutely fine, no difference whatsoever' to 'OMG!! WHY HAS IT JUST FORMATTED MY HARD DRIVE??' (Well, perhaps not this second one, but it serves to support the point of it going from nothing to possibly bad :)). Your class could also pick up on bug fixes in the library as well, which would mean niggling bugs disappear (or could be introduced depending on if you were relying on buggy behaviour or not). AFAIK though, the java bytecode is backwards compatible so you shouldn't get any issues with it just not doing anything. A: One positive consequence is that the 1.4 classes will still take advantage of speed improvements made to the JVM (although not necesarily improvements made to library classes). A: just ran into a problem like this myself. I was writing code that should work with 1.6 but the college had 1.3 installed. Lots of methods just don't work i.e input = ""+ JOptionPane.showInputDialog(null,"Enter a four digit number to " + (b?"encrypt":"decrypt")+".",(b?"4086":"5317")); wouldn't work but input = ""+ JOptionPane.showInputDialog(null,"Enter a four digit number to " + (b?"encrypt":"decrypt")+"."); would. the inputdialog method that accepts three agruments doesn't seam to exist in 1.3. this is just a long winded way of saying working with 1.6 api on 1.3 results in head slamming incidents.
Consequences of running a Java Class file on different JREs?
What are the consequences of running a Java class file compiled in JDK 1.4.2 on JRE 1.6 or 1.5?
[ "The Java SE 6 Compatibility page lists the compatibility of Jave SE 6 to Java SE 5.0. Furthermore, there is a link to Incompatibilities in J2SE 5.0 (since 1.4.2) as well. By looking at the two documents, it should be possible to find out whether there are any incomapatibilities of programs written under JDK 1.4.2 and Java SE 6.\nIn terms of the binary compatibility of the Java class files, the Java SE 6 Compatibility page has the following to say:\n\nJava SE 6 is upwards binary-compatible\n with J2SE 5.0 except for the\n incompatibilities listed below. Except\n for the noted incompatibilities, class\n files built with version 5.0 compilers\n will run correctly in JDK 6.\n\nSo, in general, as workmad3 noted, Java class files compiled on a older JDK will still be compatible with the newest version. Furthermore, as noted by Desty, any changes to the API are generally deprecated rather than removed.\nFrom the Source Compatibilities section:\n\nDeprecated APIs are interfaces that\n are supported only for backwards\n compatibility. The javac compiler\n generates a warning message whenever\n one of these is used, unless the\n -nowarn command-line option is used. It is recommended that programs be\n modified to eliminate the use of \n deprecated APIs, although there are no\n current plans to remove such APIs\n entirely from the system with the\n exception of JVMDI and JVMPI.\n\nThere is a long listing of performance improvements in the Java SE 6 Performance White Paper.\n", "Java classes are forward compatible , e.g. classes generated using 1.5 compiler will be loaded and executed successfully without any problems on JRE 1.6. Generally your classes genereated by today java compilers will be compatible with future JREs (for example Java7)\nThe inverse does not hold : you can not run classes generated by 1.6 on older JREs (1.3, 1.4, etc).\n", "Java compilers specify source and target compliance levels. This way, you can compile for any JRE from any other higher-versioned JRE. You need to make sure to use these compliance levels because there are API differences between JREs. For example, JRE 1.5 introduced StringBuilder at the compiler level. This means any time you do:\nString s = \"string1\" + \"string2\";\n\nThe compiler changes it to:\nString s = new StringBuilder(\"string1\").append(\"string2\").toString();\n\nObviously, this will break with a NoClassDefFoundError when you attempt to construct the StringBuilder.\n", "Theoretically, nothing. The JVM is supposedly backwards compatible. Myself, I've never had a problem in that direction.\n", "Depends entirely on what parts of the java library you are using. It could be anything from 'absolutely fine, no difference whatsoever' to 'OMG!! WHY HAS IT JUST FORMATTED MY HARD DRIVE??' (Well, perhaps not this second one, but it serves to support the point of it going from nothing to possibly bad :)).\nYour class could also pick up on bug fixes in the library as well, which would mean niggling bugs disappear (or could be introduced depending on if you were relying on buggy behaviour or not).\nAFAIK though, the java bytecode is backwards compatible so you shouldn't get any issues with it just not doing anything.\n", "One positive consequence is that the 1.4 classes will still take advantage of speed improvements made to the JVM (although not necesarily improvements made to library classes).\n", "just ran into a problem like this myself. I was writing code that should work with 1.6 but the college had 1.3 installed. Lots of methods just don't work i.e\ninput = \"\"+ JOptionPane.showInputDialog(null,\"Enter a four digit number to \" + (b?\"encrypt\":\"decrypt\")+\".\",(b?\"4086\":\"5317\"));\nwouldn't work but \ninput = \"\"+ JOptionPane.showInputDialog(null,\"Enter a four digit number to \" + (b?\"encrypt\":\"decrypt\")+\".\");\nwould. the inputdialog method that accepts three agruments doesn't seam to exist in 1.3.\nthis is just a long winded way of saying working with 1.6 api on 1.3 results in head slamming incidents.\n" ]
[ 6, 5, 1, 0, 0, 0, 0 ]
[ "It should work. I don't remember encountering any problems with it, except when parts of the Java API are deprecated, in which case it'll explain what they are anyway and you can hopefully write a workaround.\nOf course, running a class file compiled with JDK 1.6 in JRE 1.5 would cause a problem - even a JRE only minor build revisions older will throw an error.\n" ]
[ -2 ]
[ "java", "java1.4" ]
stackoverflow_0000114457_java_java1.4.txt
Q: WCF faults and exceptions I'm writing a WCF service for the first time. The service and all of its clients (at least for now) are written in C#. The service has to do a lot of input validation on the data it gets passed, so I need to have some way to indicate invalid data back to the client. I've been reading a lot about faults and exceptions, wrapping exceptions in faults, and a lot of conflicting articles that are just confusing me further. What is the proper way to handle this case? Should I avoid exceptions altogether and package a Results return message? Should I create a special Fault, or a special Exception, or just throw ArgumentExceptions like I would for a non-WCF validation function? The code I have right now (influenced by MSDN) is: [DataContract] public class ValidationFault { [DataMember] public Dictionary<string, string> Errors { get; private set; } [DataMember] public bool Fatal { get; private set; } [DataMember] public Guid SeriesIdentifier { get; private set; } public ValidationFault(Guid id, string argument, string error, bool fatal) { SeriesIdentifier = id; Errors = new Dictionary<string, string> {{argument, error}}; Fatal = fatal; } public void AddError(string argument, string error, bool fatal) { Errors.Add(argument, error); Fatal |= fatal; } } And on the method there's [FaultContract(typeof(ValidationFault))]. So is this the "right" way to approach this? A: Throwing an exception is not useful from a WCF service Why not? Because it comes back as a bare fault and you need to a) Set the fault to include exceptions b) Parse the fault to get the text of the exception and see what happened. So yes you need a fault rather than an exception. I would, in your case, create a custom fault which contains a list of the fields that failed the validation as part of the fault contract. Note that WCF does fun things with dictionaries, which aren't ISerializable; it has special handling, so check the message coming back looks good over the wire; if not it's back to arrays for you. A: If you are doing validation on the client and should have valid values once they are passed into the method (the web service call) then I would throw an exception. It could be an exception indicating that a parameters is invalid with the name of the parameter. (see: ArgumentException) But you may not want to rely on the client to properly validate the data and that leaves you with the assumption that data could be invalid coming into the web service. In that case it is not truly an exceptional case and should not be an exception. In that case you could return an enum or a Result object that has a Status property set to an enum (OK, Invalid, Incomplete) and a Message property set with specifics, like the name of the parameter. I would ensure that these sorts of errors are found and fixed during development. Your QA process should carefully test valid and invalid uses of the client and you do not want to relay these technical messages back to the client. What you want to do instead is update your validation system to prevent invalid data from getting to the service call. My assumption for any WCF service is that there will be more than one UI. One could be a web UI now, but later I may add another using WinForms, WinCE or even a native iPhone/Android mobile application that does not conform to what you expect from .NET clients. A: you might want to take a look at the MS Patterns and Practices Enterprise Library Validation block in conjunction with the policy injection block link text it allows you to decorate your data contract members with validation attributes and also decorate the service implementation, this together with its integration with WCF this means that failures in validation are returned as ArgumentValidationException faults automatically each containing a ValidationDetail object for each validation failure. Using the entlib with WCf you can get a lot of validation, error reporting without having to write much code
WCF faults and exceptions
I'm writing a WCF service for the first time. The service and all of its clients (at least for now) are written in C#. The service has to do a lot of input validation on the data it gets passed, so I need to have some way to indicate invalid data back to the client. I've been reading a lot about faults and exceptions, wrapping exceptions in faults, and a lot of conflicting articles that are just confusing me further. What is the proper way to handle this case? Should I avoid exceptions altogether and package a Results return message? Should I create a special Fault, or a special Exception, or just throw ArgumentExceptions like I would for a non-WCF validation function? The code I have right now (influenced by MSDN) is: [DataContract] public class ValidationFault { [DataMember] public Dictionary<string, string> Errors { get; private set; } [DataMember] public bool Fatal { get; private set; } [DataMember] public Guid SeriesIdentifier { get; private set; } public ValidationFault(Guid id, string argument, string error, bool fatal) { SeriesIdentifier = id; Errors = new Dictionary<string, string> {{argument, error}}; Fatal = fatal; } public void AddError(string argument, string error, bool fatal) { Errors.Add(argument, error); Fatal |= fatal; } } And on the method there's [FaultContract(typeof(ValidationFault))]. So is this the "right" way to approach this?
[ "Throwing an exception is not useful from a WCF service Why not? Because it comes back as a bare fault and you need to\na) Set the fault to include exceptions\nb) Parse the fault to get the text of the exception and see what happened.\nSo yes you need a fault rather than an exception. I would, in your case, create a custom fault which contains a list of the fields that failed the validation as part of the fault contract.\nNote that WCF does fun things with dictionaries, which aren't ISerializable; it has special handling, so check the message coming back looks good over the wire; if not it's back to arrays for you.\n", "If you are doing validation on the client and should have valid values once they are passed into the method (the web service call) then I would throw an exception. It could be an exception indicating that a parameters is invalid with the name of the parameter. (see: ArgumentException)\nBut you may not want to rely on the client to properly validate the data and that leaves you with the assumption that data could be invalid coming into the web service. In that case it is not truly an exceptional case and should not be an exception. In that case you could return an enum or a Result object that has a Status property set to an enum (OK, Invalid, Incomplete) and a Message property set with specifics, like the name of the parameter.\nI would ensure that these sorts of errors are found and fixed during development. Your QA process should carefully test valid and invalid uses of the client and you do not want to relay these technical messages back to the client. What you want to do instead is update your validation system to prevent invalid data from getting to the service call.\nMy assumption for any WCF service is that there will be more than one UI. One could be a web UI now, but later I may add another using WinForms, WinCE or even a native iPhone/Android mobile application that does not conform to what you expect from .NET clients.\n", "you might want to take a look at the MS Patterns and Practices Enterprise Library Validation block in conjunction with the policy injection block link text it allows you to decorate your data contract members with validation attributes and also decorate the service implementation, this together with its integration with WCF this means that failures in validation are returned as ArgumentValidationException faults automatically each containing a ValidationDetail object for each validation failure.\nUsing the entlib with WCf you can get a lot of validation, error reporting without having to write much code\n" ]
[ 4, 3, 2 ]
[]
[]
[ "c#", "exception", "validation", "wcf" ]
stackoverflow_0000097324_c#_exception_validation_wcf.txt
Q: What is the fastest way to scale and display an image in Python? I am required to display a two dimensional numpy.array of int16 at 20fps or so. Using Matplotlib's imshow chokes on anything above 10fps. There obviously are some issues with scaling and interpolation. I should add that the dimensions of the array are not known, but will probably be around thirty by four hundred. These are data from a sensor that are supposed to have a real-time display, so the data has to be re-sampled on the fly. A: The fastest way to display 30x400 data points is to: Use OpenGL color arrays If you can quickly transform your data to what OpenGL understands as color array, you could create a vertex array describing quads, one for each sensor, then update your color array and draw this orthographically on screen. Use OpenGL textures If you can quickly transform your datapoints to an opengl texture you can draw one quad with fixed UV coordinates that is bound to this texture. Use pygame Pygame has support for conversion of Numpy/Numarray to surfaces, Pygame can then transform such surfaces which involves resampling, after resampling you can blit it on screen. Misc pyglet makes dealing with opengl very easy
What is the fastest way to scale and display an image in Python?
I am required to display a two dimensional numpy.array of int16 at 20fps or so. Using Matplotlib's imshow chokes on anything above 10fps. There obviously are some issues with scaling and interpolation. I should add that the dimensions of the array are not known, but will probably be around thirty by four hundred. These are data from a sensor that are supposed to have a real-time display, so the data has to be re-sampled on the fly.
[ "The fastest way to display 30x400 data points is to:\nUse OpenGL color arrays\nIf you can quickly transform your data to what OpenGL understands as color array, you could create a vertex array describing quads, one for each sensor, then update your color array and draw this orthographically on screen.\nUse OpenGL textures\nIf you can quickly transform your datapoints to an opengl texture you can draw one quad with fixed UV coordinates that is bound to this texture.\nUse pygame\nPygame has support for conversion of Numpy/Numarray to surfaces, Pygame can then transform such surfaces which involves resampling, after resampling you can blit it on screen.\nMisc\npyglet makes dealing with opengl very easy\n" ]
[ 6 ]
[]
[]
[ "animation", "image_scaling", "matplotlib", "python" ]
stackoverflow_0000114597_animation_image_scaling_matplotlib_python.txt
Q: ASP.NET: How do I create radio buttons and databind them in a DetailsView? I have a TemplateField in a DetailsView and its input should be one of a few choices in a lookup table. Currently it's a text field, but I want it to be a group of radio buttons, and it should work in both insert and edit mode (the correct current value should be selected in edit mode). How do I create mutually exclusive radio buttons and databind them in a DetailsView TemplateField? I'm on ASP.NET 3.5 using an Oracle database as a datasource. A: <EditItemTemplate> <asp:RadioButtonList ID="RadioButtonList1" runat="server" DataSourceID="LookupSqlDataSource" DataTextField="LOOKUPITEM_DESCRIPTION" DataValueField="LOOKUPITEM_ID" SelectedValue='<%# Bind("ITEM_ID")%>'> </asp:RadioButtonList> </EditItemTemplate> <InsertItemTemplate> <asp:RadioButtonList ID="RadioButtonList1" runat="server" DataSourceID="LookupSqlDataSource" DataTextField="LOOKUPITEM_DESCRIPTION" DataValueField="LOOKUPITEM_ID" SelectedValue='<%# Bind("ITEM_ID")%>'> </asp:RadioButtonList> </InsertItemTemplate>
ASP.NET: How do I create radio buttons and databind them in a DetailsView?
I have a TemplateField in a DetailsView and its input should be one of a few choices in a lookup table. Currently it's a text field, but I want it to be a group of radio buttons, and it should work in both insert and edit mode (the correct current value should be selected in edit mode). How do I create mutually exclusive radio buttons and databind them in a DetailsView TemplateField? I'm on ASP.NET 3.5 using an Oracle database as a datasource.
[ "<EditItemTemplate>\n <asp:RadioButtonList ID=\"RadioButtonList1\" runat=\"server\" \n DataSourceID=\"LookupSqlDataSource\" DataTextField=\"LOOKUPITEM_DESCRIPTION\" \n DataValueField=\"LOOKUPITEM_ID\" SelectedValue='<%# Bind(\"ITEM_ID\")%>'>\n </asp:RadioButtonList>\n</EditItemTemplate>\n\n<InsertItemTemplate>\n <asp:RadioButtonList ID=\"RadioButtonList1\" runat=\"server\" \n DataSourceID=\"LookupSqlDataSource\" DataTextField=\"LOOKUPITEM_DESCRIPTION\" \n DataValueField=\"LOOKUPITEM_ID\" SelectedValue='<%# Bind(\"ITEM_ID\")%>'>\n </asp:RadioButtonList>\n</InsertItemTemplate>\n\n" ]
[ 2 ]
[]
[]
[ "asp.net", "c#", "web_user_controls" ]
stackoverflow_0000114633_asp.net_c#_web_user_controls.txt
Q: Modal popups - usability What are the cases where you'd use a modal popup ? Does it interrupt the user's flow, if it all of a sudden opens up in his face ? Would you avoid modal popups in general ? or when should one be careful of using them ? Edit: To be a bit more specific, the situation here is this : I have a menu on the right, (VisualStudio style) when the user wants to add an element, should I expand the menu down and let them select something from it there, and then have to press the OK button, or display a Modal popup forcing them to select. (the selection step is mandatory.) A: From Wikipedia: Frequent uses of modal windows include: drawing attention to vital pieces of information. This use has been criticised as ineffective. blocking the application flow until information required to continue is entered, as for example a password in a login process. collecting application configuration options in a centralized dialog. In such cases, typically the changes are applied upon closing the dialog, and access to the application is disabled while the edits are being made. warning that the effects of the current action are not reversible. This is a frequent interaction pattern for modal dialogs, but it is also criticised by usability experts as being ineffective for its intended use (protection against errors in destructive actions) and for which better alternatives exist. A: Personally, i think that modal pop-ups can always be avoided. The most common use of a modal pop-up is to indicate errors, or seek user input to proceed. Both of these actions can be accomplished "inline", i.e., by creating suitable actions on the same page itself without a modal pop-up. E.g. errors in a text field input can be indicated by making the background red, or by making a small error icon next to the field, and the error text below it. Pop-ups are always an irritation to a user, and in my opinion can be replaced cleverly without losing any functionality at all. EDIT: In your situation, a simple solution would be to disable the commit button till the user has made a selection. This will ensure the user hits OK only after a selection is made A: If you do go the modal popup route, please please add a delay before input is accepted. There are few things as annoying as typing in some application and seeing the tell-tale flash of dialogue box that implies something popped up, accepted whatever random key you happened to be pressing at the time as its input and gone off to take some random action. A: IMO, avoid them for anything but stuff that you're absolutely sure requires immediate user attention. Otherwise, they just interupt the flow for no good reason A: I don't think avoiding modal popups is usefull. Think about confirmation on closing unsaved work, fileopen dialogs, and such sort of things. I think you should not show them all of a sudden, when the user is busy with something else. A: Minimize. Use the status bar or some non-in-your-face mechanism of notifying the user. You should be careful when you want to have automated tests. Modal dialogs love playing "show stopper". A: To be a bit more specific, the situation here is this : I have a menu on the right, (VisualStudio style) when the user wants to add an element, should I expand the menu down and let them select something from it there, and then have to press the OK button, or display a Modal popup forcing them to select. (the selction step is mandatory.) A: Modal dialogs have been condemned by usability experts for a long time because of their disruptive nature regarding user workflow. See, for instance, Jef Raskin's "Humane Interface" book for discussion of modeless interfaces.
Modal popups - usability
What are the cases where you'd use a modal popup ? Does it interrupt the user's flow, if it all of a sudden opens up in his face ? Would you avoid modal popups in general ? or when should one be careful of using them ? Edit: To be a bit more specific, the situation here is this : I have a menu on the right, (VisualStudio style) when the user wants to add an element, should I expand the menu down and let them select something from it there, and then have to press the OK button, or display a Modal popup forcing them to select. (the selection step is mandatory.)
[ "From Wikipedia:\nFrequent uses of modal windows include:\n\ndrawing attention to vital pieces of information. This use has been criticised as ineffective.\nblocking the application flow until information required to continue is entered, as for example a password in a login process.\ncollecting application configuration options in a centralized dialog. In such cases, typically the changes are applied upon closing the dialog, and access to the application is disabled while the edits are being made.\nwarning that the effects of the current action are not reversible. This is a frequent interaction pattern for modal dialogs, but it is also criticised by usability experts as being ineffective for its intended use (protection against errors in destructive actions) and for which better alternatives exist.\n\n", "Personally, i think that modal pop-ups can always be avoided. The most common use of a modal pop-up is to indicate errors, or seek user input to proceed. Both of these actions can be accomplished \"inline\", i.e., by creating suitable actions on the same page itself without a modal pop-up.\nE.g. errors in a text field input can be indicated by making the background red, or by making a small error icon next to the field, and the error text below it.\nPop-ups are always an irritation to a user, and in my opinion can be replaced cleverly without losing any functionality at all. \nEDIT:\nIn your situation, a simple solution would be to disable the commit button till the user has made a selection. This will ensure the user hits OK only after a selection is made\n", "If you do go the modal popup route, please please add a delay before input is accepted. There are few things as annoying as typing in some application and seeing the tell-tale flash of dialogue box that implies something popped up, accepted whatever random key you happened to be pressing at the time as its input and gone off to take some random action.\n", "IMO, avoid them for anything but stuff that you're absolutely sure requires immediate user attention. Otherwise, they just interupt the flow for no good reason\n", "I don't think avoiding modal popups is usefull. Think about confirmation on closing unsaved work, fileopen dialogs, and such sort of things.\nI think you should not show them all of a sudden, when the user is busy with something else.\n", "Minimize. Use the status bar or some non-in-your-face mechanism of notifying the user. \nYou should be careful when you want to have automated tests. Modal dialogs love playing \"show stopper\".\n", "To be a bit more specific, the situation here is this : \nI have a menu on the right, (VisualStudio style) when the user wants to add an element, should I expand the menu down and let them select something from it there, and then have to press the OK button, or display a Modal popup forcing them to select. \n(the selction step is mandatory.)\n", "Modal dialogs have been condemned by usability experts for a long time because of their disruptive nature regarding user workflow. See, for instance, Jef Raskin's \"Humane Interface\" book for discussion of modeless interfaces.\n" ]
[ 6, 3, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "modalpopups", "usability" ]
stackoverflow_0000114024_modalpopups_usability.txt
Q: How do I read and write raw ip packets from java on a mac? What would be the easiest way to be able to send and receive raw network packets. Do I have to write my own JNI wrapping of some c API, and in that case what API am I looking for? EDIT: I want to be able to do what wireshark does, i.e. record all incomming packets on an interface, and in addition be able to send back my own created packets. And I want to do it on a mac. A: If you start with the idea that you need something like a packet sniffer, you'll want to look at http://netresearch.ics.uci.edu/kfujii/jpcap/doc/. A: Raw Socket for Java is a request for JDK for a looong long time. See the request here. There's a long discussion there where you can look for workarounds and solutions. I once needed this for a simple PING operation, but I can't remember how I resolved this. Sorry :) A: My best bet so far seems to be the BPF api and to write a thin JNI wrapper A: TINI is a java ethernet controller, which may have libraries and classes for directly accessing data from ethernet frames to TCP streams. You may be able to find something in there that implements your needed classes. If not, there should be pointers or user groups that will give you a head start. A: You can't access raw sockets from pure Java, so you will need some sort of layer between your Java code and the network interfaces. Also note that access to raw sockets is normally only available to "root" processes, since otherwise any user could both a) sniff all traffic, and b) generate spoofed packets. Rather than write your whole program so that it needs to run as "root", you might consider having the packet capture and generation done in a standalone program with some sort of IPC (RMI, named pipe, TCP socket, etc) to exchange the data with your Java app.
How do I read and write raw ip packets from java on a mac?
What would be the easiest way to be able to send and receive raw network packets. Do I have to write my own JNI wrapping of some c API, and in that case what API am I looking for? EDIT: I want to be able to do what wireshark does, i.e. record all incomming packets on an interface, and in addition be able to send back my own created packets. And I want to do it on a mac.
[ "If you start with the idea that you need something like a packet sniffer, you'll want to look at http://netresearch.ics.uci.edu/kfujii/jpcap/doc/.\n", "Raw Socket for Java is a request for JDK for a looong long time. See the request here. There's a long discussion there where you can look for workarounds and solutions. I once needed this for a simple PING operation, but I can't remember how I resolved this. Sorry :)\n", "My best bet so far seems to be the BPF api and to write a thin JNI wrapper\n", "TINI is a java ethernet controller, which may have libraries and classes for directly accessing data from ethernet frames to TCP streams. You may be able to find something in there that implements your needed classes. If not, there should be pointers or user groups that will give you a head start.\n", "You can't access raw sockets from pure Java, so you will need some sort of layer between your Java code and the network interfaces.\nAlso note that access to raw sockets is normally only available to \"root\" processes, since otherwise any user could both a) sniff all traffic, and b) generate spoofed packets.\nRather than write your whole program so that it needs to run as \"root\", you might consider having the packet capture and generation done in a standalone program with some sort of IPC (RMI, named pipe, TCP socket, etc) to exchange the data with your Java app.\n" ]
[ 1, 1, 1, 0, 0 ]
[]
[]
[ "java", "macos", "networking" ]
stackoverflow_0000040039_java_macos_networking.txt
Q: Does the Microsoft Report Viewer Redistributable 2008 really require .NET Framework version 3.5? I'm packaging up a .NET 2.0 based web app for deployment through a Windows Installer based package. Our app uses Report Viewer 2008 and I'm including the Microsoft Report Viewer Redistributable 2008 installer. When I check the download page for Report Viewer 2008, it lists .NET 3.5 as a requirement. Is having .Net 3.5 installed really needed Report Viewer 2008? We targeted .Net 2.0 for our app, there isn't anything in our code that would use the 3.0 or 3.5 Frameworks. We are in the middle of testing and everything seems to be working with out 3.5, but I don't want to miss an edge condition and cause an error for a customer because he was missing a prerequisite run time package. A: Keep in mind that MSFT might be requiring the 3.5 Framework so they can write against it in future updates/releases, which might place your app in an unsupported (by MSFT) state. A: Uising Reflector you can see that Microsoft.ReportViewer.Common.dll has a dependency on "Microsoft.Build.Framework, Version=3.5.0.0" and "Microsoft.Build.Utilities.v3.5, Version=3.5.0.0". So strictly speaking it does have a 3.5 requirement. But if the reporting functionality you use never executes the code that uses/loads these, then you might just be OK :-) A: So far testing with or with out the .NET Framework works as expected. My installer has the user install version 2.0 of the Framework and everything works as expected. My concern is that 3.5 is listed as a prerequisite on the Report Viewer download page. A: If it works without a hitch then you don't need .NET 3.5 Framework for now. Installing .NET 3.5 Framework is easy enough to do along with later versions of your software if and only if your software stops working at that point. A: We have deployed ReportViewer 2008 with only .net v2, no problems so far.
Does the Microsoft Report Viewer Redistributable 2008 really require .NET Framework version 3.5?
I'm packaging up a .NET 2.0 based web app for deployment through a Windows Installer based package. Our app uses Report Viewer 2008 and I'm including the Microsoft Report Viewer Redistributable 2008 installer. When I check the download page for Report Viewer 2008, it lists .NET 3.5 as a requirement. Is having .Net 3.5 installed really needed Report Viewer 2008? We targeted .Net 2.0 for our app, there isn't anything in our code that would use the 3.0 or 3.5 Frameworks. We are in the middle of testing and everything seems to be working with out 3.5, but I don't want to miss an edge condition and cause an error for a customer because he was missing a prerequisite run time package.
[ "Keep in mind that MSFT might be requiring the 3.5 Framework so they can write against it in future updates/releases, which might place your app in an unsupported (by MSFT) state.\n", "Uising Reflector you can see that Microsoft.ReportViewer.Common.dll has a dependency on \"Microsoft.Build.Framework, Version=3.5.0.0\" and \"Microsoft.Build.Utilities.v3.5, Version=3.5.0.0\". So strictly speaking it does have a 3.5 requirement. But if the reporting functionality you use never executes the code that uses/loads these, then you might just be OK :-)\n", "So far testing with or with out the .NET Framework works as expected. My installer has the user install version 2.0 of the Framework and everything works as expected.\nMy concern is that 3.5 is listed as a prerequisite on the Report Viewer download page.\n", "If it works without a hitch then you don't need .NET 3.5 Framework for now. Installing .NET 3.5 Framework is easy enough to do along with later versions of your software if and only if your software stops working at that point.\n", "We have deployed ReportViewer 2008 with only .net v2, no problems so far.\n" ]
[ 1, 1, 0, 0, 0 ]
[]
[]
[ ".net_3.5", "reportviewer", "reportviewer2008", "web_deployment_project" ]
stackoverflow_0000020207_.net_3.5_reportviewer_reportviewer2008_web_deployment_project.txt
Q: Best way to deal with session timeout in web apps? I am currently building an internal web application used in a factory/warehouse type location. The users will be sharing a single PC between several people, so we need to have a fairly short session timeout to stop people wandering off and leaving the application logged in where someone else can come to the PC and do something under the previous user's username. The problem with this is a session can timeout while a user is currently entering information into a form, especially if they take a long time. How would you deal with this in a user friendly manner? A: Use AJAX to regularly stash the contents of the partially filled-out form so they have not lost their work if they get booted by the system. Heck, once you're doing that, use AJAX to keep their session from timing out if they spend the time typing. A: Keep the server informed about the fact that the user is actively entering information. For instance send a message to the server if the user presses the TAB key or clicks with a mouse on a field. The final solution is up to you. A: The best advice would probably be to ask the users to close the browser window once they're done. With the use of session-cookies, the session will automatically end when the browser is closed or otherwise on a 30 minute timeout (can be changed afaik). Since there by default is no interaction between the browser and the server once a page is loaded, you would have to have a javascript contact the server in the background on forms-pages to refresh the session, but it seems a bit too much trouble for such a minor problem. A: If the session timeout is so short that the user doesn't have the time to fill in a form, I would put an AJAX script that makes a http request to the server, every few minutes, to keep the session alive. I would do that only on pages that the user has to fill in something or has already started filling something. Another solution would be to use a session timeout reminder script that popups a dialog to remind the user that the session is about to time out. The popup should display a "Logout" and a "Continue using application" that makes a ajax request to update the session time out. A: Maybe that a keep-alive javascript process could be helpfull in this case. If the script capture some key triggers, it send a "I'm still typing" message to the server to keep the session alive. A: have you considered breaking the form into smaller chunks? A: Monitor the timeout and post a pop-up to notify the user that their current session will expire and present "OK" or "Cancel" buttons. OK to keep the session going (i.e. reset the counter to another 5 minutes or 10 minutes - whatever you need) -or- Cancel to allow the session to continue to countdown to zero and thus, ending. That's one of lots of ways to handle it. A: Using a JavaScript "thread" to keep the session open is, to me, a bad idea. It's against the idea of session timeout which exists to free some resources if there's no user in front of the application. I think you should adjust the session timeout with the more accurate time, in order to fill the form in an "typical normal use". You may also be proactive by : having a JavaScript alert displaying a non-intrusive warning (not a popup) to the user before the timeout expire, which say that the session will expire soon (and give an link to send an ajax request to reset the timeout and remove that warning - that will avoid the user to lost the form he is currently typing), and also have a second JavaScript "thread", which, if the session has expired, redirect to the login page with a message saying that the session has now expired. It think that's the best because it avoid the user to fill a complicated form for nothing, and handle the case when the user has gone away. A: As an alternative for the technical solutions, you could make your application in such a way that everytime a particular job is done, for example filling in a form, you ask the user if he wants to continue doing another job or if he's done. Yould could have a startscreen with menu options and if the user chooses an option he first has to enter his credentials. Or put a password field on the form. Depends on how many forms they have to fill in a session. A: When the user posts the form and their session has timed out, you should make sure you save the form values somewhere and then ask the user to login again. Once they have re-authenticated you they can then re-submit the form (as none of their data will have been lost). A: I had developed something requiring very long session. The user logged in on a page when he sit on the machine and after doing his work, logged out. Now he may use system for few minutes or for hours. To keep session alive till he logged out, I used timer with javascript, it went to server and updated an anthem label with current time on server.
Best way to deal with session timeout in web apps?
I am currently building an internal web application used in a factory/warehouse type location. The users will be sharing a single PC between several people, so we need to have a fairly short session timeout to stop people wandering off and leaving the application logged in where someone else can come to the PC and do something under the previous user's username. The problem with this is a session can timeout while a user is currently entering information into a form, especially if they take a long time. How would you deal with this in a user friendly manner?
[ "Use AJAX to regularly stash the contents of the partially filled-out form so they have not lost their work if they get booted by the system. Heck, once you're doing that, use AJAX to keep their session from timing out if they spend the time typing.\n", "Keep the server informed about the fact that the user is actively entering information.\nFor instance send a message to the server if the user presses the TAB key or clicks with a mouse on a field.\nThe final solution is up to you.\n", "The best advice would probably be to ask the users to close the browser window once they're done. With the use of session-cookies, the session will automatically end when the browser is closed or otherwise on a 30 minute timeout (can be changed afaik).\nSince there by default is no interaction between the browser and the server once a page is loaded, you would have to have a javascript contact the server in the background on forms-pages to refresh the session, but it seems a bit too much trouble for such a minor problem.\n", "If the session timeout is so short that the user doesn't have the time to fill in a form, I would put an AJAX script that makes a http request to the server, every few minutes, to keep the session alive. I would do that only on pages that the user has to fill in something or has already started filling something.\nAnother solution would be to use a session timeout reminder script that popups a dialog to remind the user that the session is about to time out. The popup should display a \"Logout\" and a \"Continue using application\" that makes a ajax request to update the session time out.\n", "Maybe that a keep-alive javascript process could be helpfull in this case. If the script capture some key triggers, it send a \"I'm still typing\" message to the server to keep the session alive.\n", "have you considered breaking the form into smaller chunks?\n", "Monitor the timeout and post a pop-up to notify the user that their current session will expire and present \"OK\" or \"Cancel\" buttons. OK to keep the session going (i.e. reset the counter to another 5 minutes or 10 minutes - whatever you need) -or- Cancel to allow the session to continue to countdown to zero and thus, ending.\nThat's one of lots of ways to handle it.\n", "Using a JavaScript \"thread\" to keep the session open is, to me, a bad idea.\nIt's against the idea of session timeout which exists to free some resources if there's no user in front of the application.\nI think you should adjust the session timeout with the more accurate time, in order to fill the form in an \"typical normal use\".\nYou may also be proactive by :\n\nhaving a JavaScript alert displaying a non-intrusive warning (not a popup) to the user before the timeout expire, which say that the session will expire soon (and give an link to send an ajax request to reset the timeout and remove that warning - that will avoid the user to lost the form he is currently typing),\nand also have a second JavaScript \"thread\", which, if the session has expired, redirect to the login page with a message saying that the session has now expired.\n\nIt think that's the best because it avoid the user to fill a complicated form for nothing, and handle the case when the user has gone away.\n", "As an alternative for the technical solutions, you could make your application in such a way that everytime a particular job is done, for example filling in a form, you ask the user if he wants to continue doing another job or if he's done. Yould could have a startscreen with menu options and if the user chooses an option he first has to enter his credentials. \nOr put a password field on the form. Depends on how many forms they have to fill in a session.\n", "When the user posts the form and their session has timed out, you should make sure you save the form values somewhere and then ask the user to login again. Once they have re-authenticated you they can then re-submit the form (as none of their data will have been lost).\n", "I had developed something requiring very long session. The user logged in on a page when he sit on the machine and after doing his work, logged out. Now he may use system for few minutes or for hours. To keep session alive till he logged out, I used timer with javascript, it went to server and updated an anthem label with current time on server.\n" ]
[ 3, 3, 2, 2, 1, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "authentication", "session", "web_applications" ]
stackoverflow_0000114321_authentication_session_web_applications.txt
Q: Thoughts on Design - Core Control Logic and Rendering Layers I just wanted to see if I could have your thoughts on the design of some work I am currently doing. Here's the current situation - Basically: I am developing a series of controls for our applications. Some of these may be used in both WinForms and ASP.NET Web applications. I am on a constant endeavor to improve my testing and testability of my code. So, here is what I have done: Created the core control logic in a class that has no concept of a UI. It simply raises events when things about it change. All data as stored as custom typed objects where it needs to be distinguished from others (e.g. I have a PagingControl where it has SelectedPage and PageNumber items). I then created an abstract class to act as the interface for a rendering "engine". This ensures that any custom types used (and possibly added) to the core logic are handled by the engine. Following the above example, it contains an abstract method RenderSelectedPage. I then created concrete implementations of the abstract rendering engine (e.g. ConsoleRenderingEngine, HtmlRenderingEngine etc.). This then handled the methods and rendered them to their respective UI's/Outputs as appropriate. I found the following pro's and con's to this approach: Pro's It works. Quite well, its easy to implement a new rendering mechanism, all you do is subclass the abstract engine and render the output (which passes required references to you). It's really seperates the UI from the core code, making it much easier to test. Obviously due to the encapsulation of core/rendering logic, it's quite obvious where problems lie when they appear. Con's It can look confusing/bloated. Even though there is not a massive amount of code in each class, there are 3x classes to get it to render to 1 output (1x core, 1x interface, 1x renderer). However, when creating the WinForms/WebForms controls it also means another classe (since one needs to sublcass Control as well as the AbstractRenderingEngine). ... OK so that's the only "con" I can really think of, and the main reason for this question ^_^ So, What are your thoughts on this "pattern"? How would you change/improve it? This question may get updated as more thoughts come to me, or clarity may be requested (I know it's a heavy read!). Update Thanks for the answers guys, funny you said MVP, I thought I had seen something like this somewhere but couldn't remember for the life of me what it was! As soon as I saw "MVP" I thought "dammit". :D Thanks for the responses guys. I will study MVP more and see if I can improve what I have further. A: From your description it's a bit like how I do MVP but with the events going the other way. I usually have a very thin view that hides behind an interface and that knows nothing about the presenter. The view is the one who throws events on user actions. Usually all the view does is translate UI specific to primitives or sometimes value objects from the model (value object in a ddd sense, not .net structs) Sometimes I nest views for more complex situations and for reuse. UserControls sometimes have their own view and presenter structure. When you start doing nesting views and presenters instantiation of objects starts getting a lot of work so this is usually when I start looking for an IoC container. The presenter knows about the view through it's interface and talks direcly to it. It reacts to view events and does most of the logic. The view and model are Di'd into the presenter so all the logic in it is testable. Another approach I saw was where the view knew about the presenter and the presenter only knew about the view through the interface. This gets around having to raise events for view actions because the view can talk directly to the presenter. (I think this is what used to be called MVC in the smalltalk world) The presenter is still testable and this enables you to do databinding from the view to the presenter. I usually don't use databinding so for me this is not a big advantage. I to decouple stuff a bit more like in the first example.
Thoughts on Design - Core Control Logic and Rendering Layers
I just wanted to see if I could have your thoughts on the design of some work I am currently doing. Here's the current situation - Basically: I am developing a series of controls for our applications. Some of these may be used in both WinForms and ASP.NET Web applications. I am on a constant endeavor to improve my testing and testability of my code. So, here is what I have done: Created the core control logic in a class that has no concept of a UI. It simply raises events when things about it change. All data as stored as custom typed objects where it needs to be distinguished from others (e.g. I have a PagingControl where it has SelectedPage and PageNumber items). I then created an abstract class to act as the interface for a rendering "engine". This ensures that any custom types used (and possibly added) to the core logic are handled by the engine. Following the above example, it contains an abstract method RenderSelectedPage. I then created concrete implementations of the abstract rendering engine (e.g. ConsoleRenderingEngine, HtmlRenderingEngine etc.). This then handled the methods and rendered them to their respective UI's/Outputs as appropriate. I found the following pro's and con's to this approach: Pro's It works. Quite well, its easy to implement a new rendering mechanism, all you do is subclass the abstract engine and render the output (which passes required references to you). It's really seperates the UI from the core code, making it much easier to test. Obviously due to the encapsulation of core/rendering logic, it's quite obvious where problems lie when they appear. Con's It can look confusing/bloated. Even though there is not a massive amount of code in each class, there are 3x classes to get it to render to 1 output (1x core, 1x interface, 1x renderer). However, when creating the WinForms/WebForms controls it also means another classe (since one needs to sublcass Control as well as the AbstractRenderingEngine). ... OK so that's the only "con" I can really think of, and the main reason for this question ^_^ So, What are your thoughts on this "pattern"? How would you change/improve it? This question may get updated as more thoughts come to me, or clarity may be requested (I know it's a heavy read!). Update Thanks for the answers guys, funny you said MVP, I thought I had seen something like this somewhere but couldn't remember for the life of me what it was! As soon as I saw "MVP" I thought "dammit". :D Thanks for the responses guys. I will study MVP more and see if I can improve what I have further.
[ "From your description it's a bit like how I do MVP but with the events going the other way.\nI usually have a very thin view that hides behind an interface and that knows nothing about the presenter. The view is the one who throws events on user actions. Usually all the view does is translate UI specific to primitives or sometimes value objects from the model (value object in a ddd sense, not .net structs) Sometimes I nest views for more complex situations and for reuse. UserControls sometimes have their own view and presenter structure. When you start doing nesting views and presenters instantiation of objects starts getting a lot of work so this is usually when I start looking for an IoC container.\nThe presenter knows about the view through it's interface and talks direcly to it. It reacts to view events and does most of the logic. The view and model are Di'd into the presenter so all the logic in it is testable.\nAnother approach I saw was where the view knew about the presenter and the presenter only knew about the view through the interface. This gets around having to raise events for view actions because the view can talk directly to the presenter. (I think this is what used to be called MVC in the smalltalk world) The presenter is still testable and this enables you to do databinding from the view to the presenter. I usually don't use databinding so for me this is not a big advantage. I to decouple stuff a bit more like in the first example.\n" ]
[ 2 ]
[]
[]
[ "architecture", "design_patterns" ]
stackoverflow_0000114212_architecture_design_patterns.txt
Q: Maintaining Multiple Databases Across Several Platforms What's the best way to maintain a multiple databases across several platforms (Windows, Linux, Mac OS X and Solaris) and keep them in sync with one another? I've tried several different programs and nothing seems to work! A: I think you should ask yourself why you have to go through the hassle of maintaining multiple databases across several platforms and have them in sync with one another. Sounds like there's a lot of redundancy there. Why not just have one instance of that database, since I'm sure it can be made accessible (e.g. via SOA approach) to multiple apps on multiple platforms anyway? A: Why go through the hassle? Management claims it's more expensive? Here's how to prove them wrong. Pick one database, call it the "master" or "system of record". Write scripts to export data from the master and load it into your copies. If you have a nice database (MySQL, SQL/Server, Oracle or DB2) there are nice tools to do this replication for you. If you have a mixture of databases, you'll have to resort to exporting changed data and reloading changed data. The idea is that this is a 1-way copy: master to replicants. Fix each application, one at a time, to do updates in the master database only. Since each application has a JDBC (or ODBC or whatever) connection to a database, it can just as easily be a connection to the master database. Once you've fixed the applications to update only the master, the replicas are worthless. Management can insist that it's cheaper to have them. And there they are -- clones of the master database -- just what management says you must have. Your life is simpler because the apps are only updating the system of record. They're happy because you have all the cloned databases lying around.
Maintaining Multiple Databases Across Several Platforms
What's the best way to maintain a multiple databases across several platforms (Windows, Linux, Mac OS X and Solaris) and keep them in sync with one another? I've tried several different programs and nothing seems to work!
[ "I think you should ask yourself why you have to go through the hassle of maintaining multiple databases across several platforms and have them in sync with one another. Sounds like there's a lot of redundancy there. Why not just have one instance of that database, since I'm sure it can be made accessible (e.g. via SOA approach) to multiple apps on multiple platforms anyway?\n", "Why go through the hassle? Management claims it's more expensive? \nHere's how to prove them wrong.\nPick one database, call it the \"master\" or \"system of record\". \nWrite scripts to export data from the master and load it into your copies. If you have a nice database (MySQL, SQL/Server, Oracle or DB2) there are nice tools to do this replication for you. If you have a mixture of databases, you'll have to resort to exporting changed data and reloading changed data. The idea is that this is a 1-way copy: master to replicants.\nFix each application, one at a time, to do updates in the master database only. Since each application has a JDBC (or ODBC or whatever) connection to a database, it can just as easily be a connection to the master database.\nOnce you've fixed the applications to update only the master, the replicas are worthless. Management can insist that it's cheaper to have them. And there they are -- clones of the master database -- just what management says you must have.\nYour life is simpler because the apps are only updating the system of record. They're happy because you have all the cloned databases lying around.\n" ]
[ 3, 0 ]
[]
[]
[ "database", "linux", "macos", "solaris", "windows" ]
stackoverflow_0000113277_database_linux_macos_solaris_windows.txt
Q: Does CASCADE Delete execute as transaction? I want to perform cascade delete for some tables in my database, but I'm interested in what happens in case there's a failure when deleting something. Will everything rollback? A: In general¹, yes, cascade deletes are done in the same transaction (or subtransaction) as your original delete. You should read the documentation of your SQL server, though. ¹ The exception is if you're using a database that doesn't support transactions, like MySQL with MyISAM tables. A: Cascade deletes are indeed atomic, they would be of little use without that property. It is in the documentation. A: It's worth pointing out that any cascading event should be atomic (i.e. with in a transaction). But, as Joel Coehoorn points out, check the documentation for your database.
Does CASCADE Delete execute as transaction?
I want to perform cascade delete for some tables in my database, but I'm interested in what happens in case there's a failure when deleting something. Will everything rollback?
[ "In general¹, yes, cascade deletes are done in the same transaction (or subtransaction) as your original delete. You should read the documentation of your SQL server, though.\n¹ The exception is if you're using a database that doesn't support transactions, like MySQL with MyISAM tables.\n", "Cascade deletes are indeed atomic, they would be of little use without that property. It is in the documentation.\n", "It's worth pointing out that any cascading event should be atomic (i.e. with in a transaction). But, as Joel Coehoorn points out, check the documentation for your database. \n" ]
[ 15, 5, 1 ]
[]
[]
[ "cascade", "sql" ]
stackoverflow_0000114163_cascade_sql.txt
Q: How is the Page File available calculated in Windows Task Manager? In Vista Task Manager, I understand the available page file is listed like this: Page File inUse M / available M In XP it's listed as the Commit Charge Limit. I had thought that: Available Virtual Memory = Physical Memory Total + Sum of Page Files But on my machine I've got Physical Memory = 2038M, Page Files = 4096M, Page File Available = 6051. There's 83M unaccounted for here. What's that used for. I thought it might be something to do with the Kernel memory, but the number doesn't seem to match up? Info I've found so far: See http://msdn.microsoft.com/en-us/library/aa965225(VS.85).aspx for more info. Page file size can be found here: Computer Properties, advanced, performance settings, advanced. A: I think you are correct in your guess it has to do something with the kernel - the kernel memory needs some physical backup as well. However I have to admit that when trying to verify try, the numbers still do not match well and there is a significant amount of memory not accounted for by this. I have: Available Virtual Memory = 4 033 552 KB Physical Memory Total = 2 096 148 KB Sum of Page Files = 2048 MB Kernel Non-Paged Memory = 28 264 KB Kernel Paged Memory = 63 668 KB
How is the Page File available calculated in Windows Task Manager?
In Vista Task Manager, I understand the available page file is listed like this: Page File inUse M / available M In XP it's listed as the Commit Charge Limit. I had thought that: Available Virtual Memory = Physical Memory Total + Sum of Page Files But on my machine I've got Physical Memory = 2038M, Page Files = 4096M, Page File Available = 6051. There's 83M unaccounted for here. What's that used for. I thought it might be something to do with the Kernel memory, but the number doesn't seem to match up? Info I've found so far: See http://msdn.microsoft.com/en-us/library/aa965225(VS.85).aspx for more info. Page file size can be found here: Computer Properties, advanced, performance settings, advanced.
[ "I think you are correct in your guess it has to do something with the kernel - the kernel memory needs some physical backup as well.\nHowever I have to admit that when trying to verify try, the numbers still do not match well and there is a significant amount of memory not accounted for by this.\nI have:\nAvailable Virtual Memory = 4 033 552 KB\nPhysical Memory Total = 2 096 148 KB\nSum of Page Files = 2048 MB\nKernel Non-Paged Memory = 28 264 KB\nKernel Paged Memory = 63 668 KB\n" ]
[ 1 ]
[]
[]
[ "memory", "memory_management", "windows" ]
stackoverflow_0000093969_memory_memory_management_windows.txt
Q: How to update large XML file Rather than rewriting the entire contents of an xml file when a single element is updated, is there a better alternative to updating the file? A: I would recommend using VTD-XML http://vtd-xml.sourceforge.net/ From their FAQ ( http://vtd-xml.sourceforge.net/faq.html ): Why should I use VTD-XML for large XML files? For numerous reasons summarized below: Performance: The performance of VTD-XML is far better than SAX Ease to use: Random access combined with XPath makes application easy to write Better maintainability: App code is shorter and simpler to understand. Incremental update: Occasional, small changes become very efficient. Indexing: Pre-parsed form of XML will further boost processing performance. Other features: Cut, paste, split and assemble XML documents is only possible with VTD-XML. In order to take advantage of VTD-XML, we recommended that developers split their ultra large XML documents into smaller, more manageable chucks (<2GB). A: If your XML file is so large that updating it is a performance bottleneck, you should consider moving away from XML to a more efficient disk format (or a real database). If, however, you just feel like it might be a problem, remember the rules of optimization: Don't do it (experts only) Don't do it, yet. A: You have a few options here, but none of them are good. Since XML Objects aren't broken into distinct parts, you'll either have to use some filesystem level modification with regex pattern matching (sed is a good start), OR you should break your xml into smaller parts for manageability. A: If possible, serialize the XML and use diff/patch/apply Linux tools (or equivalent tools in your platform) . This way, you don't have to deal with parsing, writing.
How to update large XML file
Rather than rewriting the entire contents of an xml file when a single element is updated, is there a better alternative to updating the file?
[ "I would recommend using VTD-XML http://vtd-xml.sourceforge.net/\nFrom their FAQ ( http://vtd-xml.sourceforge.net/faq.html ):\n\nWhy should I use VTD-XML for large XML files?\nFor numerous reasons summarized below:\n\nPerformance: The performance of VTD-XML is far better than SAX\nEase to use: Random access combined with XPath makes application easy to write\nBetter maintainability: App code is shorter and simpler to understand.\nIncremental update: Occasional, small changes become very efficient.\nIndexing: Pre-parsed form of XML will further boost processing performance.\nOther features: Cut, paste, split and assemble XML documents is only possible with VTD-XML.\n\nIn order to take advantage of VTD-XML, we recommended that developers split their ultra large XML documents into smaller, more manageable chucks (<2GB). \n\n", "If your XML file is so large that updating it is a performance bottleneck, you should consider moving away from XML to a more efficient disk format (or a real database). \nIf, however, you just feel like it might be a problem, remember the rules of optimization:\n\nDon't do it\n(experts only) Don't do it, yet.\n\n", "You have a few options here, but none of them are good. \nSince XML Objects aren't broken into distinct parts, you'll either have to use some filesystem level modification with regex pattern matching (sed is a good start), OR you should break your xml into smaller parts for manageability.\n", "If possible, serialize the XML and use diff/patch/apply Linux tools (or equivalent tools in your platform) . This way, you don't have to deal with parsing, writing. \n" ]
[ 6, 4, 0, 0 ]
[ "Process Large XML Files with XQuery Works with Gigabyte Size XML Files\nhttp://www.xquery.com\nXQuery is a query language that was designed as a native XML query language. Because most types of data can be represented as XML, XQuery can also be used to query other types of data. For example, XQuery can be used to query relational data using an XML view of a relational database. This is important because many Internet applications need to integrate information from multiple sources, including data found in web messages, relational data, and various XML sources. XQuery was specifically designed for this kind of data integration.\nFor example, suppose your company is a financial institution that needs to produce reports of stock holdings for each client. A client requests a report with a Simple Object Access Protocol (SOAP) message, which is represented in XML. In most businesses, the stock holdings data is stored in multiple relational databases, such as Oracle, Microsoft SQL Server, or DB2. XQuery can query both the SOAP message and the relational databases, creating a report in XML.\nXQuery is based on the structure of XML and leverages that structure to make it possible to perform queries on any type of data that can be represented as XML, including relational data. In addition, XQuery API for Java (XQJ) lets your queries run in any environment that supports the J2EE platform.\n" ]
[ -4 ]
[ "java", "xml" ]
stackoverflow_0000062423_java_xml.txt
Q: SQL Server post-join rowcount underestimate The Query Optimizer is estimating that the results of a join will have only one row, when the actual number of rows is 2000. This is causing later joins on the dataset to have an estimated result of one row, when some of them go as high as 30,000. With a count of 1, the QO is choosing a loop join/index seek strategy for many of the joins which is much too slow. I worked around the issue by constraining the possible join strategies with a WITH OPTION (HASH JOIN, MERGE JOIN), which improved overall execution time from 60+ minutes to 12 seconds. However, I think the QO is still generating a less than optimal plan because of the bad rowcounts. I don't want to specify the join order and details manually-- there are too many queries affected by this for it to be worthwhile. This is in Microsoft SQL Server 2000, a medium query with several table selects joined to the main select. I think the QO may be overestimating the cardinality of the many side on the join, expecting the joining columns between the tables to have less rows in common. The estimated row counts from scanning the indexes before the join are accurate, it's only the estimated row count after certain joins that's much too low. The statistics for all the tables in the DB are up to date and refreshed automatically. One of the early bad joins is between a generic 'Person' table for information common to all people and a specialized person table that about 5% of all those people belong to. The clustered PK in both tables (and the join column) is an INT. The database is highly normalized. I believe that the root problem is the bad row count estimate after certain joins, so my main questions are: How can I fix the QO's post join rowcount estimate? Is there a way that I can hint that a join will have a lot of rows without specifying the entire join order manually? A: Although the statistics were up to date, the scan percentage wasn't high enough to provide accurate information. I ran this on each of the base tables that was having a problem to update all the statistics on a table by scanning all the rows, not just a default percentage. UPDATE STATISTICS <table> WITH FULLSCAN, ALL The query still has a lot of loop joins, but the join order is different and it runs in 2-3 seconds. A: can't you prod the QO with a well-placed query hint?
SQL Server post-join rowcount underestimate
The Query Optimizer is estimating that the results of a join will have only one row, when the actual number of rows is 2000. This is causing later joins on the dataset to have an estimated result of one row, when some of them go as high as 30,000. With a count of 1, the QO is choosing a loop join/index seek strategy for many of the joins which is much too slow. I worked around the issue by constraining the possible join strategies with a WITH OPTION (HASH JOIN, MERGE JOIN), which improved overall execution time from 60+ minutes to 12 seconds. However, I think the QO is still generating a less than optimal plan because of the bad rowcounts. I don't want to specify the join order and details manually-- there are too many queries affected by this for it to be worthwhile. This is in Microsoft SQL Server 2000, a medium query with several table selects joined to the main select. I think the QO may be overestimating the cardinality of the many side on the join, expecting the joining columns between the tables to have less rows in common. The estimated row counts from scanning the indexes before the join are accurate, it's only the estimated row count after certain joins that's much too low. The statistics for all the tables in the DB are up to date and refreshed automatically. One of the early bad joins is between a generic 'Person' table for information common to all people and a specialized person table that about 5% of all those people belong to. The clustered PK in both tables (and the join column) is an INT. The database is highly normalized. I believe that the root problem is the bad row count estimate after certain joins, so my main questions are: How can I fix the QO's post join rowcount estimate? Is there a way that I can hint that a join will have a lot of rows without specifying the entire join order manually?
[ "Although the statistics were up to date, the scan percentage wasn't high enough to provide accurate information. I ran this on each of the base tables that was having a problem to update all the statistics on a table by scanning all the rows, not just a default percentage.\nUPDATE STATISTICS <table> WITH FULLSCAN, ALL\n\nThe query still has a lot of loop joins, but the join order is different and it runs in 2-3 seconds.\n", "can't you prod the QO with a well-placed query hint?\n" ]
[ 3, 0 ]
[]
[]
[ "performance", "sql_server" ]
stackoverflow_0000093150_performance_sql_server.txt
Q: Mac toolbar via WINE / Crossover Does anyone know if it's possible to get a Win32 application to run under wine / crossover but have the main toolbar appear as a Mac toolbar (i.e. outside the wine / crossover app)? A: What is the "main toolbar"? In Win32, windows do not require a menu bar (ie: IE), or even a main window (!) so this is obviously not possible in general. If you really wanted to, you could send GetMenu() to the first created window, then use (something like? I haven't used the menu APIs much) GetMenuItemInfo() to fill the mac toolbar whenever the app gains focus, but I think this would be a lot of work for an 80% at best solution, not to mention I wouldn't know where to start to integrate this with WINE or crossover.
Mac toolbar via WINE / Crossover
Does anyone know if it's possible to get a Win32 application to run under wine / crossover but have the main toolbar appear as a Mac toolbar (i.e. outside the wine / crossover app)?
[ "What is the \"main toolbar\"? In Win32, windows do not require a menu bar (ie: IE), or even a main window (!) so this is obviously not possible in general. If you really wanted to, you could send GetMenu() to the first created window, then use (something like? I haven't used the menu APIs much) GetMenuItemInfo() to fill the mac toolbar whenever the app gains focus, but I think this would be a lot of work for an 80% at best solution, not to mention I wouldn't know where to start to integrate this with WINE or crossover.\n" ]
[ 1 ]
[]
[]
[ "macos", "winapi", "wine" ]
stackoverflow_0000114559_macos_winapi_wine.txt
Q: Why do my exception stack traces always point to the last method line? I have a problem with my Visual Studio installation. When I got an exception I always have incorrect line numbers in it's stack trace. There are always point to last line of each method in my codebase. At the same time it's OK when I'm tracing programs with debugger. What's happed with PDBs? No, I'm not re-throwing exception at each method. In each line of stack trace I have last row of corresponding method, while exception had thrown by statement in the middle. A: Sounds like you're running your app in Release mode. Release mode has difficulties with line numbers for exceptions and whatnot. Compile your app in Debug mode (no need to attach the debugger) and see if it sorts itself out.
Why do my exception stack traces always point to the last method line?
I have a problem with my Visual Studio installation. When I got an exception I always have incorrect line numbers in it's stack trace. There are always point to last line of each method in my codebase. At the same time it's OK when I'm tracing programs with debugger. What's happed with PDBs? No, I'm not re-throwing exception at each method. In each line of stack trace I have last row of corresponding method, while exception had thrown by statement in the middle.
[ "Sounds like you're running your app in Release mode. Release mode has difficulties with line numbers for exceptions and whatnot.\nCompile your app in Debug mode (no need to attach the debugger) and see if it sorts itself out.\n" ]
[ 2 ]
[]
[]
[ ".net", "c#", "exception", "stack_trace", "visual_studio" ]
stackoverflow_0000028607_.net_c#_exception_stack_trace_visual_studio.txt
Q: Any experience with unusual technologies? 99 bottles of beers made me realize that ADA, Erlang and Smalltalk were not so odd languages after all. There are plenty of unusual tools and I supposed that a lot of them are even used :-) Have you ever worked with very original technologies ? If yes, let us know in which context, and what did you think about it. Funny snippets strongly expected. A: I've been working professionally with Dyalog APL for almost three years now. It's always fun and challenging to learn a completely different language, and the language has its advantages. But I'm more annoyed than intrigued by it nowadays. Some particular drawbacks: There's almost noone outside the office to ask if you're stuck. There's almost no resources, tips and tricks available online. And noone else in the world has probably done what you're doing anyway. You have to reinvent the wheel all the time, since there's really no class/function library to use. (This can be fun for a geek like me, but not very productive.) You constantly have to write workarounds or avoid using "modern" features, since the IDE and interpreter are closed-source, and the vendor is too small to have the resources to fixing all bugs. A: I haven't worked with any unusual technologies but I believe Ada is still very much alive within the defence/aerospace/high reliability circles. It's something I would like to pick up one day. A: I think the strangest thing I've 'worked' with was in grade 11 in high school. We were learning about back propogation in neural networks, and we had to do an assignment in some strange hypothetical language that our teacher had come up with.
Any experience with unusual technologies?
99 bottles of beers made me realize that ADA, Erlang and Smalltalk were not so odd languages after all. There are plenty of unusual tools and I supposed that a lot of them are even used :-) Have you ever worked with very original technologies ? If yes, let us know in which context, and what did you think about it. Funny snippets strongly expected.
[ "I've been working professionally with Dyalog APL for almost three years now. It's always fun and challenging to learn a completely different language, and the language has its advantages. But I'm more annoyed than intrigued by it nowadays.\nSome particular drawbacks:\n\nThere's almost noone outside the office to ask if you're stuck. There's almost no resources, tips and tricks available online. And noone else in the world has probably done what you're doing anyway.\nYou have to reinvent the wheel all the time, since there's really no class/function library to use. (This can be fun for a geek like me, but not very productive.)\nYou constantly have to write workarounds or avoid using \"modern\" features, since the IDE and interpreter are closed-source, and the vendor is too small to have the resources to fixing all bugs.\n\n", "I haven't worked with any unusual technologies but I believe Ada is still very much alive within the defence/aerospace/high reliability circles. It's something I would like to pick up one day.\n", "I think the strangest thing I've 'worked' with was in grade 11 in high school. We were learning about back propogation in neural networks, and we had to do an assignment in some strange hypothetical language that our teacher had come up with.\n" ]
[ 1, 0, 0 ]
[]
[]
[ "language_agnostic" ]
stackoverflow_0000114659_language_agnostic.txt
Q: How do I handle data which must be persisted in a database, but isn't a proper model, in Ruby on Rails? Imagine a web application written in Ruby on Rails. Part of the state of that application is represented in a piece of data which doesn't fit the description of a model. This state descriptor needs to be persisted in the same database as the models. Where it differs from a model is that there needs to be only one instance of its class and it doesn't have relationships with other classes. Has anyone come across anything like this? A: If it's data, and it's in the database, it's part of the model. A: From your description I think the rails-settings plugin should do what you need. From the Readme: "Settings is a plugin that makes managing a table of global key, value pairs easy. Think of it like a global Hash stored in you database, that uses simple ActiveRecord like methods for manipulation. Keep track of any global setting that you dont want to hard code into your rails app. You can store any kind of object. Strings, numbers, arrays, or any object." http://github.com/Squeegy/rails-settings/tree/master A: This isn't really a RoR problem; it's a general OO design problem. If it were me, I'd probably find a way to conceptualize the data as a model and then just make it a singleton with a factory method and a private constructor. Alternatively, you could think of this as a form of logging. In that case, you'd just have a Logger class (also a singleton) that reads/writes the database directly and is invoked at the beginning and end of each request. A: In Rails, if data is in the database it's in a model. In this case the model may be called "Configuration", but it is still mapped to an ActiveRecord class in your Rails system. If this data is truly static, you may not need the database at all. You could use (as an example) a variable in your application controller: class ApplicationController < ActionController::Base helper :all @data = "YOUR DATA HERE" end There are a number of approaches that can be used to instantiate data for use in a Rails application. A: I'm not sure I understand why you say it can't fit in a Rails model. If it's just a complex data structure, just save a bunch of Ruby code in a text field in the database :-) If for example you have a complex nested hash you want to save, assign the following to your 'data' text field: ComplexThing.data = complex_hash.inspect When you want to read it back, simply complex_hash = eval ComplexThing.data Let me point out 2 more things about this solution: If your data structure is not standard Ruby classes, a simple inspect may not do it. If you see #<MyClass:0x4066e3c> anywhere, something's not being serialized properly. This is a naive implementation. You may want to check out real marshalling solutions if you risk having unicode data or if you really are saving a lot of custom-made classes.
How do I handle data which must be persisted in a database, but isn't a proper model, in Ruby on Rails?
Imagine a web application written in Ruby on Rails. Part of the state of that application is represented in a piece of data which doesn't fit the description of a model. This state descriptor needs to be persisted in the same database as the models. Where it differs from a model is that there needs to be only one instance of its class and it doesn't have relationships with other classes. Has anyone come across anything like this?
[ "If it's data, and it's in the database, it's part of the model. \n", "From your description I think the rails-settings plugin should do what you need. \nFrom the Readme:\n\"Settings is a plugin that makes managing a table of global key, value pairs easy. Think of it like a global Hash stored in you database, that uses simple ActiveRecord like methods for manipulation. Keep track of any global setting that you dont want to hard code into your rails app. You can store any kind of object. Strings, numbers, arrays, or any object.\"\nhttp://github.com/Squeegy/rails-settings/tree/master\n", "This isn't really a RoR problem; it's a general OO design problem. \nIf it were me, I'd probably find a way to conceptualize the data as a model and then just make it a singleton with a factory method and a private constructor.\nAlternatively, you could think of this as a form of logging. In that case, you'd just have a Logger class (also a singleton) that reads/writes the database directly and is invoked at the beginning and end of each request.\n", "In Rails, if data is in the database it's in a model. In this case the model may be called \"Configuration\", but it is still mapped to an ActiveRecord class in your Rails system.\nIf this data is truly static, you may not need the database at all.\nYou could use (as an example) a variable in your application controller:\nclass ApplicationController < ActionController::Base\n helper :all \n @data = \"YOUR DATA HERE\" \nend\n\nThere are a number of approaches that can be used to instantiate data for use in a Rails application.\n", "I'm not sure I understand why you say it can't fit in a Rails model. \nIf it's just a complex data structure, just save a bunch of Ruby code in a text field in the database :-)\nIf for example you have a complex nested hash you want to save, assign the following to your 'data' text field:\nComplexThing.data = complex_hash.inspect\n\nWhen you want to read it back, simply\ncomplex_hash = eval ComplexThing.data\n\nLet me point out 2 more things about this solution:\n\nIf your data structure is not standard Ruby classes, a simple inspect may not do it. If you see #<MyClass:0x4066e3c> anywhere, something's not being serialized properly.\nThis is a naive implementation. You may want to check out real marshalling solutions if you risk having unicode data or if you really are saving a lot of custom-made classes.\n\n" ]
[ 3, 3, 1, 1, 0 ]
[]
[]
[ "persistence", "ruby", "ruby_on_rails" ]
stackoverflow_0000114192_persistence_ruby_ruby_on_rails.txt
Q: IIS 6.0 Is Stubbornly Remembering Authentication Settings I have an .asmx in a folder in my application and I keep getting a 401 trying to access it. I have double and triple checked the setting including the directory security settings. It allows anonymous. I turned off Windows Authentication. If I delete the application and the folder its in, then redeploy it under the same application name it magically reapplies the old settings. If I deploy the exact same application to a different folder on the server and create another application under a new name and set up the directory security setting again it works!!! How do I get IIS to forget the setting under the original application name? A: After deleting the first application in IIS and its associated files on the disk, try restarting IIS (or your server if possible). Then come back and recreate the whole setup. A: Eventually I got it working again. By deploying to a different folder and recreating the virtual folder / application to it. I am not sure how that makes a difference but at least things are working again. A: I ran into a similar situation with asp.net pages. I had Anonymous on and Integrated off for a virtual directory, but one page was the opposite. Everything worked fine until I went to the one special page, then my post backs stopped working and I couldn't log out of the site until I deployed to a new virtual directory. My eventual solution was to enable anonymous and integrated for the entire site and just turn off anonymous on that one page.
IIS 6.0 Is Stubbornly Remembering Authentication Settings
I have an .asmx in a folder in my application and I keep getting a 401 trying to access it. I have double and triple checked the setting including the directory security settings. It allows anonymous. I turned off Windows Authentication. If I delete the application and the folder its in, then redeploy it under the same application name it magically reapplies the old settings. If I deploy the exact same application to a different folder on the server and create another application under a new name and set up the directory security setting again it works!!! How do I get IIS to forget the setting under the original application name?
[ "After deleting the first application in IIS and its associated files on the disk, try restarting IIS (or your server if possible). Then come back and recreate the whole setup.\n", "Eventually I got it working again. By deploying to a different folder and recreating the virtual folder / application to it.\nI am not sure how that makes a difference but at least things are working again.\n", "I ran into a similar situation with asp.net pages. I had Anonymous on and Integrated off for a virtual directory, but one page was the opposite. Everything worked fine until I went to the one special page, then my post backs stopped working and I couldn't log out of the site until I deployed to a new virtual directory.\nMy eventual solution was to enable anonymous and integrated for the entire site and just turn off anonymous on that one page.\n" ]
[ 1, 0, 0 ]
[]
[]
[ "asp.net", "authentication", "http", "http_status_code_401", "iis_6" ]
stackoverflow_0000113013_asp.net_authentication_http_http_status_code_401_iis_6.txt
Q: Excel Addin Access Violation Using c#, VS2005, and .NET 2.0. (XP 32 bit) This is a Winforms app that gets called by a VBA addin (.xla) via Interop libraries. This app has been around for a while and works fine when the assembly is compiled and executed anywhere other than my dev machine. On dev it crashes hard (in debugger and just running the object) with "Unhandled exception at 0x... in EXCEL.EXE: 0x...violation reading location 0x... But here's the weird part: The first method in my interface works fine. All the other methods crash as above. Here is an approximation of the code: [Guid("123Fooetc...")] [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] public interface IBar { [DispId(1)] void ThisOneWorksFine(Excel.Workbook ActiveWorkBook); [DispId(2)] string Crash1(Excel.Workbook ActiveWorkBook); [DispId(3)] int Crash2(Excel.Workbook activeWorkBook, Excel.Range target, string someStr); } [Guid("345Fooetc..")] [ClassInterface(ClassInterfaceType.None)] [ProgId("MyNameSpace.MyClass")] public class MyClass : IBar { public void ThisOneWorksFine(Excel.Workbook ActiveWorkBook) {...} string Crash1(Excel.Workbook ActiveWorkBook); {...} int Crash2(Excel.Workbook activeWorkBook, Excel.Range target, string someStr); {...} } It seems like some kind of environmental thing. Registry chundered? Could be code bugs, but it works fine elsewhere. A: I've had problems in this scenario with Office 2003 in the past. Some things that have helped: Installing Office 2003 Service Pack 2 stopped some crashes that happened when closing Excel. Installing Office 2003 Service Pack 3 fixes a bug with using XP styles in a VSTO2005 application (not your case here) Running the Excel VBA CodeCleaner http://www.appspro.com/Utilities/CodeCleaner.htm periodically helps prevent random crashes. Accessing Excel objects from multiple threads would be dodgy, so I hope you aren't doing that. If you have the possibility you could also try opening a case with Microsoft PSS. They are pretty good if you are able to reproduce the problem. And in most cases, this kind of thing is a bug, so you won't be charged for it :) A: Is your dev machine Win64? I've had problems with win64 builds of apps that go away if you set the build platform to x86. A: Is your dev machine running a different version of Office than the other machines? I know that the PIAs differ. So if you're developing on Office 2003 and testing on Office 2007 (or vice versa), for example, you will run into problems.
Excel Addin Access Violation
Using c#, VS2005, and .NET 2.0. (XP 32 bit) This is a Winforms app that gets called by a VBA addin (.xla) via Interop libraries. This app has been around for a while and works fine when the assembly is compiled and executed anywhere other than my dev machine. On dev it crashes hard (in debugger and just running the object) with "Unhandled exception at 0x... in EXCEL.EXE: 0x...violation reading location 0x... But here's the weird part: The first method in my interface works fine. All the other methods crash as above. Here is an approximation of the code: [Guid("123Fooetc...")] [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] public interface IBar { [DispId(1)] void ThisOneWorksFine(Excel.Workbook ActiveWorkBook); [DispId(2)] string Crash1(Excel.Workbook ActiveWorkBook); [DispId(3)] int Crash2(Excel.Workbook activeWorkBook, Excel.Range target, string someStr); } [Guid("345Fooetc..")] [ClassInterface(ClassInterfaceType.None)] [ProgId("MyNameSpace.MyClass")] public class MyClass : IBar { public void ThisOneWorksFine(Excel.Workbook ActiveWorkBook) {...} string Crash1(Excel.Workbook ActiveWorkBook); {...} int Crash2(Excel.Workbook activeWorkBook, Excel.Range target, string someStr); {...} } It seems like some kind of environmental thing. Registry chundered? Could be code bugs, but it works fine elsewhere.
[ "I've had problems in this scenario with Office 2003 in the past. Some things that have helped:\n\nInstalling Office 2003 Service Pack 2 stopped some crashes that happened when closing Excel.\nInstalling Office 2003 Service Pack 3 fixes a bug with using XP styles in a VSTO2005 application (not your case here)\nRunning the Excel VBA CodeCleaner http://www.appspro.com/Utilities/CodeCleaner.htm periodically helps prevent random crashes.\nAccessing Excel objects from multiple threads would be dodgy, so I hope you aren't doing that.\n\nIf you have the possibility you could also try opening a case with Microsoft PSS. They are pretty good if you are able to reproduce the problem. And in most cases, this kind of thing is a bug, so you won't be charged for it :)\n", "Is your dev machine Win64? I've had problems with win64 builds of apps that go away if you set the build platform to x86.\n", "Is your dev machine running a different version of Office than the other machines? I know that the PIAs differ. So if you're developing on Office 2003 and testing on Office 2007 (or vice versa), for example, you will run into problems.\n" ]
[ 2, 0, 0 ]
[]
[]
[ ".net_2.0", "add_in", "c#", "interop" ]
stackoverflow_0000103516_.net_2.0_add_in_c#_interop.txt
Q: Editable data grid for C# WinForms I need to present the user with a matrix of which one column is editable. What is the most appropriate control to use? I can't use a ListView because you can only edit the first column (the label) and that's no good to me. Is the DataGridView the way to go, or are there third party alternative components that do a better job? A: DataGridView is the best choice as it is free and comes with .NET WinForms 2.0. You can define editable columns or read-only. Plus you can customize the appearance if required. A: DataGridView is good. If you prefer a prettier interface, Telerik controls are better. A: If DataGridView will handle your needs, it's the right answer. Another option (although it seems to be unpopular around these parts!) is Infragistics NetAdvantage. The downsides to Infragistics are primarily a high cost and somewhat steep learning curve; the upsides are that these are some of the most powerful controls you'll ever find -- so if you need their flexibility, go for it. I don't have experience with Telerik (which has been mentioned by others here), but they do seem quite good. Being that my company has invested fairly heavily in Infragistics, we're not liable to switch any time soon ...
Editable data grid for C# WinForms
I need to present the user with a matrix of which one column is editable. What is the most appropriate control to use? I can't use a ListView because you can only edit the first column (the label) and that's no good to me. Is the DataGridView the way to go, or are there third party alternative components that do a better job?
[ "DataGridView is the best choice as it is free and comes with .NET WinForms 2.0. You can define editable columns or read-only. Plus you can customize the appearance if required.\n", "DataGridView is good. \nIf you prefer a prettier interface, Telerik controls are better.\n", "If DataGridView will handle your needs, it's the right answer. Another option (although it seems to be unpopular around these parts!) is Infragistics NetAdvantage. The downsides to Infragistics are primarily a high cost and somewhat steep learning curve; the upsides are that these are some of the most powerful controls you'll ever find -- so if you need their flexibility, go for it. \nI don't have experience with Telerik (which has been mentioned by others here), but they do seem quite good. Being that my company has invested fairly heavily in Infragistics, we're not liable to switch any time soon ... \n" ]
[ 13, 0, 0 ]
[]
[]
[ "c#", "editing", "user_interface", "winforms" ]
stackoverflow_0000114707_c#_editing_user_interface_winforms.txt
Q: Remote installing of windows service I need to remotely install windows service on number of computers, so I use CreateService() and other service functions from winapi. I know admin password and user name for machines that I need access to. In order to gain access to remote machine I impersonate calling process with help of LogonUser like this: //all variables are initialized correctly int status = 0; status = LogonUser(lpwUsername, lpwDomain, lpwPassword, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, &hToken); if (status == 0) { //here comes a error } status = ImpersonateLoggedOnUser(hToken); if (status == 0) { //once again a error } //ok, now we are impersonated, do all service work there So, I gain access to machine in a domain, but some of computers are out of domain. On machines that are out of domain this code doesn't work. Is there any way to access service manager on machine out of domain? A: You can do it , the account needs to exist on the remote machine and you need to use the machine name for the domain name in the LogonUser call. A: Rather than rolling your own, why not just use the SC built-in command? A: OK, problem resolved (not really very good, but rather OK). I used WNetAddConnection() to ipc$ on remote machine.
Remote installing of windows service
I need to remotely install windows service on number of computers, so I use CreateService() and other service functions from winapi. I know admin password and user name for machines that I need access to. In order to gain access to remote machine I impersonate calling process with help of LogonUser like this: //all variables are initialized correctly int status = 0; status = LogonUser(lpwUsername, lpwDomain, lpwPassword, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, &hToken); if (status == 0) { //here comes a error } status = ImpersonateLoggedOnUser(hToken); if (status == 0) { //once again a error } //ok, now we are impersonated, do all service work there So, I gain access to machine in a domain, but some of computers are out of domain. On machines that are out of domain this code doesn't work. Is there any way to access service manager on machine out of domain?
[ "You can do it , the account needs to exist on the remote machine and you need to use the machine name for the domain name in the LogonUser call.\n", "Rather than rolling your own, why not just use the SC built-in command?\n", "OK, problem resolved (not really very good, but rather OK). I used WNetAddConnection() to ipc$ on remote machine. \n" ]
[ 2, 0, 0 ]
[]
[]
[ "c++", "windows", "windows_services" ]
stackoverflow_0000062501_c++_windows_windows_services.txt
Q: How do I overlap widgets with the Tkinter pack geometry manager? I want to put a Canvas with an image in my window, and then I want to pack widgets on top of it, so the Canvas acts as a background. Is it possible to have two states for the pack manager: one for one set of widgets and another for another set? A: The answer to your specific question is no. You can't have two states or otherwise use pack two different ways in the same parent. However, what I think you want to accomplish is simple. Use the built-in features of the canvas to create an image item that is part of the canvas, then pack things into the canvas as if it were a frame. You can accomplish a similar thing by creating a label widget with an image, then pack your other widgets into the label. One advantage to using a canvas is you can easily tile an image to fill the whole canvas with a repeating background image so as the window grows the image will continue to fill the window (of course you can just use a sufficiently large original image...) A: I believe that Bryan's answer is probably the best general solution. However, you may also want to look at the place geometry manager. The place geometry manager lets you specify the exact size and position of the widget... which can get tedious quickly, but will get the job done. A: ... turned out to be unworkable because I wanted to add labels and more canvases to it, but I can't find any way to make their backgrounds transparent If it is acceptable to load an additional extension, take a look at Tkzinc. From the web site, Tkzinc (historically called Zinc) widget is very similar to the Tk Canvas in that they both support structured graphics. Like the Canvas, Tkzinc implements items used to display graphical entities. Those items can be manipulated and bindings can be associated with them to implement interaction behaviors. But unlike the Canvas, Tkzinc can structure the items in a hierarchy, has support for scaling and rotation, clipping can be set for sub-trees of the item hierarchy, supports muti-contour curves. It also provides advanced rendering with the help of OpenGL, such as color gradient, antialiasing, transparencies and a triangles item. I'm currently using it on a tcl project and am quite pleased with the results. Extensions for tcl, perl, and python are available. A: Not without swapping widget trees in and out, which I don't think can be done cleanly with Tk. Other toolkits can do this a little more elegantly. COM/VB/MFC can do this with an ActiveX control - you can hide/show multiple ActiveX controls in the same region. Any of the containers will let you do this by changing the child around. If you're doing a windows-specific program you may be able to accomplish it this way. QT will also let you do this in a similar manner. GTK is slightly harder.
How do I overlap widgets with the Tkinter pack geometry manager?
I want to put a Canvas with an image in my window, and then I want to pack widgets on top of it, so the Canvas acts as a background. Is it possible to have two states for the pack manager: one for one set of widgets and another for another set?
[ "The answer to your specific question is no. You can't have two states or otherwise use pack two different ways in the same parent. \nHowever, what I think you want to accomplish is simple. Use the built-in features of the canvas to create an image item that is part of the canvas, then pack things into the canvas as if it were a frame. \nYou can accomplish a similar thing by creating a label widget with an image, then pack your other widgets into the label.\nOne advantage to using a canvas is you can easily tile an image to fill the whole canvas with a repeating background image so as the window grows the image will continue to fill the window (of course you can just use a sufficiently large original image...)\n", "I believe that Bryan's answer is probably the best general solution. However, you may also want to look at the place geometry manager. The place geometry manager lets you specify the exact size and position of the widget... which can get tedious quickly, but will get the job done.\n", "\n... turned out to be unworkable because I wanted to add labels and more canvases to it, but I can't find any way to make their backgrounds transparent\n\nIf it is acceptable to load an additional extension, take a look at Tkzinc. From the web site, \n\nTkzinc (historically called Zinc) widget is very similar to the Tk Canvas in that they both support structured graphics. Like the Canvas, Tkzinc implements items used to display graphical entities. Those items can be manipulated and bindings can be associated with them to implement interaction behaviors. But unlike the Canvas, Tkzinc can structure the items in a hierarchy, has support for scaling and rotation, clipping can be set for sub-trees of the item hierarchy, supports muti-contour curves. It also provides advanced rendering with the help of OpenGL, such as color gradient, antialiasing, transparencies and a triangles item. \n\nI'm currently using it on a tcl project and am quite pleased with the results. Extensions for tcl, perl, and python are available.\n", "Not without swapping widget trees in and out, which I don't think can be done cleanly with Tk. Other toolkits can do this a little more elegantly.\n\nCOM/VB/MFC can do this with an ActiveX control - you can hide/show multiple ActiveX controls in the same region. Any of the containers will let you do this by changing the child around. If you're doing a windows-specific program you may be able to accomplish it this way.\nQT will also let you do this in a similar manner.\nGTK is slightly harder.\n\n" ]
[ 2, 1, 1, 0 ]
[]
[]
[ "geometry", "pack", "python", "tkinter" ]
stackoverflow_0000112263_geometry_pack_python_tkinter.txt
Q: What is the cost of using a pointer to member function vs. a switch? I have the following situation: class A { public: A(int whichFoo); int foo1(); int foo2(); int foo3(); int callFoo(); // cals one of the foo's depending on the value of whichFoo }; In my current implementation I save the value of whichFoo in a data member in the constructor and use a switch in callFoo() to decide which of the foo's to call. Alternatively, I can use a switch in the constructor to save a pointer to the right fooN() to be called in callFoo(). My question is which way is more efficient if an object of class A is only constructed once, while callFoo() is called a very large number of times. So in the first case we have multiple executions of a switch statement, while in the second there is only one switch, and multiple calls of a member function using the pointer to it. I know that calling a member function using a pointer is slower than just calling it directly. Does anybody know if this overhead is more or less than the cost of a switch? Clarification: I realize that you never really know which approach gives better performance until you try it and time it. However, in this case I already have approach 1 implemented, and I wanted to find out if approach 2 can be more efficient at least in principle. It appears that it can be, and now it makes sense for me to bother to implement it and try it. Oh, and I also like approach 2 better for aesthetic reasons. I guess I am looking for a justification to implement it. :) A: How sure are you that calling a member function via a pointer is slower than just calling it directly? Can you measure the difference? In general, you should not rely on your intuition when making performance evaluations. Sit down with your compiler and a timing function, and actually measure the different choices. You may be surprised! More info: There is an excellent article Member Function Pointers and the Fastest Possible C++ Delegates which goes into very deep detail about the implementation of member function pointers. A: You can write this: class Foo { public: Foo() { calls[0] = &Foo::call0; calls[1] = &Foo::call1; calls[2] = &Foo::call2; calls[3] = &Foo::call3; } void call(int number, int arg) { assert(number < 4); (this->*(calls[number]))(arg); } void call0(int arg) { cout<<"call0("<<arg<<")\n"; } void call1(int arg) { cout<<"call1("<<arg<<")\n"; } void call2(int arg) { cout<<"call2("<<arg<<")\n"; } void call3(int arg) { cout<<"call3("<<arg<<")\n"; } private: FooCall calls[4]; }; The computation of the actual function pointer is linear and fast: (this->*(calls[number]))(arg); 004142E7 mov esi,esp 004142E9 mov eax,dword ptr [arg] 004142EC push eax 004142ED mov edx,dword ptr [number] 004142F0 mov eax,dword ptr [this] 004142F3 mov ecx,dword ptr [this] 004142F6 mov edx,dword ptr [eax+edx*4] 004142F9 call edx Note that you don't even have to fix the actual function number in the constructor. I've compared this code to the asm generated by a switch. The switch version doesn't provide any performance increase. A: To answer the asked question: at the finest-grained level, the pointer to the member function will perform better. To address the unasked question: what does "better" mean here? In most cases I would expect the difference to be negligible. Depending on what the class it doing, however, the difference may be significant. Performance testing before worrying about the difference is obviously the right first step. A: If you are going to keep using a switch, which is perfectly fine, then you probably should put the logic in a helper method and call if from the constructor. Alternatively, this is a classic case of the Strategy Pattern. You could create an interface (or abstract class) named IFoo which has one method with Foo's signature. You would have the constructor take in an instance of IFoo (constructor Dependancy Injection that implemented the foo method that you want. You would have a private IFoo that would be set with this constructor, and every time you wanted to call Foo you would call your IFoo's version. Note: I haven't worked with C++ since college, so my lingo might be off here, ut the general ideas hold for most OO languages. A: If your example is real code, then I think you should revisit your class design. Passing in a value to the constructor, and using that to change behaviour is really equivalent to creating a subclass. Consider refactoring to make it more explicit. The effect of doing so is that your code will end up using a function pointer (all virtual methods are, really, are function pointers in jump tables). If, however your code was just a simplified example to ask whether, in general, jump tables are faster than switch statements, then my intuition would say that jump tables are quicker, but you are dependent on the compiler's optimisation step. But if performance is really such a concern, never rely on intuition - knock up a test program and test it, or look at the generated assembler. One thing is certain, a switch statement will never be slower than a jump table. The reason being that the best a compiler's optimiser can do will be too turn a series of conditional tests (i.e. a switch) into a jump table. So if you really want to be certain, take the compiler out of the decision process and use a jump table. A: Sounds like you should make callFoo a pure virtual function and create some subclasses of A. Unless you really need the speed, have done extensive profiling and instrumenting, and determined that the calls to callFoo are really the bottleneck. Have you? A: Function pointers are almost always better than chained-ifs. They make cleaner code, and are nearly always faster (except perhaps in a case where its only a choice between two functions and is always correctly predicted). A: I should think that the pointer would be faster. Modern CPUs prefetch instructions; mis-predicted branches flush the cache, which means it stalls while it refills the cache. A pointer doens't do that. Of course, you should measure both. A: Optimize only when needed First: Most of the time you most likely do not care, the difference will be very small. Make sure optimizing this call really makes sense first. Only if your measurements show there is really significant time spent in the call overhead, proceed to optimizing it (shameless plug - Cf. How to optimize an application to make it faster?) If the optimization is not significant, prefer the more readable code. Indirect call cost depends on target platform Once you have determined it is worth to apply low-level optimization, then it is a time to understand your target platform. The cost you can avoid here is the branch misprediction penalty. On modern x86/x64 CPU this misprediction is likely to be very small (they can predict indirect calls quite well most of the time), but when targeting PowerPC or other RISC platforms, the indirect calls/jumps are often not predicted at all and avoiding them can cause significant performance gain. See also Virtual call cost depends on platform. Compiler can implement switch using jump table as well One gotcha: Switch can sometimes be implemented as an indirect call (using a table) as well, especially when switching between many possible values. Such switch exhibits the same misprediction as a virtual function. To make this optimization reliable, one would probably prefer using if instead of switch for the most common case. A: Use timers to see which is quicker. Although unless this code is going to be over and over then it's unlikely that you'll notice any difference. Be sure that if you are running code from the constructor that if the contruction fails that you wont leak memory. This technique is used heavily with Symbian OS: http://www.titu.jyu.fi/modpa/Patterns/pattern-TwoPhaseConstruction.html A: If you are only calling callFoo() once, than most likely the function pointer will be slower by an insignificant amount. If you are calling it many times than most likely the function pointer will be faster by an insignificant amount (because it doesn't need to keep going through the switch). Either way look at the assembled code to find out for sure it is doing what you think it is doing. A: One often overlooked advantage to switch (even over sorting and indexing) is if you know that a particular value is used in the vast majority of cases. It's easy to order the switch so that the most common are checked first. ps. To reinforce greg's answer, if you care about speed - measure. Looking at assembler doesn't help when CPUs have prefetch / predictive branching and pipeline stalls etc
What is the cost of using a pointer to member function vs. a switch?
I have the following situation: class A { public: A(int whichFoo); int foo1(); int foo2(); int foo3(); int callFoo(); // cals one of the foo's depending on the value of whichFoo }; In my current implementation I save the value of whichFoo in a data member in the constructor and use a switch in callFoo() to decide which of the foo's to call. Alternatively, I can use a switch in the constructor to save a pointer to the right fooN() to be called in callFoo(). My question is which way is more efficient if an object of class A is only constructed once, while callFoo() is called a very large number of times. So in the first case we have multiple executions of a switch statement, while in the second there is only one switch, and multiple calls of a member function using the pointer to it. I know that calling a member function using a pointer is slower than just calling it directly. Does anybody know if this overhead is more or less than the cost of a switch? Clarification: I realize that you never really know which approach gives better performance until you try it and time it. However, in this case I already have approach 1 implemented, and I wanted to find out if approach 2 can be more efficient at least in principle. It appears that it can be, and now it makes sense for me to bother to implement it and try it. Oh, and I also like approach 2 better for aesthetic reasons. I guess I am looking for a justification to implement it. :)
[ "How sure are you that calling a member function via a pointer is slower than just calling it directly? Can you measure the difference?\nIn general, you should not rely on your intuition when making performance evaluations. Sit down with your compiler and a timing function, and actually measure the different choices. You may be surprised!\nMore info: There is an excellent article Member Function Pointers and the Fastest Possible C++ Delegates which goes into very deep detail about the implementation of member function pointers.\n", "You can write this:\nclass Foo {\npublic:\n Foo() {\n calls[0] = &Foo::call0;\n calls[1] = &Foo::call1;\n calls[2] = &Foo::call2;\n calls[3] = &Foo::call3;\n }\n void call(int number, int arg) {\n assert(number < 4);\n (this->*(calls[number]))(arg);\n }\n void call0(int arg) {\n cout<<\"call0(\"<<arg<<\")\\n\";\n }\n void call1(int arg) {\n cout<<\"call1(\"<<arg<<\")\\n\";\n }\n void call2(int arg) {\n cout<<\"call2(\"<<arg<<\")\\n\";\n }\n void call3(int arg) {\n cout<<\"call3(\"<<arg<<\")\\n\";\n }\nprivate:\n FooCall calls[4];\n};\n\nThe computation of the actual function pointer is linear and fast: \n (this->*(calls[number]))(arg);\n004142E7 mov esi,esp \n004142E9 mov eax,dword ptr [arg] \n004142EC push eax \n004142ED mov edx,dword ptr [number] \n004142F0 mov eax,dword ptr [this] \n004142F3 mov ecx,dword ptr [this] \n004142F6 mov edx,dword ptr [eax+edx*4] \n004142F9 call edx \n\nNote that you don't even have to fix the actual function number in the constructor. \nI've compared this code to the asm generated by a switch. The switch version doesn't provide any performance increase.\n", "To answer the asked question: at the finest-grained level, the pointer to the member function will perform better.\nTo address the unasked question: what does \"better\" mean here? In most cases I would expect the difference to be negligible. Depending on what the class it doing, however, the difference may be significant. Performance testing before worrying about the difference is obviously the right first step.\n", "If you are going to keep using a switch, which is perfectly fine, then you probably should put the logic in a helper method and call if from the constructor. Alternatively, this is a classic case of the Strategy Pattern. You could create an interface (or abstract class) named IFoo which has one method with Foo's signature. You would have the constructor take in an instance of IFoo (constructor Dependancy Injection that implemented the foo method that you want. You would have a private IFoo that would be set with this constructor, and every time you wanted to call Foo you would call your IFoo's version.\nNote: I haven't worked with C++ since college, so my lingo might be off here, ut the general ideas hold for most OO languages.\n", "If your example is real code, then I think you should revisit your class design. Passing in a value to the constructor, and using that to change behaviour is really equivalent to creating a subclass. Consider refactoring to make it more explicit. The effect of doing so is that your code will end up using a function pointer (all virtual methods are, really, are function pointers in jump tables).\nIf, however your code was just a simplified example to ask whether, in general, jump tables are faster than switch statements, then my intuition would say that jump tables are quicker, but you are dependent on the compiler's optimisation step. But if performance is really such a concern, never rely on intuition - knock up a test program and test it, or look at the generated assembler.\nOne thing is certain, a switch statement will never be slower than a jump table. The reason being that the best a compiler's optimiser can do will be too turn a series of conditional tests (i.e. a switch) into a jump table. So if you really want to be certain, take the compiler out of the decision process and use a jump table.\n", "Sounds like you should make callFoo a pure virtual function and create some subclasses of A.\nUnless you really need the speed, have done extensive profiling and instrumenting, and determined that the calls to callFoo are really the bottleneck. Have you?\n", "Function pointers are almost always better than chained-ifs. They make cleaner code, and are nearly always faster (except perhaps in a case where its only a choice between two functions and is always correctly predicted).\n", "I should think that the pointer would be faster.\nModern CPUs prefetch instructions; mis-predicted branches flush the cache, which means it stalls while it refills the cache. A pointer doens't do that.\nOf course, you should measure both.\n", "Optimize only when needed\nFirst: Most of the time you most likely do not care, the difference will be very small. Make sure optimizing this call really makes sense first. Only if your measurements show there is really significant time spent in the call overhead, proceed to optimizing it (shameless plug - Cf. How to optimize an application to make it faster?) If the optimization is not significant, prefer the more readable code.\nIndirect call cost depends on target platform\nOnce you have determined it is worth to apply low-level optimization, then it is a time to understand your target platform. The cost you can avoid here is the branch misprediction penalty. On modern x86/x64 CPU this misprediction is likely to be very small (they can predict indirect calls quite well most of the time), but when targeting PowerPC or other RISC platforms, the indirect calls/jumps are often not predicted at all and avoiding them can cause significant performance gain. See also Virtual call cost depends on platform.\nCompiler can implement switch using jump table as well\nOne gotcha: Switch can sometimes be implemented as an indirect call (using a table) as well, especially when switching between many possible values. Such switch exhibits the same misprediction as a virtual function. To make this optimization reliable, one would probably prefer using if instead of switch for the most common case.\n", "Use timers to see which is quicker. Although unless this code is going to be over and over then it's unlikely that you'll notice any difference.\nBe sure that if you are running code from the constructor that if the contruction fails that you wont leak memory.\nThis technique is used heavily with Symbian OS:\nhttp://www.titu.jyu.fi/modpa/Patterns/pattern-TwoPhaseConstruction.html\n", "If you are only calling callFoo() once, than most likely the function pointer will be slower by an insignificant amount. If you are calling it many times than most likely the function pointer will be faster by an insignificant amount (because it doesn't need to keep going through the switch).\nEither way look at the assembled code to find out for sure it is doing what you think it is doing.\n", "One often overlooked advantage to switch (even over sorting and indexing) is if you know that a particular value is used in the vast majority of cases.\nIt's easy to order the switch so that the most common are checked first.\nps. To reinforce greg's answer, if you care about speed - measure.\nLooking at assembler doesn't help when CPUs have prefetch / predictive branching and pipeline stalls etc\n" ]
[ 12, 9, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1 ]
[]
[]
[ "c++", "function_pointers" ]
stackoverflow_0000113150_c++_function_pointers.txt
Q: how to find rowsize in table One of my DBs have grown closer to permitted size. Inorder to find out the table containing the max data, i used the following query: exec sp_MSforeachtable @command1="print '?' exec sp_spaceused '?'" It returned the culprit table comprising the max data. As a next step, i want to cleanup the rows based on the size. For this, i would like to order the rows based on size. How to achieve this using a query? Are there any tools to do this? A: This will give you a list of rows by size, just set @table and @idcol accordingly (as written it'll run against the Northwind sample) declare @table varchar(20) declare @idcol varchar(10) declare @sql varchar(1000) set @table = 'Employees' set @idcol = 'EmployeeId' set @sql = 'select ' + @idcol +' , (0' select @sql = @sql + ' + isnull(datalength(' + name + '), 1)' from syscolumns where id = object_id(@table) set @sql = @sql + ') as rowsize from ' + @table + ' order by rowsize desc' exec (@sql) A: An easier approach for all table sizes is to use the stored procedure at this site. You could alter the select statement of that stored procedure to: SELECT * FROM #TempTable Order by dataSize desc to have it ordered by size. How do you want to cleanup? Cleanup the biggest row of a specific table? Not sure I understand the question. EDIT (response to comment) Assuming your eventlog has the same layout as mine (DNN eventlog): SELECT LEN(CONVERT(nvarchar(MAX), LogProperties)) AS length FROM EventLog ORDER BY length DESC A: You can also use this to get the size of the indexes and keys: (edit:sorry for wall of text, cant get the format to work) WITH table_space_usage ( schema_name, table_name, index_name, used, reserved, ind_rows, tbl_rows ) AS ( SELECT s.Name , o.Name , coalesce(i.Name, 'HEAP') , p.used_page_count * 8 , p.reserved_page_count * 8 , p.row_count , case when i.index_id in ( 0, 1 ) then p.row_count else 0 end FROM sys.dm_db_partition_stats p INNER JOIN sys.objects as o ON o.object_id = p.object_id INNER JOIN sys.schemas as s ON s.schema_id = o.schema_id LEFT OUTER JOIN sys.indexes as i on i.object_id = p.object_id and i.index_id = p.index_id WHERE o.type_desc = 'USER_TABLE' and o.is_ms_shipped = 0 ) SELECT t.schema_name , t.table_name , t.index_name , sum(t.used) as used_in_kb , sum(t.reserved) as reserved_in_kb , case grouping(t.index_name) when 0 then sum(t.ind_rows) else sum(t.tbl_rows) end as rows FROM table_space_usage as t GROUP BY t.schema_name , t.table_name , t.index_name WITH ROLLUP ORDER BY grouping(t.schema_name) , t.schema_name , grouping(t.table_name) , t.table_name , grouping(t.index_name) , t.index_name A: Maybe something like this will work delete table where id in ( select top 100 id from table order by datalength(event_text) + length(varchar_column) desc ) (since you are dealing with an event table its probably a text column you are looking at ordering on so the datalength sql command is key here)
how to find rowsize in table
One of my DBs have grown closer to permitted size. Inorder to find out the table containing the max data, i used the following query: exec sp_MSforeachtable @command1="print '?' exec sp_spaceused '?'" It returned the culprit table comprising the max data. As a next step, i want to cleanup the rows based on the size. For this, i would like to order the rows based on size. How to achieve this using a query? Are there any tools to do this?
[ "This will give you a list of rows by size, just set @table and @idcol accordingly (as written it'll run against the Northwind sample)\ndeclare @table varchar(20)\ndeclare @idcol varchar(10)\ndeclare @sql varchar(1000)\n\nset @table = 'Employees'\nset @idcol = 'EmployeeId'\nset @sql = 'select ' + @idcol +' , (0'\n\nselect @sql = @sql + ' + isnull(datalength(' + name + '), 1)' \n from syscolumns where id = object_id(@table)\nset @sql = @sql + ') as rowsize from ' + @table + ' order by rowsize desc'\n\nexec (@sql)\n\n", "An easier approach for all table sizes is to use the stored procedure at this site.\nYou could alter the select statement of that stored procedure to:\nSELECT * \nFROM #TempTable\nOrder by dataSize desc\n\nto have it ordered by size.\nHow do you want to cleanup? Cleanup the biggest row of a specific table? Not sure I understand the question.\nEDIT (response to comment)\nAssuming your eventlog has the same layout as mine (DNN eventlog): \nSELECT LEN(CONVERT(nvarchar(MAX), LogProperties)) AS length\nFROM EventLog\nORDER BY length DESC\n\n", "You can also use this to get the size of the indexes and keys: (edit:sorry for wall of text, cant get the format to work)\n\nWITH table_space_usage\n( schema_name, table_name, index_name, used, reserved, ind_rows, tbl_rows )\nAS (\nSELECT s.Name\n , o.Name\n , coalesce(i.Name, 'HEAP')\n , p.used_page_count * 8\n , p.reserved_page_count * 8\n , p.row_count\n , case when i.index_id in ( 0, 1 ) then p.row_count else 0 end\nFROM sys.dm_db_partition_stats p\n INNER JOIN sys.objects as o\n ON o.object_id = p.object_id\n INNER JOIN sys.schemas as s\n ON s.schema_id = o.schema_id\n LEFT OUTER JOIN sys.indexes as i\n on i.object_id = p.object_id and i.index_id = p.index_id\n WHERE o.type_desc = 'USER_TABLE'\n and o.is_ms_shipped = 0\n)\n SELECT t.schema_name\n , t.table_name\n , t.index_name\n , sum(t.used) as used_in_kb\n , sum(t.reserved) as reserved_in_kb\n , case grouping(t.index_name) \n when 0 then sum(t.ind_rows) \n else sum(t.tbl_rows) end as rows\n FROM table_space_usage as t\n GROUP BY\n t.schema_name\n , t.table_name\n , t.index_name\n WITH ROLLUP\n ORDER BY\n grouping(t.schema_name)\n , t.schema_name\n , grouping(t.table_name)\n , t.table_name\n , grouping(t.index_name)\n , t.index_name\n\n", "Maybe something like this will work \ndelete table where id in \n(\n select top 100 id\n from table\n order by datalength(event_text) + length(varchar_column) desc\n) \n\n(since you are dealing with an event table its probably a text column you are looking at ordering on so the datalength sql command is key here)\n" ]
[ 11, 1, 1, 0 ]
[]
[]
[ "sql_server", "tsql" ]
stackoverflow_0000114728_sql_server_tsql.txt
Q: How to determine the value of socket listen() backlog parameter? How should I determine what to use for a listening socket's backlog parameter? Is it a problem to simply specify a very large number? A: There's a very long answer to this in the Winsock Programmer's FAQ. It details the standard setting, and the dynamic backlog feature added in a hotfix to NT 4.0. A: I second using SOMAXCONN, unless you have a specific reason to use a short queue. Keep in mind that if there is no room in the queue for a new connection, no RST will be sent, allowing the client to automatically continue trying to connect by retransmitting SYN. Also, the backlog argument can have different meanings in different socket implementations. In most it means the size of the half-open connection queue, in some it means the size of the completed connection queue. In many implementations, the backlog argument will multiplied to yield a different queue length. If a value is specified that is too large, all implementations will silently truncate the value to maximum queue length anyways. A: From the docs: A value for the backlog of SOMAXCONN is a special constant that instructs the underlying service provider responsible for socket s to set the length of the queue of pending connections to a maximum reasonable value.
How to determine the value of socket listen() backlog parameter?
How should I determine what to use for a listening socket's backlog parameter? Is it a problem to simply specify a very large number?
[ "There's a very long answer to this in the Winsock Programmer's FAQ. It details the standard setting, and the dynamic backlog feature added in a hotfix to NT 4.0.\n", "I second using SOMAXCONN, unless you have a specific reason to use a short queue. \nKeep in mind that if there is no room in the queue for a new connection, no RST will be sent, allowing the client to automatically continue trying to connect by retransmitting SYN. \nAlso, the backlog argument can have different meanings in different socket implementations. \n\nIn most it means the size of the half-open connection queue, in some it means the size of the completed connection queue.\nIn many implementations, the backlog argument will multiplied to yield a different queue length.\nIf a value is specified that is too large, all implementations will silently truncate the value to maximum queue length anyways.\n\n", "From the docs:\n\nA value for the backlog of SOMAXCONN is a special constant that instructs the underlying service provider responsible for socket s to set the length of the queue of pending connections to a maximum reasonable value.\n\n" ]
[ 36, 4, 1 ]
[]
[]
[ "c", "c++", "listen", "sockets", "tcp" ]
stackoverflow_0000114874_c_c++_listen_sockets_tcp.txt
Q: How do I bind the result of DataTable.Select() to a ListBox control? I have the following code: ListBox.DataSource = DataSet.Tables("table_name").Select("some_criteria = match") ListBox.DisplayMember = "name" The DataTable.Select() method returns an array of System.Data.DataRow objects. No matter what I specify in the ListBox.DisplayMember property, all I see is the ListBox with the correct number of items all showing as System.Data.DataRow instead of the value I want which is in the "name" column! Is it possible to bind to the resulting array from DataTable.Select(), instead of looping through it and adding each one to the ListBox? (I've no problem with looping, but doesn't seem an elegant ending!) A: Use a DataView instead. ListBox.DataSource = new DataView(DataSet.Tables("table_name"), "some_criteria = match", "name", DataViewRowState.CurrentRows); ListBox.DisplayMember = "name" A: Josh has it right with the DataView. If you need a very large hammer, you can take the array of rows from any DataTable.Select("...") and do a merge into a different DataSet. DataSet copy = new DataSet(); copy.Merge(myDataTable.Select("Foo='Bar'")); // copy.Tables[0] has a clone That approach for what you're trying to do is most probably overkill but there are instances when you may need to get a datatable out of an array of rows where it's helpful.
How do I bind the result of DataTable.Select() to a ListBox control?
I have the following code: ListBox.DataSource = DataSet.Tables("table_name").Select("some_criteria = match") ListBox.DisplayMember = "name" The DataTable.Select() method returns an array of System.Data.DataRow objects. No matter what I specify in the ListBox.DisplayMember property, all I see is the ListBox with the correct number of items all showing as System.Data.DataRow instead of the value I want which is in the "name" column! Is it possible to bind to the resulting array from DataTable.Select(), instead of looping through it and adding each one to the ListBox? (I've no problem with looping, but doesn't seem an elegant ending!)
[ "Use a DataView instead.\nListBox.DataSource = new DataView(DataSet.Tables(\"table_name\"), \"some_criteria = match\", \"name\", DataViewRowState.CurrentRows);\nListBox.DisplayMember = \"name\"\n\n", "Josh has it right with the DataView. If you need a very large hammer, you can take the array of rows from any DataTable.Select(\"...\") and do a merge into a different DataSet.\n\n\n DataSet copy = new DataSet();\n copy.Merge(myDataTable.Select(\"Foo='Bar'\"));\n // copy.Tables[0] has a clone\n\n\nThat approach for what you're trying to do is most probably overkill but there are instances when you may need to get a datatable out of an array of rows where it's helpful.\n" ]
[ 33, 1 ]
[]
[]
[ ".net", "data_binding", "datarow", "datatable", "listbox" ]
stackoverflow_0000114851_.net_data_binding_datarow_datatable_listbox.txt
Q: MySQL: Advisable number of rows Consider an indexed MySQL table with 7 columns, being constantly queried and written to. What is the advisable number of rows that this table should be allowed to contain before the performance would be improved by splitting the data off into other tables? A: Whether or not you would get a performance gain by partitioning the data depends on the data and the queries you will run on it. You can store many millions of rows in a table and with good indexes and well-designed queries it will still be super-fast. Only consider partitioning if you are already confident that your indexes and queries are as good as they can be, as it can be more trouble than its worth. A: There's no magic number, but there's a few things that affect performance in particular: Index Cardinality: don't bother indexing a row that has 2 or 3 values (like an ENUM). On a large table, the query optimizer will ignore these. There's a trade off between writes and indexes. The more indexes you have, the longer writes take. Don't just index every column. Analyze your queries and see which columns need to be indexed for your app. Disk IO and a memory play an important role. If you can fit your whole table into memory, you take disk IO out of the equation (once the table is cached, anyway). My guess is that you'll see a big performance change when your table is too big to buffer in memory. Consider partitioning your servers based on use. If your transactional system is reading/writing single rows, you can probably buy yourself some time by replicating the data to a read only server for aggregate reporting. As you probably know, table performance changes based on the data size. Keep an eye on your table/queries. You'll know when it's time for a change. A: MySQL 5 has partitioning built in and is very nice. What's nice is you can define how your table should be split up. For instance, if you query mostly based on a userid you can partition your tables based on userid, or if you're querying by dates do it by date. What's nice about this is that MySQL will know exactly which partition table to search through to find your values. The downside is if you're search on a field that isn't defining your partition its going to scan through each table, which could possibly decrease performance. A: While after the fact you could point to the table size at which performance became a problem, I don't think you can predict it, and certainly not from the information given on a web site such as this! Some questions you might usefully ask yourself: Is performance currently acceptable? How is performance measured - is there a metric? How do we recognise unacceptable performance? Do we measure performance in any way that might allow us to forecast a problem? Are all our queries using an efficient index? Have we simulated extreme loads and volumes on the system? A: Using the MyISAM engine, you'll run into a 2GB hard limit on table size unless you change the default. A: Don't ever apply an optimisation if you don't think it's needed. Ideally this should be determined by testing (as others have alluded). Horizontal or vertical partitioning can improve performance but also complicate you application. Don't do it unless you're sure that you need it AND it will definitely help. The 2G data MyISAM file size is only a default and can be changed at table creation time (or later by an ALTER, but it needs to rebuild the table). It doesn't apply to other engines (e.g. InnoDB). A: Actually this is a good question for performance. Have you read Jay Pipes? There isn't a specific number of rows but there is a specific page size for reads and there can be good reasons for vertical partitioning. Check out his kung fu presentation and have a look through his posts. I'm sure you'll find that he's written some useful advice on this. A: Are you using MyISAM? Are you planning to store more than a couple of gigabytes? Watch out for MAX_ROWS and AVG_ROW_LENGTH. Jeremy Zawodny has an excellent write-up on how to solve this problem.
MySQL: Advisable number of rows
Consider an indexed MySQL table with 7 columns, being constantly queried and written to. What is the advisable number of rows that this table should be allowed to contain before the performance would be improved by splitting the data off into other tables?
[ "Whether or not you would get a performance gain by partitioning the data depends on the data and the queries you will run on it. You can store many millions of rows in a table and with good indexes and well-designed queries it will still be super-fast. Only consider partitioning if you are already confident that your indexes and queries are as good as they can be, as it can be more trouble than its worth.\n", "There's no magic number, but there's a few things that affect performance in particular:\n\nIndex Cardinality: don't bother indexing a row that has 2 or 3 values (like an ENUM). On a large table, the query optimizer will ignore these.\nThere's a trade off between writes and indexes. The more indexes you have, the longer writes take. Don't just index every column. Analyze your queries and see which columns need to be indexed for your app.\nDisk IO and a memory play an important role. If you can fit your whole table into memory, you take disk IO out of the equation (once the table is cached, anyway). My guess is that you'll see a big performance change when your table is too big to buffer in memory.\nConsider partitioning your servers based on use. If your transactional system is reading/writing single rows, you can probably buy yourself some time by replicating the data to a read only server for aggregate reporting.\n\nAs you probably know, table performance changes based on the data size. Keep an eye on your table/queries. You'll know when it's time for a change.\n", "MySQL 5 has partitioning built in and is very nice. What's nice is you can define how your table should be split up. For instance, if you query mostly based on a userid you can partition your tables based on userid, or if you're querying by dates do it by date. What's nice about this is that MySQL will know exactly which partition table to search through to find your values. The downside is if you're search on a field that isn't defining your partition its going to scan through each table, which could possibly decrease performance.\n", "While after the fact you could point to the table size at which performance became a problem, I don't think you can predict it, and certainly not from the information given on a web site such as this!\nSome questions you might usefully ask yourself:\n\nIs performance currently acceptable?\nHow is performance measured - is\nthere a metric? \nHow do we recognise\nunacceptable performance?\nDo we\nmeasure performance in any way that\nmight allow us to forecast a\nproblem?\nAre all our queries using\nan efficient index?\nHave we simulated extreme loads and volumes on the system?\n\n", "Using the MyISAM engine, you'll run into a 2GB hard limit on table size unless you change the default.\n", "Don't ever apply an optimisation if you don't think it's needed. Ideally this should be determined by testing (as others have alluded).\nHorizontal or vertical partitioning can improve performance but also complicate you application. Don't do it unless you're sure that you need it AND it will definitely help.\nThe 2G data MyISAM file size is only a default and can be changed at table creation time (or later by an ALTER, but it needs to rebuild the table). It doesn't apply to other engines (e.g. InnoDB).\n", "Actually this is a good question for performance. Have you read Jay Pipes? There isn't a specific number of rows but there is a specific page size for reads and there can be good reasons for vertical partitioning. \nCheck out his kung fu presentation and have a look through his posts. I'm sure you'll find that he's written some useful advice on this.\n", "Are you using MyISAM? Are you planning to store more than a couple of gigabytes? Watch out for MAX_ROWS and AVG_ROW_LENGTH.\nJeremy Zawodny has an excellent write-up on how to solve this problem.\n" ]
[ 11, 3, 2, 0, 0, 0, 0, 0 ]
[]
[]
[ "database_design", "mysql", "optimization", "performance" ]
stackoverflow_0000108503_database_design_mysql_optimization_performance.txt
Q: Why is ENUM better than INT I just ran a "PROCEDURE ANALYSE ( )" on one of my tables. And I have this column that is of type INT and it only ever contains values from 0 to 12 (category IDs). And MySQL said that I would be better of with a ENUM('0','1','2',...,'12'). This category's are basically static and won't change in the future, but if they do I can just alter that column and add it to the ENUM list... So why is ENUM better in this case? edit: I'm mostly interested in the performance aspect of this... A: Put simply, it's because it's indexed in a different way. In this case, ENUM says "It's one of these 13 values" whereas INT is saying "It could be any integer." This means that indexing is easier, as it doesn't have to take into account indexing for those integers you don't use "just in case" you ever use them. It's all to do with the algorithms. I'd be interested myself though when it gets to a point where the INT would be quicker than the ENUM. Using numbers in an ENUM might be a little dangerous though... as if you send this number unquoted to SQL - you might end up getting the wrong value back! A: Yikes! There's a bunch of ambiguities with using numbers in an ENUM field. Be careful. The one gotcha I remember is that you can access values in ENUMS by index: if your enum is ENUM('A', 'B', 'C', '1', '2, '3'), then these two queries are very different: INSERT INTO TABLE (example_col) VALUES( '1' ); -- example_col == 1 INSERT INTO TABLE (example_col) VALUES( 1 ); -- example_col == A I'm assuming the recommendation is because it limits the valid values that can get into the table. For instance, inserting 13 should get the default choice. A better choice would by to use TINYINT instead of INT. an UNSIGNED TINYINT has a range of 0 to 255 and only takes 1 byte to store. An INT takes 4 bytes to store. If you want to constrain the values getting into the table, you can add ON INSERT and ON UPDATE triggers that check the values. If you're worried about the performance difference between ENUM and TINYINT, you can always benchmark to see the different. This article seems somewhat relevant. A: Because it introduces a constraint on the possible values. A: I'm not a MySQL expert, but my guess is that integers always take up four bytes of space where enums take up varying amounts of space based upon the range of data needed. Since you only need 13 items, it could get away with using 1 byte for your column. A: On Oracle I would have a BITMAP index which is much faster than a hash-based lookup for such a small number of values. (So I presume a similar benefit in query optomisation or indexing is available for MySQL.) Interestingly The MySQL docs suggest that using 'things that look like numbers' are a bad choice for the ENUM type because of potential confusion between the enum value and the enum index (http://dev.mysql.com/doc/refman/5.0/en/enum.html).
Why is ENUM better than INT
I just ran a "PROCEDURE ANALYSE ( )" on one of my tables. And I have this column that is of type INT and it only ever contains values from 0 to 12 (category IDs). And MySQL said that I would be better of with a ENUM('0','1','2',...,'12'). This category's are basically static and won't change in the future, but if they do I can just alter that column and add it to the ENUM list... So why is ENUM better in this case? edit: I'm mostly interested in the performance aspect of this...
[ "Put simply, it's because it's indexed in a different way.\nIn this case, ENUM says \"It's one of these 13 values\" whereas INT is saying \"It could be any integer.\"\nThis means that indexing is easier, as it doesn't have to take into account indexing for those integers you don't use \"just in case\" you ever use them.\nIt's all to do with the algorithms.\nI'd be interested myself though when it gets to a point where the INT would be quicker than the ENUM.\nUsing numbers in an ENUM might be a little dangerous though... as if you send this number unquoted to SQL - you might end up getting the wrong value back!\n", "Yikes! There's a bunch of ambiguities with using numbers in an ENUM field. Be careful. The one gotcha I remember is that you can access values in ENUMS by index: if your enum is ENUM('A', 'B', 'C', '1', '2, '3'), then these two queries are very different:\nINSERT INTO TABLE (example_col) VALUES( '1' ); -- example_col == 1\nINSERT INTO TABLE (example_col) VALUES( 1 ); -- example_col == A\n\nI'm assuming the recommendation is because it limits the valid values that can get into the table. For instance, inserting 13 should get the default choice.\nA better choice would by to use TINYINT instead of INT. an UNSIGNED TINYINT has a range of 0 to 255 and only takes 1 byte to store. An INT takes 4 bytes to store. If you want to constrain the values getting into the table, you can add ON INSERT and ON UPDATE triggers that check the values.\nIf you're worried about the performance difference between ENUM and TINYINT, you can always benchmark to see the different. This article seems somewhat relevant.\n", "Because it introduces a constraint on the possible values.\n", "I'm not a MySQL expert, but my guess is that integers always take up four bytes of space where enums take up varying amounts of space based upon the range of data needed. Since you only need 13 items, it could get away with using 1 byte for your column.\n", "On Oracle I would have a BITMAP index which is much faster than a hash-based lookup for such a small number of values. (So I presume a similar benefit in query optomisation or indexing is available for MySQL.) \nInterestingly The MySQL docs suggest that using 'things that look like numbers' are a bad choice for the ENUM type because of potential confusion between the enum value and the enum index (http://dev.mysql.com/doc/refman/5.0/en/enum.html). \n" ]
[ 29, 20, 4, 2, 1 ]
[]
[]
[ "mysql" ]
stackoverflow_0000113609_mysql.txt
Q: How do "spikes" figure in the schedule / estimation game? Might be subjective and/or discussion.. but here goes. I've been asked to estimate a feature for the next big thing at work. I break it down.. use story points come up with a estimate. The feature however calls for interfacing with GoDiagrams a third party diagramming component in addition to various other company initiatives.. (a whole set of 2008_Limited_Edition frameworks/services:). I've been tracking myself using a burn-up chart and I find that I'm unable to sustain my pace primarily due to "spikes".. Definition I estimate for 2 points a week and then I find myself working weekends (well trying to.. end up neither here nor there) because I can't figure out where to hook in so that I can preview user-actions, show a context menu, etc. In the end I spend time making spikes that throw my schedule off-track... and decreases its value.. doesn't give the right picture. Spikes are needed to drive nails through the planks of ignorance. But how are they factored into the estimation equation? Doing all required spikes before the feature seems wrong.. (might turn out to be YAGNI) Doing it in between disrupts my flow. Right now it's during pre-iteration planning.. but this is pushing the touchline out on a weekly basis. A: I guess you are constantly underestimating what you do already know about the 3rd party component how long it takes you to create usable/helpful spikes for unknown areas 1. Get better at estimating those two things. So, it's all about experience. No matter what methodology you use, they will help you to use your experience better, not replace it. 2. Try not to get lose track when working on those spikes. They should be short, time boxed sessions. They are not about playing around with all the possible features listed on the marketing slides. Give them focus, two or three options to explore. Expect them to deliver one concrete result. Update(Gishu): To summarize Spikes need to be explicit tasks defined in the iteration planning step. If spikes exceed the timebox period, stop working on it. Shelve the associated task. Complete the other tasks in the current iteration bucket. Return to the shelved task or add a more elaborate/broken down spike to the next iteration along with the associated task. Tag a more conservative estimate to the generation 1 spike the next time. A: If you run out of time in your timeboxed spike, you should still stop and complete your other committed work. You should then add another spike to your next iteration to complete the necessary work you need to complete in order to accurately estimate the task resulting from the spike. If there is a concern over spiking things for too long and this becoming a problem - this is one reason I like 1 week iterations. :-) A: @pointernil.. It's more of no estimation coupled with a Indy-Jones Head-First approach to tackling a story. I estimate stories by their content.. currently I don't take into account the time required to find the right incantation for the control library to play nice. That sometimes takes more time than my application logic.. So to rephrase the Original question, should spikes be separate tasks in the iteration plan, added on a JIT basis before you start working on a particular story? My Spikes are extremely focussed.. I just can't wait to get back to the "real" problems. e.g. 'How do I show a context menu from this control?' I may be guilty of not reading the entire 150+ page manual or code samples.. but then time is scarce. The first solution that solves the problem gets the nod and I move on. But when you're unable to find that elusive event or NIH pattern of notification used by the component, spikes can be time-consuming. How do I timebox something that is unknown? e.g. My timebox has elapsed and I still have no clue for plugging-in my custom context menu. How do I proceed? Keep hacking away? Maybe this comes in the "Buffering Uncertainity" scheme of things.. I'll look if I find something useful in Mike Cohn's book. A: I agree with pointernil. The only issue is that your estimates are incorrect. Which is no big drama, unless you've just blown out a 3 million dollar project of course :-) If it happens once, its a learning experience. If it happens again and the result is better, then you've got another learning experience under your belt. If you are constantly underestimating and your percentages are getting worse, you need to wisen up a bit. No methodology will get you out of this. Spikes just need to be given the time that they need. The one thing I've seen happen repeatedly in my experience is that people expect to be able to nail a technology within a couple of hours, or a day. That just doesn't happen in real life. The simplest issue, even a bug caused by a typo, can have a developer pulling their hair our for huge chunks of time. Be honest about how competent yourself or your staff really are, and put it in the budget.
How do "spikes" figure in the schedule / estimation game?
Might be subjective and/or discussion.. but here goes. I've been asked to estimate a feature for the next big thing at work. I break it down.. use story points come up with a estimate. The feature however calls for interfacing with GoDiagrams a third party diagramming component in addition to various other company initiatives.. (a whole set of 2008_Limited_Edition frameworks/services:). I've been tracking myself using a burn-up chart and I find that I'm unable to sustain my pace primarily due to "spikes".. Definition I estimate for 2 points a week and then I find myself working weekends (well trying to.. end up neither here nor there) because I can't figure out where to hook in so that I can preview user-actions, show a context menu, etc. In the end I spend time making spikes that throw my schedule off-track... and decreases its value.. doesn't give the right picture. Spikes are needed to drive nails through the planks of ignorance. But how are they factored into the estimation equation? Doing all required spikes before the feature seems wrong.. (might turn out to be YAGNI) Doing it in between disrupts my flow. Right now it's during pre-iteration planning.. but this is pushing the touchline out on a weekly basis.
[ "I guess you are constantly underestimating \n\nwhat you do already know about the 3rd party component \nhow long it takes you to create usable/helpful spikes for unknown areas\n\n1. Get better at estimating those two things.\nSo, it's all about experience. No matter what methodology you use, they will help you to use your experience better, not replace it.\n2. Try not to get lose track when working on those spikes.\nThey should be short, time boxed sessions. They are not about playing around with all the possible features listed on the marketing slides.\nGive them focus, two or three options to explore. Expect them to deliver one concrete result.\nUpdate(Gishu): To summarize\n\nSpikes need to be explicit tasks defined in the iteration planning step.\nIf spikes exceed the timebox period, stop working on it. Shelve the associated task. Complete the other tasks in the current iteration bucket. Return to the shelved task or add a more elaborate/broken down spike to the next iteration along with the associated task. Tag a more conservative estimate to the generation 1 spike the next time.\n\n", "If you run out of time in your timeboxed spike, you should still stop and complete your other committed work. You should then add another spike to your next iteration to complete the necessary work you need to complete in order to accurately estimate the task resulting from the spike.\nIf there is a concern over spiking things for too long and this becoming a problem - this is one reason I like 1 week iterations. :-)\n", "@pointernil..\nIt's more of no estimation coupled with a Indy-Jones Head-First approach to tackling a story. I estimate stories by their content.. currently I don't take into account the time required to find the right incantation for the control library to play nice. That sometimes takes more time than my application logic.. So to rephrase the Original question, should spikes be separate tasks in the iteration plan, added on a JIT basis before you start working on a particular story?\nMy Spikes are extremely focussed.. I just can't wait to get back to the \"real\" problems. e.g. 'How do I show a context menu from this control?' I may be guilty of not reading the entire 150+ page manual or code samples.. but then time is scarce. The first solution that solves the problem gets the nod and I move on. But when you're unable to find that elusive event or NIH pattern of notification used by the component, spikes can be time-consuming. How do I timebox something that is unknown? e.g. My timebox has elapsed and I still have no clue for plugging-in my custom context menu. How do I proceed? Keep hacking away?\nMaybe this comes in the \"Buffering Uncertainity\" scheme of things.. I'll look if I find something useful in Mike Cohn's book. \n", "I agree with pointernil. The only issue is that your estimates are incorrect. Which is no big drama, unless you've just blown out a 3 million dollar project of course :-)\nIf it happens once, its a learning experience. If it happens again and the result is better, then you've got another learning experience under your belt. If you are constantly underestimating and your percentages are getting worse, you need to wisen up a bit. No methodology will get you out of this.\nSpikes just need to be given the time that they need. The one thing I've seen happen repeatedly in my experience is that people expect to be able to nail a technology within a couple of hours, or a day. That just doesn't happen in real life. The simplest issue, even a bug caused by a typo, can have a developer pulling their hair our for huge chunks of time. Be honest about how competent yourself or your staff really are, and put it in the budget.\n" ]
[ 6, 2, 1, 1 ]
[]
[]
[ "agile", "estimation", "project_management" ]
stackoverflow_0000111665_agile_estimation_project_management.txt
Q: CVS: Replace HEAD with a branch How do I replace the HEAD of a CVS repository with a branch? A: Check out this page, which has a pretty easy to follow walk through of branching and merging in CVS http://kb.wisc.edu/middleware/page.php?id=4087 It also includes an example of replacing HEAD with a specified branch Replacing One Branch With Another Tag the end of your branch cvs tag merge_NEW_BRANCH Switch back to the branch you're replacing To head: cvs up -A To branch: cvs up -r OLD_BRANCH Do the replace: Replace head cvs up -jHEAD -j NEW_BRANCH Replace branch cvs up -jOLD_BRANCH -j NEW_BRANCH Commit changes and tag if you need to.
CVS: Replace HEAD with a branch
How do I replace the HEAD of a CVS repository with a branch?
[ "Check out this page, which has a pretty easy to follow walk through of branching and merging in CVS\nhttp://kb.wisc.edu/middleware/page.php?id=4087\nIt also includes an example of replacing HEAD with a specified branch\nReplacing One Branch With Another\nTag the end of your branch\ncvs tag merge_NEW_BRANCH\n\nSwitch back to the branch you're replacing\nTo head:\ncvs up -A\n\nTo branch:\ncvs up -r OLD_BRANCH\n\nDo the replace:\nReplace head\ncvs up -jHEAD -j NEW_BRANCH\n\nReplace branch\ncvs up -jOLD_BRANCH -j NEW_BRANCH\n\nCommit changes and tag if you need to.\n" ]
[ 23 ]
[]
[]
[ "branch", "cvs" ]
stackoverflow_0000115098_branch_cvs.txt
Q: An Issue with converting enumerations in C++\CLI I have an assembly, written in C++\CLI, which uses some of enumerations, provided by .Net. It has such kind of properties: property System::ServiceProcess::ServiceControllerStatus ^ Status { ServiceControllerStatus ^ get() { return (ServiceControllerStatus)_status->dwCurrentState; } } it works fine, but when i use this assembly from my C# code, type of this property is System.Enum and i have to make type-cast if ((ServiceControllerStatus)currentService.Status == ServiceControllerStatus.Running) //do smth The question is simple: why is it so, and how to fix it ? A: In C++/CLI ^ is like the analagous * in standard C++. Because enumerations are value types the ^ should not be included otherwise you will see them as System.Enum. Remove the ^ and you will see the correct enumeration on C# side. property System::ServiceProcess::ServiceControllerStatus Status { System::ServiceProcess::ServiceControllerStatus get() { return (System::ServiceProcess::ServiceControllerStatus)_status->dwCurrentState; } } A: I think enums don't use the ^ -- try removing it from the property declaration and get().
An Issue with converting enumerations in C++\CLI
I have an assembly, written in C++\CLI, which uses some of enumerations, provided by .Net. It has such kind of properties: property System::ServiceProcess::ServiceControllerStatus ^ Status { ServiceControllerStatus ^ get() { return (ServiceControllerStatus)_status->dwCurrentState; } } it works fine, but when i use this assembly from my C# code, type of this property is System.Enum and i have to make type-cast if ((ServiceControllerStatus)currentService.Status == ServiceControllerStatus.Running) //do smth The question is simple: why is it so, and how to fix it ?
[ "In C++/CLI ^ is like the analagous * in standard C++. Because enumerations are value types the ^ should not be included otherwise you will see them as System.Enum.\nRemove the ^ and you will see the correct enumeration on C# side.\nproperty System::ServiceProcess::ServiceControllerStatus Status \n{ \n System::ServiceProcess::ServiceControllerStatus get() \n { \n return (System::ServiceProcess::ServiceControllerStatus)_status->dwCurrentState; \n } \n}\n\n", "I think enums don't use the ^ -- try removing it from the property declaration and get().\n" ]
[ 5, 3 ]
[]
[]
[ "c#", "c++_cli", "enumeration", "enums" ]
stackoverflow_0000115031_c#_c++_cli_enumeration_enums.txt
Q: Retrieve Web Browser Stored Form Data? I have my web browsers set to save what I type into text boxes on forms. I have a lot of search terms stored in the text box of my browser and would like to get at it via a program of some sort before I clear these values out. There are far too many for me to go through one at a time. The web browser must store this data somewhere, does anyone know where? Is it possible to retrieve these values? Firefox, more so than IE -- but either, if anyone knows a script that can extract these values? Thanks. A: Firefox 3 In Firefox on Windows it's stored in a SQLite file, in: C:\Documents and Settings\<Username>\Application Data \Mozilla\Firefox\Profiles\<UID>.default\formhistory.sqlite Once you have the SQLite file, you can put together a script to read the data from it pretty quickly - here's a good primer to using SQLite with PHP 5 for example. Firefox pre-version 3 Apparently SQLite has only been used for the saved form history since version 3. Version 2 still uses formhistory.dat, which is written using Mork. From the wiki on Mork: Also, despite being plain text, Mork is generally regarded as unintelligible to humans and as a hard format to write parsers for. There has been an item files on Bugzilla asking for a more sane and readable format to be introduced, the filer even attempted to write a perl parser for his .dat files, with limited success. A: It seems that you can find the form history in the form of a sqlite database under USER_DIR/Mozilla/Firefox/Profiles//formhistory.sqlite I didn't try to browse it with Sqlite but the filename seems to be explicit. You can find several wrappers on the sqlite website to access it from the language of your choice. Good Luck
Retrieve Web Browser Stored Form Data?
I have my web browsers set to save what I type into text boxes on forms. I have a lot of search terms stored in the text box of my browser and would like to get at it via a program of some sort before I clear these values out. There are far too many for me to go through one at a time. The web browser must store this data somewhere, does anyone know where? Is it possible to retrieve these values? Firefox, more so than IE -- but either, if anyone knows a script that can extract these values? Thanks.
[ "Firefox 3 \nIn Firefox on Windows it's stored in a SQLite file, in:\nC:\\Documents and Settings\\<Username>\\Application Data\n \\Mozilla\\Firefox\\Profiles\\<UID>.default\\formhistory.sqlite\n\nOnce you have the SQLite file, you can put together a script to read the data from it pretty quickly - here's a good primer to using SQLite with PHP 5 for example.\nFirefox pre-version 3 \nApparently SQLite has only been used for the saved form history since version 3. Version 2 still uses formhistory.dat, which is written using Mork. \nFrom the wiki on Mork:\n\nAlso, despite being plain text, Mork is generally regarded as unintelligible to humans and as a hard format to write parsers for.\n\nThere has been an item files on Bugzilla asking for a more sane and readable format to be introduced, the filer even attempted to write a perl parser for his .dat files, with limited success.\n", "It seems that you can find the form history in the form of a sqlite database under USER_DIR/Mozilla/Firefox/Profiles//formhistory.sqlite\nI didn't try to browse it with Sqlite but the filename seems to be explicit.\nYou can find several wrappers on the sqlite website to access it from the language of your choice.\nGood Luck\n" ]
[ 1, 1 ]
[]
[]
[ "browser", "cross_browser", "firefox", "internet_explorer" ]
stackoverflow_0000115095_browser_cross_browser_firefox_internet_explorer.txt
Q: The doesn't display properly when using inside In a JSP page, I created a <h:form enctype="multipart/form-data"> with some elements: <t:inputText>, <t:inputDate>, etc. Also, I added some <t:message for="someElement"> And I wanted to allow the user upload several files (one at a time) within the form (using <t:inputFileUpload> ) At this point my code works fine. The headache comes when I try to put the form inside a <t:panelTabbedPane serverSideTabSwitch="false"> (and thus of course, inside a <t:panelTab> ) I copied the structure shown in the source code for TabbedPane example from Tomahawk's examples, by using the <f:subview> tag and putting the panelTab tag inside a new jsp page (using <jsp:include page="somePage.jsp"> directive) First at all, the <t:inputFileUpload> fails to load the file at the value assigned in the Managed Bean UploadedFile attribute #{myBean.upFile} Then, googling for a clue, I knew that <t:panelTabbedPane> generates a form called "autoform", so I was getting nested forms. Ok, I fixed that creating the <h:form> out of the <t:panelTabbedPane> and eureka! file input worked again! (the autoform doesn't generate) But, oh surprise! oh terrible Murphy law! All my <h:message> begins to fail. The Eclipse console's output show me that all <t:message> are looking for nonexistents elements ID's (who have their ID's in part equals to they are looking for, but at the end of the ID's their names change) At this point, I put a <t:mesagges> tag (note the "s" at the end) to show me all validation errors at once at the beginning of the Panel, and it works fine. So, validation errors exists and they show properly at the beginning of the Panel. All validation error messages generated in this page are the JSF built-in validation messages. The backing bean at this moment doesn't have any validators defined. ¿How can I get the <t:message for="xyz"> working properly? I'm using Tomahawk-1.1.6 with myFaces-impl-1.2.3 in a eclipse Ganymede project with Geronimo as Application Server (Geronimo gives me the myFaces jar implementation while I put the tomahawk jar in the WEB-INF/lib folder of application) "SOLVED": This problem is an issue reported to myFaces forum. Thanks to Kyle Renfro for the soon response and information. (Good job Kyle!) See the issue EDIT 1 1.- Thanks to Kyle Renfro for his soon response. The forceID attribute used inside the input element doesn't works at first time, but doing some very tricky tweaks I could make the <t:message for="xyz"> tags work. What I did was: 1. Having my tag <inputText id="name" forceId="true" required="true"> The <t:message> doesn't work. 2. Then, after looking the error messages on eclipse console, I renamed my "id" attribute to this: <inputText id="namej_id_1" forceId="true" required="true"> 3. Then the <t:message> worked!! but after pressing the "Submit" button of the form the second time. ¡The second time! (I suspect that something is going on at the JSF lifecycle) 4. This implies that the user have to press 2 times the submit button to get the error messages on the page. 5. And using the "j_id_1" phrase at the end of IDs is very weird. EDIT 2 Ok, here comes the code, hope it not be annoying. 1.- mainPage.jsp (here is the <t:panelTabbedPane> and <f:subview> tags) <%@ taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <%@ taglib prefix="t" uri="http://myfaces.apache.org/tomahawk"%> <html> <body> <f:view> <h:form enctype="multipart/form-data"> <t:panelTabbedPane serverSideTabSwitch="false" > <f:subview id="subview_tab_detail"> <jsp:include page="detail.jsp"/> </f:subview> </t:panelTabbedPane> </h:form> </f:view> </body> </html> 2.- detail.jsp (here is the <t:panelTab> tag) <%@ taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <%@ taglib prefix="t" uri="http://myfaces.apache.org/tomahawk"%> <t:panelTab label="TAB_1"> <t:panelGrid columns="3"> <f:facet name="header"> <h:outputText value="CREATING A TICKET" /> </f:facet> <t:outputLabel for="ticket_id" value="TICKET ID" /> <t:inputText id="ticket_id" value="#{myBean.ticketId}" required="true" /> <t:message for="ticket_id" /> <t:outputLabel for="description" value="DESCRIPTION" /> <t:inputText id="description" value="#{myBean.ticketDescription}" required="true" /> <t:message for="description" /> <t:outputLabel for="attachment" value="ATTACHMENTS" /> <t:panelGroup> <!-- This is for listing multiple file uploads --> <!-- The panelGrid binding make attachment list grow as the user inputs several files (one at a time) --> <t:panelGrid columns="3" binding="#{myBean.panelUpload}" /> <t:inputFileUpload id="attachment" value="#{myBean.upFile}" storage="file" /> <t:commandButton value="ADD FILE" action="#{myBean.upload}" /> </t:panelGroup> <t:message for="attachment" /> <t:commandButton action="#{myBean.create}" value="CREATE TICKET" /> </t:panelGrid> </t:panelTab> EDIT 3 On response to Kyle Renfro follow-up: Kyle says: "At the first view of the page, if you press the "CREATE TICKET" button with nothing in any of the inputTexts and no files uploaded, do the message tags work for the inputTexts? (ie. required = true) I'm just curious if the messages for the inputTexts are working but the message for the inputFileUpload is not." Here is the behavior found: 1.- There is no validation error messages shown at all (the message tags don't work) Even when I try to test only one validation error message (for example, testing the message for the first input text) none of them shows up. 2.- The eclipse console shows me these internal errors: ERROR [HtmlMessageRendererBase] Could not render Message. Unable to find component 'ticket_id' (calling findComponent on component 'j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:j_id_jsp_1716158401_5j_id_1'). If the provided id was correct, wrap the message and its component into an h:panelGroup or h:panelGrid. ERROR [HtmlMessageRendererBase] Could not render Message. Unable to find component 'description' (calling findComponent on component 'j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:j_id_jsp_1716158401_8j_id_1'). If the provided id was correct, wrap the message and its component into an h:panelGroup or h:panelGrid. ERROR [HtmlMessageRendererBase] Could not render Message. Unable to find component 'attachment' (calling findComponent on component 'j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:j_id_jsp_1716158401_14j_id_1'). If the provided id was correct, wrap the message and its component into an h:panelGroup or h:panelGrid. Here is when I saw the "j_id_1" word at the generated IDs, for example, for the id "ticket_id": j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:j_id_jsp_1716158401_5j_id_1 And, viewing the resulting HTML generated page, I saw that the IDs names are like this (whitout using "ForceId" atribute): <input id="j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:ticket_idj_id_1" name="j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:ticket_idj_id_1"> A: The forceId attribute of the tomahawk components should solve this problem. something like: &lt;t:outputText id="xyz" forceId="true" value="#{mybean.stuff}"/&gt; At the first view of the page, if you press the "CREATE TICKET" button with nothing in any of the inputTexts and no files uploaded, do the message tags work for the inputTexts? (ie. required = true) I'm just curious if the messages for the inputTexts are working but the message for the inputFileUpload is not. A: Looks like it may be related a bug in myfaces. There is a newer version of myfaces and tomahawk that you might try. I would remove the subview functionality as a quick test - copy the detail.jsp page back into the main page. https://issues.apache.org/jira/browse/MYFACES-1807?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=12567158#action_12567158
The doesn't display properly when using inside
In a JSP page, I created a <h:form enctype="multipart/form-data"> with some elements: <t:inputText>, <t:inputDate>, etc. Also, I added some <t:message for="someElement"> And I wanted to allow the user upload several files (one at a time) within the form (using <t:inputFileUpload> ) At this point my code works fine. The headache comes when I try to put the form inside a <t:panelTabbedPane serverSideTabSwitch="false"> (and thus of course, inside a <t:panelTab> ) I copied the structure shown in the source code for TabbedPane example from Tomahawk's examples, by using the <f:subview> tag and putting the panelTab tag inside a new jsp page (using <jsp:include page="somePage.jsp"> directive) First at all, the <t:inputFileUpload> fails to load the file at the value assigned in the Managed Bean UploadedFile attribute #{myBean.upFile} Then, googling for a clue, I knew that <t:panelTabbedPane> generates a form called "autoform", so I was getting nested forms. Ok, I fixed that creating the <h:form> out of the <t:panelTabbedPane> and eureka! file input worked again! (the autoform doesn't generate) But, oh surprise! oh terrible Murphy law! All my <h:message> begins to fail. The Eclipse console's output show me that all <t:message> are looking for nonexistents elements ID's (who have their ID's in part equals to they are looking for, but at the end of the ID's their names change) At this point, I put a <t:mesagges> tag (note the "s" at the end) to show me all validation errors at once at the beginning of the Panel, and it works fine. So, validation errors exists and they show properly at the beginning of the Panel. All validation error messages generated in this page are the JSF built-in validation messages. The backing bean at this moment doesn't have any validators defined. ¿How can I get the <t:message for="xyz"> working properly? I'm using Tomahawk-1.1.6 with myFaces-impl-1.2.3 in a eclipse Ganymede project with Geronimo as Application Server (Geronimo gives me the myFaces jar implementation while I put the tomahawk jar in the WEB-INF/lib folder of application) "SOLVED": This problem is an issue reported to myFaces forum. Thanks to Kyle Renfro for the soon response and information. (Good job Kyle!) See the issue EDIT 1 1.- Thanks to Kyle Renfro for his soon response. The forceID attribute used inside the input element doesn't works at first time, but doing some very tricky tweaks I could make the <t:message for="xyz"> tags work. What I did was: 1. Having my tag <inputText id="name" forceId="true" required="true"> The <t:message> doesn't work. 2. Then, after looking the error messages on eclipse console, I renamed my "id" attribute to this: <inputText id="namej_id_1" forceId="true" required="true"> 3. Then the <t:message> worked!! but after pressing the "Submit" button of the form the second time. ¡The second time! (I suspect that something is going on at the JSF lifecycle) 4. This implies that the user have to press 2 times the submit button to get the error messages on the page. 5. And using the "j_id_1" phrase at the end of IDs is very weird. EDIT 2 Ok, here comes the code, hope it not be annoying. 1.- mainPage.jsp (here is the <t:panelTabbedPane> and <f:subview> tags) <%@ taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <%@ taglib prefix="t" uri="http://myfaces.apache.org/tomahawk"%> <html> <body> <f:view> <h:form enctype="multipart/form-data"> <t:panelTabbedPane serverSideTabSwitch="false" > <f:subview id="subview_tab_detail"> <jsp:include page="detail.jsp"/> </f:subview> </t:panelTabbedPane> </h:form> </f:view> </body> </html> 2.- detail.jsp (here is the <t:panelTab> tag) <%@ taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <%@ taglib prefix="t" uri="http://myfaces.apache.org/tomahawk"%> <t:panelTab label="TAB_1"> <t:panelGrid columns="3"> <f:facet name="header"> <h:outputText value="CREATING A TICKET" /> </f:facet> <t:outputLabel for="ticket_id" value="TICKET ID" /> <t:inputText id="ticket_id" value="#{myBean.ticketId}" required="true" /> <t:message for="ticket_id" /> <t:outputLabel for="description" value="DESCRIPTION" /> <t:inputText id="description" value="#{myBean.ticketDescription}" required="true" /> <t:message for="description" /> <t:outputLabel for="attachment" value="ATTACHMENTS" /> <t:panelGroup> <!-- This is for listing multiple file uploads --> <!-- The panelGrid binding make attachment list grow as the user inputs several files (one at a time) --> <t:panelGrid columns="3" binding="#{myBean.panelUpload}" /> <t:inputFileUpload id="attachment" value="#{myBean.upFile}" storage="file" /> <t:commandButton value="ADD FILE" action="#{myBean.upload}" /> </t:panelGroup> <t:message for="attachment" /> <t:commandButton action="#{myBean.create}" value="CREATE TICKET" /> </t:panelGrid> </t:panelTab> EDIT 3 On response to Kyle Renfro follow-up: Kyle says: "At the first view of the page, if you press the "CREATE TICKET" button with nothing in any of the inputTexts and no files uploaded, do the message tags work for the inputTexts? (ie. required = true) I'm just curious if the messages for the inputTexts are working but the message for the inputFileUpload is not." Here is the behavior found: 1.- There is no validation error messages shown at all (the message tags don't work) Even when I try to test only one validation error message (for example, testing the message for the first input text) none of them shows up. 2.- The eclipse console shows me these internal errors: ERROR [HtmlMessageRendererBase] Could not render Message. Unable to find component 'ticket_id' (calling findComponent on component 'j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:j_id_jsp_1716158401_5j_id_1'). If the provided id was correct, wrap the message and its component into an h:panelGroup or h:panelGrid. ERROR [HtmlMessageRendererBase] Could not render Message. Unable to find component 'description' (calling findComponent on component 'j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:j_id_jsp_1716158401_8j_id_1'). If the provided id was correct, wrap the message and its component into an h:panelGroup or h:panelGrid. ERROR [HtmlMessageRendererBase] Could not render Message. Unable to find component 'attachment' (calling findComponent on component 'j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:j_id_jsp_1716158401_14j_id_1'). If the provided id was correct, wrap the message and its component into an h:panelGroup or h:panelGrid. Here is when I saw the "j_id_1" word at the generated IDs, for example, for the id "ticket_id": j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:j_id_jsp_1716158401_5j_id_1 And, viewing the resulting HTML generated page, I saw that the IDs names are like this (whitout using "ForceId" atribute): <input id="j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:ticket_idj_id_1" name="j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:ticket_idj_id_1">
[ "The forceId attribute of the tomahawk components should solve this problem.\nsomething like:\n&lt;t:outputText id=\"xyz\" forceId=\"true\" value=\"#{mybean.stuff}\"/&gt;\n\nAt the first view of the page, if you press the \"CREATE TICKET\" button with nothing in any of the inputTexts and no files uploaded, do the message tags work for the inputTexts? (ie. required = true) I'm just curious if the messages for the inputTexts are working but the message for the inputFileUpload is not. \n", "Looks like it may be related a bug in myfaces. There is a newer version of myfaces and tomahawk that you might try. I would remove the subview functionality as a quick test - copy the detail.jsp page back into the main page.\nhttps://issues.apache.org/jira/browse/MYFACES-1807?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=12567158#action_12567158\n" ]
[ 1, 0 ]
[]
[]
[ "jsf" ]
stackoverflow_0000066912_jsf.txt
Q: Multiple file inputs? Within an XSLT document, is it possible to loop over a set of files in the current directory? I have a situation where I have a directory full of xml files that need some analysis done to generate a report. I have my stylesheet operating on a single document fine, but I'd like to extend that without going to another tool to merge the xml documents. I was thinking along these lines: <xsl:for-each select="{IO Selector Here}"> <xsl:variable select="document(@url)" name="contents" /> <!--More stuff here--> </xsl:for-each> A: In XSLT 2.0, and with Saxon, you can do this with the collection() function: <xsl:for-each select="file:///path/to/directory"> <!-- process the documents --> </xsl:for-each> See http://www.saxonica.com/documentation/sourcedocs/collections.html for more details. In XSLT 1.0, you have to create an index that lists the documents you want to process with a separate tool. Your environment may provide such a tool; for example, Cocoon has a Directory Generator that creates such an index. But without knowing what your environment is, it's hard to know what to recommend. A: As others said, you cannot do it in a platform-independent way. In .NET world, you could create a custom XmlResolver so that document('dir://c:/foo/') would return the list of files in the 'c:\foo' directory in an arbitrary format you wish. See the following links for more information on custom XmlResolver's: Customizing the XmlUrlResolver Class The power of XmlResolver Also you may resort to using scripts (like the msxsl:script element) or extensions in your XSLT stylesheet. All these approaches will make your XSLT code unportable to other platforms. A: I don't think XSL is set up to work that way: it's designed to be used by something else on one or more documents, and the something else would be responsible for finding files to which the XSLT should be applied. If you had one main document and a fixed set of supporting documents, you could possibly use the document() function to return specific nodes and/or values, but I suspect your case is different. A: From within XSLT I think this will not be possible. You could pass in all the XML file names to an <xsl:param name="files" /> as a comma separated list and loop over it using recursion and substring-before() and substring-after(). A: I have a command-line tool that could be used for this - it uses the XSLT processor built into Ant (the java build tool) to process input + transform into output. Would be easy to wrap with a batch file for loop. svn://donie.homeip.net/public/tools A: If you are using .Net you can use XsltExtension to make calls from your XSLT document to methods in your .net class. The method could then return nodesets back to your XSLT. So your method could handle the file IO part.
Multiple file inputs?
Within an XSLT document, is it possible to loop over a set of files in the current directory? I have a situation where I have a directory full of xml files that need some analysis done to generate a report. I have my stylesheet operating on a single document fine, but I'd like to extend that without going to another tool to merge the xml documents. I was thinking along these lines: <xsl:for-each select="{IO Selector Here}"> <xsl:variable select="document(@url)" name="contents" /> <!--More stuff here--> </xsl:for-each>
[ "In XSLT 2.0, and with Saxon, you can do this with the collection() function:\n<xsl:for-each select=\"file:///path/to/directory\">\n <!-- process the documents -->\n</xsl:for-each>\n\nSee http://www.saxonica.com/documentation/sourcedocs/collections.html for more details.\nIn XSLT 1.0, you have to create an index that lists the documents you want to process with a separate tool. Your environment may provide such a tool; for example, Cocoon has a Directory Generator that creates such an index. But without knowing what your environment is, it's hard to know what to recommend.\n", "As others said, you cannot do it in a platform-independent way. In .NET world, you could create a custom XmlResolver so that document('dir://c:/foo/') would return the list of files in the 'c:\\foo' directory in an arbitrary format you wish. See the following links for more information on custom XmlResolver's:\nCustomizing the XmlUrlResolver Class\nThe power of XmlResolver\nAlso you may resort to using scripts (like the msxsl:script element) or extensions in your XSLT stylesheet.\nAll these approaches will make your XSLT code unportable to other platforms.\n", "I don't think XSL is set up to work that way: it's designed to be used by something else on one or more documents, and the something else would be responsible for finding files to which the XSLT should be applied. \nIf you had one main document and a fixed set of supporting documents, you could possibly use the document() function to return specific nodes and/or values, but I suspect your case is different. \n", "From within XSLT I think this will not be possible. \nYou could pass in all the XML file names to an <xsl:param name=\"files\" /> as a comma separated list and loop over it using recursion and substring-before() and substring-after().\n", "I have a command-line tool that could be used for this - it uses the XSLT processor built into Ant (the java build tool) to process input + transform into output. Would be easy to wrap with a batch file for loop.\nsvn://donie.homeip.net/public/tools\n", "If you are using .Net you can use XsltExtension to make calls from your XSLT document to methods in your .net class. The method could then return nodesets back to your XSLT. So your method could handle the file IO part.\n" ]
[ 8, 2, 0, 0, 0, 0 ]
[]
[]
[ "io", "xml", "xslt" ]
stackoverflow_0000102531_io_xml_xslt.txt
Q: When should I use # and = in ASP.NET controls? I have been using ASP.NET for years, but I can never remember when using the # and = are appropriate. For example: <%= Grid.ClientID %> or <%# Eval("FullName")%> Can someone explain when each should be used so I can keep it straight in my mind? Is # only used in controls that support databinding? A: There are a couple of different 'bee-stings': <%@ - page directive <%$ - resource access <%= - explicit output to page <%# - data binding <%-- - server side comment block Also new in ASP.Net 4: <%: - writes out to the page, but with HTML encoded Also new in ASP.Net 4.5: <%#: - HTML encoded data binding A: <%= %> is the equivalent of doing Response.Write("") wherever you place it. <%# %> is for Databinding and can only be used where databinding is supported (you can use these on the page-level outside a control if you call Page.DataBind() in your codebehind) Databinding Expressions Overview A: Here's a great blog post by Dan Crevier that walks through a test app he wrote to show the differences. In essence: The <%= expressions are evaluated at render time The <%# expressions are evaluated at DataBind() time and are not evaluated at all if DataBind() is not called. <%# expressions can be used as properties in server-side controls. <%= expressions cannot.
When should I use # and = in ASP.NET controls?
I have been using ASP.NET for years, but I can never remember when using the # and = are appropriate. For example: <%= Grid.ClientID %> or <%# Eval("FullName")%> Can someone explain when each should be used so I can keep it straight in my mind? Is # only used in controls that support databinding?
[ "There are a couple of different 'bee-stings':\n\n<%@ - page directive\n<%$ - resource access\n<%= - explicit output to page\n<%# - data binding\n<%-- - server side comment block\n\nAlso new in ASP.Net 4:\n\n<%: - writes out to the page, but with HTML encoded\n\nAlso new in ASP.Net 4.5:\n\n<%#: - HTML encoded data binding\n\n", "<%= %> is the equivalent of doing Response.Write(\"\") wherever you place it.\n<%# %> is for Databinding and can only be used where databinding is supported (you can use these on the page-level outside a control if you call Page.DataBind() in your codebehind)\nDatabinding Expressions Overview\n", "Here's a great blog post by Dan Crevier that walks through a test app he wrote to show the differences.\nIn essence:\n\nThe <%= expressions are evaluated at render time\nThe <%# expressions are evaluated at DataBind() time and are not evaluated at all if DataBind() is not called.\n<%# expressions can be used as properties in server-side controls. <%= expressions cannot.\n\n" ]
[ 44, 24, 9 ]
[]
[]
[ "asp.net", "data_binding" ]
stackoverflow_0000115159_asp.net_data_binding.txt
Q: Should unit test classes be kept under version control with the rest of the code? If I create a test suite for a development project, should those classes be kept under version control with the rest of the project code? A: Yes, there is no reason not to put them in source control. What if the tests change? What if the interfaces change, necessitating that the tests change? A: Yes, all the same reasons you put production code in to source control still apply to any unit tests you write. It's the classic who, where and why questions: Who changed the code? When did they change it? What did they change it for? These questions are just as pertinent to testing code as they are to production code. You absolutely should put your unit testing code in to the repository. A: Absolutely. Test classes must stay up-to-date with the code. This means checking it in and running the tests under continuous integration. A: Absolutely! Test classes are source code and should be managed like any other source code. You will need to modify them and keep track of versions and you want to know the maintenance history. You should also keep test data under source control unless it is massively large. A: Unit tests should be tied to a code base in your repository. For no other reason than if you have to produce a maintenance release for a previous version, you can guarantee that, by the metric of your unit tests, you code is no worse than it was before (and hopefully is now better). A: Indeed yes. How could anyone ever think otherwise? If you use code branches, you should try and make your testing code naturally fit under the main codeline so when you branch, the right versions of the tests branch too. A: Yes they should. People checking out the latest release should be able to unit test the code on their machine. This will help to identify missing dependencies and can also provide them with unofficial documentation on how the code works. A: Yes. Test code is a code. It should be maintained, refactored, and versioned. It is a part of your system source. A: Absolutely, they should be treated as first class citizens of your code base. They'll need all the love and care ie maintenance as any piece of code does. A: Yes they should. You should be checking the tests out and running them whenever you make code changes. If you put them somewhere else that is that much more trouble to go through to run them. A: Yes. For all of the other reasons mentioned here, plus also the fact that as functionality changes, your test suite will change, and it should be easy to get the right test suite for any given release, branch, etc. and having the tests not only in version control but the same repository as your code is the way to achieve that. A: Absolutely. You'll likely find that as your code changes your tests may need to change as well, so you'll likely want to have a record of those changes, especially if the tests or code all of a sudden stop working. ;-) Also, the unit testcases should be kept as close as possible to the actual code they are testing (the bottom of the same file seems to be the standard). It's as much for convenience as it is for maintenance. For some additional reading about what makes a good unit test, check out this stackoverflow post. A: Yes for all the reasons above also if you are using a continuous integration server that is "watching" your source control you can have it run the latest unit tests on every commit. This means that a broken build results from unit tests failing as well as from code not compiling.
Should unit test classes be kept under version control with the rest of the code?
If I create a test suite for a development project, should those classes be kept under version control with the rest of the project code?
[ "Yes, there is no reason not to put them in source control. What if the tests change? What if the interfaces change, necessitating that the tests change?\n", "Yes, all the same reasons you put production code in to source control still apply to any unit tests you write.\nIt's the classic who, where and why questions:\n\nWho changed the code?\nWhen did they change it?\nWhat did they change it for?\n\nThese questions are just as pertinent to testing code as they are to production code. You absolutely should put your unit testing code in to the repository.\n", "Absolutely. Test classes must stay up-to-date with the code. This means checking it in and running the tests under continuous integration.\n", "Absolutely! Test classes are source code and should be managed like any other source code. You will need to modify them and keep track of versions and you want to know the maintenance history. \nYou should also keep test data under source control unless it is massively large.\n", "Unit tests should be tied to a code base in your repository.\nFor no other reason than if you have to produce a maintenance release for a previous version, you can guarantee that, by the metric of your unit tests, you code is no worse than it was before (and hopefully is now better).\n", "Indeed yes. How could anyone ever think otherwise?\nIf you use code branches, you should try and make your testing code naturally fit under the main codeline so when you branch, the right versions of the tests branch too.\n", "Yes they should. People checking out the latest release should be able to unit test the code on their machine. This will help to identify missing dependencies and can also provide them with unofficial documentation on how the code works.\n", "Yes. \nTest code is a code. It should be maintained, refactored, and versioned. It is a part of your system source.\n", "Absolutely, they should be treated as first class citizens of your code base. They'll need all the love and care ie maintenance as any piece of code does.\n", "Yes they should. You should be checking the tests out and running them whenever you make code changes. If you put them somewhere else that is that much more trouble to go through to run them.\n", "Yes. For all of the other reasons mentioned here, plus also the fact that as functionality changes, your test suite will change, and it should be easy to get the right test suite for any given release, branch, etc. and having the tests not only in version control but the same repository as your code is the way to achieve that.\n", "Absolutely. You'll likely find that as your code changes your tests may need to change as well, so you'll likely want to have a record of those changes, especially if the tests or code all of a sudden stop working. ;-)\nAlso, the unit testcases should be kept as close as possible to the actual code they are testing (the bottom of the same file seems to be the standard). It's as much for convenience as it is for maintenance.\nFor some additional reading about what makes a good unit test, check out this stackoverflow post.\n", "Yes for all the reasons above also if you are using a continuous integration server that is \"watching\" your source control you can have it run the latest unit tests on every commit.\nThis means that a broken build results from unit tests failing as well as from code not compiling.\n" ]
[ 31, 5, 4, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "unit_testing", "version_control" ]
stackoverflow_0000115116_unit_testing_version_control.txt
Q: Encoding user input for emails On a website if I have a form where the user can input some text and then a page which displays what the user has entered. I know to html encode the values the user has entered to prevent scripting attacks. If the form was sending emails addresses I presume I would do the same but is there any special cases for emails and will email clients run the any script injected into the email? A: While it would still be a good idea to strip <script> tags from your document before sending it, I think that the threat is low. I believe that you would be hard pressed to find an email client (still receiving support) that does not strip scripts before rendering an email. A: I believe that by marking the email body as text/plain would avoid javascript and/or html attacks (but I wouldn't trust outlook on following what the headers suggest). A: You should use an SMTP library that takes any burden (and potential bugs) which are caused by duplicated or missing escaping. Then, use plaintext mails only (text/plain). To avoid security problems with buggy mail clients, you could also send a nearly empty mail, and the text as attachment (file extension ".txt", content-type "text/plain"). A: You should definitely HTML encode before assigning posted content to the HTML body of an email. Your code should already be rejecting content such as '<script>' as invalid, not just in the case of an email but in all cases. There are no other considerations you need to worry about. A: I would highly suggest using an existing, tested solution for sending mails. If you're passing user input to, say, the PHP mail() function--even with HTML encoding--it's possible for an attacker to craft a "body" that actually contains the headers to create a multi-part message.
Encoding user input for emails
On a website if I have a form where the user can input some text and then a page which displays what the user has entered. I know to html encode the values the user has entered to prevent scripting attacks. If the form was sending emails addresses I presume I would do the same but is there any special cases for emails and will email clients run the any script injected into the email?
[ "While it would still be a good idea to strip <script> tags from your document before sending it, I think that the threat is low. I believe that you would be hard pressed to find an email client (still receiving support) that does not strip scripts before rendering an email.\n", "I believe that by marking the email body as text/plain would avoid javascript and/or html attacks (but I wouldn't trust outlook on following what the headers suggest).\n", "You should use an SMTP library that takes any burden (and potential bugs) which are caused by duplicated or missing escaping. Then, use plaintext mails only (text/plain).\nTo avoid security problems with buggy mail clients, you could also send a nearly empty mail, and the text as attachment (file extension \".txt\", content-type \"text/plain\").\n", "You should definitely HTML encode before assigning posted content to the HTML body of an email. Your code should already be rejecting content such as '<script>' as invalid, not just in the case of an email but in all cases.\nThere are no other considerations you need to worry about.\n", "I would highly suggest using an existing, tested solution for sending mails. If you're passing user input to, say, the PHP mail() function--even with HTML encoding--it's possible for an attacker to craft a \"body\" that actually contains the headers to create a multi-part message.\n" ]
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "email", "javascript" ]
stackoverflow_0000114148_email_javascript.txt
Q: Adding video to a site In your opinion, what are the best options for adding video to a website assuming it would be rendered as FLV. What are the key considerations? Would you use a 3rd party service (youtube.com, vimeo.com, etc.) or host yourself? Why? If you used a service, which one? If you hosted yourself is it as simple as using an existing embeddable flash FLV player to access FLV files via HTTP or is there something more you would do in terms of content management, etc.? A: I guess the question boils down to whether you need to be in complete control of the video, and whether you have money to throw at the project. If you host on youtube etc you are subject to their terms of service and need to work within the constraints of their branding. When I have needed complete control of Flash video clips for clients I have used the JW-FLV player. It will happily serve FLV files off an HTTP server. It is possible to embed the player in another Flash movie, but most often you will control the playlist from HTML links. Hosting video files can get very expensive, so expect to pay a hefty bandwidth bill. I would use a 3rd party service if I was creating video for public consumption that had some sort of marketing aspect to it. Host it on YouTube and you can get very good exposure, and people have a chance of finding your video. These services also have global reach in their networks so you may get better performance worldwide. Google recently released Video for Google Apps customers. This allows you to secure your Google video to users belonging to your organisation. This bridges the gap for some projects that would traditionally use self-hosting. A: Whether you decide to host the video yourself depends greatly on your requirements, hosting environment and technology you use. If it's a small personal site, than it's prefectly ok to host it on youtube or another hosting service, but if you are making a corporate site, it looks much more professional if you host it yourself. Or if the video won't change very frequently it's pretty easy to just host it yourself. To host it yourself it's just simply puting in a web accessible directory on the server and setting the URL in the player. If you need to do content management, than keep in mind the possible upload limits you will have on the server, and the fact, that HTTP is not the ideal protocol for uploading large files. If you have to recode the video on the server, than don't forget that it will be a serious performance hit to it while the encoding is running. To recode the video on the server I prefer to use FFMPEG or mencoder (both have windows and linux/unix versions).
Adding video to a site
In your opinion, what are the best options for adding video to a website assuming it would be rendered as FLV. What are the key considerations? Would you use a 3rd party service (youtube.com, vimeo.com, etc.) or host yourself? Why? If you used a service, which one? If you hosted yourself is it as simple as using an existing embeddable flash FLV player to access FLV files via HTTP or is there something more you would do in terms of content management, etc.?
[ "I guess the question boils down to whether you need to be in complete control of the video, and whether you have money to throw at the project. If you host on youtube etc you are subject to their terms of service and need to work within the constraints of their branding.\nWhen I have needed complete control of Flash video clips for clients I have used the JW-FLV player. It will happily serve FLV files off an HTTP server. It is possible to embed the player in another Flash movie, but most often you will control the playlist from HTML links. Hosting video files can get very expensive, so expect to pay a hefty bandwidth bill.\nI would use a 3rd party service if I was creating video for public consumption that had some sort of marketing aspect to it. Host it on YouTube and you can get very good exposure, and people have a chance of finding your video. These services also have global reach in their networks so you may get better performance worldwide.\nGoogle recently released Video for Google Apps customers. This allows you to secure your Google video to users belonging to your organisation. This bridges the gap for some projects that would traditionally use self-hosting.\n", "Whether you decide to host the video yourself depends greatly on your requirements, hosting environment and technology you use. If it's a small personal site, than it's prefectly ok to host it on youtube or another hosting service, but if you are making a corporate site, it looks much more professional if you host it yourself. Or if the video won't change very frequently it's pretty easy to just host it yourself.\nTo host it yourself it's just simply puting in a web accessible directory on the server and setting the URL in the player.\nIf you need to do content management, than keep in mind the possible upload limits you will have on the server, and the fact, that HTTP is not the ideal protocol for uploading large files.\nIf you have to recode the video on the server, than don't forget that it will be a serious performance hit to it while the encoding is running.\nTo recode the video on the server I prefer to use FFMPEG or mencoder (both have windows and linux/unix versions).\n" ]
[ 3, 0 ]
[ "If you are going to use a 3rd party site, use vimeo - it's a great user experience and great video quality.\n" ]
[ -2 ]
[ "flash", "video", "web" ]
stackoverflow_0000114931_flash_video_web.txt
Q: How to pass an array parameter in TOAD Using toad and an oracle database, how can I call a sp and see the results by passing an array to one of the parameters of the sp? A: In the Editor tab you can call it like this: begin myproc (my_array_type(1,4,7,9)); end;
How to pass an array parameter in TOAD
Using toad and an oracle database, how can I call a sp and see the results by passing an array to one of the parameters of the sp?
[ "In the Editor tab you can call it like this:\nbegin\n myproc (my_array_type(1,4,7,9));\nend;\n\n" ]
[ 3 ]
[]
[]
[ "associative_array", "oracle", "toad" ]
stackoverflow_0000114910_associative_array_oracle_toad.txt
Q: Does a caching-nameserver usually cache the negative DNS response SERVFAIL Does a caching-nameserver usually cache the negative DNS response SERVFAIL? EDIT: To clarify the question, I can see the caching nameserver caching negative responses NXDOMAIN, NODATA. But it does not do this for SERVFAIL responses. Is this intentional? A: SERVFAIL is covered by §7.1 of RFC2308: Server failures fall into two major classes. The first is where a server can determine that it has been misconfigured for a zone. This may be where it has been listed as a server, but not configured to be a server for the zone, or where it has been configured to be a server for the zone, but cannot obtain the zone data for some reason. This can occur either because the zone file does not exist or contains errors, or because another server from which the zone should have been available either did not respond or was unable or unwilling to supply the zone. The second class is where the server needs to obtain an answer from elsewhere, but is unable to do so, due to network failures, other servers that don't reply, or return server failure errors, or similar. In either case a resolver MAY cache a server failure response. If it does so it MUST NOT cache it for longer than five (5) minutes, and it MUST be cached against the specific query tuple <query name, type, class, server IP address>. So basically, it's dependent on the implementation of your name server. A: RFC 1034 describes how to cache negative responses but did not define a mechanism for returning those cache results to peer resolvers. RFC 2308 defines these attributes. Negative caching was an optional part of the DNS Specifications... A: One of the timeout fields in the SOA is a "negative timeout". It is usually set to a short time, such as 30 or 60 seconds. So, yes, but for a shorter time than a "positive" response.
Does a caching-nameserver usually cache the negative DNS response SERVFAIL
Does a caching-nameserver usually cache the negative DNS response SERVFAIL? EDIT: To clarify the question, I can see the caching nameserver caching negative responses NXDOMAIN, NODATA. But it does not do this for SERVFAIL responses. Is this intentional?
[ "SERVFAIL is covered by §7.1 of RFC2308:\n\nServer failures fall into two major\n classes. The first is where a \n server can determine that it has been\n misconfigured for a zone. This may\n be where it has been listed as a server, but not configured to be a\n server for the zone, or where it has\n been configured to be a server for\n the zone, but cannot obtain the zone\n data for some reason. This can\n occur either because the zone file\n does not exist or contains errors,\n or because another server from which\n the zone should have been available\n either did not respond or was unable\n or unwilling to supply the zone.\nThe second class is where the\n server needs to obtain an answer from \n elsewhere, but is unable to do so, due\n to network failures, other servers\n that don't reply, or return server\n failure errors, or similar.\nIn either case a resolver MAY cache\n a server failure response. If it \n does so it MUST NOT cache it for\n longer than five (5) minutes, and it \n MUST be cached against the specific\n query tuple <query name, type, \n class, server IP address>.\n\nSo basically, it's dependent on the implementation of your name server.\n", "RFC 1034 describes how to cache negative responses but did not define a mechanism for returning those cache results to peer resolvers. RFC 2308 defines these attributes.\nNegative caching was an optional part of the DNS Specifications...\n", "One of the timeout fields in the SOA is a \"negative timeout\". It is usually set to a short time, such as 30 or 60 seconds. So, yes, but for a shorter time than a \"positive\" response.\n" ]
[ 6, 3, 0 ]
[]
[]
[ "dns" ]
stackoverflow_0000073433_dns.txt
Q: How to list some specific images in some folder on web server? Let me explain: this is path to this folder: > www.my_site.com/images And images are created by user_id, and for example, images of user_id = 27 are, 27_1.jpg, 27_2.jpg, 27_3.jpg! How to list and print images which start with 27_%.jpg? I hope You have understood me! PS. I am totally beginmer in ASP.NET (VB) and please give me detailed information Here starts my loop while dbread.Read() 'and then id user_id dbread('user_id') NEXT??? I nedd to create XML, till now I created like this: act.WriteLine("") act.WriteLine("http://www.my_site.com/images/"&dbread("user_id")&"_1.jpg") act.WriteLine("") But this is not answer because I need to create this nodes how many images of this user exist? In database doesn't exist list of this images so that is reason why I must count them in folder. (this is not my site exacly, but I need to create XMl on this site) Do you understand me? A: The best way is to just loop through all the files in the directory. While dbRead.Read dim sUserId as String= dbread('user_id') For Each sFile As String In IO.Directory.GetFiles("C:\") if sFile.StartsWith (sUserId) Then 'Do something. End If Next Loop However, to actually show the images, you're best bet could be to create a datatable of these images, and then use a datalist or repeater control to display them. Dim dtImages as new DataTable dtImages.Columns.Add("Filename") If dbRead.Read dim sUserId as String= dbread('user_id') For Each sFile As String In IO.Directory.GetFiles("C:\") if sFile.StartsWith (sUserId) Then Dim drImage as DataRow = dtImages.NewRow drImage("Filename") = sFile dtImages.Rows.add(drImage) End If Next End If dlImages.DataSource = dtImages dlImages.DataBind Then, on your ASPX page, you would have a datalist control called dlImages defined like: <asp:datalist id="dlImages" RepeatDirection="Horizontal" runat="server" RepeatLayout="Flow" Height="100%"> <ItemTemplate> <asp:Image ID="Image1" Runat=server ImageUrl='<%# Server.MapPath("photos") & Container.DataItem("FileName") %>'> </asp:Image> </ItemTemplate> </asp:datalist> A: The appropriate method would be to do the following Get the listing of files using System.IO.Directory.GetFiles("YourPath", UserId + "_*.jpg") Loop through this listing and build your XML or then render it out to the user. Basically the GetFiles method accepts a path, and a "filter" parameter which allows you to do a wildcard search! EDIT: The GetFiles operation returns a listing of strings that represent the full file name, you can then manipulate those values using the System.IO.Path.GetFileName() method to get the actual file name. You can use the XmlDocument class if you want to actually build the document, or you could do it with a simple loop and a string builder. Something like the following. StringBuilder oBuilder = new StringBuilder(); oBuilder.Append("<root>"); string[] ofiles = Directory.GetFiles("YourPath", "yourMask"); foreach(string currentString in oFiles) { oBuilder.AppendLine("<file>http://yourpath/" + Path.GetFileName(currentString) + "</file>"); } oBuilder.Append("</root");
How to list some specific images in some folder on web server?
Let me explain: this is path to this folder: > www.my_site.com/images And images are created by user_id, and for example, images of user_id = 27 are, 27_1.jpg, 27_2.jpg, 27_3.jpg! How to list and print images which start with 27_%.jpg? I hope You have understood me! PS. I am totally beginmer in ASP.NET (VB) and please give me detailed information Here starts my loop while dbread.Read() 'and then id user_id dbread('user_id') NEXT??? I nedd to create XML, till now I created like this: act.WriteLine("") act.WriteLine("http://www.my_site.com/images/"&dbread("user_id")&"_1.jpg") act.WriteLine("") But this is not answer because I need to create this nodes how many images of this user exist? In database doesn't exist list of this images so that is reason why I must count them in folder. (this is not my site exacly, but I need to create XMl on this site) Do you understand me?
[ "The best way is to just loop through all the files in the directory. \nWhile dbRead.Read\n dim sUserId as String= dbread('user_id')\n For Each sFile As String In IO.Directory.GetFiles(\"C:\\\")\n if sFile.StartsWith (sUserId) Then\n 'Do something.\n End If\n Next\nLoop\n\nHowever, to actually show the images, you're best bet could be to create a datatable of these images, and then use a datalist or repeater control to display them. \nDim dtImages as new DataTable\ndtImages.Columns.Add(\"Filename\")\nIf dbRead.Read\n dim sUserId as String= dbread('user_id')\n For Each sFile As String In IO.Directory.GetFiles(\"C:\\\")\n if sFile.StartsWith (sUserId) Then\n Dim drImage as DataRow = dtImages.NewRow\n drImage(\"Filename\") = sFile\n dtImages.Rows.add(drImage)\n End If\n Next\nEnd If\ndlImages.DataSource = dtImages\ndlImages.DataBind\n\nThen, on your ASPX page, you would have a datalist control called dlImages defined like:\n <asp:datalist id=\"dlImages\" RepeatDirection=\"Horizontal\" runat=\"server\" RepeatLayout=\"Flow\" Height=\"100%\">\n <ItemTemplate>\n <asp:Image ID=\"Image1\" Runat=server ImageUrl='<%# Server.MapPath(\"photos\") & Container.DataItem(\"FileName\") %>'>\n </asp:Image>\n </ItemTemplate>\n </asp:datalist>\n\n", "The appropriate method would be to do the following\n\nGet the listing of files using System.IO.Directory.GetFiles(\"YourPath\", UserId + \"_*.jpg\")\nLoop through this listing and build your XML or then render it out to the user.\n\nBasically the GetFiles method accepts a path, and a \"filter\" parameter which allows you to do a wildcard search!\nEDIT:\nThe GetFiles operation returns a listing of strings that represent the full file name, you can then manipulate those values using the System.IO.Path.GetFileName() method to get the actual file name.\nYou can use the XmlDocument class if you want to actually build the document, or you could do it with a simple loop and a string builder. Something like the following.\nStringBuilder oBuilder = new StringBuilder();\noBuilder.Append(\"<root>\");\nstring[] ofiles = Directory.GetFiles(\"YourPath\", \"yourMask\");\nforeach(string currentString in oFiles)\n{\n oBuilder.AppendLine(\"<file>http://yourpath/\" + Path.GetFileName(currentString) + \"</file>\");\n}\noBuilder.Append(\"</root\");\n\n" ]
[ 1, 1 ]
[]
[]
[ "asp.net", "vb.net" ]
stackoverflow_0000114208_asp.net_vb.net.txt
Q: error when switching to different svn branch I've got two SVN branches (eg development and stable) and want to switch from one to another... In every tutorial there is command like: rootOfLocalSvnCopy:>svn switch urlToNewBranch . But it leads in error in my case: svn: REPORT request failed on '/svn/rootOfLocalSvnCopy/!svn/vcc/default'<br/> svn: Cannot replace a directory from within Every help that I found is about svn switch --relocate but I don't want to relocate, just to change my working copy to another branch A: OK, I get it work. Error was in dot that I used to specify local directory in a command. correct usage is without it, svn can handle it all itself: rootOfLocalSvnCopy:>svn switch urlToNewBranch (No dot at the end...)
error when switching to different svn branch
I've got two SVN branches (eg development and stable) and want to switch from one to another... In every tutorial there is command like: rootOfLocalSvnCopy:>svn switch urlToNewBranch . But it leads in error in my case: svn: REPORT request failed on '/svn/rootOfLocalSvnCopy/!svn/vcc/default'<br/> svn: Cannot replace a directory from within Every help that I found is about svn switch --relocate but I don't want to relocate, just to change my working copy to another branch
[ "OK, I get it work.\nError was in dot that I used to specify local directory in a command. correct usage is without it, svn can handle it all itself:\n\nrootOfLocalSvnCopy:>svn switch urlToNewBranch\n\n(No dot at the end...)\n" ]
[ 5 ]
[]
[]
[ "branch", "svn", "switch_statement" ]
stackoverflow_0000115281_branch_svn_switch_statement.txt
Q: Does the MVC pattern describe Roles or Layers? I read a text recently saying the MVC pattern describes the layers in an application. But personally I see MVC showing several key roles in an application. Which word do you think is better, layer or role, to describe the three main pieces of MVC? A: Layers should imply a very narrow coupling between the respective sets of code. MVC involves relatively tight coupling between the model, view, and controller. Therefore, if you characterize this as a layering pattern, it becomes problematic in terms of defining an API between the layers. To do this properly, you would have to implement some unintuitive patterns. Because of this, I would agree with your tendency to view it as a pattern that defines roles within a single layer. A: I think roles is a better description. The view and the controller are both in the same "layer" and usually the model is described as a layer but is used between layers. Usually my applications are centered around the domain model with stuff like presentation, persistence and file-io around it. Thinking about an architecture as layered doesn't really work for me. A: MVC clearly defines ROLES. these are 3 roles you can implement in any number of layers. For example u can have a multi layer controller A: Roles, not layers. Layers are completely dependent on the underlying implementation of the MVC pattern. For instance, a service layer may be a single layer on one implementation, but it could have a web service remoting layer and a database layer (for two differing service layers) on another implementation. The concept of layers is just to help you organize it, as is the pattern, but layers are not as easy to spot as patterns, and layers can change, whereas the pattern remains the same despite the layers changing due to different implementations. A: You cannot compare those two words, because they describe different concepts. To me, a layer is something opaque that offers some functions I can use to do things. For example, a good hardware layer for a wireless transmitter would just give me a send and a receive-function (based on bytes, for example), hiding all the ugly, ugly details from me. A role is a way an object will behave. For example, a transformation in one of my compilers is going to take an abstract syntaxtree and return an abstract syntaxtree or an affection in my current project is going to take a state-difference and return a specifically altered state-difference. However, coming with those two definitions, I do not see the need to chose a single "correct" term and burn the other as wrong, because they don't conflict much. A part of a layer has a certain role, and a set of objects conforming to certain roles form a layer. Certainly, the controller forms a certain layer between the UI and the model (at least for input), however, ot also has a role - it turns certain event into certain other events (and thus, it is some sort of adapter). A: I think either can be reasonably argued for, but I think describing the parts as "layers" is more consistent with other conventions, like the OSI model. Since the View, Controller, and Model get progressively closer to your data, it's more of a layered structure. It seems that "roles" would apply to different parts of an application on the same layer.
Does the MVC pattern describe Roles or Layers?
I read a text recently saying the MVC pattern describes the layers in an application. But personally I see MVC showing several key roles in an application. Which word do you think is better, layer or role, to describe the three main pieces of MVC?
[ "Layers should imply a very narrow coupling between the respective sets of code. MVC involves relatively tight coupling between the model, view, and controller. Therefore, if you characterize this as a layering pattern, it becomes problematic in terms of defining an API between the layers. To do this properly, you would have to implement some unintuitive patterns.\nBecause of this, I would agree with your tendency to view it as a pattern that defines roles within a single layer.\n", "I think roles is a better description. The view and the controller are both in the same \"layer\" and usually the model is described as a layer but is used between layers.\nUsually my applications are centered around the domain model with stuff like presentation, persistence and file-io around it. Thinking about an architecture as layered doesn't really work for me. \n", "MVC clearly defines ROLES. these are 3 roles you can implement in any number of layers. For example u can have a multi layer controller\n", "Roles, not layers. Layers are completely dependent on the underlying implementation of the MVC pattern. For instance, a service layer may be a single layer on one implementation, but it could have a web service remoting layer and a database layer (for two differing service layers) on another implementation. The concept of layers is just to help you organize it, as is the pattern, but layers are not as easy to spot as patterns, and layers can change, whereas the pattern remains the same despite the layers changing due to different implementations.\n", "You cannot compare those two words, because they describe different concepts. \nTo me, a layer is something opaque that offers some functions I can use to do things. For example, a good hardware layer for a wireless transmitter would just give me a send and a receive-function (based on bytes, for example), hiding all the ugly, ugly details from me.\nA role is a way an object will behave. For example, a transformation in one of my compilers is going to take an abstract syntaxtree and return an abstract syntaxtree or an affection in my current project is going to take a state-difference and return a specifically altered state-difference.\nHowever, coming with those two definitions, I do not see the need to chose a single \"correct\" term and burn the other as wrong, because they don't conflict much. A part of a layer has a certain role, and a set of objects conforming to certain roles form a layer. Certainly, the controller forms a certain layer between the UI and the model (at least for input), however, ot also has a role - it turns certain event into certain other events (and thus, it is some sort of adapter).\n", "I think either can be reasonably argued for, but I think describing the parts as \"layers\" is more consistent with other conventions, like the OSI model. Since the View, Controller, and Model get progressively closer to your data, it's more of a layered structure. It seems that \"roles\" would apply to different parts of an application on the same layer.\n" ]
[ 4, 2, 1, 1, 0, 0 ]
[ "Why not Both? I see it as 3 separate layers implementing 3 different roles. \n", "It's all terminology, but I think the correct software architecture term would be \"layer\", as in logical layer. You could use the term \"architectural layer\" if it is clearer.\nThe thing is, it's just a different way of slicing an application: a classic n-layer app would be:\n\nUI\nBusiness Logic\nPersistence\n\nYou could have the following logical layers in a simple MVC application:\n\nUI\nController\nModel\nPersistence\n\nBut you could still talk about the \"UI\" and \"Controller\" together as forming the User Interface layer -- I usually split out the Controller into a separate layer when describing and diagramming these architectures, though.\n" ]
[ -1, -1 ]
[ "design_patterns", "model_view_controller" ]
stackoverflow_0000115198_design_patterns_model_view_controller.txt
Q: Will having multiple filegroups help speed up my database? Currently, I am developing a product that does fairly intensive calculations using MS SQL Server 2005. At a high level, the architecture of my product is based on the concept of "runs" where each time I do some analytics it gets stored in a series of run tables (~100 tables per run). The problem I'm having is that when the number of runs grows to be about 1,000 or so after a few months, performance on the database really seems to drop off, and specifically simple queries like checking for the existence of tables or creating views can take up to a second to two. I've heard that using multiple filegroups, which I'm not currently doing, could help. Is this true, and if so, why/how would that help? Also, if there are other suggestions, even ones like, use fewer tables, I'm open to them. I just want to speed the database up and hopefully get it in a state where it will scale. A: In terms of performance, the big gain in using separate files/filegroups is that it lets you spread your data across multiple physical disks. This is beneficial because with several disks, multiple data requests can be handled simultaneously (parallel is generally faster than serial). All other things being equal, this would tend to benefit performance, but the question of how much depends on your particular data set and the queries you're running. From your description, the slow operations you're concerned about are creating tables and checking for the existence of tables. If you are generating 100 tables per run, then after 1000 runs you have 100,000 tables. I don't have much experience with creating that many tables in a single database, but you may be pressing the limits of the system tables that track the database schema. In this case, you might see some benefit by spreading your tables across more than one database (these databases could still all live within the same instance of SQL Server). In general, the SQL Profiler tool is the best starting point for finding slow queries. There are data columns which indicate the CPU and IO cost of each SQL batch, which should point you to the worst offenders. Once you have found the problem queries, I would use the Query Analyzer to generate query plans for each of these queries, and see if you can tell what's making them slow. Do this by opening a query window, entering your query, and hitting Ctrl+L. A complete discussion of what might be slow would fill an entire book, but good things to look for are table scans (very slow for large tables) and inefficient joins. In the end, you may be able to improve things simply by rewriting your queries, or you may have to make more broad changes to the table schema. For instance, maybe there's a way to create only one or a few tables per run, instead of 1000. More specifics about your particular setup would help us give a more detailed answer. I also recommend this website for lots of tips on how to make things faster: http://www.sql-server-performance.com/ A: About 1000 of what? Single row writes? Multiple row transactions? Deletes? A general tip would be to place the data files and log files on separate physical drives. SQL Server keeps track of every write to the log so having those in different drives should give you a general better performance. But SQL Server tuning depends on what the application is actually doing. There are general tips but you have to measure your own thing... A: When you talk about 100 tables per run, do you actually mean that you're creating new SQL tables? If so, I think that the architecture of your application may be the issue. I can't imagine a situation where you would need that many new tables as opposed to reusing the same few tables multiple times and simply adding a column or two to differentiate between runs. If you're already reusing the same group of tables and new runs just mean additional rows in those tables, then the issue could simply be that the new data over time is hurting performance in one of several ways. For example: The tables/indexes could be fragmented after awhile. Make sure that all of your tables have a clustered index. Check for fragmentation using sys.DM_DB_INDEX_PHYSICAL_STATS and issue ALTER INDEX with the REBUILD option if needed to defrag them. The tables could simply be too large, so that inefficient on small tables are now obvious on the larger tables. Look into proper indexes on the tables to improve performance. SQL Server will cache query plans (especially for stored procedures), but if the data in a table changes significantly over time that query plan may no longer be appropriate. Look into sp_recompile for your stored procedures to see if that's needed. #2 is the culprit that I see most often in real world situations. Developers tend to develop using only a small set of test data and overlook proper indexing because you can do almost anything with a table of 20 rows and it will look fast. Hope this helps A: It could if you place them on separate drives - not logical but physical drives so IO is not slowing you down so much. A: The file groups being on different physical drives is what will give you the biggest performance boost, can also split up where the indexes are housed so that table writes and index accesses are hitting different disks. There's a lot you can do with partitioning, but that general concept is where the biggest speed impact comes from. A: It can help with performance. moving certain tables/elemnts to distinct file areas/portions of the disk. this can reduce to a certain extent the amount of external fragmentation impacting the daabase. I would also look at other factors such as tracesql to determine why queries etc are slowing down - there can be other factors such as query statistics, SP recompiles etc that are easier to fix and can give you greater gains in performance. A: Split the tables across separate physical drives. If you have that much disk IO, you need a decent IO solution. Raid 10, fast disks, split the logs and DBs onto separate drives. Re-examine your architecture - can you use multiple databases? If you create 1000s of tables in a go, you will soon hit some interesting bottlenecks that I've not had to deal with before. Multiple DBs should solve that. Think about having one "Controlling" db containing all your main meta-data, and then satellite DBs containing the actual data. You don't mention any specs about your server - but we saw a decent increase in performance when we went from 8GB to 20GB RAM.
Will having multiple filegroups help speed up my database?
Currently, I am developing a product that does fairly intensive calculations using MS SQL Server 2005. At a high level, the architecture of my product is based on the concept of "runs" where each time I do some analytics it gets stored in a series of run tables (~100 tables per run). The problem I'm having is that when the number of runs grows to be about 1,000 or so after a few months, performance on the database really seems to drop off, and specifically simple queries like checking for the existence of tables or creating views can take up to a second to two. I've heard that using multiple filegroups, which I'm not currently doing, could help. Is this true, and if so, why/how would that help? Also, if there are other suggestions, even ones like, use fewer tables, I'm open to them. I just want to speed the database up and hopefully get it in a state where it will scale.
[ "In terms of performance, the big gain in using separate files/filegroups is that it lets you spread your data across multiple physical disks. This is beneficial because with several disks, multiple data requests can be handled simultaneously (parallel is generally faster than serial). All other things being equal, this would tend to benefit performance, but the question of how much depends on your particular data set and the queries you're running.\nFrom your description, the slow operations you're concerned about are creating tables and checking for the existence of tables. If you are generating 100 tables per run, then after 1000 runs you have 100,000 tables. I don't have much experience with creating that many tables in a single database, but you may be pressing the limits of the system tables that track the database schema. In this case, you might see some benefit by spreading your tables across more than one database (these databases could still all live within the same instance of SQL Server).\nIn general, the SQL Profiler tool is the best starting point for finding slow queries. There are data columns which indicate the CPU and IO cost of each SQL batch, which should point you to the worst offenders. Once you have found the problem queries, I would use the Query Analyzer to generate query plans for each of these queries, and see if you can tell what's making them slow. Do this by opening a query window, entering your query, and hitting Ctrl+L. A complete discussion of what might be slow would fill an entire book, but good things to look for are table scans (very slow for large tables) and inefficient joins.\nIn the end, you may be able to improve things simply by rewriting your queries, or you may have to make more broad changes to the table schema. For instance, maybe there's a way to create only one or a few tables per run, instead of 1000. More specifics about your particular setup would help us give a more detailed answer.\nI also recommend this website for lots of tips on how to make things faster:\nhttp://www.sql-server-performance.com/\n", "About 1000 of what? Single row writes? Multiple row transactions? Deletes?\nA general tip would be to place the data files and log files on separate physical drives. SQL Server keeps track of every write to the log so having those in different drives should give you a general better performance.\nBut SQL Server tuning depends on what the application is actually doing. There are general tips but you have to measure your own thing...\n", "When you talk about 100 tables per run, do you actually mean that you're creating new SQL tables? If so, I think that the architecture of your application may be the issue. I can't imagine a situation where you would need that many new tables as opposed to reusing the same few tables multiple times and simply adding a column or two to differentiate between runs.\nIf you're already reusing the same group of tables and new runs just mean additional rows in those tables, then the issue could simply be that the new data over time is hurting performance in one of several ways. For example:\n\nThe tables/indexes could be fragmented after awhile. Make sure that all of your tables have a clustered index. Check for fragmentation using sys.DM_DB_INDEX_PHYSICAL_STATS and issue ALTER INDEX with the REBUILD option if needed to defrag them.\nThe tables could simply be too large, so that inefficient on small tables are now obvious on the larger tables. Look into proper indexes on the tables to improve performance.\nSQL Server will cache query plans (especially for stored procedures), but if the data in a table changes significantly over time that query plan may no longer be appropriate. Look into sp_recompile for your stored procedures to see if that's needed.\n\n#2 is the culprit that I see most often in real world situations. Developers tend to develop using only a small set of test data and overlook proper indexing because you can do almost anything with a table of 20 rows and it will look fast.\nHope this helps\n", "It could if you place them on separate drives - not logical but physical drives so IO is not slowing you down so much.\n", "The file groups being on different physical drives is what will give you the biggest performance boost, can also split up where the indexes are housed so that table writes and index accesses are hitting different disks. There's a lot you can do with partitioning, but that general concept is where the biggest speed impact comes from.\n", "It can help with performance. moving certain tables/elemnts to distinct file areas/portions of the disk. this can reduce to a certain extent the amount of external fragmentation impacting the daabase.\nI would also look at other factors such as tracesql to determine why queries etc are slowing down - there can be other factors such as query statistics, SP recompiles etc that are easier to fix and can give you greater gains in performance.\n", "Split the tables across separate physical drives. If you have that much disk IO, you need a decent IO solution. Raid 10, fast disks, split the logs and DBs onto separate drives.\nRe-examine your architecture - can you use multiple databases? If you create 1000s of tables in a go, you will soon hit some interesting bottlenecks that I've not had to deal with before. Multiple DBs should solve that. Think about having one \"Controlling\" db containing all your main meta-data, and then satellite DBs containing the actual data.\nYou don't mention any specs about your server - but we saw a decent increase in performance when we went from 8GB to 20GB RAM.\n" ]
[ 3, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "sql_server" ]
stackoverflow_0000108445_sql_server.txt
Q: SQL Query Help: Selecting Rows That Appear A Certain Number Of Times I have a table with a "Date" column. Each Date may appear multiple times. How do I select only the dates that appear < k number of times? A: SELECT * FROM [MyTable] WHERE [Date] IN ( SELECT [Date] FROM [MyTable] GROUP By [Date] HAVING COUNT(*) < @Max ) See @[SQLMenace] 's response also. It's very similar to this, but depending on your database his JOIN will probably run faster, assuming the optimizer doesn't make the difference moot. A: select dates from table t group by dates having count(dates) < k ; Hopefully, it works for ORACLE. HTH A: Use the COUNT aggregate: SELECT Date FROM SomeTable GROUP BY Date HAVING COUNT(*) < @k A: For "appears x times" queries it is best to use HAVING clause. In your case, query can be like: SELECT Date FROM table GROUP BY Date HAVING COUNT(*)<k or, in you need to select other columns except Date: SELECT * FROM Table WHERE Date IN ( SELECT Date FROM table GROUP BY Date HAVING COUNT(*)<k) You can also rewrite the IN to INNER JOIN, however this won't give performance gain, as, in fact, query optimizer will do this for you in most RDBMS. Having index on Date will certainly improve performance for this query. A: example DECLARE @Max int SELECT @Max = 5 SELECT t1.* FROM [MyTable] t1 JOIN( SELECT [Date] FROM [MyTable] GROUP By [Date] HAVING COUNT(*) < @Max ) t2 on t1.[Date] = t2.[Date] A: SELECT date, COUNT(date) FROM table GROUP BY date HAVING COUNT(date) < k And then to get the original data back: SELECT table.* FROM table INNER JOIN ( SELECT date, COUNT(date) FROM table GROUP BY date HAVING COUNT(date) < k) dates ON table.date = dates.date A: Assuming you are using Oracle, and k = 5:- select date_col,count(*) from your_table group by date_col having count(*) < 5; If your date column has time filled out as well, and you want to ignore it, modify the query so it looks as follows:- select trunc(date_col) as date_col,count(*) from your_table group by trunc(date_col) having count(*) < 5; A: You may not be able to count directly on the datefield if your dates include times. You may need to convert to just the year/month/day format first and then do the count on that. Otherwise your counts will be off as usually there are very few records withthe exact same time.
SQL Query Help: Selecting Rows That Appear A Certain Number Of Times
I have a table with a "Date" column. Each Date may appear multiple times. How do I select only the dates that appear < k number of times?
[ "SELECT * FROM [MyTable] WHERE [Date] IN\n(\n SELECT [Date] \n FROM [MyTable] \n GROUP By [Date] \n HAVING COUNT(*) < @Max\n)\n\nSee @[SQLMenace] 's response also. It's very similar to this, but depending on your database his JOIN will probably run faster, assuming the optimizer doesn't make the difference moot.\n", "select dates \n from table t \n group by dates having count(dates) < k ;\n\nHopefully, it works for ORACLE.\nHTH\n", "Use the COUNT aggregate:\nSELECT Date\nFROM SomeTable\nGROUP BY Date\nHAVING COUNT(*) < @k\n\n", "For \"appears x times\" queries it is best to use HAVING clause. In your case, query can be like:\nSELECT Date FROM table GROUP BY Date HAVING COUNT(*)<k\n\nor, in you need to select other columns except Date:\nSELECT * FROM Table WHERE Date IN (\nSELECT Date FROM table GROUP BY Date HAVING COUNT(*)<k)\n\nYou can also rewrite the IN to INNER JOIN, however this won't give performance gain, as, in fact, query optimizer will do this for you in most RDBMS. Having index on Date will certainly improve performance for this query.\n", "example\nDECLARE @Max int\nSELECT @Max = 5\n\nSELECT t1.* \nFROM [MyTable] t1 \nJOIN(\n SELECT [Date] \n FROM [MyTable] \n GROUP By [Date] \n HAVING COUNT(*) < @Max\n) t2 on t1.[Date] = t2.[Date] \n\n", "SELECT date, COUNT(date)\nFROM table\nGROUP BY date\nHAVING COUNT(date) < k\n\nAnd then to get the original data back:\nSELECT table.*\nFROM table\nINNER JOIN (\n SELECT date, COUNT(date) \n FROM table\n GROUP BY date\n HAVING COUNT(date) < k) dates ON table.date = dates.date\n\n", "Assuming you are using Oracle, and k = 5:-\nselect date_col,count(*)\nfrom your_table\ngroup by date_col\nhaving count(*) < 5;\n\nIf your date column has time filled out as well, and you want to ignore it, modify the query so it looks as follows:-\nselect trunc(date_col) as date_col,count(*)\nfrom your_table\ngroup by trunc(date_col)\nhaving count(*) < 5;\n\n", "You may not be able to count directly on the datefield if your dates include times. You may need to convert to just the year/month/day format first and then do the count on that.\nOtherwise your counts will be off as usually there are very few records withthe exact same time.\n" ]
[ 8, 6, 3, 2, 2, 1, 1, 0 ]
[]
[]
[ "date", "select", "sql" ]
stackoverflow_0000104971_date_select_sql.txt
Q: Using JET with EMF I need to run JET templates on a EMF model metadata - i.e. the model itself (not data) is input to my JET template. More practically - I want generate non java code, based on EMF templates. How I do it? Thank you A: I'm not sure I get you right, but you can pass your model just like any other object into the JET template (as described in the JET tutorial). Also, it makes no difference if you generate Java or any other text with JET. As an additional pointer, you might want to consider using Xpand (part of openArchitectureWare) for very comfortable model to text generation (including things like content assist for your model in the template editor). A: For code generation, you could use Acceleo. That is like Xpand very comfortable model to text generation (Acceleo language is very intuitive for model browsing) and also less painful than JET.
Using JET with EMF
I need to run JET templates on a EMF model metadata - i.e. the model itself (not data) is input to my JET template. More practically - I want generate non java code, based on EMF templates. How I do it? Thank you
[ "I'm not sure I get you right, but you can pass your model just like any other object into the JET template (as described in the JET tutorial). Also, it makes no difference if you generate Java or any other text with JET. As an additional pointer, you might want to consider using Xpand (part of openArchitectureWare) for very comfortable model to text generation (including things like content assist for your model in the template editor).\n", "For code generation, you could use Acceleo. That is like Xpand very comfortable model to text generation (Acceleo language is very intuitive for model browsing) and also less painful than JET.\n" ]
[ 3, 0 ]
[]
[]
[ "eclipse_emf", "eclipse_m2t_jet" ]
stackoverflow_0000114415_eclipse_emf_eclipse_m2t_jet.txt
Q: How do I convert between time formats? I am looking to convert a MySQL timestamp to a epoch time in seconds using PHP, and vice versa. What's the cleanest way to do this? A: See strtotime and date functions in PHP manual. $unixTimestamp = strtotime($mysqlDate); $mysqlDate = date('Y-m-d h:i:s', $unixTimestamp); A: There are two functions in MySQL which are useful for converting back and forth from the unix epoch time that PHP likes: from_unixtime() unix_timestamp() For example, to get it back in PHP unix time, you could do: SELECT unix_timestamp(timestamp_col) FROM tbl WHERE ... A: From MySQL timestamp to epoch seconds: strtotime($mysql_timestamp); From epoch seconds to MySQL timestamp: $mysql_timestamp = date('Y-m-d H:i:s', time());
How do I convert between time formats?
I am looking to convert a MySQL timestamp to a epoch time in seconds using PHP, and vice versa. What's the cleanest way to do this?
[ "See strtotime and date functions in PHP manual.\n$unixTimestamp = strtotime($mysqlDate);\n$mysqlDate = date('Y-m-d h:i:s', $unixTimestamp);\n\n", "There are two functions in MySQL which are useful for converting back and forth from the unix epoch time that PHP likes:\nfrom_unixtime()\nunix_timestamp()\nFor example, to get it back in PHP unix time, you could do:\nSELECT unix_timestamp(timestamp_col) FROM tbl WHERE ...\n", "From MySQL timestamp to epoch seconds:\nstrtotime($mysql_timestamp);\n\nFrom epoch seconds to MySQL timestamp:\n$mysql_timestamp = date('Y-m-d H:i:s', time());\n\n" ]
[ 6, 5, 0 ]
[]
[]
[ "mysql", "php", "time", "timestamp" ]
stackoverflow_0000115428_mysql_php_time_timestamp.txt