content
stringlengths
86
88.9k
title
stringlengths
0
150
question
stringlengths
1
35.8k
answers
sequence
answers_scores
sequence
non_answers
sequence
non_answers_scores
sequence
tags
sequence
name
stringlengths
30
130
Q: Automating MSI Build Process Does anyone have a good way to build MSI (vdproj) projects using MsBuild or Nant? I know one answer was to install Visual Studio on the build server and just use devenv.exe to build the project, but, I prefer not to install Visual Studio on our build servers. A: Short of the method you mentioned above (devenv), there is no way to do this with the current version of MSBuild. The method the Visual Studio team uses to run their MSI builds is with Windows Installer XML. You can learn more about using WiX to deploy setup packages here. Please note WiX doesn't support vdproj files so it means you'll be recreating your installer projects. Edit: Looks like I was beat to the chase when grabbing my references :) A: We use Wix to automate MSI builds for IronPython and IronRuby. EDIT: to clarify, this probably means starting over from scratch when building your installer. While Wix has a mechanism to create a configuration directly from a preexisting MSI file, I've never gotten a satisfactory result from using this tool
Automating MSI Build Process
Does anyone have a good way to build MSI (vdproj) projects using MsBuild or Nant? I know one answer was to install Visual Studio on the build server and just use devenv.exe to build the project, but, I prefer not to install Visual Studio on our build servers.
[ "Short of the method you mentioned above (devenv), there is no way to do this with the current version of MSBuild. \nThe method the Visual Studio team uses to run their MSI builds is with Windows Installer XML. You can learn more about using WiX to deploy setup packages here.\nPlease note WiX doesn't support vdproj files so it means you'll be recreating your installer projects.\nEdit: Looks like I was beat to the chase when grabbing my references :)\n", "We use Wix to automate MSI builds for IronPython and IronRuby.\nEDIT: to clarify, this probably means starting over from scratch when building your installer. While Wix has a mechanism to create a configuration directly from a preexisting MSI file, I've never gotten a satisfactory result from using this tool\n" ]
[ 8, 1 ]
[]
[]
[ "build_automation", "build_process" ]
stackoverflow_0000024813_build_automation_build_process.txt
Q: How to add "Project Description" in FogBugz? When I create a new project (or even when I edit the Sample Project) there is no way to add Description to the project. Or am I blind to the obvious? A: There's no such thing as a project description, really. There's a column in the Projects page which is used so you can see which project is the default, built-in inbox, and we couldn't think of anything better to put as the column header for that column. A: You are not crazy. It is used internally and not even stored in the database. I wondered the same thing when I first started using FogBugz, but found a forum entry to answer my question. As of today, I still don't think they have implemented it. Jump over to FogCreek and submit a request, if you would like to make it editable. "Description" missing from Project? How to Edit a Project Description A: The description is mostly for system projects, like e-mail inbox. You might be able to set one in the underlying DB table.
How to add "Project Description" in FogBugz?
When I create a new project (or even when I edit the Sample Project) there is no way to add Description to the project. Or am I blind to the obvious?
[ "There's no such thing as a project description, really. There's a column in the Projects page which is used so you can see which project is the default, built-in inbox, and we couldn't think of anything better to put as the column header for that column.\n", "You are not crazy. It is used internally and not even stored in the database. I wondered the same thing when I first started using FogBugz, but found a forum entry to answer my question. As of today, I still don't think they have implemented it. Jump over to FogCreek and submit a request, if you would like to make it editable.\n\n\"Description\" missing from Project?\nHow to Edit a Project Description\n\n", "The description is mostly for system projects, like e-mail inbox.\nYou might be able to set one in the underlying DB table.\n" ]
[ 20, 8, 0 ]
[]
[]
[ "fogbugz" ]
stackoverflow_0000014646_fogbugz.txt
Q: Database query representation impersonating file on Windows share? Is there any way to have something that looks just like a file on a Windows file share, but is really a resource served up over HTTP? For context, I'm working with an old app that can only deal with files on a Windows file share, I want to create a simple HTTP-based service to serve the content of the files dynamically to pick up real time changes to the underlying data on request. A: WebDAV (basically) takes an existing directory, and shares it over HTTP - which sounds like the opposite of what you want. You need something that speaks SMB/CIFS on one end, and your own code on the other. The easiest way to do that is with a userspace file system. To that end, here's a couple of links: WinFUSE, which is kind of a barebones CIFS/SMB server that can host your own filesystem. I've done a couple of small samples with it - and the docs are terrible, but it more or less worked. Dokan, a userspace file driver with .NET bindings. I haven't used this one, but it looks promising. It has both .NET and Ruby bindings, so you should be able to get a POC up pretty quickly. Callback File System - yet another userspace file system. Again, I have no experience with this one. A Linux box with SAMBA and FUSE that shares the drive out to the Windows box. A: This won't answer your question in any meaningful way, but maybe it will get you pointed in the right direction. Look into serving the "file(s)" via WebDAV--SharePoint uses this and its files can be accessed exactly as you want, as a file share where the transport mechanism is HTTP. Unfortunately I can't give any more detailed info, as I've only worked on the client end of WebDAV and not the server side of things. A: I think serving up files from WebDAV might be what you're looking for.
Database query representation impersonating file on Windows share?
Is there any way to have something that looks just like a file on a Windows file share, but is really a resource served up over HTTP? For context, I'm working with an old app that can only deal with files on a Windows file share, I want to create a simple HTTP-based service to serve the content of the files dynamically to pick up real time changes to the underlying data on request.
[ "WebDAV (basically) takes an existing directory, and shares it over HTTP - which sounds like the opposite of what you want. \nYou need something that speaks SMB/CIFS on one end, and your own code on the other. The easiest way to do that is with a userspace file system.\nTo that end, here's a couple of links:\n\nWinFUSE, which is kind of a barebones CIFS/SMB server that can host your own filesystem. I've done a couple of small samples with it - and the docs are terrible, but it more or less worked.\nDokan, a userspace file driver with .NET bindings. I haven't used this one, but it looks promising. It has both .NET and Ruby bindings, so you should be able to get a POC up pretty quickly.\nCallback File System - yet another userspace file system. Again, I have no experience with this one.\nA Linux box with SAMBA and FUSE that shares the drive out to the Windows box.\n\n", "This won't answer your question in any meaningful way, but maybe it will get you pointed in the right direction. Look into serving the \"file(s)\" via WebDAV--SharePoint uses this and its files can be accessed exactly as you want, as a file share where the transport mechanism is HTTP. Unfortunately I can't give any more detailed info, as I've only worked on the client end of WebDAV and not the server side of things. \n", "I think serving up files from WebDAV might be what you're looking for.\n" ]
[ 2, 0, 0 ]
[]
[]
[ "file", "http", "webdav" ]
stackoverflow_0000024408_file_http_webdav.txt
Q: What to do about ScanAlert? One of my clients uses McAfee ScanAlert (i.e., HackerSafe). It basically hits the site with about 1500 bad requests a day looking for security holes. Since it demonstrates malicious behavior it is tempting to just block it after a couple bad requests, but maybe I should let it exercise the UI. Is it a true test if I don't let it finish? A: Isn't it a security flaw of the site to let hackers throw everything in their arsenal against the site? Well, you should focus on closing holes, rather than trying to thwart scanners (which is a futile battle). Consider running such tests yourself. A: It's good that you block bad request after a couple of trials, but you should let it continue. If you block it after 5 bad requests you won't know if the 6th request wouldn't crash your site. EDIT: I meant that some attacker might send only one request but similar to one of those 1495 that You didn't test because you blocked., and this one request might chrash your site. A: Preventing security breaches requires different strategies for different attacks. For instance, it would not be unusual to block traffic from certain sources during a denial of service attack. If a user fails to provide proper credentials more than 3 times the IP address is blocked or the account is locked. When ScanAlert issues hundreds of requests which may include SQL injection--to name one--it certainly matches what the site code should consider "malicious behavior". In fact, just putting UrlScan or eEye SecureIIS in place may deny many such requests, but is that a true test of the site code. It's the job of the site code to detect malicious users/requests and deny them. At what layer is the test valid? ScanAlert presents in two different ways: the number of requests which are malformed and the variety of each individual request as a test. It's seems like the 2 pieces of advice that emerge are as follows: The site code should not try to detect malicious traffic from a particular source and block that traffic, because that is a futile effort. If you do attempt such a futile effort, as least make an exception for requests from ScanAlert in order to test lower layers. A: If it's not hurting the performance of the site, I think its a good thing. If you had 1000 clients to the same site all doing that, yeah, block it. But if the site was built for that client, I think it's fair enough they do that.
What to do about ScanAlert?
One of my clients uses McAfee ScanAlert (i.e., HackerSafe). It basically hits the site with about 1500 bad requests a day looking for security holes. Since it demonstrates malicious behavior it is tempting to just block it after a couple bad requests, but maybe I should let it exercise the UI. Is it a true test if I don't let it finish?
[ "\nIsn't it a security flaw of the site to let hackers throw everything in their arsenal against the site?\n\nWell, you should focus on closing holes, rather than trying to thwart scanners (which is a futile battle). Consider running such tests yourself.\n", "It's good that you block bad request after a couple of trials, but you should let it continue.\nIf you block it after 5 bad requests you won't know if the 6th request wouldn't crash your site. \nEDIT:\nI meant that some attacker might send only one request but similar to one of those 1495 that You didn't test because you blocked., and this one request might chrash your site.\n", "Preventing security breaches requires different strategies for different attacks. For instance, it would not be unusual to block traffic from certain sources during a denial of service attack. If a user fails to provide proper credentials more than 3 times the IP address is blocked or the account is locked.\nWhen ScanAlert issues hundreds of requests which may include SQL injection--to name one--it certainly matches what the site code should consider \"malicious behavior\".\nIn fact, just putting UrlScan or eEye SecureIIS in place may deny many such requests, but is that a true test of the site code. It's the job of the site code to detect malicious users/requests and deny them. At what layer is the test valid? \nScanAlert presents in two different ways: the number of requests which are malformed and the variety of each individual request as a test. It's seems like the 2 pieces of advice that emerge are as follows: \n\nThe site code should not try to detect malicious traffic from a particular source and block that traffic, because that is a futile effort.\nIf you do attempt such a futile effort, as least make an exception for requests from ScanAlert in order to test lower layers.\n\n", "If it's not hurting the performance of the site, I think its a good thing. If you had 1000 clients to the same site all doing that, yeah, block it. \nBut if the site was built for that client, I think it's fair enough they do that. \n" ]
[ 2, 1, 1, 0 ]
[]
[]
[ "performance", "security" ]
stackoverflow_0000023961_performance_security.txt
Q: What are the most important things to learn about .net as a Project Manager? Thinking about getting into .net technology project management I've had plenty of experience with PHP projects: I'm aware of most of the existing frameworks and libraries, and I've written specs and case studies based on this knowledge. What should I know about .net? Which top resources would you recommend me to know so I can rapidly learn and later stay up to date on the technology? Edit (8.24.08): The answers I got so far essentially discuss being a good PM. Thanks, but this is not what I meant. Any .net essentials would be appreciated. A: The number one rule is do NOT just ask for status updates. It is Especially annoying when phrases like "where are we on this?" are used. If you aren't directly involved in the details then just make sure you have established communication times or plans so that you know whats going on rather than asking for updates. A: Start with the basics before you get to the higher level stuff like web services (though that is important too). The most important things you need to learn, as a project manager, are the things you're going to be questioning your underlings about later. For example, my PM (also a PHP guy) has absolutely no knowledge of garbage collection and its implications, which makes it incredibly difficult for me to explain to him why our .NET Windows service appears to be taking 80MB of RAM. Remember, you are not the one who needs to know everything. You should be issuing overarching directives, and let the people with the expertise sort out the details. That said, study up on the technicals a bit so that they can communicate effectively with you. Edit (8/24/08):You should know something about the underlying technicals; not necessarily all .NET stuff either (garbage collection, .config files, pipes and services if you're running services adjacent to your project's main focus, stuff like that). Higher-reaching concepts would probably include WPF (maybe Silverlight as well), LINQ (or your ORM of choice), as well as the Vista bridge and related bridging code if your project includes desktop apps at all. Those three things seem to be the focus for this round of .NET. Something else that's very important to have at least a passing knowledge of is the ways that .NET code can/must interoperate with native code: P/Invoke, Runtime Callable Wrapping and COM Callable Wrapping. There are still a lot of native things that don't have a .NET equivalent. As for resources, I'd highly recommend MSDN Magazine. They tend to preview upcoming technologies and tools well before average developers will ever see them. A: The biggest thing you'll probably want to learn is the differences between Windows and non-Windows programmers. They approach fundamental things differently. Knowing the difference will be key to successfully managing the project. If you listen to the stack overflow podcast, and Jeff and Joel have multiple discussions on this topic. Understanding the details of the underlying technology is mostly irrelevant and you'll never know it well enough to go toe to toe with someone who works in it day in and day out. You can probably pick it up as you go. A: The #1 thing you need to be aware of (and I'm guessing you probably already are) is that the guys doing the coding should know what they are doing. Depending on the personailties of the members of your team, you should be able to find someone who is willing and able to explain any of the intricacies to you on an as-required basis. In my experience, the biggest hinderence to a project is the PM who understands the project, but not how to accomplish it (not in itself a problem), but who is also unwilling to listen to what his team tell him. As with any project management, accept that you can't know everything, and be humble enough to ask for explanations where needed. A: This may be old, but should get your started on the high-level overview of the .NET Framework. http://news.zdnet.co.uk/software/0,1000000121,2134207,00.htm
What are the most important things to learn about .net as a Project Manager?
Thinking about getting into .net technology project management I've had plenty of experience with PHP projects: I'm aware of most of the existing frameworks and libraries, and I've written specs and case studies based on this knowledge. What should I know about .net? Which top resources would you recommend me to know so I can rapidly learn and later stay up to date on the technology? Edit (8.24.08): The answers I got so far essentially discuss being a good PM. Thanks, but this is not what I meant. Any .net essentials would be appreciated.
[ "The number one rule is do NOT just ask for status updates. It is Especially annoying when phrases like \"where are we on this?\" are used. If you aren't directly involved in the details then just make sure you have established communication times or plans so that you know whats going on rather than asking for updates.\n", "Start with the basics before you get to the higher level stuff like web services (though that is important too). The most important things you need to learn, as a project manager, are the things you're going to be questioning your underlings about later. For example, my PM (also a PHP guy) has absolutely no knowledge of garbage collection and its implications, which makes it incredibly difficult for me to explain to him why our .NET Windows service appears to be taking 80MB of RAM.\nRemember, you are not the one who needs to know everything. You should be issuing overarching directives, and let the people with the expertise sort out the details. That said, study up on the technicals a bit so that they can communicate effectively with you.\nEdit (8/24/08):You should know something about the underlying technicals; not necessarily all .NET stuff either (garbage collection, .config files, pipes and services if you're running services adjacent to your project's main focus, stuff like that). Higher-reaching concepts would probably include WPF (maybe Silverlight as well), LINQ (or your ORM of choice), as well as the Vista bridge and related bridging code if your project includes desktop apps at all. Those three things seem to be the focus for this round of .NET. Something else that's very important to have at least a passing knowledge of is the ways that .NET code can/must interoperate with native code: P/Invoke, Runtime Callable Wrapping and COM Callable Wrapping. There are still a lot of native things that don't have a .NET equivalent.\nAs for resources, I'd highly recommend MSDN Magazine. They tend to preview upcoming technologies and tools well before average developers will ever see them.\n", "The biggest thing you'll probably want to learn is the differences between Windows and non-Windows programmers. They approach fundamental things differently. Knowing the difference will be key to successfully managing the project. If you listen to the stack overflow podcast, and Jeff and Joel have multiple discussions on this topic. Understanding the details of the underlying technology is mostly irrelevant and you'll never know it well enough to go toe to toe with someone who works in it day in and day out. You can probably pick it up as you go.\n", "The #1 thing you need to be aware of (and I'm guessing you probably already are) is that the guys doing the coding should know what they are doing. Depending on the personailties of the members of your team, you should be able to find someone who is willing and able to explain any of the intricacies to you on an as-required basis.\nIn my experience, the biggest hinderence to a project is the PM who understands the project, but not how to accomplish it (not in itself a problem), but who is also unwilling to listen to what his team tell him. As with any project management, accept that you can't know everything, and be humble enough to ask for explanations where needed.\n", "This may be old, but should get your started on the high-level overview of the .NET Framework.\nhttp://news.zdnet.co.uk/software/0,1000000121,2134207,00.htm\n" ]
[ 3, 2, 1, 1, 1 ]
[]
[]
[ ".net", "project_management" ]
stackoverflow_0000020040_.net_project_management.txt
Q: How do I profile a Maven Application in Netbeans? I've got a project using Maven 2 as the build tool. Now I am using Netbeans 6 as my IDE and really want to be able to use the profiler. Is there any way I can get this to work? A: I thought this might be more complicated. It wasn't. To use the Netbeans profiler with your Maven 2 project you simply need to add a single pair of parameters when running your java app. Call up the project's Properties dialogue, select the "Run" tab and add something like the following to the jvm args: -agentpath:"C:\Program Files\NetBeans 6.0\profiler2\lib\deployed\jdk15\windows\profilerinterface.dll=\"C:\\\"Program Files\"\\\"NetBeans 6.0\"\\profiler2\\lib\\"",5140 This meant that now when I ran my app (F6) execution would wait for me to attach the profiler. Cue real time graphy goodness. Sweet.
How do I profile a Maven Application in Netbeans?
I've got a project using Maven 2 as the build tool. Now I am using Netbeans 6 as my IDE and really want to be able to use the profiler. Is there any way I can get this to work?
[ "I thought this might be more complicated. It wasn't. To use the Netbeans profiler with your Maven 2 project you simply need to add a single pair of parameters when running your java app. Call up the project's Properties dialogue, select the \"Run\" tab and add something like the following to the jvm args:\n-agentpath:\"C:\\Program Files\\NetBeans 6.0\\profiler2\\lib\\deployed\\jdk15\\windows\\profilerinterface.dll=\\\"C:\\\\\\\"Program Files\\\"\\\\\\\"NetBeans 6.0\\\"\\\\profiler2\\\\lib\\\\\"\",5140\n\nThis meant that now when I ran my app (F6) execution would wait for me to attach the profiler. Cue real time graphy goodness. Sweet.\n" ]
[ 1 ]
[]
[]
[ "maven_2", "netbeans", "profiler", "profiling" ]
stackoverflow_0000024986_maven_2_netbeans_profiler_profiling.txt
Q: How Does One Sum Dimensions of an Array Specified at Run-Time? I am working on a function to establish the entropy of a distribution. It uses a copula, if any are familiar with that. I need to sum up the values in the array based on which dimensions are "cared about." Example: Consider the following example... Dimension 0 (across) _ _ _ _ _ _ _ _ _ _ _ _ _ |_ 0 _|_ 0 _|_ 0 _|_ 2 _| Dimension 1 |_ 1 _|_ 0 _|_ 2 _|_ 0 _| (down) |_ 0 _|_ 3 _|_ 0 _|_ 6 _| |_ 0 _|_ 0 _|_ 0 _|_ 0 _| I "care about" dimension 0 only, and "don't care" about the rest (dim 1). Summing this array with the above specifications will "collapse" the "stacks" of dimension 1 down to a single 4 x 1 array: _ _ _ _ _ _ _ _ _ _ _ _ _ |_ 1 _|_ 3 _|_ 2 _|_ 8 _| This can then be summed, or have any operation performed. I need to do this with an array of 'n' dimensions, which could feasibly be 20. Also, I need to be able to do this, caring about certain dimensions, and collapsing the rest. I am having an especially hard time with this because I cant visualize 20 dimensions :p . If anyone could help me set up some c/c++ code to collapse/sum, I would be very very grateful. Update: Just got home. Here is some info to answer your questions: Sorry for rolling back the edits, I was hoping when I clicked roll-back it would show me the changes so I could see what I messed up, a bit like wikipedia. This wasn't the case, as I found out. @jeff - What doesnt make sense? I am using this great service for (what I think is) a legit reason. I want to get better at my hobby, which is all it is, as I am in high school. Many of my posts regard implementing a genetic algorithm (This post, sparsearray, rank an array, pointer manipulation). I am using a sparse array representation, as it is possible to exceed the number of molecules in the universe using a traditional (dense) array. For now, the implementation of the sparsearray itself doesnt matter a whole lot, as I am working to make it work with a standard array before going to a sparse representation. For those who havent seen my previous questions, I am using a binary search tree as the structure to contain the sparse array points, and a "driver" function to traverse the tree as necessary, returning whatever the function is designed to do. This is flexible, so I can accomodate a lot of different methods of accessing the array. The structure is a hypercube, and the number of dimensions is specified at run time, as well as the length of each dimension (which are all the same, as it is a hypercube). Thanks everyone for your imput. A: @Jeff I actually think this is an interesting question. I'm not sure how useful it is, but it is a valid question. @Ed Can you provide a little more info on this question? You said the dimension of the array is dynamic, but is the number of elements dynamic as well? EDIT: I'm going to try and answer the question anyways. I can't give you the code off the top of my head (it would take a while to get it right without any compiler here on this PC), but I can point you in the right direction ... Let's use 8 dimensions (0-7) with indexes 0 to 3 as an example. You care about only 1,2 and 6. This means you have two arrays. First, array_care[4][4][4] for 1,2, and 6. The array_care[4][4][4] will hold the end result. Next, we want to iterate in a very specific way. We have the array input[4][4][4][4][4][4][4][4] to parse through, and we care about dimensions 1, 2, and 6. We need to define some temporary indexes: int dim[8] = {0,0,0,0,0,0,0,0}; We also need to store the order in which we want to increase the indexes: int increase_index_order[8] = {7,5,4,3,0,6,2,1}; int i = 0; This order is important for doing what you requested. Define a termination flag: bool terminate=false; Now we can create our loop: while (terminate) { array_care[dim[1]][dim[2]][dim[6]] += input[dim[0]][dim[1]][dim[2]][dim[3]][dim[4]][dim[5]][dim[6]][dim[7]]; while ((dim[increase_index_order[i]] = 3) && (i < 8)) { dim[increase_index_order[i]]=0; i++; } if (i < 8) { dim[increase_index_order[i]]++; i=0; } else { terminate=true; } } That should work for 8 dimensions, caring about 3 dimensions. It would take a bit more time to make it dynamic, and I don't have the time. Hope this helps. I apologize, but I haven't learned the code markups yet. :( A: This kind of thing is much easier if you use STL containers, or maybe Boost.MultiArray. But if you must use an array: #include <iostream> #include <boost/foreach.hpp> #include <vector> int sum(int x) { return x; } template <class T, unsigned N> int sum(const T (&x)[N]) { int r = 0; for(int i = 0; i < N; ++i) { r += sum(x[i]); } return r; } template <class T, unsigned N> std::vector<int> reduce(const T (&x)[N]) { std::vector<int> result; for(int i = 0; i < N; ++i) { result.push_back(sum(x[i])); } return result; } int main() { int x[][2][2] = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }; BOOST_FOREACH(int v, reduce(x)) { std::cout<<v<<"\n"; } } A: This could have applications. Lets say you implemented a 2D Conway's Game of Life (which defines a 2D plane, 1 for 'alive', 0 for 'dead') and you stored the Games history for every iteration (which then defines a 3D cube). If you wanted to know how many bacteria there was alive over history, you would use the above algorithm. You could use the same algorithm for a 3D, (and 4D, 5D etc.) version of Game of Life grid. I'd say this was a question for recursion, I'm not yet a C programmer but I know it is possible in C. In python, def iter_arr(array): sum = 0 for i in array: if type(i) == type(list()): sum = sum + iter_arr(i) else: sum = sum + i return sum Iterate over each element in array If element is another array, call the function again If element is not array, add it to the sum Return sum You would then apply this to each element in the 'cared about' dimension. This is easier in python due to duck-typing though ... A: Actually, by colllapsing the colums you already summed them, so the dimension doesn't matter at all for your example. Did I miss something or did you? A: I think the best thing to do here would be one/both of two things: Rethink the design, if its too complex, find a less-complex way. Stop trying to visualise it.. :P Just store the dimensions in question that you need to sum, then do them one at a time. Once you have the base code, then look at improving the efficiency of your algorithm. A: I beg to differ, there is ALWAYS another way.. And if you really cannot refactor, then you need to break the problem down into smaller parts.. Like I said, establish which dimensions you need to sum, then hit them one at a time.. Also, stop changing the edits, they are correcting your spelling errors, they are trying to help you ;) A: When you say you don't know how many dimensions there are, how exactly are you defining the data structures? At some point, someone needs to create this array, and to do that, they need to know the dimensions of the array. You can force the creator to pass in this data along with the array. Unless the question is to define such a data structure... A: You're doing this in c/c++... so you have an array of array of array... you don't have to visualize 20 dimensions since that isn't how the data is laid out in memory, for a 2 dimensional: [1] --> [1,2,3,4,5,6,...] [2] --> [1,2,3,4,5,6,...] [3] --> [1,2,3,4,5,6,...] [4] --> [1,2,3,4,5,6,...] [5] --> [1,2,3,4,5,6,...] . . . . . . so, why can't you iterate across the first one summing it's contents? If you are trying to find the size, then sizeof(array)/sizeof(int) is a risky approach. You must know the dimension to be able to process this data, and set the memory up, so you know the depth of recursion to sum. Here is some pseudo code of what it seems you should do, sum( n_matrix, depth ) running_total = 0 if depth = 0 then foreach element in the array running_total += elm else foreach element in the array running_total += sum( elm , depth-1 ) return running_total A: x = number_of_dimensions; while (x > 1) { switch (x) { case 20: reduce20DimensionArray(); x--; break; case 19: ..... } } (Sorry, couldn't resist.) A: If I understand correctly, you want to sum all values in the cross section defined at each "bin" along 1 dimension. I suggest making a 1D array for your destination, then looping through each element in your array adding the value to the destination with the index of the dimension of interest. If you are using arbitrary number of dimensions, you must have a way of addressing elements (I would be curious how you are implementing this). Your implementation of this will affect how you set the destination index. But an obvious way would be with if statements checked in the iteration loops.
How Does One Sum Dimensions of an Array Specified at Run-Time?
I am working on a function to establish the entropy of a distribution. It uses a copula, if any are familiar with that. I need to sum up the values in the array based on which dimensions are "cared about." Example: Consider the following example... Dimension 0 (across) _ _ _ _ _ _ _ _ _ _ _ _ _ |_ 0 _|_ 0 _|_ 0 _|_ 2 _| Dimension 1 |_ 1 _|_ 0 _|_ 2 _|_ 0 _| (down) |_ 0 _|_ 3 _|_ 0 _|_ 6 _| |_ 0 _|_ 0 _|_ 0 _|_ 0 _| I "care about" dimension 0 only, and "don't care" about the rest (dim 1). Summing this array with the above specifications will "collapse" the "stacks" of dimension 1 down to a single 4 x 1 array: _ _ _ _ _ _ _ _ _ _ _ _ _ |_ 1 _|_ 3 _|_ 2 _|_ 8 _| This can then be summed, or have any operation performed. I need to do this with an array of 'n' dimensions, which could feasibly be 20. Also, I need to be able to do this, caring about certain dimensions, and collapsing the rest. I am having an especially hard time with this because I cant visualize 20 dimensions :p . If anyone could help me set up some c/c++ code to collapse/sum, I would be very very grateful. Update: Just got home. Here is some info to answer your questions: Sorry for rolling back the edits, I was hoping when I clicked roll-back it would show me the changes so I could see what I messed up, a bit like wikipedia. This wasn't the case, as I found out. @jeff - What doesnt make sense? I am using this great service for (what I think is) a legit reason. I want to get better at my hobby, which is all it is, as I am in high school. Many of my posts regard implementing a genetic algorithm (This post, sparsearray, rank an array, pointer manipulation). I am using a sparse array representation, as it is possible to exceed the number of molecules in the universe using a traditional (dense) array. For now, the implementation of the sparsearray itself doesnt matter a whole lot, as I am working to make it work with a standard array before going to a sparse representation. For those who havent seen my previous questions, I am using a binary search tree as the structure to contain the sparse array points, and a "driver" function to traverse the tree as necessary, returning whatever the function is designed to do. This is flexible, so I can accomodate a lot of different methods of accessing the array. The structure is a hypercube, and the number of dimensions is specified at run time, as well as the length of each dimension (which are all the same, as it is a hypercube). Thanks everyone for your imput.
[ "@Jeff\nI actually think this is an interesting question. I'm not sure how useful it is, but it is a valid question.\n@Ed\nCan you provide a little more info on this question? You said the dimension of the array is dynamic, but is the number of elements dynamic as well?\nEDIT: I'm going to try and answer the question anyways. I can't give you the code off the top of my head (it would take a while to get it right without any compiler here on this PC), but I can point you in the right direction ...\nLet's use 8 dimensions (0-7) with indexes 0 to 3 as an example. You care about only 1,2 and 6. This means you have two arrays. First, array_care[4][4][4] for 1,2, and 6. The array_care[4][4][4] will hold the end result.\nNext, we want to iterate in a very specific way. We have the array input[4][4][4][4][4][4][4][4] to parse through, and we care about dimensions 1, 2, and 6.\nWe need to define some temporary indexes:\nint dim[8] = {0,0,0,0,0,0,0,0};\n\nWe also need to store the order in which we want to increase the indexes:\nint increase_index_order[8] = {7,5,4,3,0,6,2,1};\nint i = 0;\n\nThis order is important for doing what you requested.\nDefine a termination flag:\nbool terminate=false;\n\nNow we can create our loop:\nwhile (terminate)\n{\narray_care[dim[1]][dim[2]][dim[6]] += input[dim[0]][dim[1]][dim[2]][dim[3]][dim[4]][dim[5]][dim[6]][dim[7]];\n\nwhile ((dim[increase_index_order[i]] = 3) && (i < 8))\n{\ndim[increase_index_order[i]]=0;\ni++;\n}\n\nif (i < 8) {\ndim[increase_index_order[i]]++; i=0;\n} else {\nterminate=true;\n}\n}\n\nThat should work for 8 dimensions, caring about 3 dimensions. It would take a bit more time to make it dynamic, and I don't have the time. Hope this helps. I apologize, but I haven't learned the code markups yet. :(\n", "This kind of thing is much easier if you use STL containers, or maybe Boost.MultiArray. But if you must use an array:\n#include <iostream>\n#include <boost/foreach.hpp>\n#include <vector>\n\nint sum(int x) {\n return x;\n}\n\ntemplate <class T, unsigned N>\nint sum(const T (&x)[N]) {\n int r = 0;\n for(int i = 0; i < N; ++i) {\n r += sum(x[i]);\n }\n return r;\n}\n\ntemplate <class T, unsigned N>\nstd::vector<int> reduce(const T (&x)[N]) {\n std::vector<int> result;\n for(int i = 0; i < N; ++i) {\n result.push_back(sum(x[i]));\n }\n return result;\n}\n\nint main() {\n int x[][2][2] = {\n { { 1, 2 }, { 3, 4 } },\n { { 5, 6 }, { 7, 8 } }\n };\n\n BOOST_FOREACH(int v, reduce(x)) {\n std::cout<<v<<\"\\n\";\n }\n}\n\n", "This could have applications. Lets say you implemented a 2D Conway's Game of Life (which defines a 2D plane, 1 for 'alive', 0 for 'dead') and you stored the Games history for every iteration (which then defines a 3D cube). If you wanted to know how many bacteria there was alive over history, you would use the above algorithm. You could use the same algorithm for a 3D, (and 4D, 5D etc.) version of Game of Life grid.\nI'd say this was a question for recursion, I'm not yet a C programmer but I know it is possible in C. In python,\n\ndef iter_arr(array):\n sum = 0\n for i in array:\n if type(i) == type(list()):\n sum = sum + iter_arr(i)\n else:\n sum = sum + i\n return sum \n\n\nIterate over each element in array\nIf element is another array, call the function again\nIf element is not array, add it to the sum\nReturn sum\n\nYou would then apply this to each element in the 'cared about' dimension.\nThis is easier in python due to duck-typing though ...\n", "Actually, by colllapsing the colums you already summed them, so the dimension doesn't matter at all for your example. Did I miss something or did you?\n", "I think the best thing to do here would be one/both of two things:\n\nRethink the design, if its too complex, find a less-complex way.\nStop trying to visualise it.. :P Just store the dimensions in question that you need to sum, then do them one at a time. Once you have the base code, then look at improving the efficiency of your algorithm.\n\n", "I beg to differ, there is ALWAYS another way..\nAnd if you really cannot refactor, then you need to break the problem down into smaller parts.. Like I said, establish which dimensions you need to sum, then hit them one at a time..\nAlso, stop changing the edits, they are correcting your spelling errors, they are trying to help you ;)\n", "When you say you don't know how many dimensions there are, how exactly are you defining the data structures?\nAt some point, someone needs to create this array, and to do that, they need to know the dimensions of the array. You can force the creator to pass in this data along with the array.\nUnless the question is to define such a data structure...\n", "You're doing this in c/c++... so you have an array of array of array... you don't have to visualize 20 dimensions since that isn't how the data is laid out in memory, for a 2 dimensional:\n[1] --> [1,2,3,4,5,6,...]\n[2] --> [1,2,3,4,5,6,...]\n[3] --> [1,2,3,4,5,6,...]\n[4] --> [1,2,3,4,5,6,...]\n[5] --> [1,2,3,4,5,6,...]\n . .\n . .\n . .\n\nso, why can't you iterate across the first one summing it's contents? If you are trying to find the size, then sizeof(array)/sizeof(int) is a risky approach. You must know the dimension to be able to process this data, and set the memory up, so you know the depth of recursion to sum. Here is some pseudo code of what it seems you should do, \nsum( n_matrix, depth )\n running_total = 0\n if depth = 0 then\n foreach element in the array\n running_total += elm\n else \n foreach element in the array\n running_total += sum( elm , depth-1 )\n return running_total\n\n", "x = number_of_dimensions;\nwhile (x > 1)\n{\n switch (x)\n {\n case 20:\n reduce20DimensionArray();\n x--;\n break;\n case 19:\n .....\n }\n}\n\n(Sorry, couldn't resist.)\n", "If I understand correctly, you want to sum all values in the cross section defined at each \"bin\" along 1 dimension. I suggest making a 1D array for your destination, then looping through each element in your array adding the value to the destination with the index of the dimension of interest.\nIf you are using arbitrary number of dimensions, you must have a way of addressing elements (I would be curious how you are implementing this). Your implementation of this will affect how you set the destination index. But an obvious way would be with if statements checked in the iteration loops.\n" ]
[ 2, 2, 2, 0, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "arrays", "c", "c++", "microsoft_dynamics" ]
stackoverflow_0000023190_arrays_c_c++_microsoft_dynamics.txt
Q: Implementing a custom Windows Workflow activity that executes an asynchronous operation I'm having some conceptual trouble on figuring out how to best implement this... I want to create a custom Activity class for Windows Workflow. The activity has to call out to a third party library method that itself runs another process asynchronously and may take anywhere from seconds to many hours to complete. This library offers the ability for me to either poll for the method result or to subscribe to an event that indicates its completion. In my non-workflow apps, I typically just subscribe to that event, but that doesn't seem to be reasonable in the workflow case. I'm also not sure exactly how to best implement a polling scheme. Can someone recommend some pointers to similar problems? A: Kirk Allen Evans wrote an interesting blog about this with some pretty good code examples.
Implementing a custom Windows Workflow activity that executes an asynchronous operation
I'm having some conceptual trouble on figuring out how to best implement this... I want to create a custom Activity class for Windows Workflow. The activity has to call out to a third party library method that itself runs another process asynchronously and may take anywhere from seconds to many hours to complete. This library offers the ability for me to either poll for the method result or to subscribe to an event that indicates its completion. In my non-workflow apps, I typically just subscribe to that event, but that doesn't seem to be reasonable in the workflow case. I'm also not sure exactly how to best implement a polling scheme. Can someone recommend some pointers to similar problems?
[ "Kirk Allen Evans wrote an interesting blog about this with some pretty good code examples. \n" ]
[ 1 ]
[]
[]
[ "asynchronous", "workflow", "workflow_activity", "workflow_foundation" ]
stackoverflow_0000024823_asynchronous_workflow_workflow_activity_workflow_foundation.txt
Q: How Do You Communicate Service Layer Messages/Errors to Higher Layers Using MVP? I'm currently writing an ASP.Net app from the UI down. I'm implementing an MVP architecture because I'm sick of Winforms and wanted something that had a better separation of concerns. So with MVP, the Presenter handles events raised by the View. Here's some code that I have in place to deal with the creation of users: public class CreateMemberPresenter { private ICreateMemberView view; private IMemberTasks tasks; public CreateMemberPresenter(ICreateMemberView view) : this(view, new StubMemberTasks()) { } public CreateMemberPresenter(ICreateMemberView view, IMemberTasks tasks) { this.view = view; this.tasks = tasks; HookupEventHandlersTo(view); } private void HookupEventHandlersTo(ICreateMemberView view) { view.CreateMember += delegate { CreateMember(); }; } private void CreateMember() { if (!view.IsValid) return; try { int newUserId; tasks.CreateMember(view.NewMember, out newUserId); view.NewUserCode = newUserId; view.Notify(new NotificationDTO() { Type = NotificationType.Success }); } catch(Exception e) { this.LogA().Message(string.Format("Error Creating User: {0}", e.Message)); view.Notify(new NotificationDTO() { Type = NotificationType.Failure, Message = "There was an error creating a new member" }); } } } I have my main form validation done using the built in .Net Validation Controls, but now I need to verify that the data sufficiently satisfies the criteria for the Service Layer. Let's say the following Service Layer messages can show up: E-mail account already exists (failure) Refering user entered does not exist (failure) Password length exceeds datastore allowed length (failure) Member created successfully (success) Let's also say that more rules will be in the service layer that the UI cannot anticipate. Currently I'm having the service layer throw an exception if things didn't go as planned. Is that a sufficent strategy? Does this code smell to you guys? If I wrote a service layer like this would you be annoyed at having to write Presenters that use it in this way? Return codes seem too old school and a bool is just not informative enough. Edit not by OP: merging in follow-up comments that were posted as answers by the OP Cheekysoft, I like the concept of a ServiceLayerException. I already have a global exception module for the exceptions that I don't anticipate. Do you find making all these custom exceptions tedious? I was thinking that catching base Exception class was a bit smelly but wasn't exactly sure how progress from there. tgmdbm, I like the clever use of the lambda expression there! Thanks Cheekysoft for the follow-up. So I'm guessing that would be the strategy if you don't mind the user being displayed a separate page (I'm primarily a web developer) if the Exception is not handled. However, if I want to return the error message in the same view where the user submitted the data that caused the error, I would then have to catch the Exception in the Presenter? Here's what the CreateUserView looks like when the Presenter has handled the ServiceLayerException: For this kind of error, it's nice to report it to the same view. Anyways, I think we're going beyond the scope of my original question now. I'll play around with what you've posted and if I need further details I'll post a new question. A: That sounds just right to me. Exceptions are preferable as they can be thrown up to the top of the service layer from anywhere inside the service layer, no matter how deeply nested inside the service method implementation it is. This keeps the service code clean as you know the calling presenter will always get notification of the problem. Don't catch Exception However, don't catch Exception in the presenter, I know its tempting because it keeps the code shorter, but you need to catch specific exceptions to avoid catching the system-level exceptions. Plan a Simple Exception Hierarchy If you are going to use exceptions in this way, you should design an exception hierarchy for your own exception classes. At a minumum create a ServiceLayerException class and throw one of these in your service methods when a problem occurs. Then if you need to throw an exception that should/could be handled differently by the presenter, you can throw a specific subclass of ServiceLayerException: say, AccountAlreadyExistsException. Your presenter then has the option of doing try { // call service etc. // handle success to view } catch (AccountAlreadyExistsException) { // set the message and some other unique data in the view } catch (ServiceLayerException) { // set the message in the view } // system exceptions, and unrecoverable exceptions are allowed to bubble // up the call stack so a general error can be shown to the user, rather // than showing the form again. Using inheritance in your own exception classes means you are not required to catch multipile exceptions in your presenter -- you can if there's a need to -- and you don't end up accidentally catching exceptions you can't handle. If your presenter is already at the top of the call stack, add a catch( Exception ) block to handle the system errors with a different view. I always try and think of my service layer as a seperate distributable library, and throw as specific an exception as makes sense. It is then up to the presenter/controller/remote-service implementation to decide if it needs to worry about the specific details or just to treat problems as a generic error. A: As Cheekysoft suggests, I would tend to move all major exceptions into an ExceptionHandler and let those exceptions bubble up. The ExceptionHandler would render the appropriate view for the type of exception. Any validation exceptions however should be handled in the view but typically this logic is common to many parts of your application. So I like to have a helper like this public static class Try { public static List<string> This( Action action ) { var errors = new List<string>(); try { action(); } catch ( SpecificException e ) { errors.Add( "Something went 'orribly wrong" ); } catch ( ... ) // ... return errors; } } Then when calling your service just do the following var errors = Try.This( () => { // call your service here tasks.CreateMember( ... ); } ); Then in errors is empty, you're good to go. You can take this further and extend it with custome exception handlers which handle uncommon exceptions. A: In reply to the follow-up question: As for creating exceptions becoming tedious, you kinda get used to it. Use of a good code generator or template can create the exception class with minimal hand editing within about 5 or 10 seconds. However, in many real world applications, error handling can be 70% of the work, so it's all just part of the game really. As tgmdbm suggests, in MVC/MVP applications I let all my unhandlable exceptions bubble up to the top and get caught by the dispatcher which delegates to an ExceptionHandler. I set it up so that it uses an ExceptionResolver that looks in the config file to choose an appropriate view to show the user. Java's Spring MVC library does this very well. Here's a snippet from a config file for Spring MVC's Exception resolver - its for Java/Spring but you'll get the idea. This takes a huge amount of exception handling out of your presenters/controllers altogether. <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <prop key="UserNotFoundException"> rescues/UserNotFound </prop> <prop key="HibernateJdbcException"> rescues/databaseProblem </prop> <prop key="java.net.ConnectException"> rescues/networkTimeout </prop> <prop key="ValidationException"> rescues/validationError </prop> <prop key="EnvironmentNotConfiguredException"> rescues/environmentNotConfigured </prop> <prop key="MessageRejectedPleaseRetryException"> rescues/messageRejected </prop> </props> </property> <property name="defaultErrorView" value="rescues/general" /> </bean>
How Do You Communicate Service Layer Messages/Errors to Higher Layers Using MVP?
I'm currently writing an ASP.Net app from the UI down. I'm implementing an MVP architecture because I'm sick of Winforms and wanted something that had a better separation of concerns. So with MVP, the Presenter handles events raised by the View. Here's some code that I have in place to deal with the creation of users: public class CreateMemberPresenter { private ICreateMemberView view; private IMemberTasks tasks; public CreateMemberPresenter(ICreateMemberView view) : this(view, new StubMemberTasks()) { } public CreateMemberPresenter(ICreateMemberView view, IMemberTasks tasks) { this.view = view; this.tasks = tasks; HookupEventHandlersTo(view); } private void HookupEventHandlersTo(ICreateMemberView view) { view.CreateMember += delegate { CreateMember(); }; } private void CreateMember() { if (!view.IsValid) return; try { int newUserId; tasks.CreateMember(view.NewMember, out newUserId); view.NewUserCode = newUserId; view.Notify(new NotificationDTO() { Type = NotificationType.Success }); } catch(Exception e) { this.LogA().Message(string.Format("Error Creating User: {0}", e.Message)); view.Notify(new NotificationDTO() { Type = NotificationType.Failure, Message = "There was an error creating a new member" }); } } } I have my main form validation done using the built in .Net Validation Controls, but now I need to verify that the data sufficiently satisfies the criteria for the Service Layer. Let's say the following Service Layer messages can show up: E-mail account already exists (failure) Refering user entered does not exist (failure) Password length exceeds datastore allowed length (failure) Member created successfully (success) Let's also say that more rules will be in the service layer that the UI cannot anticipate. Currently I'm having the service layer throw an exception if things didn't go as planned. Is that a sufficent strategy? Does this code smell to you guys? If I wrote a service layer like this would you be annoyed at having to write Presenters that use it in this way? Return codes seem too old school and a bool is just not informative enough. Edit not by OP: merging in follow-up comments that were posted as answers by the OP Cheekysoft, I like the concept of a ServiceLayerException. I already have a global exception module for the exceptions that I don't anticipate. Do you find making all these custom exceptions tedious? I was thinking that catching base Exception class was a bit smelly but wasn't exactly sure how progress from there. tgmdbm, I like the clever use of the lambda expression there! Thanks Cheekysoft for the follow-up. So I'm guessing that would be the strategy if you don't mind the user being displayed a separate page (I'm primarily a web developer) if the Exception is not handled. However, if I want to return the error message in the same view where the user submitted the data that caused the error, I would then have to catch the Exception in the Presenter? Here's what the CreateUserView looks like when the Presenter has handled the ServiceLayerException: For this kind of error, it's nice to report it to the same view. Anyways, I think we're going beyond the scope of my original question now. I'll play around with what you've posted and if I need further details I'll post a new question.
[ "That sounds just right to me. Exceptions are preferable as they can be thrown up to the top of the service layer from anywhere inside the service layer, no matter how deeply nested inside the service method implementation it is. This keeps the service code clean as you know the calling presenter will always get notification of the problem.\nDon't catch Exception\nHowever, don't catch Exception in the presenter, I know its tempting because it keeps the code shorter, but you need to catch specific exceptions to avoid catching the system-level exceptions. \nPlan a Simple Exception Hierarchy\nIf you are going to use exceptions in this way, you should design an exception hierarchy for your own exception classes. \nAt a minumum create a ServiceLayerException class and throw one of these in your service methods when a problem occurs. Then if you need to throw an exception that should/could be handled differently by the presenter, you can throw a specific subclass of ServiceLayerException: say, AccountAlreadyExistsException.\nYour presenter then has the option of doing\ntry {\n // call service etc.\n // handle success to view\n} \ncatch (AccountAlreadyExistsException) {\n // set the message and some other unique data in the view\n}\ncatch (ServiceLayerException) {\n // set the message in the view\n}\n// system exceptions, and unrecoverable exceptions are allowed to bubble \n// up the call stack so a general error can be shown to the user, rather \n// than showing the form again.\n\nUsing inheritance in your own exception classes means you are not required to catch multipile exceptions in your presenter -- you can if there's a need to -- and you don't end up accidentally catching exceptions you can't handle. If your presenter is already at the top of the call stack, add a catch( Exception ) block to handle the system errors with a different view.\nI always try and think of my service layer as a seperate distributable library, and throw as specific an exception as makes sense. It is then up to the presenter/controller/remote-service implementation to decide if it needs to worry about the specific details or just to treat problems as a generic error.\n", "As Cheekysoft suggests, I would tend to move all major exceptions into an ExceptionHandler and let those exceptions bubble up. The ExceptionHandler would render the appropriate view for the type of exception. \nAny validation exceptions however should be handled in the view but typically this logic is common to many parts of your application. So I like to have a helper like this\npublic static class Try {\n public static List<string> This( Action action ) {\n var errors = new List<string>();\n try {\n action();\n }\n catch ( SpecificException e ) {\n errors.Add( \"Something went 'orribly wrong\" );\n }\n catch ( ... )\n // ...\n return errors;\n }\n}\n\nThen when calling your service just do the following\nvar errors = Try.This( () => {\n // call your service here\n tasks.CreateMember( ... );\n} );\n\nThen in errors is empty, you're good to go.\nYou can take this further and extend it with custome exception handlers which handle uncommon exceptions.\n", "In reply to the follow-up question:\nAs for creating exceptions becoming tedious, you kinda get used to it. Use of a good code generator or template can create the exception class with minimal hand editing within about 5 or 10 seconds. \nHowever, in many real world applications, error handling can be 70% of the work, so it's all just part of the game really. \nAs tgmdbm suggests, in MVC/MVP applications I let all my unhandlable exceptions bubble up to the top and get caught by the dispatcher which delegates to an ExceptionHandler. I set it up so that it uses an ExceptionResolver that looks in the config file to choose an appropriate view to show the user. Java's Spring MVC library does this very well. Here's a snippet from a config file for Spring MVC's Exception resolver - its for Java/Spring but you'll get the idea.\nThis takes a huge amount of exception handling out of your presenters/controllers altogether.\n<bean id=\"exceptionResolver\"\n class=\"org.springframework.web.servlet.handler.SimpleMappingExceptionResolver\">\n\n <property name=\"exceptionMappings\">\n <props>\n <prop key=\"UserNotFoundException\">\n rescues/UserNotFound\n </prop>\n <prop key=\"HibernateJdbcException\">\n rescues/databaseProblem\n </prop>\n <prop key=\"java.net.ConnectException\">\n rescues/networkTimeout\n </prop>\n <prop key=\"ValidationException\">\n rescues/validationError\n </prop>\n <prop key=\"EnvironmentNotConfiguredException\">\n rescues/environmentNotConfigured\n </prop>\n <prop key=\"MessageRejectedPleaseRetryException\">\n rescues/messageRejected\n </prop>\n </props>\n </property>\n <property name=\"defaultErrorView\" value=\"rescues/general\" />\n</bean>\n\n" ]
[ 15, 3, 1 ]
[]
[]
[ "asp.net", "c#", "exception", "mvp", "n_tier_architecture" ]
stackoverflow_0000021697_asp.net_c#_exception_mvp_n_tier_architecture.txt
Q: Is it "bad practice" to be sensitive to linebreaks in XML documents? I'm generating some XML documents and when it comes to the address part I have fragments that look like this: <Address>15 Sample St Example Bay Some Country</Address> The XSLT that I have for converting this to XHTML has some funky recursive template to convert newline characters within strings to <br/> tags. This is all working fine; but is it considered "bad practice" to rely on linebreaks within XML documents? If so, is it recommended that I do this instead? <Address><Line>15 Sample St</Line> <Line>Example Bay</Line> <Line>Some Country</Line></Address> Seems like it'd be really awkward to wrap every place where my text may be multiple lines with tags like that.. A: It's generally considered bad practice to rely on linebreaks, since it's a fragile way to differentiate data. While most XML processors will preserve any whitespace you put in your XML, it's not guaranteed. The real problem is that most applications that output your XML into a readable format consider all whitespace in an XML interchangable, and might collapse those linebreaks into a single space. That's why your XSLT has to jump through such hoops to render the data properly. Using a "br" tag would vastly simplify the transform. Another potential problem is that if you open up your XML document in an XML editor and pretty-print it, you're likely to lose those line breaks. If you do keep using linebreaks, make sure add an xml:space="preserve" attribute to "address." (You can do this in your DTD, if you're using one.) Some suggested reading An article from XML.com says the following: XML applications often seem to take a cavalier attitude toward whitespace because the rules about the places in an XML document where whitespace doesn't matter sometimes give these applications free rein to add or remove whitespace in certain places. A collection of XSL-list posts regarding whitespace. A: What about using attributes to store the data, rather than text nodes: <Address Street="15 Sample St" City="Example Bay" State="" Country="Some Country"/> I know the use of attributes vs. text nodes is an often debated subject, but I've stuck with attributes 95% of the time, and haven't had any troubles because of it. A: Few people have said that CDATA blocks will allow you to retain line breaks. This is wrong. CDATA sections will only make markup be processed as character data, they will not change line break processing. <Address>15 Sample St Example Bay Some Country</Address> is exactly the same as <Address><![CDATA[15 Sample St Example Bay Some Country]]></Address> The only difference is how different APIs report this. A: I think the only real problem is that it makes the XML harder to read. e.g. <Something> <Contains> <An> <Address>15 Sample St Example Bay Some Country</Address> </An> </Contains> </Something> If pretty XML isn't a concern, I'd probably not worry about it, so long as it's working. If pretty XML is a concern, I'd convert the explicit newlines into <br /> tags or \n before embedding them in the XML. A: It depends on how you're reading and writing the XML. If XML is being generated automatically - if newlines or explicit \n flags are being parsed into - then there's nothing to worry about. Your input likely doesn't have any other XML in it so it's just cleaner to not mess with XML at all. If tags are being worked with manually, it's still cleaner to just have a line break, if you ask me. The exception is if you're using DOM to get some structure out of the XML. In that case line breaks are obviously evil because they don't represent the heirarchy properly. It sounds like the heirarchy is irrelevant for your application, though, so line breaks sound sufficient. If the XML just looks bad (especially when automatically generated), Tidy can help, although it works better with HTML than with XML. A: This is probably a bit deceptive example, since address is a bit non-normalized in this case. It is a reasonable trade-off, however since address fields are difficult to normalize. If you make the line breaks carry important information, you're un-normalizing and making the post office interpret the meaning of the line break. I would say that normally this is not a big problem, but in this case I think the Line tag is most correct since it explicitly shows that you don't actually interpret what the lines may mean in different cultures. (Remember that most forms for entering an address has zip code etc, and address line 1 and 2.) The awkwardness of having the line tag comes with normal XML, and has been much debated at coding horror. http://www.codinghorror.com/blog/archives/001139.html A: The XML spec has something to say regarding whitespace and linefeeds and carriage returns in particular. So if you limit yourself to true linefeeds (x0A) you should be Ok. However, many editing tools will reformat XML for "better presentation" and possibly get rid of the special syntax. A more robust and cleaner approach than the "< line>< / line>" idea would be to simply use namespaces and embed XHTML content, e.g.: <Address xmlns="http://www.w3.org/1999/xhtml">15 Sample St<br />Example Bay<br />Some Country</Address> No need to reinvent the wheel when it comes to standard vocabularies. A: I don't see what's wrong with <Line> tags. Apparently, the visualization of the data is important to you, important enough to keep it in your data (via line breaks in your first example). Fine. Then really keep it, don't rely on "magic" to keep it for you. Keep every bit of data you'll need later on and can't deduce perfectly from the saved portion of the data, keep it even if it's visualization data (line breaks and other formatting). Your user (end user of another developer) took the time to format that data to his liking - either tell him (API doc / text near the input) that you don't intend on keeping it, or - just keep it.
Is it "bad practice" to be sensitive to linebreaks in XML documents?
I'm generating some XML documents and when it comes to the address part I have fragments that look like this: <Address>15 Sample St Example Bay Some Country</Address> The XSLT that I have for converting this to XHTML has some funky recursive template to convert newline characters within strings to <br/> tags. This is all working fine; but is it considered "bad practice" to rely on linebreaks within XML documents? If so, is it recommended that I do this instead? <Address><Line>15 Sample St</Line> <Line>Example Bay</Line> <Line>Some Country</Line></Address> Seems like it'd be really awkward to wrap every place where my text may be multiple lines with tags like that..
[ "It's generally considered bad practice to rely on linebreaks, since it's a fragile way to differentiate data. While most XML processors will preserve any whitespace you put in your XML, it's not guaranteed. \nThe real problem is that most applications that output your XML into a readable format consider all whitespace in an XML interchangable, and might collapse those linebreaks into a single space. That's why your XSLT has to jump through such hoops to render the data properly. Using a \"br\" tag would vastly simplify the transform.\nAnother potential problem is that if you open up your XML document in an XML editor and pretty-print it, you're likely to lose those line breaks. \nIf you do keep using linebreaks, make sure add an xml:space=\"preserve\" attribute to \"address.\" (You can do this in your DTD, if you're using one.)\nSome suggested reading\n\nAn article from XML.com says the following:\n\n\nXML applications often seem to take a\n cavalier attitude toward whitespace\n because the rules about the places in\n an XML document where whitespace\n doesn't matter sometimes give these\n applications free rein to add or\n remove whitespace in certain places.\n\n\nA collection of XSL-list posts regarding whitespace. \n\n", "What about using attributes to store the data, rather than text nodes:\n<Address Street=\"15 Sample St\" City=\"Example Bay\" State=\"\" Country=\"Some Country\"/>\n\nI know the use of attributes vs. text nodes is an often debated subject, but I've stuck with attributes 95% of the time, and haven't had any troubles because of it.\n", "Few people have said that CDATA blocks will allow you to retain line breaks. This is wrong. CDATA sections will only make markup be processed as character data, they will not change line break processing.\n<Address>15 Sample St\nExample Bay\nSome Country</Address>\n\nis exactly the same as\n<Address><![CDATA[15 Sample St\nExample Bay\nSome Country]]></Address>\n\nThe only difference is how different APIs report this.\n", "I think the only real problem is that it makes the XML harder to read. e.g.\n<Something>\n <Contains>\n <An>\n <Address>15 Sample St\nExample Bay\nSome Country</Address>\n </An>\n </Contains>\n</Something>\n\nIf pretty XML isn't a concern, I'd probably not worry about it, so long as it's working. If pretty XML is a concern, I'd convert the explicit newlines into <br /> tags or \\n before embedding them in the XML.\n", "It depends on how you're reading and writing the XML.\nIf XML is being generated automatically - if newlines or explicit \\n flags are being parsed into - then there's nothing to worry about. Your input likely doesn't have any other XML in it so it's just cleaner to not mess with XML at all.\nIf tags are being worked with manually, it's still cleaner to just have a line break, if you ask me.\nThe exception is if you're using DOM to get some structure out of the XML. In that case line breaks are obviously evil because they don't represent the heirarchy properly. It sounds like the heirarchy is irrelevant for your application, though, so line breaks sound sufficient.\nIf the XML just looks bad (especially when automatically generated), Tidy can help, although it works better with HTML than with XML.\n", "This is probably a bit deceptive example, since address is a bit non-normalized in this case. It is a reasonable trade-off, however since address fields are difficult to normalize.\nIf you make the line breaks carry important information, you're un-normalizing and making the post office interpret the meaning of the line break.\nI would say that normally this is not a big problem, but in this case I think the Line tag is most correct since it explicitly shows that you don't actually interpret what the lines may mean in different cultures. (Remember that most forms for entering an address has zip code etc, and address line 1 and 2.)\nThe awkwardness of having the line tag comes with normal XML, and has been much debated at coding horror. http://www.codinghorror.com/blog/archives/001139.html\n", "The XML spec has something to say regarding whitespace and linefeeds and carriage returns in particular. So if you limit yourself to true linefeeds (x0A) you should be Ok. However, many editing tools will reformat XML for \"better presentation\" and possibly get rid of the special syntax. A more robust and cleaner approach than the \"< line>< / line>\" idea would be to simply use namespaces and embed XHTML content, e.g.:\n<Address xmlns=\"http://www.w3.org/1999/xhtml\">15 Sample St<br />Example Bay<br />Some Country</Address>\n\nNo need to reinvent the wheel when it comes to standard vocabularies.\n", "I don't see what's wrong with <Line> tags.\nApparently, the visualization of the data is important to you, important enough to keep it in your data (via line breaks in your first example). Fine. Then really keep it, don't rely on \"magic\" to keep it for you. Keep every bit of data you'll need later on and can't deduce perfectly from the saved portion of the data, keep it even if it's visualization data (line breaks and other formatting). Your user (end user of another developer) took the time to format that data to his liking - either tell him (API doc / text near the input) that you don't intend on keeping it, or - just keep it.\n" ]
[ 9, 3, 3, 2, 1, 1, 1, 0 ]
[ "Yes, I think using a CDATA block would protect the whitespace. Although some parser APIs allow you to preserve whitespace.\n", "What you really should be doing is converting your XML to a format that preserves white-space.\nSo rather than seek to replace \\n with <br /> you should wrap the whole block in a <pre>\nThat way, your address is functionally preserved (whether you include line breaks or not) and the XSTL can choose whether to preserve white-space in the result.\n", "I recommend you should either add the <br/> line breaks or maybe use line-break entity - &#x000D;\n", "If you need your linebreaks preserved, use a CDATA block, as tweakt said\nOtherwise beware. Most of the time, the linebreaks will be preserved by XML software, but sometimes they won't, and you really don't want to be relying on things which only work by coincidence\n" ]
[ -1, -1, -1, -2 ]
[ "line_breaks", "whitespace", "xhtml", "xml", "xslt" ]
stackoverflow_0000007277_line_breaks_whitespace_xhtml_xml_xslt.txt
Q: Where can I find extended HTML reporters for Simpletest? I am using Simpletest as my unit test framework for the PHP site I am currently working on. I like the fact that it is shipped with a simple HTML reporter, but I would like a bit more advanced reporter. I have read the reporter API documentation, but it would be nice to be able to use an existing reporter, instead of having to do it yourself. Are there any good extended HTML reporters or GUI's out there for Simpletest? Tips on GUI's for PHPUnit would also be appreciated, but my main focus is Simpletest, for this project. I have tried Cool PHPUnit Test Runner, but was not convinced. A: For SimpleTest I can't say I've ever found any "better" test reporters, so you may have to just buckle down and hack together some quick HTML/PHP for what you need. As for PHPUnit, there's PHPUnit2_HTML_Runner, but it is far from ideal. However, if you're willing to set up a continuous integration server like Xinc or phpUnderControl you can get two very nice, very detailed automated testing interfaces. A: Does SimpleTest output JUnit XML style reports? If it does, you should be able to integrate it into CruiseControl or Bamboo.
Where can I find extended HTML reporters for Simpletest?
I am using Simpletest as my unit test framework for the PHP site I am currently working on. I like the fact that it is shipped with a simple HTML reporter, but I would like a bit more advanced reporter. I have read the reporter API documentation, but it would be nice to be able to use an existing reporter, instead of having to do it yourself. Are there any good extended HTML reporters or GUI's out there for Simpletest? Tips on GUI's for PHPUnit would also be appreciated, but my main focus is Simpletest, for this project. I have tried Cool PHPUnit Test Runner, but was not convinced.
[ "For SimpleTest I can't say I've ever found any \"better\" test reporters, so you may have to just buckle down and hack together some quick HTML/PHP for what you need.\nAs for PHPUnit, there's PHPUnit2_HTML_Runner, but it is far from ideal. However, if you're willing to set up a continuous integration server like Xinc or phpUnderControl you can get two very nice, very detailed automated testing interfaces.\n", "Does SimpleTest output JUnit XML style reports? If it does, you should be able to integrate it into CruiseControl or Bamboo.\n" ]
[ 1, 1 ]
[]
[]
[ "php", "simpletest", "unit_testing", "user_interface" ]
stackoverflow_0000024941_php_simpletest_unit_testing_user_interface.txt
Q: Are named entities in HTML still necessary in the age of Unicode aware browsers? I did a lot of PHP programming in the last years and one thing that keeps annoying me is the weak support for Unicode and multibyte strings (to be sure, natively there is none). For example, "htmlentities" seems to be a much used function in the PHP world and I found it to be absolutely annoying when you've put an effort into keeping every string localizable, only store UTF-8 in your database, only deliver UTF-8 webpages etc. Suddenly, somewhere between your database and the browser there's this hopelessly naive function pretending every byte is a character and messes everything up. I would just love to just dump this kind of functions, they seem totally superfluous. Is it still necessary these days to write '&auml;' instead of 'ä'? At least my Firefox seems perfectly happy to display even the strangest Asian glyphs as long as they're served in a proper encoding. Update: To be more precise: Are named entities necessary for anything else than displaying HTML tags (as in "&lt;" for "<") Update 2: @Konrad: Are you saying that, no, named entities are not needed? @Ross: But wouldn't it be better to sanitize user input when it's entered, to keep my output logic free from such issues? (assuming of course, that reliable sanitizing on input is possible - but then, if it isn't, can it be on output?) A: Named entities in "real" XHTML (i.e. with application/xhtml+xml, rather than the more frequently-used text/html compatibility mode) are discouraged. Aside from the five defined in XML itself (&lt;, &gt;, &amp;, &quot;, &apos;), they'd all have to be defined in the DTD of the particular DocType you're using. That means your browser has to explicitly support that DocType, which is far from a given. Numbered entities, on the other hand, obviously only require a lookup table to get the right Unicode character. As for whether you need entities at all these days: you can pretty much expect any modern browser to support UTF-8. Therefore, as long as you can guarantee that the database, the markup and the web server all agree to serve that, ditch the entities. A: If using XHTML, it's actually recommended not to use named entities ([citation needed]). Some browsers (Firefox …), when parsing this as XML (which they normally don't), don't read the DTD files and thus are unable to handle the entities. As it's best practice anyway to use UTF-8 as encoding if there are no compelling reasons to do otherwise, this only means that the creator of the documents needs a decent editor that can not only handle the documents but also provides a good way of entering the divers glyphs. OS X doesn't really have this problem because most needed glyphs can be reached via “alt” keys but Windows doesn't have this feature. @Konrad: Are you saying that, no, named entities are not needed? Precisely. Unless, of course, there are silly restrictions, e.g. legacy database drivers that choke on UTF-8 etc. A: Safari seems to have issues with some glyphs but not others, it may not be needed but it's probably best to do so, of course, this is my opinion and not backed up by anything but my own observations.
Are named entities in HTML still necessary in the age of Unicode aware browsers?
I did a lot of PHP programming in the last years and one thing that keeps annoying me is the weak support for Unicode and multibyte strings (to be sure, natively there is none). For example, "htmlentities" seems to be a much used function in the PHP world and I found it to be absolutely annoying when you've put an effort into keeping every string localizable, only store UTF-8 in your database, only deliver UTF-8 webpages etc. Suddenly, somewhere between your database and the browser there's this hopelessly naive function pretending every byte is a character and messes everything up. I would just love to just dump this kind of functions, they seem totally superfluous. Is it still necessary these days to write '&auml;' instead of 'ä'? At least my Firefox seems perfectly happy to display even the strangest Asian glyphs as long as they're served in a proper encoding. Update: To be more precise: Are named entities necessary for anything else than displaying HTML tags (as in "&lt;" for "<") Update 2: @Konrad: Are you saying that, no, named entities are not needed? @Ross: But wouldn't it be better to sanitize user input when it's entered, to keep my output logic free from such issues? (assuming of course, that reliable sanitizing on input is possible - but then, if it isn't, can it be on output?)
[ "Named entities in \"real\" XHTML (i.e. with application/xhtml+xml, rather than the more frequently-used text/html compatibility mode) are discouraged. Aside from the five defined in XML itself (&lt;, &gt;, &amp;, &quot;, &apos;), they'd all have to be defined in the DTD of the particular DocType you're using. That means your browser has to explicitly support that DocType, which is far from a given. Numbered entities, on the other hand, obviously only require a lookup table to get the right Unicode character.\nAs for whether you need entities at all these days: you can pretty much expect any modern browser to support UTF-8. Therefore, as long as you can guarantee that the database, the markup and the web server all agree to serve that, ditch the entities.\n", "If using XHTML, it's actually recommended not to use named entities ([citation needed]). Some browsers (Firefox …), when parsing this as XML (which they normally don't), don't read the DTD files and thus are unable to handle the entities.\nAs it's best practice anyway to use UTF-8 as encoding if there are no compelling reasons to do otherwise, this only means that the creator of the documents needs a decent editor that can not only handle the documents but also provides a good way of entering the divers glyphs. OS X doesn't really have this problem because most needed glyphs can be reached via “alt” keys but Windows doesn't have this feature.\n\n\n@Konrad: Are you saying that, no, named entities are not needed?\n\nPrecisely. Unless, of course, there are silly restrictions, e.g. legacy database drivers that choke on UTF-8 etc.\n", "Safari seems to have issues with some glyphs but not others, it may not be needed but it's probably best to do so, of course, this is my opinion and not backed up by anything but my own observations.\n" ]
[ 7, 3, 0 ]
[]
[]
[ "html", "internationalization", "php", "unicode" ]
stackoverflow_0000025132_html_internationalization_php_unicode.txt
Q: My VMware ESX server console volume went readonly. How can I save my VMs? Two RAID volumes, VMware kernel/console running on a RAID1, vmdks live on a RAID5. Entering a login at the console just results in SCSI errors, no password prompt. Praise be, the VMs are actually still running. We're thinking, though, that upon reboot the kernel may not start again and the VMs will be down. We have database and disk backups of the VMs, but not backups of the vmdks themselves. What are my options? Our current best idea is Use VMware Converter to create live vmdks from the running VMs, as if it was a P2V migration. Reboot host server and run RAID diagnostics, figure out what in the "h" happened Attempt to start ESX again, possibly after rebuilding its RAID volume Possibly have to re-install ESX on its volume and re-attach VMs If that doesn't work, attach the "live" vmdks created in step 1 to a different VM host. A: It was the backplane. Both drives of the RAID1 and one drive of the RAID5 were inaccessible. Incredibly, the VMware hypervisor continued to run for three days from memory with no access to its host disk, keeping the VMs it managed alive. At step 3 above we diagnosed the hardware problem and replaced the RAID controller, cables, and backplane. After restart, we re-initialized the RAID by instructing the controller to query the drives for their configurations. Both were degraded and both were repaired successfully. At step 4, it was not necessary to reinstall ESX; although, at bootup, it did not want to register the VMs. We had to dig up some buried management stuff to instruct the kernel to resignature the VMs. (Search VM docs for "resignature.") I believe that our fallback plan would have worked, the VMware Converter images of the VMs that were running "orphaned" were tested and ran fine with no data loss. I highly recommend performing a VMware Converter imaging of any VM that gets into this state, after shutting down as many services as possible and getting the VM into as read-only a state as possible. Loading a vmdk either elsewhere or on the original host as a repair is usually going to be WAY faster than rebuilding a server from the ground up with backups.
My VMware ESX server console volume went readonly. How can I save my VMs?
Two RAID volumes, VMware kernel/console running on a RAID1, vmdks live on a RAID5. Entering a login at the console just results in SCSI errors, no password prompt. Praise be, the VMs are actually still running. We're thinking, though, that upon reboot the kernel may not start again and the VMs will be down. We have database and disk backups of the VMs, but not backups of the vmdks themselves. What are my options? Our current best idea is Use VMware Converter to create live vmdks from the running VMs, as if it was a P2V migration. Reboot host server and run RAID diagnostics, figure out what in the "h" happened Attempt to start ESX again, possibly after rebuilding its RAID volume Possibly have to re-install ESX on its volume and re-attach VMs If that doesn't work, attach the "live" vmdks created in step 1 to a different VM host.
[ "It was the backplane. Both drives of the RAID1 and one drive of the RAID5 were inaccessible. Incredibly, the VMware hypervisor continued to run for three days from memory with no access to its host disk, keeping the VMs it managed alive.\nAt step 3 above we diagnosed the hardware problem and replaced the RAID controller, cables, and backplane. After restart, we re-initialized the RAID by instructing the controller to query the drives for their configurations. Both were degraded and both were repaired successfully.\nAt step 4, it was not necessary to reinstall ESX; although, at bootup, it did not want to register the VMs. We had to dig up some buried management stuff to instruct the kernel to resignature the VMs. (Search VM docs for \"resignature.\")\nI believe that our fallback plan would have worked, the VMware Converter images of the VMs that were running \"orphaned\" were tested and ran fine with no data loss. I highly recommend performing a VMware Converter imaging of any VM that gets into this state, after shutting down as many services as possible and getting the VM into as read-only a state as possible. Loading a vmdk either elsewhere or on the original host as a repair is usually going to be WAY faster than rebuilding a server from the ground up with backups.\n" ]
[ 1 ]
[]
[]
[ "esx", "recovery", "vmware" ]
stackoverflow_0000020899_esx_recovery_vmware.txt
Q: Set and Oldset in sigprocmask() I haven't completely understood, how to use sigprocmask(). Particularly, how the set and oldset and its syntax work and how to use them. int sigprocmask(int how, const sigset_t *set, sigset_t *oldset); Please explain with an example, to block, say SIGUSR1 for a few seconds and then unblock and handle it. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­ A: The idea is that you provide a mask in set, effectively a list of signals. The how argument says what you should do with the mask in set. You can either use SIG_BLOCK to block the signals in the set list, or SIG_UNBLOCK to unblock them. Neither of these changes the signals that aren't set in the list. SIG_SETMASK blocks the signals in the list, and unblocks the ones that aren't set in the list. For instance, assume that the old blocking list was {SIGSEGV, SIGSUSP} and you call sigprocmask with these arguments: sigset_t x; sigemptyset (&x); sigaddset(&x, SIGUSR1); sigprocmask(SIG_BLOCK, &x, NULL) The new blocking list will now be {SIGSEGV, SIGSUSP, SIGUSR1}. If you call sigprocmask with these arguments now: sigprocmask(SIG_UNBLOCK, &x, NULL) The new blocking list will go back to being {SIGSEGV, SIGSUSP}. If you call sigprocmask with these arguments now: sigprocmask(SIG_SETMASK, &x, NULL) The new blocking list will now be set to {SIGUSR1}. The oldset argument tells you what the previous blocking list was. If we have this declaration: sigset_t y; and we call the code in the previous examples like this: sigprocmask(SIG_BLOCK, &x, &y) now we have: y == {SIGSEGV, SIGSUSP} If we now do: sigprocmask(SIG_UNBLOCK, &x, &y) we'll get y == {SIGSEGV, SIGSUSP, SIGUSR1} and if we do: sigprocmask(SIG_SET, &x, &y) we'll get this: y == {SIGSEGV, SIGSUSP} because this is the previous value of the blocking set.
Set and Oldset in sigprocmask()
I haven't completely understood, how to use sigprocmask(). Particularly, how the set and oldset and its syntax work and how to use them. int sigprocmask(int how, const sigset_t *set, sigset_t *oldset); Please explain with an example, to block, say SIGUSR1 for a few seconds and then unblock and handle it. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
[ "The idea is that you provide a mask in set, effectively a list of signals. The how argument says what you should do with the mask in set.\nYou can either use SIG_BLOCK to block the signals in the set list, or SIG_UNBLOCK to unblock them. Neither of these changes the signals that aren't set in the list. SIG_SETMASK blocks the signals in the list, and unblocks the ones that aren't set in the list.\nFor instance, assume that the old blocking list was {SIGSEGV, SIGSUSP} and you call sigprocmask with these arguments:\nsigset_t x;\nsigemptyset (&x);\nsigaddset(&x, SIGUSR1);\nsigprocmask(SIG_BLOCK, &x, NULL)\n\nThe new blocking list will now be {SIGSEGV, SIGSUSP, SIGUSR1}.\nIf you call sigprocmask with these arguments now:\nsigprocmask(SIG_UNBLOCK, &x, NULL)\n\nThe new blocking list will go back to being {SIGSEGV, SIGSUSP}.\nIf you call sigprocmask with these arguments now:\nsigprocmask(SIG_SETMASK, &x, NULL)\n\nThe new blocking list will now be set to {SIGUSR1}.\nThe oldset argument tells you what the previous blocking list was. If we have this declaration:\nsigset_t y;\n\nand we call the code in the previous examples like this:\n sigprocmask(SIG_BLOCK, &x, &y)\n\nnow we have:\ny == {SIGSEGV, SIGSUSP}\n\nIf we now do:\n sigprocmask(SIG_UNBLOCK, &x, &y)\n\nwe'll get\ny == {SIGSEGV, SIGSUSP, SIGUSR1}\n\nand if we do:\n sigprocmask(SIG_SET, &x, &y)\n\nwe'll get this:\ny == {SIGSEGV, SIGSUSP}\n\nbecause this is the previous value of the blocking set.\n" ]
[ 77 ]
[]
[]
[ "c", "posix", "signals", "sigprocmask" ]
stackoverflow_0000025261_c_posix_signals_sigprocmask.txt
Q: What's optimal? UNION vs WHERE IN (str1, str2, str3) I'm writing a program that sends an email out at a client's specific local time. I have a .NET method that takes a timezone & time and destination timezone and returns the time in that timezone. So my method is to select every distinct timezone in the database, check if it is the correct time using the method, then select every client out of the database with that timezone(s). The query will look like one of these. Keep in mind the order of the result set does not matter, so a union would be fine. Which runs faster, or do they really do the same thing? SELECT email FROM tClient WHERE timezoneID in (1, 4, 9) or SELECT email FROM tClient WHERE timezoneID = 1 UNION ALL SELECT email FROM tClient WHERE timezoneID = 4 UNION ALL SELECT email FROM tCLIENT WHERE timezoneID = 9 Edit: timezoneID is a foreign key to tTimezone, a table with primary key timezoneID and varchar(20) field timezoneName. Also, I went with WHERE IN since I didn't feel like opening up the analyzer. Edit 2: Query processes 200k rows in under 100 ms, so at this point I'm done. A: For most database related performance questions, the real answer is to run it and analyze what the DB does for your dataset. Run an explain plan or trace to see if your query is hitting the proper indexes or create indexes if necessary. I would likely go with the first using the IN clause since that carries the most semantics of what you want. The timezoneID seems like a primary key on some timezone table, so it should be a foreign key on email and indexed. Depending on the DB optimizer, I would think it should do an index scan on the foreign key index. A: Hey! These queries are not equivalent. Results will be same only if assuming that one email belongs only to the one time zone. Of course it does however SQL engine doesn't know that and tries to remove duplicities. So the first query should be faster. Always use UNION ALL, unless you know why you want to use UNION. If you are not sure what is difference see this SO question. Note: that yell belongs to previous version of question. A: In the book "SQL Performance Tuning", the authors found that the UNION queries were slower in all 7 DBMS' that they tested (SQL Server 2000, Sybase ASE 12.5, Oracle 9i, DB2, etc.): http://books.google.com/books?id=3H9CC54qYeEC&pg=PA32&vq=UNION&dq=sql+performance+tuning&source=gbs_search_s&sig=ACfU3U18uYZWYVHxr2I3uUj8kmPz9RpmiA#PPA33,M1 The later DBMS' may have optimized that difference away, but it's doubtful. Also, the UNION method is much longer and more difficult to maintain (what if you want a third?) vs. the IN. Unless you have good reason to use UNION, stick with the OR/IN method. A: My first guess would be that SELECT email FROM tClient WHERE timezoneID in (1, 4, 9) will be faster as it requires only single scan of the table to find the results, but I suggest checking the execution plan for both queries. A: I do not have MS SQL Query Analyzer at hand to actually check my hypothesis, but think that WHERE IN variant would be faster because with UNION server will have to do 3 table scans whereas with WHERE IN will need only one. If you have Query Analyzer check execution plans for both queries. On the Internet you may often encounter suggestions to avoid using WHERE IN, but that refers to cases where subqueries a used. So this case is out of scope of this recommendation and additionally is easier for reading and understanding. A: I think that there are several very important information missing in the question. First of all, it is of great importance weather timezoneID is indexed or not, is it part of the primary key etc. I would advice everyone to have a look at the analyzer, but in my experience the WHERE clause should be faster, especially with an index. The logic is something like, there is an additional overhead in the union query, checking types, column numbers in each etc. A: Some DBMS's Query Optimizers modify your query to make it more efficient, so depending on the DBMS your using, you probably shouldn't care.
What's optimal? UNION vs WHERE IN (str1, str2, str3)
I'm writing a program that sends an email out at a client's specific local time. I have a .NET method that takes a timezone & time and destination timezone and returns the time in that timezone. So my method is to select every distinct timezone in the database, check if it is the correct time using the method, then select every client out of the database with that timezone(s). The query will look like one of these. Keep in mind the order of the result set does not matter, so a union would be fine. Which runs faster, or do they really do the same thing? SELECT email FROM tClient WHERE timezoneID in (1, 4, 9) or SELECT email FROM tClient WHERE timezoneID = 1 UNION ALL SELECT email FROM tClient WHERE timezoneID = 4 UNION ALL SELECT email FROM tCLIENT WHERE timezoneID = 9 Edit: timezoneID is a foreign key to tTimezone, a table with primary key timezoneID and varchar(20) field timezoneName. Also, I went with WHERE IN since I didn't feel like opening up the analyzer. Edit 2: Query processes 200k rows in under 100 ms, so at this point I'm done.
[ "For most database related performance questions, the real answer is to run it and analyze what the DB does for your dataset. Run an explain plan or trace to see if your query is hitting the proper indexes or create indexes if necessary.\nI would likely go with the first using the IN clause since that carries the most semantics of what you want. The timezoneID seems like a primary key on some timezone table, so it should be a foreign key on email and indexed. Depending on the DB optimizer, I would think it should do an index scan on the foreign key index.\n", "Hey! These queries are not equivalent.\nResults will be same only if assuming that one email belongs only to the one time zone. Of course it does however SQL engine doesn't know that and tries to remove duplicities. So the first query should be faster.\nAlways use UNION ALL, unless you know why you want to use UNION.\nIf you are not sure what is difference see this SO question.\nNote: that yell belongs to previous version of question.\n", "In the book \"SQL Performance Tuning\", the authors found that the UNION queries were slower in all 7 DBMS' that they tested (SQL Server 2000, Sybase ASE 12.5, Oracle 9i, DB2, etc.): http://books.google.com/books?id=3H9CC54qYeEC&pg=PA32&vq=UNION&dq=sql+performance+tuning&source=gbs_search_s&sig=ACfU3U18uYZWYVHxr2I3uUj8kmPz9RpmiA#PPA33,M1\nThe later DBMS' may have optimized that difference away, but it's doubtful. Also, the UNION method is much longer and more difficult to maintain (what if you want a third?) vs. the IN.\nUnless you have good reason to use UNION, stick with the OR/IN method.\n", "My first guess would be that SELECT email FROM tClient WHERE timezoneID in (1, 4, 9) will be faster as it requires only single scan of the table to find the results, but I suggest checking the execution plan for both queries.\n", "I do not have MS SQL Query Analyzer at hand to actually check my hypothesis, but think that WHERE IN variant would be faster because with UNION server will have to do 3 table scans whereas with WHERE IN will need only one. If you have Query Analyzer check execution plans for both queries.\nOn the Internet you may often encounter suggestions to avoid using WHERE IN, but that refers to cases where subqueries a used. So this case is out of scope of this recommendation and additionally is easier for reading and understanding.\n", "I think that there are several very important information missing in the question. First of all, it is of great importance weather timezoneID is indexed or not, is it part of the primary key etc. I would advice everyone to have a look at the analyzer, but in my experience the WHERE clause should be faster, especially with an index. The logic is something like, there is an additional overhead in the union query, checking types, column numbers in each etc. \n", "Some DBMS's Query Optimizers modify your query to make it more efficient, so depending on the DBMS your using, you probably shouldn't care.\n" ]
[ 3, 3, 2, 1, 1, 1, 0 ]
[]
[]
[ "optimization", "sql" ]
stackoverflow_0000025182_optimization_sql.txt
Q: What would be the fastest way to remove Newlines from a String in C#? I have a string that has some Environment.Newline in it. I'd like to strip those from the string and instead, replace the Newline with something like a comma. What would be, in your opinion, the best way to do this using C#.NET 2.0? A: Why not: string s = "foobar\ngork"; string v = s.Replace(Environment.NewLine,","); System.Console.WriteLine(v); A: Like this: string s = "hello\nworld"; s = s.Replace(Environment.NewLine, ","); A: string sample = "abc" + Environment.NewLine + "def"; string replaced = sample.Replace(Environment.NewLine, ","); A: Don't reinvent the wheel — just use: myString.Replace(Environment.NewLine, ",") A: The best way is the builtin way: Use string.Replace. Why do you need alternatives?
What would be the fastest way to remove Newlines from a String in C#?
I have a string that has some Environment.Newline in it. I'd like to strip those from the string and instead, replace the Newline with something like a comma. What would be, in your opinion, the best way to do this using C#.NET 2.0?
[ "Why not:\nstring s = \"foobar\\ngork\";\nstring v = s.Replace(Environment.NewLine,\",\");\nSystem.Console.WriteLine(v);\n\n", "Like this:\nstring s = \"hello\\nworld\";\ns = s.Replace(Environment.NewLine, \",\");\n\n", "string sample = \"abc\" + Environment.NewLine + \"def\";\nstring replaced = sample.Replace(Environment.NewLine, \",\");\n\n", "Don't reinvent the wheel — just use: \nmyString.Replace(Environment.NewLine, \",\")\n\n", "The best way is the builtin way: Use string.Replace. Why do you need alternatives?\n" ]
[ 19, 7, 2, 2, 0 ]
[]
[]
[ ".net", "c#", "replace", "string" ]
stackoverflow_0000025349_.net_c#_replace_string.txt
Q: Custom Attribute Binding in Silverlight I've got two Silverlight Controls in my project, both have properties TeamId. I would like to bind these together in XAML in the control hosting both user controls similar to: <agChat:UserTeams x:Name="oUserTeams" /> <agChat:OnlineUser x:Name="oOnlineUsers" TeamId="{Binding ElementName=oUserTeams, Path=TeamId}" /> In the first control, I'm implementing System.ComponentModel.INotifyPropertyChanged and raising the PropertyChanged event upon the TeamId property changing. In the second control, I've used the propdp snippet to identify the TeamId as a Dependency property. // Using a DependencyProperty as the backing store for TeamId. This enables animation, styling, binding, etc... public static readonly DependencyProperty TeamIdProperty = DependencyProperty.Register( "TeamId", typeof(string), typeof(OnlineUsers), new System.Windows.PropertyMetadata(new System.Windows.PropertyChangedCallback(TeamChanged))); However when the silverlight controls first gets created, I get the follow exception from Silverlight: Unhandled Error in Silverlight 2 Application Invalid attribute value {Binding ElementName=oUserTeams, Path=TeamId} for property TeamId. [Line: 21 Position: 146] at System.Windows.Application.LoadComponent(Object component, Uri xamlUri) at agChat.Page.InitializeComponent() at agChat.Page..ctor() at agChat.App.Application_Startup(Object sender, StartupEventArgs e) at System.Windows.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args) at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, String eventName) Any ideas what I'm doing wrong? Obviously this could all be done in code-behind, but this seems like the correct approach. A: That is the correct approach in WPF, but not in Silverlight. You cannot bind to elements using xaml in Silverlight. This is the offending line: TeamId="{Binding ElementName=oUserTeams, Path=TeamId}" Specificly ElementName If you can, place the data object into Resources and declare it there, then you can do this: <agChat:UserTeams x:Name="oUserTeams" DataContext="{StaticResource myDataObject}" /> <agChat:OnlineUser x:Name="oOnlineUsers" DataContext="{StaticResource myDataObject}" TeamId="{Binding TeamId}" />
Custom Attribute Binding in Silverlight
I've got two Silverlight Controls in my project, both have properties TeamId. I would like to bind these together in XAML in the control hosting both user controls similar to: <agChat:UserTeams x:Name="oUserTeams" /> <agChat:OnlineUser x:Name="oOnlineUsers" TeamId="{Binding ElementName=oUserTeams, Path=TeamId}" /> In the first control, I'm implementing System.ComponentModel.INotifyPropertyChanged and raising the PropertyChanged event upon the TeamId property changing. In the second control, I've used the propdp snippet to identify the TeamId as a Dependency property. // Using a DependencyProperty as the backing store for TeamId. This enables animation, styling, binding, etc... public static readonly DependencyProperty TeamIdProperty = DependencyProperty.Register( "TeamId", typeof(string), typeof(OnlineUsers), new System.Windows.PropertyMetadata(new System.Windows.PropertyChangedCallback(TeamChanged))); However when the silverlight controls first gets created, I get the follow exception from Silverlight: Unhandled Error in Silverlight 2 Application Invalid attribute value {Binding ElementName=oUserTeams, Path=TeamId} for property TeamId. [Line: 21 Position: 146] at System.Windows.Application.LoadComponent(Object component, Uri xamlUri) at agChat.Page.InitializeComponent() at agChat.Page..ctor() at agChat.App.Application_Startup(Object sender, StartupEventArgs e) at System.Windows.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args) at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, String eventName) Any ideas what I'm doing wrong? Obviously this could all be done in code-behind, but this seems like the correct approach.
[ "That is the correct approach in WPF, but not in Silverlight. \nYou cannot bind to elements using xaml in Silverlight. \nThis is the offending line:\n TeamId=\"{Binding ElementName=oUserTeams, Path=TeamId}\"\nSpecificly ElementName\nIf you can, place the data object into Resources and declare it there, then you can do this:\n<agChat:UserTeams x:Name=\"oUserTeams\" \n DataContext=\"{StaticResource myDataObject}\" />\n<agChat:OnlineUser x:Name=\"oOnlineUsers\" \n DataContext=\"{StaticResource myDataObject}\" \n TeamId=\"{Binding TeamId}\" />\n\n" ]
[ 4 ]
[]
[]
[ "silverlight" ]
stackoverflow_0000025355_silverlight.txt
Q: What is appliance and how to use lambda expressions? I've read that Lambda Expressions are an incredibly powerful addition to C#, yet I find myself mystified by them. How can they improve my life or make my code better? Can anyone point to a good resource for learning such expressions? They seem cool as hell, but how do they relate to my day-to-day life as an asp.net developer? Edit: Thanks for the examples, and thanks for the link to Eric White's articles. I'm still digesting those now. One quick question: are lambda expressions useful for anything other than querying? Every example I've seen has been a query construct. A: : are lambda expressions useful for anything other than querying Lamba expressions are nothing much other than a convenient way of writing a function 'in-line'. So they're useful any place you wanted a bit of code which can be called as though it's a separate function but which is actually written inside its caller. (In addition to keeping related code in the same location in a file, this also allows you to play fun games with variable scoping - see 'closures' for a reference.) An example of a non-query-related use of a lamba might be a bit of code which does something asynchronously that you start with ThreadPool.QueueUserWorkItem. The important point is that you could also write this using anonymous delegates (which were a C#2 introduction), or just a plain separate class member function. This http://blogs.msdn.com/jomo_fisher/archive/2005/09/13/464884.aspx is a superb step-by-step introduction into all this stuff, which might help you. A: Lambdas bring functional programing to C#. They are anonymous functions that can be passed as values to certain other functions. Used most in LINQ. Here is a contrived example: List<int> myInts = GetAll(); IEnumerable<int> evenNumbers = myInts.Where(x => x % 2 == 0); Now when you foreach through evenNumbers the lamda x=> x % 2 == 0 is then applied as a filter to myInts. They become really useful in increasing readability to complicated algorithms that would have many nested IF conditionals and loops. A: Here's a simple example of something cool you can do with lambdas: List<int> myList = new List<int>{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }; myList.RemoveAll(x => x > 5); //myList now == {1,2,3,4,5} The RemoveAll method takes a predicate(a delegate that takes argurments and returns a bool), any that match it get removed. Using a lambda expression makes it simpler than actually declaring the predicate.
What is appliance and how to use lambda expressions?
I've read that Lambda Expressions are an incredibly powerful addition to C#, yet I find myself mystified by them. How can they improve my life or make my code better? Can anyone point to a good resource for learning such expressions? They seem cool as hell, but how do they relate to my day-to-day life as an asp.net developer? Edit: Thanks for the examples, and thanks for the link to Eric White's articles. I'm still digesting those now. One quick question: are lambda expressions useful for anything other than querying? Every example I've seen has been a query construct.
[ "\n: are lambda expressions useful for anything other than querying\n\nLamba expressions are nothing much other than a convenient way of writing a function 'in-line'.\nSo they're useful any place you wanted a bit of code which can be called as though it's a separate function but which is actually written inside its caller. (In addition to keeping related code in the same location in a file, this also allows you to play fun games with variable scoping - see 'closures' for a reference.)\nAn example of a non-query-related use of a lamba might be a bit of code which does something asynchronously that you start with ThreadPool.QueueUserWorkItem. The important point is that you could also write this using anonymous delegates (which were a C#2 introduction), or just a plain separate class member function.\nThis http://blogs.msdn.com/jomo_fisher/archive/2005/09/13/464884.aspx is a superb step-by-step introduction into all this stuff, which might help you.\n", "Lambdas bring functional programing to C#.\nThey are anonymous functions that can be passed as values to certain other functions. Used most in LINQ.\nHere is a contrived example:\nList<int> myInts = GetAll();\nIEnumerable<int> evenNumbers = myInts.Where(x => x % 2 == 0);\n\nNow when you foreach through evenNumbers the lamda \nx=> x % 2 == 0\n\nis then applied as a filter to myInts.\nThey become really useful in increasing readability to complicated algorithms that would have many nested IF conditionals and loops. \n", "Here's a simple example of something cool you can do with lambdas:\nList<int> myList = new List<int>{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };\nmyList.RemoveAll(x => x > 5);\n//myList now == {1,2,3,4,5}\n\nThe RemoveAll method takes a predicate(a delegate that takes argurments and returns a bool), any that match it get removed. Using a lambda expression makes it simpler than actually declaring the predicate.\n" ]
[ 12, 7, 5 ]
[]
[]
[ "c#", "lambda" ]
stackoverflow_0000025376_c#_lambda.txt
Q: Linq 2 SQL on shared host I recently ran into an issue with linq on a shared host. The host is Shared Intellect and they support v3.5 of the framework. However, I am uncertain to whether they have SP1 installed. My suspicion is that they do not. I have a simple News table that has the following structure: NewsID uniqueidentifier Title nvarchar(250) Introduction nvarchar(1000) Article ntext DateEntered datetime (default getdate()) IsPublic bit (default true) My goal is to display the 3 most recent records from this table. I initially went the D&D method (I know, I know) and created a linq data-source and was unable to find a way to limit the results the way I desired, so I removed that and wrote the following: var dc = new NewsDataContext(); var news = from a in dc.News where a.IsPublic == true orderby a.DateEntered descending select new { a.NewsID, a.Introduction }; lstNews.DataSource = news.Take(3); lstNews.DataBind(); This worked perfectly on my local machine. However, when I uploaded everything to the shared host, I recieved the following error: .Read_<>f__AnonymousType0`2 (System.Data.Linq.SqlClient.Implementation.ObjectMaterializer`1<System.Data.SqlClient.SqlDataReader>) Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.MethodAccessException: .Read_<>f__AnonymousType0`2 (System.Data.Linq.SqlClient.Implementation.ObjectMaterializer`1<System.Data.SqlClient.SqlDataReader>) I tried to search the error on Google, but met with no success. I then tried to modify my query in every way I could imagine, removing various combinations of the where/orderby parameters as well as limiting my query to a single column and even removing the Take command. My Question therefore comes in 3 parts: Has anyone else encountered this and if so, is there a "quick" fix? Is there a way to use the datasource to limit the rows? Is there some way to determine what version of the framework the shared host is running short of emailing them directly (which I have done and am awaiting an answer) A: System.MethodAccessException is thrown by the framework when it is missing an assembly, or one of the references are of the wrong version. The first thing I would do is try uploading and referencing your code to the LINQ assemblies in your BIN, instead of the shared hosting providers GAC.
Linq 2 SQL on shared host
I recently ran into an issue with linq on a shared host. The host is Shared Intellect and they support v3.5 of the framework. However, I am uncertain to whether they have SP1 installed. My suspicion is that they do not. I have a simple News table that has the following structure: NewsID uniqueidentifier Title nvarchar(250) Introduction nvarchar(1000) Article ntext DateEntered datetime (default getdate()) IsPublic bit (default true) My goal is to display the 3 most recent records from this table. I initially went the D&D method (I know, I know) and created a linq data-source and was unable to find a way to limit the results the way I desired, so I removed that and wrote the following: var dc = new NewsDataContext(); var news = from a in dc.News where a.IsPublic == true orderby a.DateEntered descending select new { a.NewsID, a.Introduction }; lstNews.DataSource = news.Take(3); lstNews.DataBind(); This worked perfectly on my local machine. However, when I uploaded everything to the shared host, I recieved the following error: .Read_<>f__AnonymousType0`2 (System.Data.Linq.SqlClient.Implementation.ObjectMaterializer`1<System.Data.SqlClient.SqlDataReader>) Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.MethodAccessException: .Read_<>f__AnonymousType0`2 (System.Data.Linq.SqlClient.Implementation.ObjectMaterializer`1<System.Data.SqlClient.SqlDataReader>) I tried to search the error on Google, but met with no success. I then tried to modify my query in every way I could imagine, removing various combinations of the where/orderby parameters as well as limiting my query to a single column and even removing the Take command. My Question therefore comes in 3 parts: Has anyone else encountered this and if so, is there a "quick" fix? Is there a way to use the datasource to limit the rows? Is there some way to determine what version of the framework the shared host is running short of emailing them directly (which I have done and am awaiting an answer)
[ "System.MethodAccessException is thrown by the framework when it is missing an assembly, or one of the references are of the wrong version.\nThe first thing I would do is try uploading and referencing your code to the LINQ assemblies in your BIN, instead of the shared hosting providers GAC.\n" ]
[ 2 ]
[]
[]
[ "hosting", "linq_to_sql", "shared" ]
stackoverflow_0000025432_hosting_linq_to_sql_shared.txt
Q: Can you perform an AND search of keywords using FREETEXT() on SQL Server 2005? There is a request to make the SO search default to an AND style functionality over the current OR when multiple terms are used. The official response was: not as simple as it sounds; we use SQL Server 2005's FREETEXT() function, and I can't find a way to specify AND vs. OR -- can you? So, is there a way? There are a number of resources on it I can find, but I am not an expert. A: As far as I've seen, it is not possible to do AND when using FREETEXT() under SQL 2005 (nor 2008, afaik). A FREETEXT query ignores Boolean, proximity, and wildcard operators by design. However you could do this: WHERE FREETEXT('You gotta love MS-SQL') > 0 AND FREETEXT('You gotta love MySQL too...') > 0 Or that's what I think :) -- The idea is make it evaluate to Boolean, so you can use boolean operators. Don't know if this would give an error or not. I think it should work. But reference material is pointing to the fact that this is not possible by design. The use of CONTAINS() instead of FREETEXT() could help. A: I just started reading about freetext so bear with me. If what you are trying to do is allow searches for a tag, say VB, also find things tagged as VB6, Visual Basic, VisualBasic and VB.Net, wouldn't those values be set as synonyms in the DB's Thesaurus rather than query parameters? If that is indeed the case, this link on MSDN explains how to add items to the Thesaurus. A: OK, this change is in -- we now use CONTAINS() with implicit AND instead of FREETEXT() and its implicit OR.
Can you perform an AND search of keywords using FREETEXT() on SQL Server 2005?
There is a request to make the SO search default to an AND style functionality over the current OR when multiple terms are used. The official response was: not as simple as it sounds; we use SQL Server 2005's FREETEXT() function, and I can't find a way to specify AND vs. OR -- can you? So, is there a way? There are a number of resources on it I can find, but I am not an expert.
[ "As far as I've seen, it is not possible to do AND when using FREETEXT() under SQL 2005 (nor 2008, afaik). \nA FREETEXT query ignores Boolean, proximity, and wildcard operators by design. However you could do this: \nWHERE FREETEXT('You gotta love MS-SQL') > 0\n AND FREETEXT('You gotta love MySQL too...') > 0\n\nOr that's what I think :)\n-- The idea is make it evaluate to Boolean, so you can use boolean operators. Don't know if this would give an error or not. I think it should work. But reference material is pointing to the fact that this is not possible by design. \nThe use of CONTAINS() instead of FREETEXT() could help.\n", "I just started reading about freetext so bear with me. If what you are trying to do is allow searches for a tag, say VB, also find things tagged as VB6, Visual Basic, VisualBasic and VB.Net, wouldn't those values be set as synonyms in the DB's Thesaurus rather than query parameters?\nIf that is indeed the case, this link on MSDN explains how to add items to the Thesaurus.\n", "OK, this change is in -- we now use CONTAINS() with implicit AND instead of FREETEXT() and its implicit OR.\n" ]
[ 2, 1, 1 ]
[]
[]
[ "freetext", "full_text_search", "search", "sql_server_2005" ]
stackoverflow_0000025277_freetext_full_text_search_search_sql_server_2005.txt
Q: How do I put unicode characters in my Antlr grammar? I'm trying to build a grammar with the following: NUMERIC: INTEGER | FLOAT | INFINITY | PI ... INFINITY: '∞' PI: 'π' But Antlr refuses to load the grammar. A: Use the Java expression representing the Unicode character: 'π' = '\u03C0' '∞' = '\u221E' That will work up to '\uFFFF'; Java doesn't support five-digit Unicode.
How do I put unicode characters in my Antlr grammar?
I'm trying to build a grammar with the following: NUMERIC: INTEGER | FLOAT | INFINITY | PI ... INFINITY: '∞' PI: 'π' But Antlr refuses to load the grammar.
[ "Use the Java expression representing the Unicode character:\n\n'π' = '\\u03C0'\n'∞' = '\\u221E'\n\nThat will work up to '\\uFFFF'; Java doesn't support five-digit Unicode.\n" ]
[ 3 ]
[]
[]
[ "antlr", "internationalization", "parsing", "unicode" ]
stackoverflow_0000025475_antlr_internationalization_parsing_unicode.txt
Q: Asynchronous Stored Procedure Calls Is it possible to call a stored procedure from another stored procedure asynchronously? Edit: Specifically I'm working with a DB2 database. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­ A: Executive summary: Yes, if your database has a message queue service. You can push a message onto a queue and the queue processor will consume it asynchronously. Oracle: queues Sql Server: service broker DB2: event broker For "pure" stored procedure languages (PL/Sql or T-Sql) the answer is no, since it works against the fundamental transaction model most databases have. However, if your database has a queuing mechanism, you can use that to get the same result. A: With MS Sql Server 2005, try the Service Broker and/or CLR stored procedures. I don't think there's anything built directly into TSQL. A: It sounds like you need to put some scheduled jobs in place with Cron (or windows equiv). You could use the initial stored proc call to set some kind of flag in the DB, which is then checked periodically by a cron job. If you need to have a specific delay before the 2nd job executes, you should be able to do that by having the task scheduled by the cron job.
Asynchronous Stored Procedure Calls
Is it possible to call a stored procedure from another stored procedure asynchronously? Edit: Specifically I'm working with a DB2 database. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
[ "Executive summary: Yes, if your database has a message queue service.\nYou can push a message onto a queue and the queue processor will consume it asynchronously.\n\nOracle: queues\nSql Server: service broker\nDB2: event broker\n\nFor \"pure\" stored procedure languages (PL/Sql or T-Sql) the answer is no, since it works against the fundamental transaction model most databases have.\nHowever, if your database has a queuing mechanism, you can use that to get the same result.\n", "With MS Sql Server 2005, try the Service Broker and/or CLR stored procedures. I don't think there's anything built directly into TSQL.\n", "It sounds like you need to put some scheduled jobs in place with Cron (or windows equiv). You could use the initial stored proc call to set some kind of flag in the DB, which is then checked periodically by a cron job. If you need to have a specific delay before the 2nd job executes, you should be able to do that by having the task scheduled by the cron job.\n" ]
[ 5, 1, 0 ]
[]
[]
[ "db2", "sql", "stored_procedures" ]
stackoverflow_0000025460_db2_sql_stored_procedures.txt
Q: Stored Procedure and Timeout I'm running a long process stored procedure. I'm wondering if in case of a timeout or any case of disconnection with the database after initiating the call to the stored procedure. Is it still working and implementing the changes on the server? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­ A: Anyway if the client is not there to commit at the end of the job the changes should be rolled back by the server. In other words, if you have a stored procedure making changes to the database and there is a possibility that the connection might disconnect in the middle, be sure to enclose all changes within a transaction. A: It depends on the server I guess. I know Firebird will detect disconnected clients and stop working. Anyway if the client is not there to commit at the end of the job the changes should be rolled back by the server. A: I would suggest running your profiler on the database and watching the activity, and also create a basic test case so that you know for sure what happens. The outcome is dependent on your database and what you are using to connect to it.
Stored Procedure and Timeout
I'm running a long process stored procedure. I'm wondering if in case of a timeout or any case of disconnection with the database after initiating the call to the stored procedure. Is it still working and implementing the changes on the server? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
[ "\nAnyway if the client is not there to commit at the end of the job the changes should be rolled back by the server.\n\nIn other words, if you have a stored procedure making changes to the database and there is a possibility that the connection might disconnect in the middle, be sure to enclose all changes within a transaction.\n", "It depends on the server I guess.\nI know Firebird will detect disconnected clients and stop working.\nAnyway if the client is not there to commit at the end of the job the changes should be rolled back by the server.\n", "I would suggest running your profiler on the database and watching the activity, and also create a basic test case so that you know for sure what happens. The outcome is dependent on your database and what you are using to connect to it.\n" ]
[ 2, 1, 0 ]
[]
[]
[ "database", "stored_procedures", "timeout" ]
stackoverflow_0000025142_database_stored_procedures_timeout.txt
Q: Combining values from different files into one CSV file I have a couple of files containing a value in each line. EDIT : I figured out the answer to this question while in the midst of writing the post and didn't realize I had posted it by mistake in its incomplete state. I was trying to do: paste -d ',' file1 file2 file 3 file 4 > file5.csv and was getting a weird output. I later realized that was happening because some files had both a carriage return and a newline character at the end of the line while others had only the newline character. I got to always remember to pay attention to those things. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­ A: file 1: 1 2 3 file2: 2 4 6 paste --delimiters=\; file1 file2 Will yield: 1;2 3;4 5;6 A: I have a feeling you haven't finished typing your question yet, but I'll give it a shot still. ;) file1: file2: file3: 1 a A 2 b B 3 c C ~$ paste file{1,2,3} |sed 's/^\|$/"/g; s/\t/","/g' "1","a","A" "2","b","B" "3","c","C" Or, ~$ paste --delimiter , file{1,2,3} 1,a,A 2,b,B 3,c,C A: you probably need to clarify or retag your question but as it stands the answer is below. joining two files under Linux cat filetwo >> fileone A: Also don't forget about the ever versatile LogParser if you're on Windows. It can run SQL-like queries against flat text files to perform all sorts of merge operations. A: The previous answers using logparser or the commandline tools should work. If you want to do some more complicated operations to the records like filtering or joins, you could consider using an ETL Tool (Pentaho, Mapforce and Talend come to mind). These tools generally give you a graphical palette to define the relationships between data sources and any operations you want to perform on the rows.
Combining values from different files into one CSV file
I have a couple of files containing a value in each line. EDIT : I figured out the answer to this question while in the midst of writing the post and didn't realize I had posted it by mistake in its incomplete state. I was trying to do: paste -d ',' file1 file2 file 3 file 4 > file5.csv and was getting a weird output. I later realized that was happening because some files had both a carriage return and a newline character at the end of the line while others had only the newline character. I got to always remember to pay attention to those things. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
[ "file 1:\n\n1\n2\n3\n\nfile2:\n\n2\n4\n6\n\npaste --delimiters=\\; file1 file2\n\nWill yield:\n\n1;2\n3;4\n5;6\n\n", "I have a feeling you haven't finished typing your question yet, but I'll give it a shot still. ;)\nfile1: file2: file3:\n1 a A\n2 b B\n3 c C\n\n~$ paste file{1,2,3} |sed 's/^\\|$/\"/g; s/\\t/\",\"/g'\n\"1\",\"a\",\"A\"\n\"2\",\"b\",\"B\"\n\"3\",\"c\",\"C\"\n\nOr,\n~$ paste --delimiter , file{1,2,3}\n1,a,A\n2,b,B\n3,c,C\n\n", "you probably need to clarify or retag your question but as it stands the answer is below.\njoining two files under Linux\ncat filetwo >> fileone\n\n", "Also don't forget about the ever versatile LogParser if you're on Windows.\nIt can run SQL-like queries against flat text files to perform all sorts of merge operations.\n", "The previous answers using logparser or the commandline tools should work. If you want to do some more complicated operations to the records like filtering or joins, you could consider using an ETL Tool (Pentaho, Mapforce and Talend come to mind). These tools generally give you a graphical palette to define the relationships between data sources and any operations you want to perform on the rows.\n" ]
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "linux", "regex", "shell", "unix" ]
stackoverflow_0000025225_linux_regex_shell_unix.txt
Q: Filtering out anchor tags in a string I need to filter out anchor tags in a string. For instance, Check out this site: <a href="http://www.stackoverflow.com">stackoverflow</a> I need to be able to filter out the anchor tag to this: Check out this site: http://www.stackoverflow.com That format may not be constant, either. There could be other attributes to the anchor tag. Also, there could be more than 1 anchor tag in the string. I'm doing the filtering in vb.net before it goes to the database. A: Here's a simple regular expression that should work. Imports System.Text.RegularExpressions ' .... Dim reg As New Regex("<a.*?href=(?:'|"")(.+?)(?:'|"").*?>.+?</a>") Dim input As String = "This is a link: <a href='http://www.stackoverflow.com'>Stackoverflow</a>" input = reg.Replace(input, "$1", RegexOptions.IgnoreCase)
Filtering out anchor tags in a string
I need to filter out anchor tags in a string. For instance, Check out this site: <a href="http://www.stackoverflow.com">stackoverflow</a> I need to be able to filter out the anchor tag to this: Check out this site: http://www.stackoverflow.com That format may not be constant, either. There could be other attributes to the anchor tag. Also, there could be more than 1 anchor tag in the string. I'm doing the filtering in vb.net before it goes to the database.
[ "Here's a simple regular expression that should work.\nImports System.Text.RegularExpressions\n\n' ....\n\nDim reg As New Regex(\"<a.*?href=(?:'|\"\")(.+?)(?:'|\"\").*?>.+?</a>\")\nDim input As String = \"This is a link: <a href='http://www.stackoverflow.com'>Stackoverflow</a>\"\ninput = reg.Replace(input, \"$1\", RegexOptions.IgnoreCase)\n\n" ]
[ 8 ]
[]
[]
[ "asp.net", "html", "vb.net" ]
stackoverflow_0000025519_asp.net_html_vb.net.txt
Q: Add 1 to a field How do I turn the following 2 queries into 1 query $sql = "SELECT level FROM skills WHERE id = $id LIMIT 1;"; $result = $db->sql_query($sql); $level = (int) $db->sql_fetchfield('level'); $db->sql_freeresult($result); ++$level; $sql = "UPDATE skills SET level = $level WHERE id = $id;"; $result = $db->sql_query($sql); $db->sql_freeresult($result); I'm using it in a phpBB mod but the gist is that I grab the level, add one to it then update, it seems that it'd be much easier and faster if I could do it as one query. Edit: $id has already been forced to be an integer, thus no escaping is needed this time. A: I get downmodded for this? $sql = "UPDATE skills SET level = level+1 WHERE id = $id"; $result = $db->sql_query($sql); $db->sql_freeresult($result); In Teifion's specific case, the phpBB DDL lists that particular field as NOT NULL, so there's no danger of incrementing NULL. In the general case, you should not use NULL to represent zero. Incrementing NULL should give an answer of NULL. If you're the kind of misguided developer who thinks NULL=0, step away from keyboard and find another pastime, you're just making life hard for the rest of us. Of course, this is the computer industry and who are we to say you're wrong? If you're not wrong, use $sql = "UPDATE skills SET level = COALESCE(level,0)+1 WHERE id = $id"; ...but let's face it: you're wrong. If everyone starts at level 0, then your DDL should include level INT DEFAULT '0' NOT NULL in case the programmers forget to set it when they create a record. If not everyone starts on level 0, then skip the DEFAULT and force the programmer to supply a value on creation. If some people are beyond levels, for whom having a level is a meaningless thing, then adding one to their level equally has no meaning. In that case, drop the NOT NULL from the DDL. A: This way: UPDATE skills SET level = level + 1 WHERE id = $id A: With PDO and prepared query: $query = $db->prepare("UPDATE skills SET level = level + 1 WHERE id = :id") $query->bindValue(":id", $id); $result = $query->execute(); A: $sql = "UPDATE skills SET level = level + 1 WHERE id = $id"; I just hope you are properly sanitising $id elsewhere in your code! A: try this UPDATE skills SET level = level + 1 WHERE id = $id A: How about: UPDATE skills SET level = level + 1 WHERE id = $id;
Add 1 to a field
How do I turn the following 2 queries into 1 query $sql = "SELECT level FROM skills WHERE id = $id LIMIT 1;"; $result = $db->sql_query($sql); $level = (int) $db->sql_fetchfield('level'); $db->sql_freeresult($result); ++$level; $sql = "UPDATE skills SET level = $level WHERE id = $id;"; $result = $db->sql_query($sql); $db->sql_freeresult($result); I'm using it in a phpBB mod but the gist is that I grab the level, add one to it then update, it seems that it'd be much easier and faster if I could do it as one query. Edit: $id has already been forced to be an integer, thus no escaping is needed this time.
[ "I get downmodded for this?\n$sql = \"UPDATE skills SET level = level+1 WHERE id = $id\";\n$result = $db->sql_query($sql);\n$db->sql_freeresult($result);\n\nIn Teifion's specific case, the phpBB DDL lists that particular field as NOT NULL, so there's no danger of incrementing NULL.\nIn the general case, you should not use NULL to represent zero. Incrementing NULL should give an answer of NULL. If you're the kind of misguided developer who thinks NULL=0, step away from keyboard and find another pastime, you're just making life hard for the rest of us. Of course, this is the computer industry and who are we to say you're wrong? If you're not wrong, use\n$sql = \"UPDATE skills SET level = COALESCE(level,0)+1 WHERE id = $id\";\n\n...but let's face it: you're wrong. If everyone starts at level 0, then your DDL should include\nlevel INT DEFAULT '0' NOT NULL\n\nin case the programmers forget to set it when they create a record. If not everyone starts on level 0, then skip the DEFAULT and force the programmer to supply a value on creation. If some people are beyond levels, for whom having a level is a meaningless thing, then adding one to their level equally has no meaning. In that case, drop the NOT NULL from the DDL.\n", "This way:\nUPDATE skills\nSET level = level + 1\nWHERE id = $id\n\n", "With PDO and prepared query:\n$query = $db->prepare(\"UPDATE skills SET level = level + 1 WHERE id = :id\")\n$query->bindValue(\":id\", $id);\n$result = $query->execute();\n\n", "$sql = \"UPDATE skills SET level = level + 1 WHERE id = $id\";\n\nI just hope you are properly sanitising $id elsewhere in your code!\n", "try this\nUPDATE skills SET level = level + 1 WHERE id = $id\n\n", "How about: \nUPDATE skills SET level = level + 1 WHERE id = $id;\n\n" ]
[ 31, 11, 6, 3, 2, 1 ]
[ "Mat: That's what pasted in from the question. It hasn't been edited, so I attribute that to a bug in Markdown. But, oddly enough, I have noticed.\nAlso: yes, mysql_escape_string()!\n" ]
[ -1 ]
[ "mysql", "php" ]
stackoverflow_0000005846_mysql_php.txt
Q: What is the most efficient way to populate a time (or time range)? While plenty of solutions exist for entering dates (such as calendars, drop-down menus, etc.), it doesn't seem like there are too many "standard" ways to ask for a time (or time range). I've personally tried drop-down menus for the hour, minute, and second fields (and sometimes an "AM/PM" field, as well). I've also tried several clock-like input devices, most of which are too hard to use for the typical end-user. I've even tried "pop-out" time selection menus (which allow you to, for example, hover over the hour "10" to receive a sub-menu that contains ":00",":15",":30", and ":45") -- but none of these methods seem natural. So far, the best (and most universal) method I have found is just using simple text fields and forcing a user to manually populate the hour, minute, and second. Alternatively, I've had good experiences creating something similar to Outlook's "Day View" which allows you to drag and drop an event to set the start and end times. Is there a "best way" to ask for this information? Is anybody using some type of time input widget that's really intuitive and easy to use? Or is there at least a way that's more efficient than using plain text boxes? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­ A: There is quite a useful time entry tool for JQuery. It provides a 'spinner' type approach, in addition to a standard text field. It also supports the use of the mouse scroll-wheel for adjustment (as well as the traditional 'just type it in' approach) and can be configured to restrict to n-minute steps too if you like. It's pretty customisable, supports localisation and a variety of other settings, I've used it successfully in a couple of projects/demo sites. A: I am a huge fan of plain language input (there was a topic on it the other day). I like the way 37signals backpack calendar let's you type things in (08/12 3pm Meeting with tom). I also like the way they handle times with their reminder system (they give you options like later today, tomorrow morning). A: I find Google Calendar's approach to be the best. Use a text box, but use JavaScript to make it sort of a drop-down for picking your time. A good demo can be found for a jQuery implementation here I haven't implemented this on my site yet so I'm not 100% sure, but I think you also need code from this jQuery plugin here: http://www.texotela.co.uk/code/jquery/timepicker/ Edit The first link I posted does not require the second link's code. It is simply based off of it. To get the actual JavaScript file from the example, you can view the source of the page to find where the file is, or you can go to the URL directly http://labs.perifer.se/timedatepicker/jquery.timePicker.js
What is the most efficient way to populate a time (or time range)?
While plenty of solutions exist for entering dates (such as calendars, drop-down menus, etc.), it doesn't seem like there are too many "standard" ways to ask for a time (or time range). I've personally tried drop-down menus for the hour, minute, and second fields (and sometimes an "AM/PM" field, as well). I've also tried several clock-like input devices, most of which are too hard to use for the typical end-user. I've even tried "pop-out" time selection menus (which allow you to, for example, hover over the hour "10" to receive a sub-menu that contains ":00",":15",":30", and ":45") -- but none of these methods seem natural. So far, the best (and most universal) method I have found is just using simple text fields and forcing a user to manually populate the hour, minute, and second. Alternatively, I've had good experiences creating something similar to Outlook's "Day View" which allows you to drag and drop an event to set the start and end times. Is there a "best way" to ask for this information? Is anybody using some type of time input widget that's really intuitive and easy to use? Or is there at least a way that's more efficient than using plain text boxes? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
[ "There is quite a useful time entry tool for JQuery. It provides a 'spinner' type approach, in addition to a standard text field. It also supports the use of the mouse scroll-wheel for adjustment (as well as the traditional 'just type it in' approach) and can be configured to restrict to n-minute steps too if you like. It's pretty customisable, supports localisation and a variety of other settings, I've used it successfully in a couple of projects/demo sites.\n", "I am a huge fan of plain language input (there was a topic on it the other day). I like the way 37signals backpack calendar let's you type things in (08/12 3pm Meeting with tom). I also like the way they handle times with their reminder system (they give you options like later today, tomorrow morning).\n", "I find Google Calendar's approach to be the best. Use a text box, but use JavaScript to make it sort of a drop-down for picking your time. A good demo can be found for a jQuery implementation here \nI haven't implemented this on my site yet so I'm not 100% sure, but I think you also need code from this jQuery plugin here:\nhttp://www.texotela.co.uk/code/jquery/timepicker/\nEdit\nThe first link I posted does not require the second link's code. It is simply based off of it. To get the actual JavaScript file from the example, you can view the source of the page to find where the file is, or you can go to the URL directly\nhttp://labs.perifer.se/timedatepicker/jquery.timePicker.js\n" ]
[ 0, 0, 0 ]
[]
[]
[ "time" ]
stackoverflow_0000025455_time.txt
Q: How do I run (unit) tests in different folders/projects separately in Visual Studio? I need some advice as to how I easily can separate test runs for unit tests and integration test in Visual Studio. Often, or always, I structure the solution as presented in the above picture: separate projects for unit tests and integration tests. The unit tests is run very frequently while the integration tests naturally is run when the context is correctly aligned. My goal is to somehow be able configure which tests (or test folders) to run when I use a keyboard shortcut. The tests should preferably be run by a graphical test runner (ReSharpers). So for example Alt+1 runs the tests in project BLL.Test, Alt+2 runs the tests in project DAL.Tests, Alt+3 runs them both (i.e. all the tests in the [Tests] folder, and Alt+4 runs the tests in folder [Tests.Integration]. TestDriven.net have an option of running just the test in the selected folder or project by right-clicking it and select Run Test(s). Being able to do this, but via a keyboard command and with a graphical test runner would be awesome. Currently I use VS2008, ReSharper 4 and nUnit. But advice for a setup in the general is of course also appreciated. A: I actually found kind of a solution for this on my own by using keyboard command bound to a macro. The macro was recorded from the menu Tools>Macros>Record TemporaryMacro. While recording I selected my [Tests] folder and ran ReSharpers UnitTest.ContextRun. This resulted in the following macro, Sub TemporaryMacro() DTE.Windows.Item(Constants.vsWindowKindSolutionExplorer).Activate DTE.ActiveWindow.Object.GetItem("TestUnitTest\Tests").Select(vsUISelectionType.vsUISelectionTypeSelect) DTE.ExecuteCommand("ReSharper.UnitTest_ContextRun") End Sub which was then bound to it's own keyboard command in Tools>Options>Environment>Keyboard. However, what would be even more awesome is a more general solution where I can configure exactly which projects/folders/classes to run and when. For example by the means of an xml file. This could then easily be checked in to version control and distributed to everyone who works with the project. A: This is a bit of fiddly solution, but you could configure some external tools for each of group of tests you want to run. I'm not sure if you'll be able to launch the ReSharper test runner this way, but you can run the console version of nunit. Once you have of those tools setup, you can assigned keyboard shortcuts to the commands "Tools.ExternalCommand1", "Tools.ExternalCommand2", etc. This wont really scale very well, and it's awkward to change - but it will give you keyboard shortcuts for running your tests. It does feel like there should be a much simpler way of doing this. A: You can use a VS macro to parse the XML file and then call nunit.exe with the /fixture command line argument to specify which classes to run or generate a selection save file and run nunit using that. A: I have never used this but maybe it could help.... http://www.codeplex.com/VS2008UnitTestGUI "Project Description This project is about running all unit test inside multiple .NET Unit tests assembly coded with Visual Studio 2008."
How do I run (unit) tests in different folders/projects separately in Visual Studio?
I need some advice as to how I easily can separate test runs for unit tests and integration test in Visual Studio. Often, or always, I structure the solution as presented in the above picture: separate projects for unit tests and integration tests. The unit tests is run very frequently while the integration tests naturally is run when the context is correctly aligned. My goal is to somehow be able configure which tests (or test folders) to run when I use a keyboard shortcut. The tests should preferably be run by a graphical test runner (ReSharpers). So for example Alt+1 runs the tests in project BLL.Test, Alt+2 runs the tests in project DAL.Tests, Alt+3 runs them both (i.e. all the tests in the [Tests] folder, and Alt+4 runs the tests in folder [Tests.Integration]. TestDriven.net have an option of running just the test in the selected folder or project by right-clicking it and select Run Test(s). Being able to do this, but via a keyboard command and with a graphical test runner would be awesome. Currently I use VS2008, ReSharper 4 and nUnit. But advice for a setup in the general is of course also appreciated.
[ "I actually found kind of a solution for this on my own by using keyboard command bound to a macro. The macro was recorded from the menu Tools>Macros>Record TemporaryMacro. While recording I selected my [Tests] folder and ran ReSharpers UnitTest.ContextRun. This resulted in the following macro, \nSub TemporaryMacro()\n DTE.Windows.Item(Constants.vsWindowKindSolutionExplorer).Activate\n DTE.ActiveWindow.Object.GetItem(\"TestUnitTest\\Tests\").Select(vsUISelectionType.vsUISelectionTypeSelect)\n DTE.ExecuteCommand(\"ReSharper.UnitTest_ContextRun\")\nEnd Sub\n\nwhich was then bound to it's own keyboard command in Tools>Options>Environment>Keyboard.\nHowever, what would be even more awesome is a more general solution where I can configure exactly which projects/folders/classes to run and when. For example by the means of an xml file. This could then easily be checked in to version control and distributed to everyone who works with the project.\n", "This is a bit of fiddly solution, but you could configure some external tools for each of group of tests you want to run. I'm not sure if you'll be able to launch the ReSharper test runner this way, but you can run the console version of nunit. Once you have of those tools setup, you can assigned keyboard shortcuts to the commands \"Tools.ExternalCommand1\", \"Tools.ExternalCommand2\", etc.\nThis wont really scale very well, and it's awkward to change - but it will give you keyboard shortcuts for running your tests. It does feel like there should be a much simpler way of doing this.\n", "You can use a VS macro to parse the XML file and then call nunit.exe with the /fixture command line argument to specify which classes to run or generate a selection save file and run nunit using that.\n", "I have never used this but maybe it could help....\nhttp://www.codeplex.com/VS2008UnitTestGUI\n\"Project Description\nThis project is about running all unit test inside multiple .NET Unit tests assembly coded with Visual Studio 2008.\"\n" ]
[ 2, 0, 0, 0 ]
[]
[]
[ "configuration", "extensibility", "unit_testing", "visual_studio", "vsx" ]
stackoverflow_0000013938_configuration_extensibility_unit_testing_visual_studio_vsx.txt
Q: Is it possible to coax Visual Studio 2008 into using italics for comments? I'm quite used to my IDE setup in Delphi 7, where I have my comments rendered in italics. This doesn't appear to be possible in VS2008. There's only an option for bold font, not italics. Is there some kind of registry hack or font magic I can perform to get it to work? The font I'm using is Consolas, if that makes a difference. Edit: This is possible. See this answer for details. Adam, as far as I can tell, you can't change the font name for just comments - only the colour, and boldness. If I'm wrong, please tell me! A: If you have a font editor, you can change an italic font to pretend it's bold. Here's an example of it. (For VS 2005, but it should work all the same.) A: I recommend Damien Guard's "Humane theme" for Visual Studio. It includes a custom font he developed, Envy R, which uses a clever hack - the bold version of the font is actually italic, so his theme italicizes comments by telling Visual Studio to bold them. Even if you don't like the colors, just grab the theme (or the Envy R font) and tweak it in. A: The pertinent registry key is HKCU\Software\Microsoft\VisualStudio\9.0\FontAndColors\{A27B4E24-A735-4D1D-B8E7-9716E1E3D8E0} Comment FontFlags Default is 0. Putting in a few test values got me various combination of normal, bold, and strike-through text, but no italics. Strikethrough isn't an option in the dialog either, so maybe there is a magic value for italics. @jon limjap: The VS 2008 version of that theme doesn't italicize comments, just bold. A: I dunno how he did it but Tomas Restrepo has a Visual Studio theme that is able to italicize comments and string literals. This one is in Visual Studio 2005, but the theme editing for both versions appear unchange so it might provide you with some clues as to how to do it on your own theme. Update: I didn't notice that he had a link to a Visual Studio 2008 version at the bottom of the post. A: You can kind of fake it by changing the font to something like the Lucida Handwriting font, which looks sort of italic or, buy or find a free italic only font. Edit: I've actually gone through the built-in fonts on my VS 2008 on Vista, and chosen Monotype Corsiva, and bumped the size to 12 for my comments setting (getting old - eyes aren't what they used to be) A: I successfully used FontForge to create a copy of Consolas (although this should work with any font) with the bold style actually being italics. This other answer of mine has the details. Basically, change the name and GUID, then open the italic variant and change its font info from saying italic to saying bold. A: Unfortunately not...not sure why they don't let you do that. You can, however, change the font for just comments. So you could make it something different which will make it stand out more. You may even be able to make a custom version of the font you use that is by default italic and then set that as the comment font.
Is it possible to coax Visual Studio 2008 into using italics for comments?
I'm quite used to my IDE setup in Delphi 7, where I have my comments rendered in italics. This doesn't appear to be possible in VS2008. There's only an option for bold font, not italics. Is there some kind of registry hack or font magic I can perform to get it to work? The font I'm using is Consolas, if that makes a difference. Edit: This is possible. See this answer for details. Adam, as far as I can tell, you can't change the font name for just comments - only the colour, and boldness. If I'm wrong, please tell me!
[ "If you have a font editor, you can change an italic font to pretend it's bold. Here's an example of it. (For VS 2005, but it should work all the same.)\n", "I recommend Damien Guard's \"Humane theme\" for Visual Studio. It includes a custom font he developed, Envy R, which uses a clever hack - the bold version of the font is actually italic, so his theme italicizes comments by telling Visual Studio to bold them.\nEven if you don't like the colors, just grab the theme (or the Envy R font) and tweak it in.\n\n", "The pertinent registry key is\nHKCU\\Software\\Microsoft\\VisualStudio\\9.0\\FontAndColors\\{A27B4E24-A735-4D1D-B8E7-9716E1E3D8E0} \nComment FontFlags\n\nDefault is 0. Putting in a few test values got me various combination of normal, bold, and strike-through text, but no italics. Strikethrough isn't an option in the dialog either, so maybe there is a magic value for italics.\n@jon limjap:\nThe VS 2008 version of that theme doesn't italicize comments, just bold.\n", "I dunno how he did it but Tomas Restrepo has a Visual Studio theme that is able to italicize comments and string literals.\nThis one is in Visual Studio 2005, but the theme editing for both versions appear unchange so it might provide you with some clues as to how to do it on your own theme.\nUpdate: I didn't notice that he had a link to a Visual Studio 2008 version at the bottom of the post. \n", "You can kind of fake it by changing the font to something like the Lucida Handwriting font, which looks sort of italic or, buy or find a free italic only font. \nEdit: I've actually gone through the built-in fonts on my VS 2008 on Vista, and chosen Monotype Corsiva, and bumped the size to 12 for my comments setting (getting old - eyes aren't what they used to be)\n", "I successfully used FontForge to create a copy of Consolas (although this should work with any font) with the bold style actually being italics.\nThis other answer of mine has the details.\nBasically, change the name and GUID, then open the italic variant and change its font info from saying italic to saying bold.\n", "Unfortunately not...not sure why they don't let you do that.\nYou can, however, change the font for just comments. So you could make it something different which will make it stand out more.\nYou may even be able to make a custom version of the font you use that is by default italic and then set that as the comment font.\n" ]
[ 3, 3, 2, 1, 1, 1, 0 ]
[]
[]
[ "consolas", "fonts", "visual_studio" ]
stackoverflow_0000015414_consolas_fonts_visual_studio.txt
Q: Audio player on Windows Mobile I'm trying to develop specialized audio player for windows mobile devices (Professional ones). And I've ran into the problem an once. There no compressed audio APIs on WM or I was unable to found house in documentation. Yes there are WM6 Sound API but it cannot even pause playback or seek to specified position. There are allways Windows Media Player on WM device but I've not found it APIs documentation. So the question is: Is there simple way to play, pause, forward, rewind, getting playback position and getting audio file length on compressed audio of several popular formats? Any library? platform APIs? Anything? A: This might be of no help at all, but the (very good) podcast player BeyondPod has a built in player, based on Windows Media Player, and it's open source - so you could have a look at what API they are using. Obviously if they've written their own custom player, you wont be able to just copy it if you're writing a commercial app. But you could use it for API documentation if they're just calling through to some Media Player API. A: I've found quite a sufficient compressed audio playback library FMOD. There are WM version of it. And I've found sample application on CodeProject to start with.
Audio player on Windows Mobile
I'm trying to develop specialized audio player for windows mobile devices (Professional ones). And I've ran into the problem an once. There no compressed audio APIs on WM or I was unable to found house in documentation. Yes there are WM6 Sound API but it cannot even pause playback or seek to specified position. There are allways Windows Media Player on WM device but I've not found it APIs documentation. So the question is: Is there simple way to play, pause, forward, rewind, getting playback position and getting audio file length on compressed audio of several popular formats? Any library? platform APIs? Anything?
[ "This might be of no help at all, but the (very good) podcast player BeyondPod has a built in player, based on Windows Media Player, and it's open source - so you could have a look at what API they are using.\nObviously if they've written their own custom player, you wont be able to just copy it if you're writing a commercial app. But you could use it for API documentation if they're just calling through to some Media Player API.\n", "I've found quite a sufficient compressed audio playback library FMOD. There are WM version of it. And I've found sample application on CodeProject to start with.\n" ]
[ 2, 0 ]
[]
[]
[ "windows_mobile" ]
stackoverflow_0000020233_windows_mobile.txt
Q: Can I capture Windows Mobile PIE keyboard events? Anyone know of a way to capture keyboard events (keyup / keydown) in Portable IE under Window mobile? I noticed that key events are not supported in JS, and would like to come up with a solution that works without any client side additions. A: Without any client side additions? As per IEMobile Team Blog, the only way for that would be wait for the next release :(
Can I capture Windows Mobile PIE keyboard events?
Anyone know of a way to capture keyboard events (keyup / keydown) in Portable IE under Window mobile? I noticed that key events are not supported in JS, and would like to come up with a solution that works without any client side additions.
[ "Without any client side additions?\nAs per IEMobile Team Blog, the only way for that would be wait for the next release :(\n" ]
[ 1 ]
[]
[]
[ "internet_explorer", "key_events", "windows_mobile" ]
stackoverflow_0000024414_internet_explorer_key_events_windows_mobile.txt
Q: Multiple YACC grammars in one program How do I compile, link and call different YACC grammars using yyparse() in one program? A: Use the -p option for each separate yacc grammar generation -p prefix Use prefix instead of yy as the prefix for all external names produced by yacc. For X/Open compliance, when the environment variable _XPG is set, then the -p option will work as described in the previous sentence. If the environment variable _XPG is not set, then the -p option will work as described below in the -P option.
Multiple YACC grammars in one program
How do I compile, link and call different YACC grammars using yyparse() in one program?
[ "Use the -p option for each separate yacc grammar generation \n -p prefix\n\n Use prefix instead of yy as the prefix for all external\n names produced by yacc. For X/Open compliance, when the\n environment variable _XPG is set, then the -p option will work\n as described in the previous sentence. If the environment\n variable _XPG is not set, then the -p option will work as\n described below in the -P option.\n\n" ]
[ 7 ]
[]
[]
[ "yacc" ]
stackoverflow_0000025823_yacc.txt
Q: Why can't I explicitly pass the type argument to a generic Java method? I have defined a Java function: static <T> List<T> createEmptyList() { return new ArrayList<T>(); } One way to call it is like so: List<Integer> myList = createEmptyList(); // Compiles Why can't I call it by explicitly passing the generic type argument? : Object myObject = createEmtpyList<Integer>(); // Doesn't compile. Why? I get the error Illegal start of expression from the compiler. A: When the java compiler cannot infer the parameter type by itself for a static method, you can always pass it using the full qualified method name: Class . < Type > method(); Object list = Collections.<String> emptyList(); A: You can, if you pass in the type as a method parameter. static <T> List<T> createEmptyList( Class<T> type ) { return new ArrayList<T>(); } @Test public void createStringList() { List<String> stringList = createEmptyList( String.class ); } Methods cannot be genericised in the same way that a type can, so the only option for a method with a dynamically-typed generic return type -- phew that's a mouthful :-) -- is to pass in the type as an argument. For a truly excellent FAQ on Java generics, see Angelika Langer's generics FAQ. . . Follow-up: It wouldn't make sense in this context to use the array argument as in Collection.toArray( T[] ). The only reason an array is used there is because the same (pre-allocated) array is used to contain the results (if the array is large enough to fit them all in). This saves on allocating a new array at run-time all the time. However, for the purposes of education, if you did want to use the array typing, the syntax is very similar: static <T> List<T> createEmptyList( T[] array ) { return new ArrayList<T>(); } @Test public void testThing() { List<Integer> integerList = createEmptyList( new Integer[ 1 ] ); } A: @pauldoo Yes, you are quite right. It is one of the weaknesses with the java generics imho. I response to Cheekysoft I'd like to propose to also look at how it is done by the Java people themselves, such as T[] AbstractCollection#toArray(T[] a). I think Cheekysofts version is superior, but the Java one has the advantage of familiarity. Edit: Added link. Re-edit: Found a bug on SO :) Follow-up on Cheekysoft: Well, as it is a list of some type that should be returned the corresponding example should look something like: static <T> List<T> createEmptyList( List<T> a ) { return new ArrayList<T>(); } But yes, passing the class object is clearly the better one. My only argument is that of familiarity, and in this exact instance it isn't worth much (in fact it is bad).
Why can't I explicitly pass the type argument to a generic Java method?
I have defined a Java function: static <T> List<T> createEmptyList() { return new ArrayList<T>(); } One way to call it is like so: List<Integer> myList = createEmptyList(); // Compiles Why can't I call it by explicitly passing the generic type argument? : Object myObject = createEmtpyList<Integer>(); // Doesn't compile. Why? I get the error Illegal start of expression from the compiler.
[ "When the java compiler cannot infer the parameter type by itself for a static method, you can always pass it using the full qualified method name: Class . < Type > method();\nObject list = Collections.<String> emptyList();\n\n", "You can, if you pass in the type as a method parameter.\nstatic <T> List<T> createEmptyList( Class<T> type ) {\n return new ArrayList<T>();\n}\n\n@Test\npublic void createStringList() {\n List<String> stringList = createEmptyList( String.class );\n}\n\nMethods cannot be genericised in the same way that a type can, so the only option for a method with a dynamically-typed generic return type -- phew that's a mouthful :-) -- is to pass in the type as an argument.\nFor a truly excellent FAQ on Java generics, see Angelika Langer's generics FAQ.\n.\n. \nFollow-up:\nIt wouldn't make sense in this context to use the array argument as in Collection.toArray( T[] ). The only reason an array is used there is because the same (pre-allocated) array is used to contain the results (if the array is large enough to fit them all in). This saves on allocating a new array at run-time all the time.\nHowever, for the purposes of education, if you did want to use the array typing, the syntax is very similar:\nstatic <T> List<T> createEmptyList( T[] array ) {\n return new ArrayList<T>();\n}\n\n@Test\npublic void testThing() {\n List<Integer> integerList = createEmptyList( new Integer[ 1 ] );\n}\n\n", "@pauldoo\nYes, you are quite right. It is one of the weaknesses with the java generics imho.\nI response to Cheekysoft I'd like to propose to also look at how it is done by the Java people themselves, such as T[] AbstractCollection#toArray(T[] a). I think Cheekysofts version is superior, but the Java one has the advantage of familiarity.\nEdit: Added link.\nRe-edit: Found a bug on SO :)\n\nFollow-up on Cheekysoft:\nWell, as it is a list of some type that should be returned the corresponding example should look something like:\nstatic <T> List<T> createEmptyList( List<T> a ) {\n return new ArrayList<T>();\n}\n\nBut yes, passing the class object is clearly the better one. My only argument is that of familiarity, and in this exact instance it isn't worth much (in fact it is bad).\n" ]
[ 49, 26, 0 ]
[]
[]
[ "generics", "java", "syntax" ]
stackoverflow_0000024991_generics_java_syntax.txt
Q: What is a data binding? What is a data binding? A: Binding generally refers to a mapping of one thing to another - i.e. a datasource to a presentation object. It can typically refer to binding data from a database, or similar source (XML file, web service etc) to a presentation control or element - think list or table in HTML, combo box or data grid in desktop software. You generally have to bind the presentation element to the datasource, not the other way around. This would involve some kind of mapping - i.e. which fields from the datasource do you want to appear in the output. For more information in a couple of environments see: Data binding in .Net using Windows Forms http://www.codeproject.com/KB/database/databindingconcepts.aspx http://www.akadia.com/services/dotnet_databinding.html ASP.NET data binding http://support.microsoft.com/kb/307860 http://www.15seconds.com/issue/040630.htm http://www.w3schools.com/ASPNET/aspnet_databinding.asp Java data binding http://www.xml.com/pub/a/2003/09/03/binding.html Python data binding http://www.xml.com/pub/a/2005/07/27/py-xml.html General XML data binding http://www.rpbourret.com/xml/XMLDataBinding.htm
What is a data binding?
What is a data binding?
[ "Binding generally refers to a mapping of one thing to another - i.e. a datasource to a presentation object. It can typically refer to binding data from a database, or similar source (XML file, web service etc) to a presentation control or element - think list or table in HTML, combo box or data grid in desktop software.\nYou generally have to bind the presentation element to the datasource, not the other way around. This would involve some kind of mapping - i.e. which fields from the datasource do you want to appear in the output.\nFor more information in a couple of environments see:\n\nData binding in .Net using Windows Forms\n\n\nhttp://www.codeproject.com/KB/database/databindingconcepts.aspx\nhttp://www.akadia.com/services/dotnet_databinding.html\n\nASP.NET data binding\n\n\nhttp://support.microsoft.com/kb/307860\nhttp://www.15seconds.com/issue/040630.htm\nhttp://www.w3schools.com/ASPNET/aspnet_databinding.asp\n\nJava data binding\n\n\nhttp://www.xml.com/pub/a/2003/09/03/binding.html\n\nPython data binding\n\n\nhttp://www.xml.com/pub/a/2005/07/27/py-xml.html\n\nGeneral XML data binding\n\n\nhttp://www.rpbourret.com/xml/XMLDataBinding.htm\n\n\n" ]
[ 12 ]
[]
[]
[ "data_binding", "glossary" ]
stackoverflow_0000025878_data_binding_glossary.txt
Q: What is a language binding? My good friend, Wikipedia, didn't give me a very good response to that question. So: What are language bindings? How do they work? Specifically accessing functions from code written in language X of a library written in language Y. A: Let's say you create a C library to post stuff to stackoverflow. Now you want to be able to use the same library from Python. In this case, you will write Python bindings for your library. Also see SWIG: http://www.swig.org A: In the context of code libraries, bindings are wrapper libraries that bridge between two programming languages so that a library that was written for one language can also be implicitly used in another language. For example, libsvn is the API for Subversion and was written in C. If you want to access Subversion from within Java code you can use libsvn-java. libsvn-java depends on libsvn being installed because libsvn-java is a mere bridge between the Java programming language and libsvn, providing an API that merely calls functions of libsvn to do the real work. A: Okay, now the question has been clarified, this isn't really relevant so I'm moving it to a new question Binding generally refers to a mapping of one thing to another - i.e. a datasource to a presentation object. It can typically refer to binding data from a database, or similar source (XML file, web service etc) to a presentation control or element - think list or table in HTML, combo box or data grid in desktop software. ...If that's the kind of binding you're interested in, read on... You generally have to bind the presentation element to the datasource, not the other way around. This would involve some kind of mapping - i.e. which fields from the datasource do you want to appear in the output. For more information in a couple of environments see: Data binding in .Net using Windows Forms http://www.codeproject.com/KB/database/databindingconcepts.aspx http://www.akadia.com/services/dotnet_databinding.html ASP.NET data binding http://support.microsoft.com/kb/307860 http://www.15seconds.com/issue/040630.htm http://www.w3schools.com/ASPNET/aspnet_databinding.asp Java data binding http://www.xml.com/pub/a/2003/09/03/binding.html Python data binding http://www.xml.com/pub/a/2005/07/27/py-xml.html General XML data binding http://www.rpbourret.com/xml/XMLDataBinding.htm
What is a language binding?
My good friend, Wikipedia, didn't give me a very good response to that question. So: What are language bindings? How do they work? Specifically accessing functions from code written in language X of a library written in language Y.
[ "Let's say you create a C library to post stuff to stackoverflow. Now you want to be able to use the same library from Python. In this case, you will write Python bindings for your library.\nAlso see SWIG: http://www.swig.org\n", "In the context of code libraries, bindings are wrapper libraries that bridge between two programming languages so that a library that was written for one language can also be implicitly used in another language.\nFor example, libsvn is the API for Subversion and was written in C. If you want to access Subversion from within Java code you can use libsvn-java. libsvn-java depends on libsvn being installed because libsvn-java is a mere bridge between the Java programming language and libsvn, providing an API that merely calls functions of libsvn to do the real work.\n", "Okay, now the question has been clarified, this isn't really relevant so I'm moving it to a new question\nBinding generally refers to a mapping of one thing to another - i.e. a datasource to a presentation object. It can typically refer to binding data from a database, or similar source (XML file, web service etc) to a presentation control or element - think list or table in HTML, combo box or data grid in desktop software.\n...If that's the kind of binding you're interested in, read on...\nYou generally have to bind the presentation element to the datasource, not the other way around. This would involve some kind of mapping - i.e. which fields from the datasource do you want to appear in the output.\nFor more information in a couple of environments see:\n\nData binding in .Net using Windows Forms\n\n\nhttp://www.codeproject.com/KB/database/databindingconcepts.aspx\nhttp://www.akadia.com/services/dotnet_databinding.html\n\nASP.NET data binding\n\n\nhttp://support.microsoft.com/kb/307860\nhttp://www.15seconds.com/issue/040630.htm\nhttp://www.w3schools.com/ASPNET/aspnet_databinding.asp\n\nJava data binding\n\n\nhttp://www.xml.com/pub/a/2003/09/03/binding.html\n\nPython data binding\n\n\nhttp://www.xml.com/pub/a/2005/07/27/py-xml.html\n\nGeneral XML data binding\n\n\nhttp://www.rpbourret.com/xml/XMLDataBinding.htm\n\n\n" ]
[ 44, 23, 5 ]
[ "In Flex (Actionscript 3). Source\nA data binding copies the value of a property in one object to a property in another object. You can bind the properties of following objects: Flex components, Flex data models, and Flex data services.\nThe object property that provides the data is known as the source property. The object property that receives the data is known as the destination property.\nThe following example binds the text property of a TextInput component (the source property) to the text property of a Label component (the destination property) so that text entered in the TextInput component is displayed by the Label component:\n<mx:TextInput id=\"LNameInput\"></mx:TextInput>\n...\n<mx:Label text=\"{LNameInput.text}\"></mx:Label>\n\n\nData binding is usually a simple way to bind a model to user interface components. For example, you have a class with a FirstName property. In flex you could easily bind that property to a textbox by setting the value of the textbox to {Object.FirstName}. Then, every time that FirstName property changes, the textbox will be updated without requiring you to write any code to monitor that property for changes.\nHope that helps.\nMatt\n" ]
[ -1 ]
[ "glossary", "language_agnostic", "language_binding" ]
stackoverflow_0000025865_glossary_language_agnostic_language_binding.txt
Q: Capturing a repeated group I am attempting to parse a string like the following using a .NET regular expression: H3Y5NC8E-TGA5B6SB-2NVAQ4E0 and return the following using Split: H3Y5NC8E TGA5B6SB 2NVAQ4E0 I validate each character against a specific character set (note that the letters 'I', 'O', 'U' & 'W' are absent), so using string.Split is not an option. The number of characters in each group can vary and the number of groups can also vary. I am using the following expression: ([ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8}-?){3} This will match exactly 3 groups of 8 characters each. Any more or less will fail the match. This works insofar as it correctly matches the input. However, when I use the Split method to extract each character group, I just get the final group. RegexBuddy complains that I have repeated the capturing group itself and that I should put a capture group around the repeated group. However, none of my attempts to do this achieve the desired result. I have been trying expressions like this: (([ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8})-?){4} But this does not work. Since I generate the regex in code, I could just expand it out by the number of groups, but I was hoping for a more elegant solution. Please note that the character set does not include the entire alphabet. It is part of a product activation system. As such, any characters that can be accidentally interpreted as numbers or other characters are removed. e.g. The letters 'I', 'O', 'U' & 'W' are not in the character set. The hyphens are optional since a user does not need top type them in, but they can be there if the user as done a copy & paste. A: BTW, you can replace [ABCDEFGHJKLMNPQRSTVXYZ0123456789] character class with a more readable subtracted character class. [[A-Z\d]-[IOUW]] If you just want to match 3 groups like that, why don't you use this pattern 3 times in your regex and just use captured 1, 2, 3 subgroups to form the new string? ([[A-Z\d]-[IOUW]]){8}-([[A-Z\d]-[IOUW]]){8}-([[A-Z\d]-[IOUW]]){8} In PHP I would return (I don't know .NET) return "$1 $2 $3"; A: I have discovered the answer I was after. Here is my working code: static void Main(string[] args) { string pattern = @"^\s*((?<group>[ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8})-?){3}\s*$"; string input = "H3Y5NC8E-TGA5B6SB-2NVAQ4E0"; Regex re = new Regex(pattern); Match m = re.Match(input); if (m.Success) foreach (Capture c in m.Groups["group"].Captures) Console.WriteLine(c.Value); } A: After reviewing your question and the answers given, I came up with this: RegexOptions options = RegexOptions.None; Regex regex = new Regex(@"([ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8})", options); string input = @"H3Y5NC8E-TGA5B6SB-2NVAQ4E0"; MatchCollection matches = regex.Matches(input); for (int i = 0; i != matches.Count; ++i) { string match = matches[i].Value; } Since the "-" is optional, you don't need to include it. I am not sure what you was using the {4} at the end for? This will find the matches based on what you want, then using the MatchCollection you can access each match to rebuild the string. A: Why use Regex? If the groups are always split by a -, can't you use Split()? A: Sorry if this isn't what you intended, but your string always has the hyphen separating the groups then instead of using regex couldn't you use the String.Split() method? Dim stringArray As Array = someString.Split("-") A: You can use this pattern: Regex.Split("H3Y5NC8E-TGA5B6SB-2NVAQ4E0", "([ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8}+)-?") But you will need to filter out empty strings from resulting array. Citation from MSDN: If multiple matches are adjacent to one another, an empty string is inserted into the array. A: What are the defining characteristics of a valid block? We'd need to know that in order to really be helpful. My generic suggestion, validate the charset in a first step, then split and parse in a seperate method based on what you expect. If this is in a web site/app then you can use the ASP Regex validation on the front end then break it up on the back end. A: If you're just checking the value of the group, with group(i).value, then you will only get the last one. However, if you want to enumerate over all the times that group was captured, use group(2).captures(i).value, as shown below. system.text.RegularExpressions.Regex.Match("H3Y5NC8E-TGA5B6SB-2NVAQ4E0","(([ABCDEFGHJKLMNPQRSTVXYZ0123456789]+)-?)*").Groups(2).Captures(i).Value A: Mike, You can use character set of your choice inside character group. All you need is to add "+" modifier to capture all groups. See my previous answer, just change [A-Z0-9] to whatever you need (i.e. [ABCDEFGHJKLMNPQRSTVXYZ0123456789])
Capturing a repeated group
I am attempting to parse a string like the following using a .NET regular expression: H3Y5NC8E-TGA5B6SB-2NVAQ4E0 and return the following using Split: H3Y5NC8E TGA5B6SB 2NVAQ4E0 I validate each character against a specific character set (note that the letters 'I', 'O', 'U' & 'W' are absent), so using string.Split is not an option. The number of characters in each group can vary and the number of groups can also vary. I am using the following expression: ([ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8}-?){3} This will match exactly 3 groups of 8 characters each. Any more or less will fail the match. This works insofar as it correctly matches the input. However, when I use the Split method to extract each character group, I just get the final group. RegexBuddy complains that I have repeated the capturing group itself and that I should put a capture group around the repeated group. However, none of my attempts to do this achieve the desired result. I have been trying expressions like this: (([ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8})-?){4} But this does not work. Since I generate the regex in code, I could just expand it out by the number of groups, but I was hoping for a more elegant solution. Please note that the character set does not include the entire alphabet. It is part of a product activation system. As such, any characters that can be accidentally interpreted as numbers or other characters are removed. e.g. The letters 'I', 'O', 'U' & 'W' are not in the character set. The hyphens are optional since a user does not need top type them in, but they can be there if the user as done a copy & paste.
[ "BTW, you can replace [ABCDEFGHJKLMNPQRSTVXYZ0123456789] character class with a more readable subtracted character class.\n[[A-Z\\d]-[IOUW]]\n\nIf you just want to match 3 groups like that, why don't you use this pattern 3 times in your regex and just use captured 1, 2, 3 subgroups to form the new string?\n([[A-Z\\d]-[IOUW]]){8}-([[A-Z\\d]-[IOUW]]){8}-([[A-Z\\d]-[IOUW]]){8}\n\nIn PHP I would return (I don't know .NET)\nreturn \"$1 $2 $3\";\n\n", "I have discovered the answer I was after. Here is my working code:\n static void Main(string[] args)\n {\n string pattern = @\"^\\s*((?<group>[ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8})-?){3}\\s*$\";\n string input = \"H3Y5NC8E-TGA5B6SB-2NVAQ4E0\";\n Regex re = new Regex(pattern);\n Match m = re.Match(input);\n\n if (m.Success)\n foreach (Capture c in m.Groups[\"group\"].Captures)\n Console.WriteLine(c.Value);\n }\n\n", "After reviewing your question and the answers given, I came up with this:\nRegexOptions options = RegexOptions.None;\nRegex regex = new Regex(@\"([ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8})\", options);\nstring input = @\"H3Y5NC8E-TGA5B6SB-2NVAQ4E0\";\n\nMatchCollection matches = regex.Matches(input);\nfor (int i = 0; i != matches.Count; ++i)\n{\n string match = matches[i].Value;\n}\n\nSince the \"-\" is optional, you don't need to include it. I am not sure what you was using the {4} at the end for? This will find the matches based on what you want, then using the MatchCollection you can access each match to rebuild the string.\n", "Why use Regex? If the groups are always split by a -, can't you use Split()?\n", "Sorry if this isn't what you intended, but your string always has the hyphen separating the groups then instead of using regex couldn't you use the String.Split() method? \nDim stringArray As Array = someString.Split(\"-\")\n\n", "You can use this pattern:\nRegex.Split(\"H3Y5NC8E-TGA5B6SB-2NVAQ4E0\", \"([ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8}+)-?\")\n\nBut you will need to filter out empty strings from resulting array.\nCitation from MSDN:\n\nIf multiple matches are adjacent to one another, an empty string is inserted into the array.\n\n", "What are the defining characteristics of a valid block? We'd need to know that in order to really be helpful. \nMy generic suggestion, validate the charset in a first step, then split and parse in a seperate method based on what you expect. If this is in a web site/app then you can use the ASP Regex validation on the front end then break it up on the back end. \n", "If you're just checking the value of the group, with group(i).value, then you will only get the last one. However, if you want to enumerate over all the times that group was captured, use group(2).captures(i).value, as shown below. \nsystem.text.RegularExpressions.Regex.Match(\"H3Y5NC8E-TGA5B6SB-2NVAQ4E0\",\"(([ABCDEFGHJKLMNPQRSTVXYZ0123456789]+)-?)*\").Groups(2).Captures(i).Value\n\n", "Mike,\nYou can use character set of your choice inside character group. All you need is to add \"+\" modifier to capture all groups. See my previous answer, just change [A-Z0-9] to whatever you need (i.e. [ABCDEFGHJKLMNPQRSTVXYZ0123456789])\n" ]
[ 5, 4, 3, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ ".net_2.0", "regex" ]
stackoverflow_0000025561_.net_2.0_regex.txt
Q: What is ASP.NET? I've been strictly in a C++ environment for years (and specialized statistical languages). Visual Studio until 2001, and Borland since. Mostly specialized desktop applications for clients. I'm not remaining willfully ignorant of it, but over the years when I've dipped into other things, I've spent my time playing around with JavaScript, PHP, and a lot of Python. Is "ASP.NET" the language? Is C# the language and "ASP.NET" the framework? What's a good answer to "What is ASP.NET"? Is there a correspondence between ASP.NET and anything I'd be familiar with in C++? I know I can google the same title, but I'd rather see answers from this crowd. (Besides, in the future, I think that Google should point here for questions like that.) A: I was going to write a lengthy answer but I felt that Wikipedia had it covered: ASP.NET is a web application framework developed and marketed by Microsoft, that programmers can use to build dynamic web sites, web applications and web services. It was first released in January 2002 with version 1.0 of the .NET Framework, and is the successor to Microsoft's Active Server Pages (ASP) technology. ASP.NET is built on the Common Language Runtime (CLR), allowing programmers to write ASP.NET code using any supported .NET language. So ASP.NET is Microsoft's web development framework and the latest version is 4.0. How do I get started? Check out the following resources: Learn ASP.NET ASP.NET Documentation ASP.NET Developer Center A: ASP.NET is the framework, just like .NET The code itself, will be a mix of HTML, JavaScript(for Client-Side) and any .NET compatible language. So C#, VB.NET, C++.NET, heck...even IronPython A: ASP.NET is a framework, it delivers: A class hierachy you hook into, that allows both usage of supplied components, as well as development of your own. Integration with and easy access to the underlying webserver. An event model, which is probably the "best" thing about it. A general abstraction from the underlying medium of HTML and HTTP. Not sure if ASP.NET compares to any C++ frameworks you may be familiar with. Web frameworks usually tend to be unique due to the statelessness of HTTP and the relatively low-tech technologies involved (HTML, scripting, etc). A: ASP.NET is a web application framework developed and marketed by Microsoft, that programmers can use to build dynamic web sites, web applications and web services. It was first released in January 2002 with version 1.0 of the .NET Framework, and is the successor to Microsoft's Active Server Pages (ASP) technology. ASP.NET is built on the Common Language Runtime (CLR), allowing programmers to write ASP.NET code using any supported .NET language. ASP.NET (Wikipedia) That's on the second result searching on Google so I'm guessing (half-expecting) that you don't understand what that means either. Webpage development started with simple static HTML pages. That meant the client asked for a page by means of an URL and the server sent the page back to him/her exactly as it has been designed. Sometime after that several technologies emerged in order to provide a more "dynamic" or personalized experience. Several "server side languages" were developed (PHP, Perl, ASP...) which allowed the server to process the Web page before sending it back to the client. This way when a client requested a webpage the server could interpret the request, process it (for example connecting to a database and fetching some results) and send it back modifying the contents and making them "dynamic". The fact that the process took place on the server stands for the name of "server side". So the original ASP (predecessor of the ASP.NET) was a server side language that was focused on serving web pages. In such way it supported several shortcuts such as the possibility to intercalate HTML and ASP source into the file which was on that time much popular due to PHP implementation. It was also (as most of these languages) a dynamic language and it was interpreted. ASP.NET is an evolution of that original ASP with some improvements. First it does truly (try to) separate the presentation (HTML) from the code (.cs) which may be implemented by using Visual Basic or C# syntax. It also incorporate some sort of compilation to the final ASP pages, encapsulating them into assemblies and thus improving performance. Finally it has access to the full .NET framework which supports a wide number of helper classes. So, summing up, it is a programming language located on the server and designed to make webpages. A: Let's say it's a technique from MS to build web applications. ASP stands for Active Server Pages, .NET is the framework behind it. C# and VB.NET are the languages which can be used, but I guess other .NET languages also can be used. A: Take a look at MS' info for those who don't know or understand the platform. http://www.asp.net/get-started
What is ASP.NET?
I've been strictly in a C++ environment for years (and specialized statistical languages). Visual Studio until 2001, and Borland since. Mostly specialized desktop applications for clients. I'm not remaining willfully ignorant of it, but over the years when I've dipped into other things, I've spent my time playing around with JavaScript, PHP, and a lot of Python. Is "ASP.NET" the language? Is C# the language and "ASP.NET" the framework? What's a good answer to "What is ASP.NET"? Is there a correspondence between ASP.NET and anything I'd be familiar with in C++? I know I can google the same title, but I'd rather see answers from this crowd. (Besides, in the future, I think that Google should point here for questions like that.)
[ "I was going to write a lengthy answer but I felt that Wikipedia had it covered:\n\nASP.NET is a web application framework\n developed and marketed by Microsoft,\n that programmers can use to build\n dynamic web sites, web applications\n and web services. It was first\n released in January 2002 with version\n 1.0 of the .NET Framework, and is the successor to Microsoft's Active Server\n Pages (ASP) technology. ASP.NET is\n built on the Common Language Runtime\n (CLR), allowing programmers to write\n ASP.NET code using any supported .NET\n language.\n\nSo ASP.NET is Microsoft's web development framework and the latest version is 4.0.\nHow do I get started? Check out the following resources:\n\nLearn ASP.NET\nASP.NET Documentation\nASP.NET Developer Center\n\n", "ASP.NET is the framework, just like .NET\nThe code itself, will be a mix of HTML, JavaScript(for Client-Side) and any .NET compatible language. So C#, VB.NET, C++.NET, heck...even IronPython\n", "ASP.NET is a framework, it delivers:\n\nA class hierachy you hook into, that allows both usage of supplied components, as well as development of your own.\nIntegration with and easy access to the underlying webserver.\nAn event model, which is probably the \"best\" thing about it.\nA general abstraction from the underlying medium of HTML and HTTP.\n\nNot sure if ASP.NET compares to any C++ frameworks you may be familiar with. Web frameworks usually tend to be unique due to the statelessness of HTTP and the relatively low-tech technologies involved (HTML, scripting, etc).\n", "\nASP.NET is a web application framework\n developed and marketed by Microsoft,\n that programmers can use to build\n dynamic web sites, web applications\n and web services. It was first\n released in January 2002 with version\n 1.0 of the .NET Framework, and is the successor to Microsoft's Active Server\n Pages (ASP) technology. ASP.NET is\n built on the Common Language Runtime\n (CLR), allowing programmers to write\n ASP.NET code using any supported .NET\n language.\n\nASP.NET (Wikipedia)\nThat's on the second result searching on Google so I'm guessing (half-expecting) that you don't understand what that means either.\nWebpage development started with simple static HTML pages. That meant the client asked for a page by means of an URL and the server sent the page back to him/her exactly as it has been designed. Sometime after that several technologies emerged in order to provide a more \"dynamic\" or personalized experience.\nSeveral \"server side languages\" were developed (PHP, Perl, ASP...) which allowed the server to process the Web page before sending it back to the client. This way when a client requested a webpage the server could interpret the request, process it (for example connecting to a database and fetching some results) and send it back modifying the contents and making them \"dynamic\". The fact that the process took place on the server stands for the name of \"server side\".\nSo the original ASP (predecessor of the ASP.NET) was a server side language that was focused on serving web pages. In such way it supported several shortcuts such as the possibility to intercalate HTML and ASP source into the file which was on that time much popular due to PHP implementation. It was also (as most of these languages) a dynamic language and it was interpreted.\nASP.NET is an evolution of that original ASP with some improvements. First it does truly (try to) separate the presentation (HTML) from the code (.cs) which may be implemented by using Visual Basic or C# syntax. It also incorporate some sort of compilation to the final ASP pages, encapsulating them into assemblies and thus improving performance. Finally it has access to the full .NET framework which supports a wide number of helper classes.\nSo, summing up, it is a programming language located on the server and designed to make webpages.\n", "Let's say it's a technique from MS to build web applications. ASP stands for Active Server Pages, .NET is the framework behind it.\nC# and VB.NET are the languages which can be used, but I guess other .NET languages also can be used.\n", "Take a look at MS' info for those who don't know or understand the platform.\nhttp://www.asp.net/get-started\n" ]
[ 8, 6, 5, 5, 2, 0 ]
[]
[]
[ "asp.net", "glossary" ]
stackoverflow_0000025921_asp.net_glossary.txt
Q: Maximum buffer length for sendto? How do you get the maximum number of bytes that can be passed to a sendto(..) call for a socket opened as a UDP port? A: Use getsockopt(). This site has a good breakdown of the usage and options you can retrieve. In Windows, you can do: int optlen = sizeof(int); int optval; getsockopt(socket, SOL_SOCKET, SO_MAX_MSG_SIZE, (int *)&optval, &optlen); For Linux, according to the UDP man page, the kernel will use MTU discovery (it will check what the maximum UDP packet size is between here and the destination, and pick that), or if MTU discovery is off, it'll set the maximum size to the interface MTU and fragment anything larger. If you're sending over Ethernet, the typical MTU is 1500 bytes. A: On Mac OS X there are different values for sending (SO_SNDBUF) and receiving (SO_RCVBUF). This is the size of the send buffer (man getsockopt): getsockopt(sock, SOL_SOCKET, SO_SNDBUF, (int *)&optval, &optlen); Trying to send a bigger message (on Leopard 9216 octets on UDP sent via the local loopback) will result in "Message too long / EMSGSIZE". A: As UDP is not connection oriented there's no way to indicate that two packets belong together. As a result you're limited by the maximum size of a single IP packet (65535). The data you can send is somewhat less that that, because the IP packet size also includes the IP header (usually 20 bytes) and the UDP header (8 bytes). Note that this IP packet can be fragmented to fit in smaller packets (eg. ~1500 bytes for ethernet). I'm not aware of any OS restricting this further. Bonus SO_MAX_MSG_SIZE of UDP packet IPv4: 65,507 bytes IPv6: 65,527 bytes
Maximum buffer length for sendto?
How do you get the maximum number of bytes that can be passed to a sendto(..) call for a socket opened as a UDP port?
[ "Use getsockopt(). This site has a good breakdown of the usage and options you can retrieve.\nIn Windows, you can do:\n\nint optlen = sizeof(int);\nint optval;\ngetsockopt(socket, SOL_SOCKET, SO_MAX_MSG_SIZE, (int *)&optval, &optlen);\n\nFor Linux, according to the UDP man page, the kernel will use MTU discovery (it will check what the maximum UDP packet size is between here and the destination, and pick that), or if MTU discovery is off, it'll set the maximum size to the interface MTU and fragment anything larger. If you're sending over Ethernet, the typical MTU is 1500 bytes.\n", "On Mac OS X there are different values for sending (SO_SNDBUF) and receiving (SO_RCVBUF).\nThis is the size of the send buffer (man getsockopt):\ngetsockopt(sock, SOL_SOCKET, SO_SNDBUF, (int *)&optval, &optlen);\n\nTrying to send a bigger message (on Leopard 9216 octets on UDP sent via the local loopback) will result in \"Message too long / EMSGSIZE\".\n", "As UDP is not connection oriented there's no way to indicate that two packets belong together. As a result you're limited by the maximum size of a single IP packet (65535). The data you can send is somewhat less that that, because the IP packet size also includes the IP header (usually 20 bytes) and the UDP header (8 bytes). \nNote that this IP packet can be fragmented to fit in smaller packets (eg. ~1500 bytes for ethernet).\nI'm not aware of any OS restricting this further.\nBonus\nSO_MAX_MSG_SIZE of UDP packet\n\nIPv4: 65,507 bytes\nIPv6: 65,527 bytes\n\n" ]
[ 14, 5, 2 ]
[]
[]
[ "ioctl", "networking", "sockets", "udp", "unix" ]
stackoverflow_0000025841_ioctl_networking_sockets_udp_unix.txt
Q: How to make a Flash movie with a transparent background This page from Adobe says to add a "wmode" parameter and set its value to "transparent": http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_1420 This works flawlessly in IE. The background renders correctly in Firefox and Safari, however as soon as you use the browser's scroll bar then mouse over the Flash control you must click once to activate the control. You can see this behavior if you try to hit the play button in Adobe's example. Anyone know a way around this? A: On another note; setting the wmode to transparent has a few kinks. For instance it can break the scrolling (the flash stays in the same place disregarding the scroll) in some older versions of Firefox (pre 2.0). I've also had issues with ALT-key combinations in textfields not working when wmode is transparent. Also, if you need to place html-content above flash-content (not a good idea generally, but there are cases when it's useful) wmode=transparent is the way to go. A: You know you can set the background color when you're embedding? The following attributes are optional when defining the object and/or embed tags. For object , all attributes are defined in param tags unless otherwise specified: bgcolor - [ hexadecimal RGB value] in the format #RRGGBB . Specifies the background color of the movie. Use this attribute to override the background color setting specified in the Flash file. This attribute does not affect the background color of the HTML page. Cut 'n paste from http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_12701&sliceId=1 A: Enabling windowless mode (wmode=) makes embedded flash act and render just like other elements. Without that, it's rendered in a seperate step and just overlaid on the browser's window. Could the flash element be losing focus? Sounds like input focus is moved to the scollbar, then you have to move it back. Also you weren't clear whether the focus issue was only in FF or also in IE. A: The Adobe example "works" in Firefox 3.0.1 in the sense that the background is transparent. However, in Firefox 3.0.1 and Safari 3.1.2 you must click the play button twice to see the animation. A: After spending some more time on this I agree with @grapefrukt. Setting wmode to transparent leads to all sorts of strange issues and in my opinion it should be avoided. Instead I've resorted to passing the background color as a parameter. I use the following ActionScript to draw the background. var parameters:Object = LoaderInfo(this.root.loaderInfo).parameters; opaqueBackground = parameters["background-color"]; EDIT: Thanks to @grapefrukt for reminding me of the bgcolor param (which makes the ActionScript above totally unnecessary)
How to make a Flash movie with a transparent background
This page from Adobe says to add a "wmode" parameter and set its value to "transparent": http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_1420 This works flawlessly in IE. The background renders correctly in Firefox and Safari, however as soon as you use the browser's scroll bar then mouse over the Flash control you must click once to activate the control. You can see this behavior if you try to hit the play button in Adobe's example. Anyone know a way around this?
[ "On another note; setting the wmode to transparent has a few kinks. For instance it can break the scrolling (the flash stays in the same place disregarding the scroll) in some older versions of Firefox (pre 2.0). I've also had issues with ALT-key combinations in textfields not working when wmode is transparent.\nAlso, if you need to place html-content above flash-content (not a good idea generally, but there are cases when it's useful) wmode=transparent is the way to go.\n", "You know you can set the background color when you're embedding?\n\nThe following attributes are optional when defining the object and/or embed tags. For object , all attributes are defined in param tags unless otherwise specified:\nbgcolor - [ hexadecimal RGB value] in the format #RRGGBB . Specifies the background color of the movie. Use this attribute to override the background color setting specified in the Flash file. This attribute does not affect the background color of the HTML page.\n\nCut 'n paste from http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_12701&sliceId=1\n", "Enabling windowless mode (wmode=) makes embedded flash act and render just like other elements. Without that, it's rendered in a seperate step and just overlaid on the browser's window.\nCould the flash element be losing focus? Sounds like input focus is moved to the scollbar, then you have to move it back.\nAlso you weren't clear whether the focus issue was only in FF or also in IE.\n", "The Adobe example \"works\" in Firefox 3.0.1 in the sense that the background is transparent. However, in Firefox 3.0.1 and Safari 3.1.2 you must click the play button twice to see the animation.\n", "After spending some more time on this I agree with @grapefrukt. Setting wmode to transparent leads to all sorts of strange issues and in my opinion it should be avoided.\nInstead I've resorted to passing the background color as a parameter. I use the following ActionScript to draw the background.\nvar parameters:Object = LoaderInfo(this.root.loaderInfo).parameters;\nopaqueBackground = parameters[\"background-color\"];\n\nEDIT: Thanks to @grapefrukt for reminding me of the bgcolor param (which makes the ActionScript above totally unnecessary)\n" ]
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "firefox", "flash", "safari" ]
stackoverflow_0000006778_firefox_flash_safari.txt
Q: How is data compression more effective than indexing for search performance? For our application, we keep large amounts of data indexed by three integer columns (source, type and time). Loading significant chunks of that data can take some time and we have implemented various measures to reduce the amount of data that has to be searched and loaded for larger queries, such as storing larger granularities for queries that don't require a high resolution (time-wise). When searching for data in our backup archives, where the data is stored in bzipped text files, but has basically the same structure, I noticed that it is significantly faster to untar to stdout and pipe it through grep than to untar it to disk and grep the files. In fact, the untar-to-pipe was even noticeably faster than just grepping the uncompressed files (i. e. discounting the untar-to-disk). This made me wonder if the performance impact of disk I/O is actually much heavier than I thought. So here's my question: Do you think putting the data of multiple rows into a (compressed) blob field of a single row and search for single rows on the fly during extraction could be faster than searching for the same rows via the table index? For example, instead of having this table CREATE TABLE data ( `source` INT, `type` INT, `timestamp` INT, `value` DOUBLE); I would have CREATE TABLE quickdata ( `source` INT, `type` INT, `day` INT, `dayvalues` BLOB ); with approximately 100-300 rows in data for each row in quickdata and searching for the desired timestamps on the fly during decompression and decoding of the blob field. Does this make sense to you? What parameters should I investigate? What strings might be attached? What DB features (any DBMS) exist to achieve similar effects? A: This made me wonder if the performance impact of disk I/O is actually much heavier than I thought. Definitely. If you have to go to disk, the performance hit is many orders of magnitude greater than memory. This reminds me of the classic Jim Gray paper, Distributed Computing Economics: Computing economics are changing. Today there is rough price parity between (1) one database access, (2) ten bytes of network traffic, (3) 100,000 instructions, (4) 10 bytes of disk storage, and (5) a megabyte of disk bandwidth. This has implications for how one structures Internet-scale distributed computing: one puts computing as close to the data as possible in order to avoid expensive network traffic. The question, then, is how much data do you have and how much memory can you afford? And if the database gets really big -- as in nobody could ever afford that much memory, even in 20 years -- you need clever distributed database systems like Google's BigTable or Hadoop. A: I made a similar discovery when working within Python on a database: the cost of accessing a disk is very, very high. It turned out to be much faster (ie nearly two orders of magnitude) to request a whole chunk of data and iterate through it in python than it was to create seven queries that were narrower. (One per day in question for the data) It blew out even further when I was getting hourly data. 24x7 lots of queries it lots!
How is data compression more effective than indexing for search performance?
For our application, we keep large amounts of data indexed by three integer columns (source, type and time). Loading significant chunks of that data can take some time and we have implemented various measures to reduce the amount of data that has to be searched and loaded for larger queries, such as storing larger granularities for queries that don't require a high resolution (time-wise). When searching for data in our backup archives, where the data is stored in bzipped text files, but has basically the same structure, I noticed that it is significantly faster to untar to stdout and pipe it through grep than to untar it to disk and grep the files. In fact, the untar-to-pipe was even noticeably faster than just grepping the uncompressed files (i. e. discounting the untar-to-disk). This made me wonder if the performance impact of disk I/O is actually much heavier than I thought. So here's my question: Do you think putting the data of multiple rows into a (compressed) blob field of a single row and search for single rows on the fly during extraction could be faster than searching for the same rows via the table index? For example, instead of having this table CREATE TABLE data ( `source` INT, `type` INT, `timestamp` INT, `value` DOUBLE); I would have CREATE TABLE quickdata ( `source` INT, `type` INT, `day` INT, `dayvalues` BLOB ); with approximately 100-300 rows in data for each row in quickdata and searching for the desired timestamps on the fly during decompression and decoding of the blob field. Does this make sense to you? What parameters should I investigate? What strings might be attached? What DB features (any DBMS) exist to achieve similar effects?
[ "\nThis made me wonder if the performance impact of disk I/O is actually much heavier than I thought.\n\nDefinitely. If you have to go to disk, the performance hit is many orders of magnitude greater than memory. This reminds me of the classic Jim Gray paper, Distributed Computing Economics:\n\nComputing economics are changing. Today there is rough price parity between (1) one database access, (2) ten bytes of network traffic, (3) 100,000 instructions, (4) 10 bytes of disk storage, and (5) a megabyte of disk bandwidth. This has implications for how one structures Internet-scale distributed computing: one puts computing as close to the data as possible in order to avoid expensive network traffic. \n\nThe question, then, is how much data do you have and how much memory can you afford?\nAnd if the database gets really big -- as in nobody could ever afford that much memory, even in 20 years -- you need clever distributed database systems like Google's BigTable or Hadoop.\n", "I made a similar discovery when working within Python on a database: the cost of accessing a disk is very, very high. It turned out to be much faster (ie nearly two orders of magnitude) to request a whole chunk of data and iterate through it in python than it was to create seven queries that were narrower. (One per day in question for the data)\nIt blew out even further when I was getting hourly data. 24x7 lots of queries it lots!\n" ]
[ 4, 0 ]
[]
[]
[ "database", "performance" ]
stackoverflow_0000026021_database_performance.txt
Q: In a PHP5 class, when does a private constructor get called? Let's say I'm writing a PHP (>= 5.0) class that's meant to be a singleton. All of the docs I've read say to make the class constructor private so the class can't be directly instantiated. So if I have something like this: class SillyDB { private function __construct() { } public static function getConnection() { } } Are there any cases where __construct() is called other than if I'm doing a new SillyDB() call inside the class itself? And why am I allowed to instantiate SillyDB from inside itself at all? A: __construct() would only be called if you called it from within a method for the class containing the private constructor. So for your Singleton, you might have a method like so: class DBConnection { private static $Connection = null; public static function getConnection() { if(!isset(self::$Connection)) { self::$Connection = new DBConnection(); } return self::$Connection; } private function __construct() { } } $dbConnection = DBConnection::getConnection(); The reason you are able/would want to instantiate the class from within itself is so that you can check to make sure that only one instance exists at any given time. This is the whole point of a Singleton, after all. Using a Singleton for a database connection ensures that your application is not making a ton of DB connections at a time. Edit: Added $, as suggested by @emanuele-del-grande
In a PHP5 class, when does a private constructor get called?
Let's say I'm writing a PHP (>= 5.0) class that's meant to be a singleton. All of the docs I've read say to make the class constructor private so the class can't be directly instantiated. So if I have something like this: class SillyDB { private function __construct() { } public static function getConnection() { } } Are there any cases where __construct() is called other than if I'm doing a new SillyDB() call inside the class itself? And why am I allowed to instantiate SillyDB from inside itself at all?
[ "__construct() would only be called if you called it from within a method for the class containing the private constructor. So for your Singleton, you might have a method like so:\nclass DBConnection\n{\n private static $Connection = null;\n\n public static function getConnection()\n {\n if(!isset(self::$Connection))\n {\n self::$Connection = new DBConnection();\n }\n return self::$Connection;\n }\n\n private function __construct()\n {\n\n }\n}\n\n$dbConnection = DBConnection::getConnection();\n\nThe reason you are able/would want to instantiate the class from within itself is so that you can check to make sure that only one instance exists at any given time. This is the whole point of a Singleton, after all. Using a Singleton for a database connection ensures that your application is not making a ton of DB connections at a time.\n\nEdit: Added $, as suggested by @emanuele-del-grande\n" ]
[ 65 ]
[]
[]
[ "constructor", "oop", "php" ]
stackoverflow_0000026079_constructor_oop_php.txt
Q: Reconnect logic with connectivity notifications Say I have an application that wants a persistent connection to a server. How do I implement connection/re-connection logic so that I'm not wasting resources (power/bandwidth) and I have fast reconnect time when connectivity appears/improves? If I only use connectivity notifications, I can get stuck on problems not related to the local network. Bonus if you could show me the C# version. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­ A: This is a very "huge" question. I can say that we use an O/R Mapper and each "query" to the database needs an object called PersistenceBroker. This class is in charge of all the DB Stuff related to connecting, authenticating etc. We've written a PersistenceBrokerFactory.GetCurrentBroker() which returns the "working" broker. If the DB suddenly fails (for whatever reason), the CONN object will "timeout()" after 30secs (or whatever you define). If that happens, we show the user that he/she is offline and display a reconnect button. On the other hand, to provide a visual indication that the user has connectivity, we have a thread running in the background, that checks for Internet connectivity every 15 seconds. We do 1 ping to google.com. ;) If that fails, we assume Internet is somehow broken, and we update a status bar. I could show you all that code for the network health monitor if you wanted. I took some bits from google and other I made myself :)
Reconnect logic with connectivity notifications
Say I have an application that wants a persistent connection to a server. How do I implement connection/re-connection logic so that I'm not wasting resources (power/bandwidth) and I have fast reconnect time when connectivity appears/improves? If I only use connectivity notifications, I can get stuck on problems not related to the local network. Bonus if you could show me the C# version. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
[ "This is a very \"huge\" question. I can say that we use an O/R Mapper and each \"query\" to the database needs an object called PersistenceBroker. This class is in charge of all the DB Stuff related to connecting, authenticating etc. \nWe've written a PersistenceBrokerFactory.GetCurrentBroker() which returns the \"working\" broker. If the DB suddenly fails (for whatever reason), the CONN object will \"timeout()\" after 30secs (or whatever you define). If that happens, we show the user that he/she is offline and display a reconnect button. \nOn the other hand, to provide a visual indication that the user has connectivity, we have a thread running in the background, that checks for Internet connectivity every 15 seconds. We do 1 ping to google.com. ;) If that fails, we assume Internet is somehow broken, and we update a status bar. \nI could show you all that code for the network health monitor if you wanted. I took some bits from google and other I made myself :)\n" ]
[ 1 ]
[]
[]
[ "networking", "offline", "sockets" ]
stackoverflow_0000026072_networking_offline_sockets.txt
Q: Setting Attributes in Webby Layouts I'm working with Webby and am looking for some clarification. Can I define attributes like title or author in my layout? A: Not really. The layout has access to the page attributes rather than the other way. The easiest way to do what you want is to populate the SITE.page_defaults hash in your site's Rakefile (probably build.rake). Add something like the following: SITE.page_defaults['title'] = "My awesome title" SITE.page_defaults['author'] = "Shazbug" SITE.page_defaults['is_mando_awesome'] = "very yes" You can now access those hash members in your template: Written by <%= @page.author %> You can find more info about Webby's page default stuff on the Google Group, specifically here: http://groups.google.com/group/webby-forum/browse_thread/thread/f3dc1f4187959634/c30d7883705f6218?lnk=gst&q=SITE#c30d7883705f6218 A: I've never used it but the tutorial here: Makes it look like the answer to your question is "yes". Specifically I'm looking under the "Making Changes" header on that page.
Setting Attributes in Webby Layouts
I'm working with Webby and am looking for some clarification. Can I define attributes like title or author in my layout?
[ "Not really. The layout has access to the page attributes rather than the other way.\nThe easiest way to do what you want is to populate the SITE.page_defaults hash in your site's Rakefile (probably build.rake). Add something like the following:\nSITE.page_defaults['title'] = \"My awesome title\"\nSITE.page_defaults['author'] = \"Shazbug\"\nSITE.page_defaults['is_mando_awesome'] = \"very yes\"\n\nYou can now access those hash members in your template:\nWritten by <%= @page.author %>\n\nYou can find more info about Webby's page default stuff on the Google Group, specifically here: \nhttp://groups.google.com/group/webby-forum/browse_thread/thread/f3dc1f4187959634/c30d7883705f6218?lnk=gst&q=SITE#c30d7883705f6218 \n", "I've never used it but the tutorial here:\nMakes it look like the answer to your question is \"yes\". Specifically I'm looking under the \"Making Changes\" header on that page.\n" ]
[ 1, 0 ]
[]
[]
[ "ruby", "webby" ]
stackoverflow_0000023996_ruby_webby.txt
Q: (N)Hibernate Auto-Join I'm developing a web- application using NHibernate. Can you tell me how to write a NHibernate Query for the following SQL query: SELECT v1.Id FROM VIEW v1 LEFT JOIN VIEW v2 ON v1.SourceView = v2.Id ORDER BY v1.Position It's basically a auto-join but I don't know how to write this in Nhibernate. Lets say the property names are the same as the table column names. A: You could just perform the select on the original entity and make the association between the two objects "lazy = false". As long as the entities are mapped then both will be returned and you wont get a lazyloadingexception when trying to access the object. If you don't want to map "lazy=false" then you can also iterate through the results and perform some sort of operation (such as asking if it is null; if(v1.AssocatedObject == null){}) to ensure the data is loaded while the session is open. Update: I think there is actually a better one than that in, NHibernateUtil.Initialise() that can initialise a collection without having to wander through it.
(N)Hibernate Auto-Join
I'm developing a web- application using NHibernate. Can you tell me how to write a NHibernate Query for the following SQL query: SELECT v1.Id FROM VIEW v1 LEFT JOIN VIEW v2 ON v1.SourceView = v2.Id ORDER BY v1.Position It's basically a auto-join but I don't know how to write this in Nhibernate. Lets say the property names are the same as the table column names.
[ "You could just perform the select on the original entity and make the association between the two objects \"lazy = false\". As long as the entities are mapped then both will be returned and you wont get a lazyloadingexception when trying to access the object.\nIf you don't want to map \"lazy=false\" then you can also iterate through the results and perform some sort of operation (such as asking if it is null; if(v1.AssocatedObject == null){}) to ensure the data is loaded while the session is open.\nUpdate:\nI think there is actually a better one than that in, NHibernateUtil.Initialise() that can initialise a collection without having to wander through it.\n" ]
[ 1 ]
[]
[]
[ "nhibernate", "orm", "sql" ]
stackoverflow_0000024467_nhibernate_orm_sql.txt
Q: Output compile time stamp in Visual C++ executable? How can I insert compilation timestamp information into an executable I build with Visual C++ 2005? I want to be able to output something like this when I execute the program: This build XXXX was compiled at dd-mm-yy, hh:mm. where date and time reflect the time when the project was built. They should not change with each successive call of the program, unless it's recompiled. A: Though not your exact format, DATE will be of the format Mmm dd yyyy, while TIME will be of the format hh:mm:ss. You can create a string like this and use it in whatever print routine makes sense for you: const char *buildString = "This build XXXX was compiled at " __DATE__ ", " __TIME__ "."; (Note on another answer: TIMESTAMP only spits out the modification date/time of the source file, not the build date/time.) A: __DATE__ __TIME__ are predefined as part of the standards for C99 so should be available to you. They run once with the preprocessor. A: Well... for Visual C++, there's a built in symbol called __ImageBase. Specifically: EXTERN_C IMAGE_DOS_HEADER __ImageBase; You can inspect that at runtime to determine the timestamp in the PE header: const IMAGE_NT_HEADERS *nt_header= (const IMAGE_NT_HEADERS *)((char *)&__ImageBase + __ImageBase.e_lfanew); And use nt_header->FileHeader.TimeDateStamp to get the timestamp, which is seconds from 1/1/1970. A: __TIME__ and __DATE__ can work, however there are some complications. If you put these definitions in a .h file, and include the definitions from multiple .c/.cpp files, each file will have a different version of the date/time based on when it gets compiled. So if you're looking to use the date/time in two different places and they should always match, you're in trouble. If you're doing an incremental build, one of the files may be rebuilt while the other is not, which again results in time stamps that could be wildly different. A slightly better approach is to make GetBuildTimeStamp() prototypes in a .h file, and put the __TIME__ and __DATE__ macros in the implementation(.c/.cpp) file. This way you can use the time stamps in multiple places in your code and they will always match. However you need to ensure that the .c/.cpp file is rebuilt every time a build is performed. If you're doing clean builds then this solution may work for you. If you're doing incremental builds, then you need to ensure the build stamp is updated on every build. In Visual C++ you can do this with PreBuild steps - however in this case I would recommend that instead of using __DATE__ and __TIME__ in a compiled .c/.cpp file, you use a text-based file that is read at run-time during your program's execution. This makes it fast for your build script to update the timestamp (no compiling or linking required) and doesn't require your PreBuild step to understand your compiler flags or options. A: I think, the suggested solutions to use DATE, TIME or TIMESTAMP would be good enough. I do recommend to get a hold of a touch program to include in a pre-build step in order to touch the file that holds the use of the preprocessor variable. Touching a file makes sure, that its timestamp is newer than at the time it was last compiled. That way, the date/time in the compiled file is changed as well with each rebuild. A: Visual C++ also supports __TIMESTAMP__ which is almost exactly what you need. That being said, the tough part about build timestamps is keeping them up to date, that means compiling the file in which __TIMESTAMP__ is used on every rebuild. Not sure if there's a way to set this up in Visual C++ though.
Output compile time stamp in Visual C++ executable?
How can I insert compilation timestamp information into an executable I build with Visual C++ 2005? I want to be able to output something like this when I execute the program: This build XXXX was compiled at dd-mm-yy, hh:mm. where date and time reflect the time when the project was built. They should not change with each successive call of the program, unless it's recompiled.
[ "Though not your exact format, DATE will be of the format Mmm dd yyyy, while TIME will be of the format hh:mm:ss. You can create a string like this and use it in whatever print routine makes sense for you:\nconst char *buildString = \"This build XXXX was compiled at \" __DATE__ \", \" __TIME__ \".\";\n\n(Note on another answer: TIMESTAMP only spits out the modification date/time of the source file, not the build date/time.)\n", "__DATE__ \n__TIME__\n\nare predefined as part of the standards for C99 so should be available to you. They run once with the preprocessor.\n", "Well... for Visual C++, there's a built in symbol called __ImageBase. Specifically:\nEXTERN_C IMAGE_DOS_HEADER __ImageBase;\nYou can inspect that at runtime to determine the timestamp in the PE header:\nconst IMAGE_NT_HEADERS *nt_header= (const IMAGE_NT_HEADERS *)((char *)&__ImageBase + __ImageBase.e_lfanew);\nAnd use nt_header->FileHeader.TimeDateStamp to get the timestamp, which is seconds from 1/1/1970.\n", "__TIME__ and __DATE__ can work, however there are some complications. \nIf you put these definitions in a .h file, and include the definitions from multiple .c/.cpp files, each file will have a different version of the date/time based on when it gets compiled. So if you're looking to use the date/time in two different places and they should always match, you're in trouble. If you're doing an incremental build, one of the files may be rebuilt while the other is not, which again results in time stamps that could be wildly different.\nA slightly better approach is to make GetBuildTimeStamp() prototypes in a .h file, and put the __TIME__ and __DATE__ macros in the implementation(.c/.cpp) file. This way you can use the time stamps in multiple places in your code and they will always match. However you need to ensure that the .c/.cpp file is rebuilt every time a build is performed. If you're doing clean builds then this solution may work for you.\nIf you're doing incremental builds, then you need to ensure the build stamp is updated on every build. In Visual C++ you can do this with PreBuild steps - however in this case I would recommend that instead of using __DATE__ and __TIME__ in a compiled .c/.cpp file, you use a text-based file that is read at run-time during your program's execution. This makes it fast for your build script to update the timestamp (no compiling or linking required) and doesn't require your PreBuild step to understand your compiler flags or options.\n", "I think, the suggested solutions to use DATE, TIME or TIMESTAMP would be good enough. I do recommend to get a hold of a touch program to include in a pre-build step in order to touch the file that holds the use of the preprocessor variable. Touching a file makes sure, that its timestamp is newer than at the time it was last compiled. That way, the date/time in the compiled file is changed as well with each rebuild.\n", "Visual C++ also supports __TIMESTAMP__ which is almost exactly what you need. That being said, the tough part about build timestamps is keeping them up to date, that means compiling the file in which __TIMESTAMP__ is used on every rebuild. Not sure if there's a way to set this up in Visual C++ though.\n" ]
[ 24, 10, 7, 5, 1, 0 ]
[]
[]
[ "c++", "compile_time", "execution", "visual_c++" ]
stackoverflow_0000025771_c++_compile_time_execution_visual_c++.txt
Q: Running "partially trusted" .NET assemblies from a network share When I try to run a .NET assembly (boo.exe) from a network share (mapped to a drive), it fails since it's only partially trusted: Unhandled Exception: System.Security.SecurityException: That assembly does not allow partially trusted callers. at System.Security.CodeAccessSecurityEngine.ThrowSecurityException(Assembly asm, PermissionSet granted, PermissionSet refused, RuntimeMethodHandle rmh, SecurityAction action, Object demand, IPermission permThatFailed) at BooCommandLine..ctor() at Program..ctor() at ProgramModule.Main(String[] argv) The action that failed was: LinkDemand The assembly or AppDomain that failed was: boo, Version=0.0.0.0, Culture=neutral, PublicKeyToken=32c39770e9a21a67 The Zone of the assembly that failed was: Intranet The Url of the assembly that failed was: file:///H:/boo-svn/bin/boo.exe With instructions from a blog post, I added a policy to the .NET Configuration fully trusting all assemblies with file:///H:/* as their URL. I verified this by entering the URL file:///H:/boo-svn/bin/boo.exe into the Evaluate Assembly tool in the .NET Configuration and noting that boo.exe had the Unrestricted permission (which it didn't have before the policy). Even with the permission, boo.exe does not run. I still get the same error message. What can I do to debug this problem? Is there another way to run "partially trusted" assemblies from network shares without having to change something for every assembly I want to run? A: With .NET 3.5 SP1, .NET assemblies running from UNC shares have full permissions. See Brad Abrams's Allow .exes to be run off a network shares for workaround and discussions, and finally the follow up .NET 3.5 SP1 allows managed code to be launched from a network share. A: I resolved the problem by using caspol as instructed in Johnny Hughes' blog post Running a .Net application from a network share: caspol -addgroup 1.2 -url file:///H:/* FullTrust It seems the .NET Configuration GUI for managing the policies simply doesn't work. A: Take a look at the 'caspol.exe' program (provided with .NET runtimes). You will have to do this on the machine you are trying to run the application from. I wasn't able to 'mark' and assembly (probably just me). However, using caspol and setting up the proper permission for my app, LocalIntranet_Zone, fix my similar issue. I have heard (but haven't tried it yet), that .NET 3.5 sp1 removed this tighten security requirement (not allowing .NET assemblies to reside on a share by default). A: I think you want to add the AllowPartiallyTrustedCallers attribute to your assembly. The error message implies that something that's calling into your boo.exe assembly is not fully trusted, and boo.exe doesn't have this attribute allowing it.
Running "partially trusted" .NET assemblies from a network share
When I try to run a .NET assembly (boo.exe) from a network share (mapped to a drive), it fails since it's only partially trusted: Unhandled Exception: System.Security.SecurityException: That assembly does not allow partially trusted callers. at System.Security.CodeAccessSecurityEngine.ThrowSecurityException(Assembly asm, PermissionSet granted, PermissionSet refused, RuntimeMethodHandle rmh, SecurityAction action, Object demand, IPermission permThatFailed) at BooCommandLine..ctor() at Program..ctor() at ProgramModule.Main(String[] argv) The action that failed was: LinkDemand The assembly or AppDomain that failed was: boo, Version=0.0.0.0, Culture=neutral, PublicKeyToken=32c39770e9a21a67 The Zone of the assembly that failed was: Intranet The Url of the assembly that failed was: file:///H:/boo-svn/bin/boo.exe With instructions from a blog post, I added a policy to the .NET Configuration fully trusting all assemblies with file:///H:/* as their URL. I verified this by entering the URL file:///H:/boo-svn/bin/boo.exe into the Evaluate Assembly tool in the .NET Configuration and noting that boo.exe had the Unrestricted permission (which it didn't have before the policy). Even with the permission, boo.exe does not run. I still get the same error message. What can I do to debug this problem? Is there another way to run "partially trusted" assemblies from network shares without having to change something for every assembly I want to run?
[ "With .NET 3.5 SP1, .NET assemblies running from UNC shares have full permissions. \nSee Brad Abrams's Allow .exes to be run off a network shares for workaround and discussions, and finally the follow up .NET 3.5 SP1 allows managed code to be launched from a network share.\n", "I resolved the problem by using caspol as instructed in Johnny Hughes' blog post Running a .Net application from a network share:\ncaspol -addgroup 1.2 -url file:///H:/* FullTrust\n\nIt seems the .NET Configuration GUI for managing the policies simply doesn't work.\n", "Take a look at the 'caspol.exe' program (provided with .NET runtimes). You will have to do this on the machine you are trying to run the application from. I wasn't able to 'mark' and assembly (probably just me). However, using caspol and setting up the proper permission for my app, LocalIntranet_Zone, fix my similar issue.\nI have heard (but haven't tried it yet), that .NET 3.5 sp1 removed this tighten security requirement (not allowing .NET assemblies to reside on a share by default).\n", "I think you want to add the AllowPartiallyTrustedCallers attribute to your assembly. The error message implies that something that's calling into your boo.exe assembly is not fully trusted, and boo.exe doesn't have this attribute allowing it.\n" ]
[ 5, 3, 2, 0 ]
[]
[]
[ ".net", "security" ]
stackoverflow_0000024468_.net_security.txt
Q: Implementing permissions in PHP I've tried to do this several times with no luck. After reading this post, it made me interested in doing this again. So can anyone tell me why the following doesn't work? <?php $guest = 1; $editor = 2; $admin = 4; $user = $editor; if( $user == ($editor | $admin) ) { echo "Test"; } ?> A: Use the bitwise OR operator (|) to set bits, use the AND operator (&) to check bits. Your code should look like this: <?php $guest = 1; $editor = 2; $admin = 4; $user = $editor; if( $user & ($editor | $admin) ) { echo "Test"; } ?> If you don't understand binary and exactly what the bitwise operators do, you should go learn it. You'll understand how to do this much better. A: In the interest of not reinventing the wheel, why not take a look at ACL/Authentication systems like Zend ACL and Zend Auth? Both can be used independently from the Zend Framework as a whole. Access Control is a tricky situation so it benefits one to at least look at how other systems do it. A: It's been a long time since I used PHP, but I will assume that this will work: <?php $guest = 1; $editor = 2; $admin = 4; $user = $editor; if( ($user == $editor) || ($user == $admin) ) { echo "Test"; } ?> A: I've used this in error reporting and it works quite well. As for user permissions it should work very well - you could have several columns for each user permission in your database or one userlevel column in your database. Go for this option. A: (2 | 4) is evaluating to 6, but 2 == 6 is false. A: @mk: (2 | 4) evaluates to 6. A: $guest = 1; $editor = 2; $admin = 4; $user = $editor; if (user == $editor || $user == $admin) { echo "Test"; } A: Awesome, this seems like the best way to do permissions in a CMS. Yes? No? Maybe, I've never really done it that way. What I have done is used bitwise operators to store a whole bunch of "yes or no" settings in a single number in a single column in the database. I guess for permissions, this way would work good if you want to store permissions in the database. If someone wants to post some content, and only wants admins and editors to see it, you just have to store the result of ($editor | $admin) into the database, then to check it, do something like if ($user & $database_row['permissions']) { // display content } else { // display permissions error } A: In my opinion this doesn't scale well. I haven't actually tried using it on a large scale project, but a CMS sounds way to complicated to use this on. A: It always depends on what you need. If you know the Zend Framework already, then I'd second the Zend_Acl/_Auth suggestion which was made earlier. But keep in mind that every framework propably comes with a similar component. The other thing that comes to mind is LiveUser. I like working with it a lot as well. I think you can do pretty much anything and while your approach looks very simple, it's also limited since (through all those if()'s) you are gonna put a lot of the ACL-logic right in the middle of your application. Which is not the greatest thing to do in order to keep it simple and extendible. ;)
Implementing permissions in PHP
I've tried to do this several times with no luck. After reading this post, it made me interested in doing this again. So can anyone tell me why the following doesn't work? <?php $guest = 1; $editor = 2; $admin = 4; $user = $editor; if( $user == ($editor | $admin) ) { echo "Test"; } ?>
[ "Use the bitwise OR operator (|) to set bits, use the AND operator (&) to check bits. Your code should look like this:\n<?php\n\n $guest = 1;\n $editor = 2;\n $admin = 4;\n\n $user = $editor;\n\n if( $user & ($editor | $admin) ) {\n echo \"Test\"; \n }\n\n?>\n\nIf you don't understand binary and exactly what the bitwise operators do, you should go learn it. You'll understand how to do this much better.\n", "In the interest of not reinventing the wheel, why not take a look at ACL/Authentication systems like Zend ACL and Zend Auth? Both can be used independently from the Zend Framework as a whole. Access Control is a tricky situation so it benefits one to at least look at how other systems do it.\n", "It's been a long time since I used PHP, but I will assume that this will work:\n<?php\n\n $guest = 1;\n $editor = 2;\n $admin = 4;\n\n $user = $editor;\n\n if( ($user == $editor) || ($user == $admin) ) {\n echo \"Test\"; \n }\n\n?>\n\n", "I've used this in error reporting and it works quite well. As for user permissions it should work very well - you could have several columns for each user permission in your database or one userlevel column in your database. Go for this option.\n", "(2 | 4) is evaluating to 6, but 2 == 6 is false. \n", "@mk: (2 | 4) evaluates to 6.\n", "$guest = 1;\n$editor = 2;\n$admin = 4;\n\n$user = $editor;\n\nif (user == $editor || $user == $admin) {\n echo \"Test\";\n}\n\n", "\nAwesome, this seems like the best way to do permissions in a CMS. Yes? No?\n\nMaybe, I've never really done it that way. What I have done is used bitwise operators to store a whole bunch of \"yes or no\" settings in a single number in a single column in the database.\nI guess for permissions, this way would work good if you want to store permissions in the database. If someone wants to post some content, and only wants admins and editors to see it, you just have to store the result of\n ($editor | $admin)\n\ninto the database, then to check it, do something like\n if ($user & $database_row['permissions']) {\n // display content\n } else {\n // display permissions error\n }\n\n", "In my opinion this doesn't scale well. I haven't actually tried using it on a large scale project, but a CMS sounds way to complicated to use this on.\n", "It always depends on what you need. If you know the Zend Framework already, then I'd second the Zend_Acl/_Auth suggestion which was made earlier. But keep in mind that every framework propably comes with a similar component.\nThe other thing that comes to mind is LiveUser. I like working with it a lot as well.\nI think you can do pretty much anything and while your approach looks very simple, it's also limited since (through all those if()'s) you are gonna put a lot of the ACL-logic right in the middle of your application. Which is not the greatest thing to do in order to keep it simple and extendible. ;)\n" ]
[ 11, 6, 2, 2, 1, 1, 1, 1, 0, 0 ]
[]
[]
[ "permissions", "php" ]
stackoverflow_0000017172_permissions_php.txt
Q: PostgreSQL: GIN or GiST indexes? From what information I could find, they both solve the same problems - more esoteric operations like array containment and intersection (&&, @>, <@, etc). However I would be interested in advice about when to use one or the other (or neither possibly). The PostgreSQL documentation has some information about this: GIN index lookups are about three times faster than GiST GIN indexes take about three times longer to build than GiST GIN indexes are about ten times slower to update than GiST GIN indexes are two-to-three times larger than GiST However I would be particularly interested to know if there is a performance impact when the memory to index size ration starts getting small (ie. the index size becomes much bigger than the available memory)? I've been told on the #postgresql IRC channel that GIN needs to keep all the index in memory, otherwise it won't be effective, because, unlike B-Tree, it doesn't know which part to read in from disk for a particular query? The question would be: is this true (because I've also been told the opposite of this)? Does GiST have the same restrictions? Are there other restrictions I should be aware of while using one of these indexing algorithms? A: First of all, do you need to use them for text search indexing? GIN and GiST are index specialized for some data types. If you need to index simple char or integer values then the normal B-Tree index is the best. Anyway, PostgreSQL documentation has a chapter on GIST and one on GIN, where you can find more info. And, last but not least, the best way to find which is best is to generate sample data (as much as you need to be a real scenario) and then create a GIST index, measuring how much time is needed to create the index, insert a new value, execute a sample query. Then drop the index and do the same with a GIN index. Compare the values and you will have the answer you need, based on your data.
PostgreSQL: GIN or GiST indexes?
From what information I could find, they both solve the same problems - more esoteric operations like array containment and intersection (&&, @>, <@, etc). However I would be interested in advice about when to use one or the other (or neither possibly). The PostgreSQL documentation has some information about this: GIN index lookups are about three times faster than GiST GIN indexes take about three times longer to build than GiST GIN indexes are about ten times slower to update than GiST GIN indexes are two-to-three times larger than GiST However I would be particularly interested to know if there is a performance impact when the memory to index size ration starts getting small (ie. the index size becomes much bigger than the available memory)? I've been told on the #postgresql IRC channel that GIN needs to keep all the index in memory, otherwise it won't be effective, because, unlike B-Tree, it doesn't know which part to read in from disk for a particular query? The question would be: is this true (because I've also been told the opposite of this)? Does GiST have the same restrictions? Are there other restrictions I should be aware of while using one of these indexing algorithms?
[ "First of all, do you need to use them for text search indexing? GIN and GiST are index specialized for some data types. If you need to index simple char or integer values then the normal B-Tree index is the best.\nAnyway, PostgreSQL documentation has a chapter on GIST and one on GIN, where you can find more info.\nAnd, last but not least, the best way to find which is best is to generate sample data (as much as you need to be a real scenario) and then create a GIST index, measuring how much time is needed to create the index, insert a new value, execute a sample query. Then drop the index and do the same with a GIN index. Compare the values and you will have the answer you need, based on your data.\n" ]
[ 18 ]
[]
[]
[ "gist_index", "gwt_gin", "indexing", "postgresql" ]
stackoverflow_0000021830_gist_index_gwt_gin_indexing_postgresql.txt
Q: What workshops / user groups / conventions do you attend? I haven't been to enough of these "live" events to really determine which, if any, are worth the time / money. Which ones do you attend and why? A: For conventions, if you're still in university, and can make it to Montreal, Canada, the Canadian Undergraduate Software Engineering Conference (CUSEC) has been extremely enjoyable. See the 2009 site for the next event, and for a take on what previous years have been like, take a look at the 2008 speakers (note: it included Jeff Atwood). I attend CUSEC primarily because our software engineering society on campus makes a point of organizing a trip to it, but also because of the speakers that present there, and the career fair. A: I used to belong to my local Linux User Group which I co-founded but I treated it more as a social event than anything else but obviously a social event full of geeks is still a great way to get a great debate going :) Conventions and the like I've not got much out of other than being pestered by businesses who can offer me nothing that is apart from a bunch of Linux and Hacker ones where I've met loads of people who I consider friends offline, again great for the social aspect but pretty worthless to me in other respects. That's not to say I never got any business out of attending various events it's just that treating them as social occasions meant any business that did come my way was a bonus so I never left an event feeling like it was a waste of time.
What workshops / user groups / conventions do you attend?
I haven't been to enough of these "live" events to really determine which, if any, are worth the time / money. Which ones do you attend and why?
[ "For conventions, if you're still in university, and can make it to Montreal, Canada, the Canadian Undergraduate Software Engineering Conference (CUSEC) has been extremely enjoyable. See the 2009 site for the next event, and for a take on what previous years have been like, take a look at the 2008 speakers (note: it included Jeff Atwood).\nI attend CUSEC primarily because our software engineering society on campus makes a point of organizing a trip to it, but also because of the speakers that present there, and the career fair.\n", "I used to belong to my local Linux User Group which I co-founded but I treated it more as a social event than anything else but obviously a social event full of geeks is still a great way to get a great debate going :)\nConventions and the like I've not got much out of other than being pestered by businesses who can offer me nothing that is apart from a bunch of Linux and Hacker ones where I've met loads of people who I consider friends offline, again great for the social aspect but pretty worthless to me in other respects.\nThat's not to say I never got any business out of attending various events it's just that treating them as social occasions meant any business that did come my way was a bonus so I never left an event feeling like it was a waste of time.\n" ]
[ 2, 0 ]
[]
[]
[ "networking" ]
stackoverflow_0000026509_networking.txt
Q: Add a shortcut to Startup folder with parameters in Adobe AIR I am trying to include a link to my application in the Startup folder with a parameter passed to the program. I think it would work if I created the shortcut locally and then added it to my source. After that I could copy it to the Startup folder on first run. File.userDirectory.resolvePath("Start Menu\\Programs\\Startup\\startup.lnk"); However, I am trying to get this to occur during install. I see there is are some settings related to the installation in app.xml, but nothing that lets me install it to two folders, or use a parameter. <!-- The subpath of the standard default installation location to use. Optional. --> <!-- <installFolder></installFolder> --> <!-- The subpath of the Windows Start/Programs menu to use. Optional. --> <!-- <programMenuFolder></programMenuFolder> --> A: I'm new to Air, but also haven't found any way to customize the install process. It looks like you're limited to your application code. (Updating appears more flexible.) From your example, it looks like you want your app' to run with a parameter constant each time Windows starts. So you're probably already aware you can set: NativeApplication.nativeApplication.startAtLogin=true when your app' first runs. Could you combine this with your parameter in a settings file in the application or user directory and accomplish what you need?
Add a shortcut to Startup folder with parameters in Adobe AIR
I am trying to include a link to my application in the Startup folder with a parameter passed to the program. I think it would work if I created the shortcut locally and then added it to my source. After that I could copy it to the Startup folder on first run. File.userDirectory.resolvePath("Start Menu\\Programs\\Startup\\startup.lnk"); However, I am trying to get this to occur during install. I see there is are some settings related to the installation in app.xml, but nothing that lets me install it to two folders, or use a parameter. <!-- The subpath of the standard default installation location to use. Optional. --> <!-- <installFolder></installFolder> --> <!-- The subpath of the Windows Start/Programs menu to use. Optional. --> <!-- <programMenuFolder></programMenuFolder> -->
[ "I'm new to Air, but also haven't found any way to customize the install process. It looks like you're limited to your application code. (Updating appears more flexible.)\nFrom your example, it looks like you want your app' to run with a parameter constant each time Windows starts. So you're probably already aware you can set:\nNativeApplication.nativeApplication.startAtLogin=true\n\nwhen your app' first runs. Could you combine this with your parameter in a settings file in the application or user directory and accomplish what you need?\n" ]
[ 2 ]
[]
[]
[ "adobe", "air" ]
stackoverflow_0000017966_adobe_air.txt
Q: .NET Multi Dimensional Array Printing Let's say I have a .NET Array of n number of dimensions. I would like to foreach through the elements and print out something like: [0, 0, 0] = 2 [0, 0, 1] = 32 And so on. I could write a loop using some the Rank and dimension functions to come up with the indices. Is there a built in function instead? A: Thanks for the answer, here is what I wrote while I waited: public static string Format(Array array) { var builder = new StringBuilder(); builder.AppendLine("Count: " + array.Length); var counter = 0; var dimensions = new List<int>(); for (int i = 0; i < array.Rank; i++) { dimensions.Add(array.GetUpperBound(i) + 1); } foreach (var current in array) { var index = ""; var remainder = counter; foreach (var bound in dimensions) { index = remainder % bound + ", " + index; remainder = remainder / bound; } index = index.Substring(0, index.Length - 2); builder.AppendLine(" [" + index + "] " + current); counter++; } return builder.ToString(); } A: Take a look at this: might helpful for you.
.NET Multi Dimensional Array Printing
Let's say I have a .NET Array of n number of dimensions. I would like to foreach through the elements and print out something like: [0, 0, 0] = 2 [0, 0, 1] = 32 And so on. I could write a loop using some the Rank and dimension functions to come up with the indices. Is there a built in function instead?
[ "Thanks for the answer, here is what I wrote while I waited:\npublic static string Format(Array array)\n{\n var builder = new StringBuilder();\n builder.AppendLine(\"Count: \" + array.Length);\n var counter = 0;\n\n var dimensions = new List<int>();\n for (int i = 0; i < array.Rank; i++)\n {\n dimensions.Add(array.GetUpperBound(i) + 1);\n }\n\n foreach (var current in array)\n {\n var index = \"\";\n var remainder = counter;\n foreach (var bound in dimensions)\n {\n index = remainder % bound + \", \" + index;\n remainder = remainder / bound;\n }\n index = index.Substring(0, index.Length - 2);\n\n builder.AppendLine(\" [\" + index + \"] \" + current);\n counter++;\n }\n return builder.ToString();\n}\n\n", "Take a look at this: might helpful for you.\n" ]
[ 2, 1 ]
[]
[]
[ ".net", "arrays", "c#" ]
stackoverflow_0000026522_.net_arrays_c#.txt
Q: How to detect which blog API Let's say that you want to create a dead simple BlogEditor and, one of your ideas, is to do what Live Writer does and ask only the URL of the persons Blog. How can you detect what type of blog is it? Basic detection can be done with the URL itself, such as “http://myblog.blogger.com” etc. But what if it's self hosted? I'm mostly interested on how to do this in Java, but this question could be also used as a reference for any other language. A: Many (most?) blogs will have a meta tag for "generator" which will list the blog engine. For example a blogger blog will contain the following meta tag: <meta name="generator" content="Blogger" /> My Subtext blog shows the following generator meta tag: <meta name="Generator" content="Subtext Version 1.9.5.177" /> This meta tag would be the first place to look. For blogs that don't set this meta tag in the source, you'd have to resort to looking for patterns to determine the blog type. A: Some blogs provide a Generator meta tag - e.g. Wordpress - you could find out if there's any exceptions to this. You'll have to be careful how you detect it though, Google surprised me with this line: <meta content='blogger' name='generator'/> Single quotes are blasphemy. A: To determine other patterns to look for in determining the blogging engine (for those that don't have a generator meta tag), you'd basically just look through the source to determine something specific to that blog type. You'd also need to compare this across multiple blogs of that type as you want to make sure that it's not something specific to the skin or theme in use on the blog only. Another thought would be to read the docs of the various common blogging engine to know how to discover the location of it's paths to things like MetaWebLog API, etc. IIRC, Live Writer has built-in support for the most common types, the rest are categorized "MetaWebLog API Blog" or something.
How to detect which blog API
Let's say that you want to create a dead simple BlogEditor and, one of your ideas, is to do what Live Writer does and ask only the URL of the persons Blog. How can you detect what type of blog is it? Basic detection can be done with the URL itself, such as “http://myblog.blogger.com” etc. But what if it's self hosted? I'm mostly interested on how to do this in Java, but this question could be also used as a reference for any other language.
[ "Many (most?) blogs will have a meta tag for \"generator\" which will list the blog engine. For example a blogger blog will contain the following meta tag: \n<meta name=\"generator\" content=\"Blogger\" /> \n\nMy Subtext blog shows the following generator meta tag: \n<meta name=\"Generator\" content=\"Subtext Version 1.9.5.177\" /> \n\nThis meta tag would be the first place to look. For blogs that don't set this meta tag in the source, you'd have to resort to looking for patterns to determine the blog type. \n", "Some blogs provide a Generator meta tag - e.g. Wordpress - you could find out if there's any exceptions to this.\nYou'll have to be careful how you detect it though, Google surprised me with this line:\n<meta content='blogger' name='generator'/>\n\nSingle quotes are blasphemy.\n", "To determine other patterns to look for in determining the blogging engine (for those that don't have a generator meta tag), you'd basically just look through the source to determine something specific to that blog type. You'd also need to compare this across multiple blogs of that type as you want to make sure that it's not something specific to the skin or theme in use on the blog only. \nAnother thought would be to read the docs of the various common blogging engine to know how to discover the location of it's paths to things like MetaWebLog API, etc. IIRC, Live Writer has built-in support for the most common types, the rest are categorized \"MetaWebLog API Blog\" or something.\n" ]
[ 3, 1, 1 ]
[]
[]
[ "api", "blogs", "java" ]
stackoverflow_0000026547_api_blogs_java.txt
Q: What HTML parsing libraries do you recommend in Java I want to parse some HTML in order to find the values of some attributes/tags etc. What HTML parsers do you recommend? Any pros and cons? A: NekoHTML, TagSoup, and JTidy will allow you to parse HTML and then process with XML tools, like XPath. A: I have tried HTML Parser which is dead simple. A: Do you need to do a full parse of the HTML? If you're just looking for specific values within the contents (a specific tag/param), then a simple regular expression might be enough, and could very well be faster.
What HTML parsing libraries do you recommend in Java
I want to parse some HTML in order to find the values of some attributes/tags etc. What HTML parsers do you recommend? Any pros and cons?
[ "NekoHTML, TagSoup, and JTidy will allow you to parse HTML and then process with XML tools, like XPath.\n", "I have tried HTML Parser which is dead simple.\n", "Do you need to do a full parse of the HTML? If you're just looking for specific values within the contents (a specific tag/param), then a simple regular expression might be enough, and could very well be faster.\n" ]
[ 12, 7, 1 ]
[]
[]
[ "html", "html_content_extraction", "java", "parsing" ]
stackoverflow_0000026638_html_html_content_extraction_java_parsing.txt
Q: Active X Control JavaScript My coworker and I have encountered a nasty situation where we have to use an active X control to manipulate a web camera on a page. Is it possible to assign a javascript event handler to a button in the active x control so that it would fire an action on the page when clicked, or do we have to create a button on the html page itself that manipulates the Active X Control and then can fire any necessary actions on the page? A: Please just use an existing ActiveX control. Like Flash or Silverlight. Flash has built-in webcam support and is controllable via JavaScript. Silverlight doesn't have built-in camera support, but it's JavaScript integration is fantastic. If you must write your own then fret not, it is trivial to get it to interact with JavaScript. You just have to expose the IDispatch interface. For events, you need to learn about Connection Points. A: Yes! You can throw events in C++/ActiveX land which makes the JavaScript code run an event handler function. I was even able to make an entire invisible ActiveX control (same color as page background) with no buttons or visual feedback that did all of its GUI work through JavaScript and CSS. edit: Frank's advice is right on. Here's the link on scripting events. My strategy was to call a C++ function called MyUpdate (which implements IConnectionPoint) when I wanted to force updates in the browser. (Also, I made sure to pump Windows messages in the Fire_MyUpdate method because sometimes JavaScript code would call back into C++ land by calling methods on the ActiveX control; this avoids freezing up the browser and ensures that the JavaScript GUI stays responsive, e.g. for a Cancel button.) On the browser side, the JavaScript code has the global variable referencing the object, followed by "::", followed by the method name: function Uploader::MyUpdate() { // ... code to fetch the current state of various // properties from the Uploader object and do something with it // for example check Uploader.IsActive and show or hide an HTML div }
Active X Control JavaScript
My coworker and I have encountered a nasty situation where we have to use an active X control to manipulate a web camera on a page. Is it possible to assign a javascript event handler to a button in the active x control so that it would fire an action on the page when clicked, or do we have to create a button on the html page itself that manipulates the Active X Control and then can fire any necessary actions on the page?
[ "Please just use an existing ActiveX control. Like Flash or Silverlight. Flash has built-in webcam support and is controllable via JavaScript. Silverlight doesn't have built-in camera support, but it's JavaScript integration is fantastic.\nIf you must write your own then fret not, it is trivial to get it to interact with JavaScript. You just have to expose the IDispatch interface.\nFor events, you need to learn about Connection Points.\n", "Yes! You can throw events in C++/ActiveX land which makes the JavaScript code run an event handler function. I was even able to make an entire invisible ActiveX control (same color as page background) with no buttons or visual feedback that did all of its GUI work through JavaScript and CSS.\nedit: Frank's advice is right on. Here's the link on scripting events.\nMy strategy was to call a C++ function called MyUpdate (which implements IConnectionPoint) when I wanted to force updates in the browser.\n(Also, I made sure to pump Windows messages in the Fire_MyUpdate method because sometimes JavaScript code would call back into C++ land by calling methods on the ActiveX control; this avoids freezing up the browser and ensures that the JavaScript GUI stays responsive, e.g. for a Cancel button.)\nOn the browser side, the JavaScript code has the global variable referencing the object, followed by \"::\", followed by the method name:\nfunction Uploader::MyUpdate()\n{\n // ... code to fetch the current state of various\n // properties from the Uploader object and do something with it\n // for example check Uploader.IsActive and show or hide an HTML div\n}\n\n" ]
[ 7, 4 ]
[]
[]
[ "activex", "javascript" ]
stackoverflow_0000026536_activex_javascript.txt
Q: Resize Infragistics GanttChart task with the mouse I loaded a custom DataTable into an UltraChart of type GanttChart. The data loads successfully. Do you know if it possible to add support for mouse resize(drag) to the tasks that show up into the chart? I have not been able to figure out if this is supported by the Infragistics control. ­­­­­­­­­­­­­­­­­­­­­­­­­­­ A: In this forum post, an Infragistics employee states that this is not implemented (as of Feb '08), but may be doable handling FillSceneGraph.
Resize Infragistics GanttChart task with the mouse
I loaded a custom DataTable into an UltraChart of type GanttChart. The data loads successfully. Do you know if it possible to add support for mouse resize(drag) to the tasks that show up into the chart? I have not been able to figure out if this is supported by the Infragistics control. ­­­­­­­­­­­­­­­­­­­­­­­­­­­
[ "In this forum post, an Infragistics employee states that this is not implemented (as of Feb '08), but may be doable handling FillSceneGraph.\n" ]
[ 1 ]
[]
[]
[ "charts", "gantt_chart", "infragistics", "winforms" ]
stackoverflow_0000026075_charts_gantt_chart_infragistics_winforms.txt
Q: Asp.net Reinstalling a DLL into the GAC I'm trying to re-install a DLL in the GAC, everything seems to work fine but the web application accessing it still seems to be using the old one. The old DLL is the same version as the new one with only a minor edit, it will be used by 50 different sites so changing the version then changing the reference in the web.config is not a good solution. Restarting the IIS server or the worker process isn't an option as there are already 50 sites running that must continue to do so. does anyone know what i'm doing wrong or what i can do to remedy this situation? A: AFAIK, you need to restart IIS for it to get a fresh reference to the updated DLL. Your best bet is to perform the reset at a low traffic time. If you are running multiple servers with load balancing, you can prevent new connections from hitting one server until all connections have been closed. Afterwards, update the DLL, restart IIS, and bring the server back into the connection pool. Repeat for each server with no visible downtime to the end users. A: Since you don't make a reference to application pools, I'm going to assume you are on the old version of IIS. In that case, what you'll need to do is to "touch" all the DLLs in each site that references the DLL. The problem is that the code is already loaded and you need to find a non-intrusive way to re-load the application. Recycling app-pools is an effective way to do this. If you are on the old IIS that doesn't have app-pools, then updating the last-modified in the /bin/ folders or web.config files will reload the application without affecting the other sites. So a script of some kind to do the above is in order. All it needs to do is update the lastmodified on the DLLs in every /bin application directory.
Asp.net Reinstalling a DLL into the GAC
I'm trying to re-install a DLL in the GAC, everything seems to work fine but the web application accessing it still seems to be using the old one. The old DLL is the same version as the new one with only a minor edit, it will be used by 50 different sites so changing the version then changing the reference in the web.config is not a good solution. Restarting the IIS server or the worker process isn't an option as there are already 50 sites running that must continue to do so. does anyone know what i'm doing wrong or what i can do to remedy this situation?
[ "AFAIK, you need to restart IIS for it to get a fresh reference to the updated DLL. Your best bet is to perform the reset at a low traffic time. If you are running multiple servers with load balancing, you can prevent new connections from hitting one server until all connections have been closed. Afterwards, update the DLL, restart IIS, and bring the server back into the connection pool. Repeat for each server with no visible downtime to the end users.\n", "Since you don't make a reference to application pools, I'm going to assume you are on the old version of IIS. In that case, what you'll need to do is to \"touch\" all the DLLs in each site that references the DLL. \nThe problem is that the code is already loaded and you need to find a non-intrusive way to re-load the application. Recycling app-pools is an effective way to do this. If you are on the old IIS that doesn't have app-pools, then updating the last-modified in the /bin/ folders or web.config files will reload the application without affecting the other sites.\nSo a script of some kind to do the above is in order. All it needs to do is update the lastmodified on the DLLs in every /bin application directory.\n" ]
[ 3, 1 ]
[]
[]
[ "dll", "gac", "iis" ]
stackoverflow_0000026711_dll_gac_iis.txt
Q: Any negative impacts when using Mod-Rewrite? I know there are a lot of positive things mod-rewrite accomplishes. But are there any negative? Obviously if you have poorly written rules your going to have problems. But what if you have a high volume site and your constantly using mod-rewrite, is it going to have a significant impact on performance? I did a quick search for some benchmarks on Google and didn't find much. A: I've used mod_rewrite on sites that get millions/hits/month without any significant performance issues. You do have to know which rewrites get applied first depending on your rules. Using mod_rewrite is most likely faster than parsing the URL with your current language. If you are really worried about performance, don't use .htaccess files, those are slow. Put all your rewrite rules in your Apache config, which is only read once on startup. .htaccess files get re-parsed on every request, along with every .htaccess file in parent folders. A: To echo what Ryan says above, rules in a .htaccess can really hurt your load times on a busy site in comparison to having the rules in your config file. We initially tried this (~60million pages/month) but didn't last very long until our servers started smoking :) The obvious downside to having the rules in your config is you have to reload the config whenever you modify your rules. The last flag ("L") is useful for speeding up execution of your rules, once your more frequently-accessed rules are towards the top and assessed first. It can make maintenance much trickier if you've a long set of rules though - I wasted a couple of very frustrating hours one morning as I was editing mid-way down my list of rules and had one up the top that was trapping more than intended! We had difficulty finding relevant benchmarks also, and ended up working out our own internal suite of tests. Once we got our rules sorted out, properly ordered and into our Apache conf, we didn't find much of a negative performance impact. A: If you're worried about apache's performance, one thing to consider if you have a lot of rewrite rules is to use the "skip" flag. It is a way to skip matching on rules. So, whatever overhead would have been spent on matching is saved. Be careful though, I was on a project which utilized the "skip" flag a lot, and it made maintenance painful, since it depends on the order in which things are written in the file.
Any negative impacts when using Mod-Rewrite?
I know there are a lot of positive things mod-rewrite accomplishes. But are there any negative? Obviously if you have poorly written rules your going to have problems. But what if you have a high volume site and your constantly using mod-rewrite, is it going to have a significant impact on performance? I did a quick search for some benchmarks on Google and didn't find much.
[ "I've used mod_rewrite on sites that get millions/hits/month without any significant performance issues. You do have to know which rewrites get applied first depending on your rules.\nUsing mod_rewrite is most likely faster than parsing the URL with your current language. \nIf you are really worried about performance, don't use .htaccess files, those are slow. Put all your rewrite rules in your Apache config, which is only read once on startup. .htaccess files get re-parsed on every request, along with every .htaccess file in parent folders.\n", "To echo what Ryan says above, rules in a .htaccess can really hurt your load times on a busy site in comparison to having the rules in your config file. We initially tried this (~60million pages/month) but didn't last very long until our servers started smoking :)\nThe obvious downside to having the rules in your config is you have to reload the config whenever you modify your rules.\nThe last flag (\"L\") is useful for speeding up execution of your rules, once your more frequently-accessed rules are towards the top and assessed first. It can make maintenance much trickier if you've a long set of rules though - I wasted a couple of very frustrating hours one morning as I was editing mid-way down my list of rules and had one up the top that was trapping more than intended! \nWe had difficulty finding relevant benchmarks also, and ended up working out our own internal suite of tests. Once we got our rules sorted out, properly ordered and into our Apache conf, we didn't find much of a negative performance impact.\n", "If you're worried about apache's performance, one thing to consider if you have a lot of rewrite rules is to use the \"skip\" flag. It is a way to skip matching on rules. So, whatever overhead would have been spent on matching is saved.\nBe careful though, I was on a project which utilized the \"skip\" flag a lot, and it made maintenance painful, since it depends on the order in which things are written in the file.\n" ]
[ 41, 7, 3 ]
[]
[]
[ "mod_rewrite", "performance" ]
stackoverflow_0000026559_mod_rewrite_performance.txt
Q: What's a good way to encapsulate data access with PHP/MySQL? Most of my experience is on the MSFT stack, but I am now working on a side project, helping someone with a personal site with cheap hosting that is built on the LAMP stack. My options for installing extras are limited, so I'm wondering about how to write my data access code without embedding raw queries in the .php files. I like to keep things simple, even with .NET. I generally write stored procedures for everything, and I have a helper class that wraps all calls to execute procedures and return data sets. I'm not looking for a full-blown ORM, but it might be the way to go and others who view this question might be looking for that. Remember that I'm on a $7/month GoDaddy account, so I'm limited to what's already installed in their basic package. Edit: Thanks rix0rr, Alan, Anders, dragon, I will check all of those out. I edited the question to be more open to ORM solutions, since they are so popular. A: ActiveRecord seems to be the state of the art at the moment. I can't recommend any good PHP frameworks for that though. I tried Propel which, while nice, is not easy to set up (especially on a host that you can't install anything on). Ultimately, I rolled my own ORM/ActiveRecord framework, which is not too much work and very instructive. I'm sure other people can recommend good PHP frameworks. A: Take a look at the Zend Framework, specifically Zend_Db. It has a Database Abstraction layer that doesn't require anything other than the MySQLi extension to be installed and isn't a full-blown ORM model. A: Maybe Doctrine would do the job? It seems to be inspired by Hibernate. A: rix0rrr hit on it a bit, in that many tools are a pain to set up. Of course, I have my own solution to this problem that has been working quite well for the past few years. It's a project called dbFacile I also wrote a bit of a usage comparison of the tools I found a few years ago. It's incomplete, but might give you a good starting point. You mentioned that you don't want to embed raw queries but you don't want ORM, so I'm a bit confused about the middle ground you're hoping to find. I also have an ORM project that aims to require minimal setup and great ease of use. The only requirement for my projects is PHP5. A: I would try a framework. Zend Framework has been cited. Symfony seems interesting. It's based on ideas from Ruby on Rails. A: You could also take a look at Prado. http://www.pradosoft.com/ It uses Active Record and DAO. Also if you use .Net then some of the formatting and conventions are similar.
What's a good way to encapsulate data access with PHP/MySQL?
Most of my experience is on the MSFT stack, but I am now working on a side project, helping someone with a personal site with cheap hosting that is built on the LAMP stack. My options for installing extras are limited, so I'm wondering about how to write my data access code without embedding raw queries in the .php files. I like to keep things simple, even with .NET. I generally write stored procedures for everything, and I have a helper class that wraps all calls to execute procedures and return data sets. I'm not looking for a full-blown ORM, but it might be the way to go and others who view this question might be looking for that. Remember that I'm on a $7/month GoDaddy account, so I'm limited to what's already installed in their basic package. Edit: Thanks rix0rr, Alan, Anders, dragon, I will check all of those out. I edited the question to be more open to ORM solutions, since they are so popular.
[ "ActiveRecord seems to be the state of the art at the moment. I can't recommend any good PHP frameworks for that though. I tried Propel which, while nice, is not easy to set up (especially on a host that you can't install anything on).\nUltimately, I rolled my own ORM/ActiveRecord framework, which is not too much work and very instructive. I'm sure other people can recommend good PHP frameworks.\n", "Take a look at the Zend Framework, specifically Zend_Db. It has a Database Abstraction layer that doesn't require anything other than the MySQLi extension to be installed and isn't a full-blown ORM model.\n", "Maybe Doctrine would do the job? It seems to be inspired by Hibernate.\n", "rix0rrr hit on it a bit, in that many tools are a pain to set up. Of course, I have my own solution to this problem that has been working quite well for the past few years. It's a project called dbFacile\nI also wrote a bit of a usage comparison of the tools I found a few years ago. It's incomplete, but might give you a good starting point.\nYou mentioned that you don't want to embed raw queries but you don't want ORM, so I'm a bit confused about the middle ground you're hoping to find. I also have an ORM project that aims to require minimal setup and great ease of use.\nThe only requirement for my projects is PHP5.\n", "I would try a framework. Zend Framework has been cited. Symfony seems interesting. It's based on ideas from Ruby on Rails.\n", "You could also take a look at Prado. http://www.pradosoft.com/ It uses Active Record and DAO. Also if you use .Net then some of the formatting and conventions are similar.\n" ]
[ 4, 3, 3, 3, 1, 1 ]
[]
[]
[ "database", "lamp", "mysql", "php" ]
stackoverflow_0000022278_database_lamp_mysql_php.txt
Q: Third party Visual Studio snippets Do you know where I could find some useful third party (free) code snippets for VS 2008? A: http://gotcodesnippets.com/ http://www.codekeep.net/ has a VS add-in for their snippets, too A: bdukes site has more options, but here are the ones MSDN has published... http://msdn.microsoft.com/en-us/vstudio/aa718338.aspx
Third party Visual Studio snippets
Do you know where I could find some useful third party (free) code snippets for VS 2008?
[ "http://gotcodesnippets.com/\nhttp://www.codekeep.net/ has a VS add-in for their snippets, too\n", "bdukes site has more options, but here are the ones MSDN has published...\nhttp://msdn.microsoft.com/en-us/vstudio/aa718338.aspx\n" ]
[ 6, 2 ]
[]
[]
[ "code_snippets", "visual_studio", "visual_studio_2008" ]
stackoverflow_0000026422_code_snippets_visual_studio_visual_studio_2008.txt
Q: Setting up a large Xcode project I have a large exiting C++ project involving: 4 applications 50+ libraries 20+ third party libraries It all builds fine on Windows using VS8, Linux using QMake (project uses Qt a lot). I also build it on OS X using QMake but I was wanting to setup an Xcode project to handle it in an IDE. I'm struggling to setup proper configuration to easily define dependencies, both to internal libraries and to the third party. I can do property sheets and .pri files in my (disturbed) sleep, but would appreciate some advice on building such large projects in Xcode. I've been experiencing with Xcode configuration files and #including one from another but it does not seem to work as I would expect, especially when defining standard locations for header files etc. Is there some good book describing the process of setting up Xcode (remember it's C++, I'm not wanting to learn ObjC at this time)? Or maybe a good open source project I could learn from? Thanks! A: Step in to Xcode may be the book you're looking for. It's got a whole section devoted to using AppleScript to automate configuration includes. I've been going through the book myself on O'Reilly Safari as I've found myself in a situation similar to yourself!
Setting up a large Xcode project
I have a large exiting C++ project involving: 4 applications 50+ libraries 20+ third party libraries It all builds fine on Windows using VS8, Linux using QMake (project uses Qt a lot). I also build it on OS X using QMake but I was wanting to setup an Xcode project to handle it in an IDE. I'm struggling to setup proper configuration to easily define dependencies, both to internal libraries and to the third party. I can do property sheets and .pri files in my (disturbed) sleep, but would appreciate some advice on building such large projects in Xcode. I've been experiencing with Xcode configuration files and #including one from another but it does not seem to work as I would expect, especially when defining standard locations for header files etc. Is there some good book describing the process of setting up Xcode (remember it's C++, I'm not wanting to learn ObjC at this time)? Or maybe a good open source project I could learn from? Thanks!
[ "Step in to Xcode may be the book you're looking for. It's got a whole section devoted to using AppleScript to automate configuration includes. I've been going through the book myself on O'Reilly Safari as I've found myself in a situation similar to yourself!\n" ]
[ 3 ]
[]
[]
[ "xcode" ]
stackoverflow_0000026875_xcode.txt
Q: Animation in javascript, a starting point I understand how JS is run and I think I understand most of the DOM but I've no idea about animation. Does anybody here know of a good guide that can explain to me how it's done in Javascript? In addition, should I even consider Javascript for animation? Should I instead be looking to learn flash? A: Avoid flash, its a horrible requirement, uncrawlable by Google, unsopported by a bunch of browsers and systems (eg iPhone) and most importantly: it forces you to reinvent web standards (e.g. scroll bars and whatnot), Javascript on the other hand is easier to maintain and code for in the noscript case. try scriptaculous for your animations; here's a quickie 3-line tutorial so you can see it working here's a more complete tutorial here's the scriptaculous wiki note that there are a gazillion JS animation libraries, some really good jQuery comes to mind. Usually they're just a script tag and an onclick event to setup. Good luck! /mp A: if your animation is simple, change colors over time, move from x to y in 3 seconds. Javascript is fine. If you want all kinds of wizbang buttons and coordinated rotation of the screen, straight up js + dhtml will be clunky at best. Silverlight vs Flash are you questions at that point. Interestingly enough, you program Silverlight with javascript, and that would be the major benefit to simply upgrading to a faster and more dynamic DOM that is implemented in Silverlight but still writing the same code. Flash programmability is very limited in my experience, you can do anything, but it will be slow and take thousands of lines of code to get there. For simple JS animations look at jQuery or Scriptaculous. A: Check out a JS animation framework like Bernard Sumption's Animator.js. It's pretty light-weight and has some excellent examples. Personally, I wouldn't be animating things in JS. Flash FTW. A: If you aren't concerned with IE support, you could also try experimenting with the canvas element: MOZILLA DEVELOPER NETWORK Basic animations
Animation in javascript, a starting point
I understand how JS is run and I think I understand most of the DOM but I've no idea about animation. Does anybody here know of a good guide that can explain to me how it's done in Javascript? In addition, should I even consider Javascript for animation? Should I instead be looking to learn flash?
[ "Avoid flash, its a horrible requirement, uncrawlable by Google, unsopported by a bunch of browsers and systems (eg iPhone) and most importantly: it forces you to reinvent web standards (e.g. scroll bars and whatnot), Javascript on the other hand is easier to maintain and code for in the noscript case.\ntry scriptaculous for your animations;\n\nhere's a quickie 3-line tutorial so\nyou can see it working\nhere's a more complete tutorial\nhere's the scriptaculous wiki\n\nnote that there are a gazillion JS animation libraries, some really good jQuery comes to mind. Usually they're just a script tag and an onclick event to setup.\nGood luck!\n/mp\n", "if your animation is simple, change colors over time, move from x to y in 3 seconds. Javascript is fine. If you want all kinds of wizbang buttons and coordinated rotation of the screen, straight up js + dhtml will be clunky at best. Silverlight vs Flash are you questions at that point. Interestingly enough, you program Silverlight with javascript, and that would be the major benefit to simply upgrading to a faster and more dynamic DOM that is implemented in Silverlight but still writing the same code. Flash programmability is very limited in my experience, you can do anything, but it will be slow and take thousands of lines of code to get there. For simple JS animations look at jQuery or Scriptaculous.\n", "Check out a JS animation framework like Bernard Sumption's Animator.js. It's pretty light-weight and has some excellent examples.\nPersonally, I wouldn't be animating things in JS. Flash FTW.\n", "If you aren't concerned with IE support, you could also try experimenting with the canvas element:\nMOZILLA DEVELOPER NETWORK Basic animations\n" ]
[ 4, 2, 1, 0 ]
[]
[]
[ "animation", "javascript" ]
stackoverflow_0000010038_animation_javascript.txt
Q: How to avoid redefining VERSION, PACKAGE, etc I haven't seen any questions relating to GNU autoconf/automake builds, but I'm hoping at least some of you out there are familiar with it. Here goes: I have a project (I'll call it myproject) that includes another project (vendor). The vendor project is a standalone project maintained by someone else. Including a project like this is fairly straightforward, but in this case there is a tiny snag: each project generates its own config.h file, each of which defines standard macros such as PACKAGE, VERSION, etc. This means that, during the build, when vendor is being built, I get lots of errors like this: ... warning: "VERSION" redefined ... warning: this is the location of the previous definition ... warning: "PACKAGE" redefined ... warning: this is the location of the previous definition These are just warnings, for the time being at least, but I would like to get rid of them. The only relevant information I've been able to turn up with a Google search is this thread on the automake mailing list, which isn't a whole lot of help. Does anybody else have any better ideas? A: Some notes: you didn't mention how config.h was included - with quotes or angle brackets. See this other question for more information on the difference. In short, config.h is typically included with quotes, not angle brackets, and this should make the preprocessor prefer the config.h from the project's own directory (which is usually what you want) You say that a subproject should be including the enclosing project's config.h Normally this is not at all what you want. The subproject is standalone, and its PACKAGE and VERSION should be the one of that subproject, not yours. If you include libxml in your xmlreader project for example, you would still want the libxml code to be compiled with PACKAGE libxml and VERSION (whatever the libxml version is). It is usually a big mistake to have config.h be included from public headers. config.h is always private to your project or the subproject, and should only be included from .c files. So, if your vendor's documentation says to include their "vendor.h" and that public header includes config.h somehow, then that is a no-no. Similarly, if your project is a library, don't include config.h anywhere from your publically installed headers. A: It's definitely a hack, but I post-process the autogen'd config.h file: sed -e 's/.*PACKAGE_.*//' < config.h > config.h.sed && mv config.h.sed config.h This is tolerable in our build environment but I'd be interested in a cleaner way. A: It turns out there was a very simple solution in my case. The vendor project gathers several header files into one monolithic header file, which is then #included by the vendor sources. But the make rule that builds the monolithic header accidentally included the generated config.h. The presence of the PACKAGE, VERSION, etc. config variables in the monolithic header is what was causing the redefinition warnings. It turns out that the vendor's config.h was irrelevant, because "config.h" always resolved to $(top_builddir)/config.h. I believe this is the way it's supposed to work. By default a subproject should be including the enclosing project's config.h instead of its own, unless the subproject explicitly includes its own, or manipulates the INCLUDE path so that its own directory comes before $(top_builddir), or otherwise manipulates the header files as in my case.
How to avoid redefining VERSION, PACKAGE, etc
I haven't seen any questions relating to GNU autoconf/automake builds, but I'm hoping at least some of you out there are familiar with it. Here goes: I have a project (I'll call it myproject) that includes another project (vendor). The vendor project is a standalone project maintained by someone else. Including a project like this is fairly straightforward, but in this case there is a tiny snag: each project generates its own config.h file, each of which defines standard macros such as PACKAGE, VERSION, etc. This means that, during the build, when vendor is being built, I get lots of errors like this: ... warning: "VERSION" redefined ... warning: this is the location of the previous definition ... warning: "PACKAGE" redefined ... warning: this is the location of the previous definition These are just warnings, for the time being at least, but I would like to get rid of them. The only relevant information I've been able to turn up with a Google search is this thread on the automake mailing list, which isn't a whole lot of help. Does anybody else have any better ideas?
[ "Some notes:\n\nyou didn't mention how config.h was included - with quotes or angle brackets. See this other question for more information on the difference. In short, config.h is typically included with quotes, not angle brackets, and this should make the preprocessor prefer the config.h from the project's own directory (which is usually what you want)\nYou say that a subproject should be including the enclosing project's config.h Normally this is not at all what you want. The subproject is standalone, and its PACKAGE and VERSION should be the one of that subproject, not yours. If you include libxml in your xmlreader project for example, you would still want the libxml code to be compiled with PACKAGE libxml and VERSION (whatever the libxml version is).\nIt is usually a big mistake to have config.h be included from public headers. config.h is always private to your project or the subproject, and should only be included from .c files. So, if your vendor's documentation says to include their \"vendor.h\" and that public header includes config.h somehow, then that is a no-no. Similarly, if your project is a library, don't include config.h anywhere from your publically installed headers.\n\n", "It's definitely a hack, but I post-process the autogen'd config.h file:\nsed -e 's/.*PACKAGE_.*//' < config.h > config.h.sed && mv config.h.sed config.h\n\nThis is tolerable in our build environment but I'd be interested in a cleaner way.\n", "It turns out there was a very simple solution in my case. The vendor project gathers several header files into one monolithic header file, which is then #included by the vendor sources. But the make rule that builds the monolithic header accidentally included the generated config.h. The presence of the PACKAGE, VERSION, etc. config variables in the monolithic header is what was causing the redefinition warnings. It turns out that the vendor's config.h was irrelevant, because \"config.h\" always resolved to $(top_builddir)/config.h.\nI believe this is the way it's supposed to work. By default a subproject should be including the enclosing project's config.h instead of its own, unless the subproject explicitly includes its own, or manipulates the INCLUDE path so that its own directory comes before $(top_builddir), or otherwise manipulates the header files as in my case.\n" ]
[ 5, 2, 1 ]
[]
[]
[ "autoconf", "automake", "c", "linux", "unix" ]
stackoverflow_0000007398_autoconf_automake_c_linux_unix.txt
Q: What are some web-based knowledge-base solutions? I've used a WordPress blog and a Screwturn Wiki (at two separate jobs) to store private, company-specific KB info, but I'm looking for something that was created to be a knowledge base. Specifically, I'd like to see: Free/low cost Simple method for users to subscribe to KB (or just sections) to get updates Ability to do page versioning/audit changes Limit access to certain pages for certain users Very simple method of posting/editing articles Very simple method of adding images to articles Excellent (fast, accurate) searching abilities Ability to rate and comment on articles I liked using the Wordpress blog because it allowed me to use Live Writer to add/edit articles and images, but it didn't have page versioning (that I could see). I like using Screwturn wiki because of it's ability to track article versions, and I like it's clean look, but some non-technical people balk at the input and editing. A: I second Luke's answer. I can Recommend Confluence and here is why: I tested extensively many commercial and free Wiki based solutions. Not a single one is a winner on all accounts, including confluence. Let me try to make your quest a little shorter by summarizing what I have learned to be a pain and what is important: WYSIWYG is a most have feature for the Enterprise. A wiki without it, skip it Saying that, in reality, WYSIWYG doesn't work perfectly. It is more of a feature you must have to get the casual users not be afraid of the monster, and start using it. But you and anyone that wants to seriously create content, will very quickly get used to the wiki markup. it is faster and more reliable. You need good permissions controls (who can see, edit etc' a page). confluence has good, but I have my complaints (to complicated to be put here) You will want a good export feature. Most will give you a single page "PDF" export, but you need much more. For example, lets say you have an FAQ, you want to export the entire FAQ right? will that work? Macros: you want a community creating macros. You asked for example about the ability to rate pages, here is a link to a Macro for Confluence that lets you do that Structure: you want to be able to say that a page is a child of a different page, and be able to browse the data. The wikipedia model, of orphaned pages with no sturcture will not work in the Enterprise. (think FAQ, you want to have a hierarchy no?) Ability to easily attache picture to be embedded in the body of the page/article. In confluence, you need to upload the image and then can embed it, it could be a little better (CTR+V) but I guess this is easy enough for 80% of the users. At the end of the day, remember that a Wiki will be valuable to you the more flexible it is. It needs to be a "blank" canvas, and your imagination is then used to "build" the application. In Confluence, I found 3 different "best practices" on how to create a FAQ. That means I can implement MANY things. Some examples (I use my Wiki for) FAQ: any error, problem is logged. Used by PS and ENG. reduced internal support time dramatically Track account status: I implemetned sophisticated "dashboard" that you can see at a glance which customer is at what state, the software version they have, who in the company 'owns" the custoemr etc' Product: all documentation, installation instructions, the "what's new" etc Technical documentation, DB structure and what the tables mean HR: contact list, Document repository My runner up (15 month ago) was free Deki_Wiki, time has passed, so I don't know if this would be still my runner up. good luck! A: I've also been investigating wiki software for use as a KB, but it is tricky to find something that is easy to use for non-technical people. There are many wikis that attempt to provide WYSIWYG editing, but most of the software I've found generates nasty inefficient html markup from the WYSIWYG editor. One notable exception to this is Confluence which generates wiki syntax from a WYSIWYG editor. This still isn't perfect (show me a WYSIWYG editor that is) but is a pretty good compromise between retaining simple wiki syntax for those who like it and allowing non-technical users to contribute content. The only problem is that Confluence isn't free ($1,200 for 25 user license). Edit: I also tried DekiWiki and while the UI is nice it doesn't seem to be quite ready for primetime (suffers terribly from the bad WYSIWYG output disease mentioned above). Also seems like they lack direction as there are so many different ways of accomplishing the same task. A: Cerberus - it's more a full featured Help Desk/Issue Tracking system but it has a nice KB solution built in. It can be free but they do have a low cost pay version that is also very good. A: I think Drupal is a very possible choice. It has a lot of built-in support for book-type information capturing. And there is a rich collection of user generated modules which you can use to enhance the features. I think it has almost all the features you ask for out of the box. Drupal CMS Benefits A: Personally I use MediaWiki for this purpose. I've tried a number of other free and paid wikis (including Confluence) and have always been impressed with MediaWiki's simplicity and ease of use. I have MediaWiki installed on a thumb drive (using XAMPP from PortableApps), which I use mostly as a personal knowledge base/code snippet repository. I can take it with me wherever I go, and view/edit it from any computer I'm using. A: We've been using a combination of TWiki OpenGrok for the codebase usenet LotusNotes based system As long as there is a google search appliance pointed at these things I think it's ok to have any or many versions as long as people use them
What are some web-based knowledge-base solutions?
I've used a WordPress blog and a Screwturn Wiki (at two separate jobs) to store private, company-specific KB info, but I'm looking for something that was created to be a knowledge base. Specifically, I'd like to see: Free/low cost Simple method for users to subscribe to KB (or just sections) to get updates Ability to do page versioning/audit changes Limit access to certain pages for certain users Very simple method of posting/editing articles Very simple method of adding images to articles Excellent (fast, accurate) searching abilities Ability to rate and comment on articles I liked using the Wordpress blog because it allowed me to use Live Writer to add/edit articles and images, but it didn't have page versioning (that I could see). I like using Screwturn wiki because of it's ability to track article versions, and I like it's clean look, but some non-technical people balk at the input and editing.
[ "I second Luke's answer.\nI can Recommend Confluence and here is why:\nI tested extensively many commercial and free Wiki based solutions. Not a single one is a winner on all accounts, including confluence. Let me try to make your quest a little shorter by summarizing what I have learned to be a pain and what is important:\n\nWYSIWYG is a most have feature for the Enterprise. A wiki without it, skip it\nSaying that, in reality, WYSIWYG doesn't work perfectly. It is more of a feature you must have to get the casual users not be afraid of the monster, and start using it. But you and anyone that wants to seriously create content, will very quickly get used to the wiki markup. it is faster and more reliable. \nYou need good permissions controls (who can see, edit etc' a page). confluence has good, but I have my complaints (to complicated to be put here)\nYou will want a good export feature. Most will give you a single page \"PDF\" export, but you need much more. For example, lets say you have an FAQ, you want to export the entire FAQ right? will that work? \nMacros: you want a community creating macros. You asked for example about the ability to rate pages, here is a link to a Macro for Confluence that lets you do that\nStructure: you want to be able to say that a page is a child of a different page, and be able to browse the data. The wikipedia model, of orphaned pages with no sturcture will not work in the Enterprise. (think FAQ, you want to have a hierarchy no?)\nAbility to easily attache picture to be embedded in the body of the page/article. In confluence, you need to upload the image and then can embed it, it could be a little better (CTR+V) but I guess this is easy enough for 80% of the users.\n\nAt the end of the day, remember that a Wiki will be valuable to you the more flexible it is. It needs to be a \"blank\" canvas, and your imagination is then used to \"build\" the application. In Confluence, I found 3 different \"best practices\" on how to create a FAQ. That means I can implement MANY things. \nSome examples (I use my Wiki for)\n\nFAQ: any error, problem is logged. Used by PS and ENG. reduced internal support time dramatically\nTrack account status: I implemetned sophisticated \"dashboard\" that you can see at a glance which customer is at what state, the software version they have, who in the company 'owns\" the custoemr etc'\nProduct: all documentation, installation instructions, the \"what's new\" etc\nTechnical documentation, DB structure and what the tables mean \nHR: contact list, Document repository \n\nMy runner up (15 month ago) was free Deki_Wiki, time has passed, so I don't know if this would be still my runner up.\ngood luck!\n", "I've also been investigating wiki software for use as a KB, but it is tricky to find something that is easy to use for non-technical people. There are many wikis that attempt to provide WYSIWYG editing, but most of the software I've found generates nasty inefficient html markup from the WYSIWYG editor. \nOne notable exception to this is Confluence which generates wiki syntax from a WYSIWYG editor. This still isn't perfect (show me a WYSIWYG editor that is) but is a pretty good compromise between retaining simple wiki syntax for those who like it and allowing non-technical users to contribute content. The only problem is that Confluence isn't free ($1,200 for 25 user license).\nEdit: I also tried DekiWiki and while the UI is nice it doesn't seem to be quite ready for primetime (suffers terribly from the bad WYSIWYG output disease mentioned above). Also seems like they lack direction as there are so many different ways of accomplishing the same task.\n", "Cerberus - it's more a full featured Help Desk/Issue Tracking system but it has a nice KB solution built in. It can be free but they do have a low cost pay version that is also very good.\n", "I think Drupal is a very possible choice. It has a lot of built-in support for book-type information capturing.\nAnd there is a rich collection of user generated modules which you can use to enhance the features.\nI think it has almost all the features you ask for out of the box.\nDrupal CMS Benefits\n", "Personally I use MediaWiki for this purpose. I've tried a number of other free and paid wikis (including Confluence) and have always been impressed with MediaWiki's simplicity and ease of use. \nI have MediaWiki installed on a thumb drive (using XAMPP from PortableApps), which I use mostly as a personal knowledge base/code snippet repository. I can take it with me wherever I go, and view/edit it from any computer I'm using.\n", "We've been using a combination of \n\nTWiki\nOpenGrok for the codebase\nusenet\nLotusNotes based system\n\nAs long as there is a google search appliance pointed at these things I think it's ok to have any or many versions as long as people use them\n" ]
[ 10, 3, 2, 1, 1, 0 ]
[]
[]
[ "language_agnostic" ]
stackoverflow_0000002639_language_agnostic.txt
Q: How can I make sure scrollbars don't overlap content? When creating scrollable user controls with .NET and WinForms I have repeatedly encountered situations where, for example, a vertical scrollbar pops up, overlapping the control's content, causing a horizontal scrollbar to also be needed. Ideally the content would shrink just a bit to make room for the vertical scrollbar. My current solution has been to just keep my controls out of the far right 40 pixels or so that the vertical scroll-bar will be taking up. Since this is still effectively client space for the control, the horizontal scroll-bar still comes up when it gets covered by the vertical scroll-bar, even though no controls are being hidden at all. But then at least the user doesn't actually need to use the horizontal scrollbar that comes up. Is there a better way to make this all work? Some way to keep the unneeded and unwanted scrollbars from showing up at all? A: You will need your controls to resize slightly to accommodate the width of the vertical scroll bar. One way to achieve this achieved through docking. Rather than just dropping controls on the form, you'll have to play a bit with panels, padding, min/max sizing and docking. Here is example code you can place behind a blank new Form1. Resize the form, in designer or runtime and you'll see that the horizontal scrollbar is not shown and the fields are not overlapped. I've also given the fields a max width for good measure : #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.textBox1 = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.panel1 = new System.Windows.Forms.Panel(); this.panel2 = new System.Windows.Forms.Panel(); this.textBox2 = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.panel1.SuspendLayout(); this.panel2.SuspendLayout(); this.SuspendLayout(); // // textBox1 // this.textBox1.Dock = System.Windows.Forms.DockStyle.Top; this.textBox1.Location = new System.Drawing.Point(32, 0); this.textBox1.MaximumSize = new System.Drawing.Size(250, 0); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(250, 20); this.textBox1.TabIndex = 0; // // label1 // this.label1.AutoSize = true; this.label1.Dock = System.Windows.Forms.DockStyle.Left; this.label1.Location = new System.Drawing.Point(0, 0); this.label1.Name = "label1"; this.label1.Padding = new System.Windows.Forms.Padding(0, 3, 0, 0); this.label1.Size = new System.Drawing.Size(32, 16); this.label1.TabIndex = 0; this.label1.Text = "Field:"; // // panel1 // this.panel1.Controls.Add(this.textBox1); this.panel1.Controls.Add(this.label1); this.panel1.Dock = System.Windows.Forms.DockStyle.Top; this.panel1.Location = new System.Drawing.Point(0, 0); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(392, 37); this.panel1.TabIndex = 2; // // panel2 // this.panel2.Controls.Add(this.textBox2); this.panel2.Controls.Add(this.label2); this.panel2.Dock = System.Windows.Forms.DockStyle.Top; this.panel2.Location = new System.Drawing.Point(0, 37); this.panel2.Name = "panel2"; this.panel2.Size = new System.Drawing.Size(392, 37); this.panel2.TabIndex = 3; // // textBox2 // this.textBox2.Dock = System.Windows.Forms.DockStyle.Top; this.textBox2.Location = new System.Drawing.Point(32, 0); this.textBox2.MaximumSize = new System.Drawing.Size(250, 0); this.textBox2.Name = "textBox2"; this.textBox2.Size = new System.Drawing.Size(250, 20); this.textBox2.TabIndex = 0; // // label2 // this.label2.AutoSize = true; this.label2.Dock = System.Windows.Forms.DockStyle.Left; this.label2.Location = new System.Drawing.Point(0, 0); this.label2.Name = "label2"; this.label2.Padding = new System.Windows.Forms.Padding(0, 3, 0, 0); this.label2.Size = new System.Drawing.Size(32, 16); this.label2.TabIndex = 0; this.label2.Text = "Field:"; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScroll = true; this.ClientSize = new System.Drawing.Size(392, 116); this.Controls.Add(this.panel2); this.Controls.Add(this.panel1); this.Name = "Form1"; this.Text = "Form1"; this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.panel2.ResumeLayout(false); this.panel2.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Label label1; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.TextBox textBox2; private System.Windows.Forms.Label label2; A: If your controls are inside a panel, try setting the AutoScroll property of the Panel to False. This will hide the scrollbars. I hope this points you in the right direction. myPanel.AutoScroll = False
How can I make sure scrollbars don't overlap content?
When creating scrollable user controls with .NET and WinForms I have repeatedly encountered situations where, for example, a vertical scrollbar pops up, overlapping the control's content, causing a horizontal scrollbar to also be needed. Ideally the content would shrink just a bit to make room for the vertical scrollbar. My current solution has been to just keep my controls out of the far right 40 pixels or so that the vertical scroll-bar will be taking up. Since this is still effectively client space for the control, the horizontal scroll-bar still comes up when it gets covered by the vertical scroll-bar, even though no controls are being hidden at all. But then at least the user doesn't actually need to use the horizontal scrollbar that comes up. Is there a better way to make this all work? Some way to keep the unneeded and unwanted scrollbars from showing up at all?
[ "You will need your controls to resize slightly to accommodate the width of the vertical scroll bar. One way to achieve this achieved through docking. Rather than just dropping controls on the form, you'll have to play a bit with panels, padding, min/max sizing and docking.\nHere is example code you can place behind a blank new Form1. Resize the form, in designer or runtime and you'll see that the horizontal scrollbar is not shown and the fields are not overlapped. I've also given the fields a max width for good measure : \n#region Windows Form Designer generated code\n\n /// <summary>\n /// Required method for Designer support - do not modify\n /// the contents of this method with the code editor.\n /// </summary>\n private void InitializeComponent() {\n this.textBox1 = new System.Windows.Forms.TextBox();\n this.label1 = new System.Windows.Forms.Label();\n this.panel1 = new System.Windows.Forms.Panel();\n this.panel2 = new System.Windows.Forms.Panel();\n this.textBox2 = new System.Windows.Forms.TextBox();\n this.label2 = new System.Windows.Forms.Label();\n this.panel1.SuspendLayout();\n this.panel2.SuspendLayout();\n this.SuspendLayout();\n // \n // textBox1\n // \n this.textBox1.Dock = System.Windows.Forms.DockStyle.Top;\n this.textBox1.Location = new System.Drawing.Point(32, 0);\n this.textBox1.MaximumSize = new System.Drawing.Size(250, 0);\n this.textBox1.Name = \"textBox1\";\n this.textBox1.Size = new System.Drawing.Size(250, 20);\n this.textBox1.TabIndex = 0;\n // \n // label1\n // \n this.label1.AutoSize = true;\n this.label1.Dock = System.Windows.Forms.DockStyle.Left;\n this.label1.Location = new System.Drawing.Point(0, 0);\n this.label1.Name = \"label1\";\n this.label1.Padding = new System.Windows.Forms.Padding(0, 3, 0, 0);\n this.label1.Size = new System.Drawing.Size(32, 16);\n this.label1.TabIndex = 0;\n this.label1.Text = \"Field:\";\n // \n // panel1\n // \n this.panel1.Controls.Add(this.textBox1);\n this.panel1.Controls.Add(this.label1);\n this.panel1.Dock = System.Windows.Forms.DockStyle.Top;\n this.panel1.Location = new System.Drawing.Point(0, 0);\n this.panel1.Name = \"panel1\";\n this.panel1.Size = new System.Drawing.Size(392, 37);\n this.panel1.TabIndex = 2;\n // \n // panel2\n // \n this.panel2.Controls.Add(this.textBox2);\n this.panel2.Controls.Add(this.label2);\n this.panel2.Dock = System.Windows.Forms.DockStyle.Top;\n this.panel2.Location = new System.Drawing.Point(0, 37);\n this.panel2.Name = \"panel2\";\n this.panel2.Size = new System.Drawing.Size(392, 37);\n this.panel2.TabIndex = 3;\n // \n // textBox2\n // \n this.textBox2.Dock = System.Windows.Forms.DockStyle.Top;\n this.textBox2.Location = new System.Drawing.Point(32, 0);\n this.textBox2.MaximumSize = new System.Drawing.Size(250, 0);\n this.textBox2.Name = \"textBox2\";\n this.textBox2.Size = new System.Drawing.Size(250, 20);\n this.textBox2.TabIndex = 0;\n // \n // label2\n // \n this.label2.AutoSize = true;\n this.label2.Dock = System.Windows.Forms.DockStyle.Left;\n this.label2.Location = new System.Drawing.Point(0, 0);\n this.label2.Name = \"label2\";\n this.label2.Padding = new System.Windows.Forms.Padding(0, 3, 0, 0);\n this.label2.Size = new System.Drawing.Size(32, 16);\n this.label2.TabIndex = 0;\n this.label2.Text = \"Field:\";\n // \n // Form1\n // \n this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);\n this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;\n this.AutoScroll = true;\n this.ClientSize = new System.Drawing.Size(392, 116);\n this.Controls.Add(this.panel2);\n this.Controls.Add(this.panel1);\n this.Name = \"Form1\";\n this.Text = \"Form1\";\n this.panel1.ResumeLayout(false);\n this.panel1.PerformLayout();\n this.panel2.ResumeLayout(false);\n this.panel2.PerformLayout();\n this.ResumeLayout(false);\n\n }\n\n #endregion\n\n private System.Windows.Forms.TextBox textBox1;\n private System.Windows.Forms.Label label1;\n private System.Windows.Forms.Panel panel1;\n private System.Windows.Forms.Panel panel2;\n private System.Windows.Forms.TextBox textBox2;\n private System.Windows.Forms.Label label2;\n\n", "If your controls are inside a panel, try setting the AutoScroll property of the Panel to False. This will hide the scrollbars. I hope this points you in the right direction.\nmyPanel.AutoScroll = False\n\n" ]
[ 1, 0 ]
[]
[]
[ ".net", "winforms" ]
stackoverflow_0000026721_.net_winforms.txt
Q: Difference between wiring events with and without "new" In C#, what is the difference (if any) between these two lines of code? tmrMain.Elapsed += new ElapsedEventHandler(tmrMain_Tick); and tmrMain.Elapsed += tmrMain_Tick; Both appear to work exactly the same. Does C# just assume you mean the former when you type the latter? A: I did this static void Hook1() { someEvent += new EventHandler( Program_someEvent ); } static void Hook2() { someEvent += Program_someEvent; } And then ran ildasm over the code. The generated MSIL was exactly the same. So to answer your question, yes they are the same thing. The compiler is just inferring that you want someEvent += new EventHandler( Program_someEvent ); -- You can see it creating the new EventHandler object in both cases in the MSIL A: It used to be (.NET 1.x days) that the long form was the only way to do it. In both cases you are newing up a delegate to point to the Program_someEvent method. A: I don't think there's any difference. Certainly resharper says the first line has redundant code. A: A little offtopic : You could instantiate a delegate (new EventHandler(MethodName)) and (if appropriate) reuse that instance. A: Wasn't the new XYZEventHandler require until C#2003, and you were allowed to omit the redundant code in C#2005?
Difference between wiring events with and without "new"
In C#, what is the difference (if any) between these two lines of code? tmrMain.Elapsed += new ElapsedEventHandler(tmrMain_Tick); and tmrMain.Elapsed += tmrMain_Tick; Both appear to work exactly the same. Does C# just assume you mean the former when you type the latter?
[ "I did this\nstatic void Hook1()\n{\n someEvent += new EventHandler( Program_someEvent );\n}\n\nstatic void Hook2()\n{\n someEvent += Program_someEvent;\n}\n\nAnd then ran ildasm over the code.\nThe generated MSIL was exactly the same.\nSo to answer your question, yes they are the same thing.\nThe compiler is just inferring that you want someEvent += new EventHandler( Program_someEvent );\n-- You can see it creating the new EventHandler object in both cases in the MSIL\n", "It used to be (.NET 1.x days) that the long form was the only way to do it. In both cases you are newing up a delegate to point to the Program_someEvent method.\n", "I don't think there's any difference. Certainly resharper says the first line has redundant code.\n", "A little offtopic :\nYou could instantiate a delegate (new EventHandler(MethodName)) and (if appropriate) reuse that instance.\n", "Wasn't the new XYZEventHandler require until C#2003, and you were allowed to omit the redundant code in C#2005?\n" ]
[ 26, 4, 2, 2, 0 ]
[ "I think the one way to really tell would be to look at the MSIL produced for the code.. Tends to be a good acid test..\nI have funny concerns that it may somehow mess with GC.. Seems odd that there would be all the overhead of declaring the new delegate type if it never needed to be done this way, you know?\n" ]
[ -1 ]
[ "c#", "delegates", "events", "syntax" ]
stackoverflow_0000026877_c#_delegates_events_syntax.txt
Q: What is your best tool or techniques for getting the same display on IE6/7 and Firefox? I'm not talking about tools that let one view a page in combinations of operating systems and browsers like crossbrowsertesting.com but in creating or figuring out the actual CSS. A: Use a css reset to level the field across browsers. YUI and Eric Meyer have good ones. A: If you guys are still coding for IE6, you're making a mistake. I use IE7.js to get IE6 to render pages like IE7. IE7 is not perfect, but at least it has some semblance of standards. Since I only have to code for IE7 and FF it makes me 33% more efficient in terms of testing against browsers, something I think makes good business sense. Link: IE7.js A: I write to the standards and both Firefox and IE7 follow a pretty good set in common. IE6 is dead as far as I am concerned but if I get back into professional web dev I'll probably have to revise that ;) A: I try to make a standards-compliant page and do all my testing in Firefox (since it has some excellent development extensions such as Web Developer and Firebug). Then when I'm finished I test the site in IE, then make whatever small changes are necessary. I find that I need to make very few changes, since I don't do anything extraordinarily complex with CSS. I used to have more problems with Javascript differences, but after I started using Javascript libraries (such as jQuery) I stopped having any serious problems with that. A: Padding. IE6 can get a little hinky when using margin to place elements horizontally on a page. If you size your elements and space the content within using padding, you can make many layouts work great in IE6/7, FF, Safari, and Opera without any hacks. IE5.5 makes things a little stickier because of the broken box model, but I think we can pretty much count it out in most circumstances now. A: I try to make a standards-compliant page and do all my testing in Firefox (since it has some excellent development extensions such as Web Developer and Firebug). Then when I'm finished I test the site in IE, then make whatever small changes are necessary. I find that I need to make very few changes, since I don't do anything extraordinarily complex with CSS. The same here, except I don't tend to need to use Firebug and such. I've only had problems with IE6 recently however - which are solved by simple CSS bypasses: /* All browsers read: */ html body { margin: 10px; } /* FF, IE7, Op etc. read: */ html > body { margin: 0; } A: I'm with Eli. Writing against firefox (with firebug installed) makes you have to write "more compatible" code to begin with and then its less of a job later down the line when you come to make it compatible with IE. Use the site QuirksMode to help you find answers to compatbility information A: If it's a brand new project I make it a point to test all html+css changes on all browsers I'm targeting as I make the changes. In the past I tended to focus on my favorite browser and then test with the others after I was done to find that one or more small quirks were present and it was very tedious to pin-point the actual cause. Now I have all browsers open and just go through refreshing each one after each html/css change to make sure the display meets my expectation. When something goes wrong, I know exactly what caused it. It might seem time-consuming to test on all browsers at once, but in the long-run it actually saves time as you catch the problems at once.
What is your best tool or techniques for getting the same display on IE6/7 and Firefox?
I'm not talking about tools that let one view a page in combinations of operating systems and browsers like crossbrowsertesting.com but in creating or figuring out the actual CSS.
[ "Use a css reset to level the field across browsers. YUI and Eric Meyer have good ones.\n", "If you guys are still coding for IE6, you're making a mistake. \nI use IE7.js to get IE6 to render pages like IE7. IE7 is not perfect, but at least it has some semblance of standards. Since I only have to code for IE7 and FF it makes me 33% more efficient in terms of testing against browsers, something I think makes good business sense.\nLink: IE7.js\n", "I write to the standards and both Firefox and IE7 follow a pretty good set in common. \nIE6 is dead as far as I am concerned but if I get back into professional web dev I'll probably have to revise that ;)\n", "I try to make a standards-compliant page and do all my testing in Firefox (since it has some excellent development extensions such as Web Developer and Firebug). Then when I'm finished I test the site in IE, then make whatever small changes are necessary. I find that I need to make very few changes, since I don't do anything extraordinarily complex with CSS.\nI used to have more problems with Javascript differences, but after I started using Javascript libraries (such as jQuery) I stopped having any serious problems with that.\n", "Padding.\nIE6 can get a little hinky when using margin to place elements horizontally on a page. If you size your elements and space the content within using padding, you can make many layouts work great in IE6/7, FF, Safari, and Opera without any hacks. IE5.5 makes things a little stickier because of the broken box model, but I think we can pretty much count it out in most circumstances now.\n", "\nI try to make a standards-compliant page and do all my testing in Firefox (since it has some excellent development extensions such as Web Developer and Firebug). Then when I'm finished I test the site in IE, then make whatever small changes are necessary. I find that I need to make very few changes, since I don't do anything extraordinarily complex with CSS.\n\nThe same here, except I don't tend to need to use Firebug and such. I've only had problems with IE6 recently however - which are solved by simple CSS bypasses:\n/* All browsers read: */\nhtml body {\n margin: 10px;\n}\n\n/* FF, IE7, Op etc. read: */\nhtml > body {\n margin: 0;\n}\n\n", "I'm with Eli. Writing against firefox (with firebug installed) makes you have to write \"more compatible\" code to begin with and then its less of a job later down the line when you come to make it compatible with IE.\nUse the site QuirksMode to help you find answers to compatbility information\n", "If it's a brand new project I make it a point to test all html+css changes on all browsers I'm targeting as I make the changes. In the past I tended to focus on my favorite browser and then test with the others after I was done to find that one or more small quirks were present and it was very tedious to pin-point the actual cause. Now I have all browsers open and just go through refreshing each one after each html/css change to make sure the display meets my expectation. When something goes wrong, I know exactly what caused it.\nIt might seem time-consuming to test on all browsers at once, but in the long-run it actually saves time as you catch the problems at once.\n" ]
[ 4, 3, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "cross_browser", "css", "firefox", "internet_explorer" ]
stackoverflow_0000026113_cross_browser_css_firefox_internet_explorer.txt
Q: How do I delete a directory with cc.net / cruiscontrol? Possible Duplicate: Pre-build task - deleting the working copy in CruiseControl.NET I would like to delete my working directory during the cruisecontrol build process...I'm sure this is easy, but I have been unable to find an example of it... If you know how to create a directory, that would be useful as well. Thanks. A: One of two ways. If you're already using an MSBuild file or something similar, add the action to the MSBuild file. Instead of directly executing some command, create a batch file that executes that command and then deletes the directory, and have CCnet call that batch file instead. A: My guess is that you want to delete the working directory before CruiseControl.NET gets the latest code from source control. If this is the case, then the only way to accomplish this is to write a custom source control provider for CruiseControl.NET that first deletes the working directory and then gets the latest code. Have a look at CruiseControl.NET's source code for examples of how to write a source control provider. If you want to delete the working directory after the latest code is retrieved from source control, then you can use CruiseControl.NET's executable task by running "cmd /c del directoryname". A: In the ASP.NET work, for me, the easiest way I do it (which allows me to hit either MSBUild or NAnt depending upon the project) was to roll my own exe that takes an argument which I pass in with a bat file fired by CC.NET. It's not the safest thing in the world, but if you have total control over your automated build machine; it's not too shabby. Quick and reusable. Drop in the exe somewhere that does the recursive delete: static void Main(string[] args) { for (int n = 0; n < args.Length; n++) { if (Directory.Exists(args[n].ToString())) { Directory.Delete(args[n].ToString(), true); } } } Drop it in somewhere multiple files can pass arguments to it and just write a custom .bat file for each project. So my task block looks like this: <tasks> <msbuild> <executable>C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe</executable> <workingDirectory>Z:\WorkingDirectory</workingDirectory> <projectFile>YourSolution.sln</projectFile> <logger>C:\Program Files\CruiseControl.NET\server\ThoughtWorks.CruiseControl.MsBuild.dll</logger> </msbuild> <exec> <executable>Z:\SomePathToBuildScripts\YourCustomBat.bat</executable> </exec> </tasks> Then the final step is setting up that .bat file to perform the delete/rebuild functions after use. In the bat file just make sure you rebuild ("MD") the directories you deleted if youexpect to publish a site back to them. On our dev boxes I found this to be the best way to prevent the beloved Frankenbuild. A: The way I've done this in the past is to not have CC.Net checkout source itself. Instead, there are two <msbuild> elements for the project, the first one calling a build target that runs svn-clean.pl (compiled to .exe), and then updates the source using svn.exe. The second <msbuild> element starts the main build process. You can easily replace svn-clean with a delete command. For my projects, deleting chaff from a checkout has always been faster than checking out a fresh working copy. The two msbuild elements are necessary because the main project build file is often updated. This is important because updates to your build file(s) will only be reloaded if you start a new msbuild process. This setup breaks down when I (very rarely) move or change the dependencies of that clean-and-update build target to the extent that the msbuild process would need to reload for valid instructions to run the clean-and-update target. When this happens, I stop CC.Net before committing, go into the CC.Net server, and do an 'svn update' by hand. Sidelight: It could well be that CC.Net has a natural clean-before-build operation by now. I've since moved to TeamCity, which is configurable to do this every build or only when the developer chooses (e.g., when you know you've made a change that would not update cleanly--svn moves of directories with build products comes to mind).
How do I delete a directory with cc.net / cruiscontrol?
Possible Duplicate: Pre-build task - deleting the working copy in CruiseControl.NET I would like to delete my working directory during the cruisecontrol build process...I'm sure this is easy, but I have been unable to find an example of it... If you know how to create a directory, that would be useful as well. Thanks.
[ "One of two ways.\n\nIf you're already using an MSBuild file or something similar, add the action to the MSBuild file.\nInstead of directly executing some command, create a batch file that executes that command and then deletes the directory, and have CCnet call that batch file instead.\n\n", "My guess is that you want to delete the working directory before CruiseControl.NET gets the latest code from source control. If this is the case, then the only way to accomplish this is to write a custom source control provider for CruiseControl.NET that first deletes the working directory and then gets the latest code. Have a look at CruiseControl.NET's source code for examples of how to write a source control provider.\nIf you want to delete the working directory after the latest code is retrieved from source control, then you can use CruiseControl.NET's executable task by running \"cmd /c del directoryname\".\n", "In the ASP.NET work, for me, the easiest way I do it (which allows me to hit either MSBUild or NAnt depending upon the project) was to roll my own exe that takes an argument which I pass in with a bat file fired by CC.NET. It's not the safest thing in the world, but if you have total control over your automated build machine; it's not too shabby. Quick and reusable.\nDrop in the exe somewhere that does the recursive delete:\n\nstatic void Main(string[] args)\n{\n for (int n = 0; n < args.Length; n++)\n {\n if (Directory.Exists(args[n].ToString()))\n {\n Directory.Delete(args[n].ToString(), true);\n }\n\n }\n\n\n}\n\n\n\nDrop it in somewhere multiple files can pass arguments to it and just write a custom .bat file for each project. So my task block looks like this:\n\n\n<tasks>\n <msbuild>\n <executable>C:\\WINDOWS\\Microsoft.NET\\Framework\\v3.5\\MSBuild.exe</executable>\n <workingDirectory>Z:\\WorkingDirectory</workingDirectory>\n <projectFile>YourSolution.sln</projectFile>\n <logger>C:\\Program Files\\CruiseControl.NET\\server\\ThoughtWorks.CruiseControl.MsBuild.dll</logger>\n </msbuild>\n <exec>\n <executable>Z:\\SomePathToBuildScripts\\YourCustomBat.bat</executable>\n </exec>\n</tasks>\n\n\nThen the final step is setting up that .bat file to perform the delete/rebuild functions after use. In the bat file just make sure you rebuild (\"MD\") the directories you deleted if youexpect to publish a site back to them. On our dev boxes I found this to be the best way to prevent the beloved Frankenbuild.\n", "The way I've done this in the past is to not have CC.Net checkout source itself. Instead, there are two <msbuild> elements for the project, the first one calling a build target that runs svn-clean.pl (compiled to .exe), and then updates the source using svn.exe. The second <msbuild> element starts the main build process.\nYou can easily replace svn-clean with a delete command. For my projects, deleting chaff from a checkout has always been faster than checking out a fresh working copy.\nThe two msbuild elements are necessary because the main project build file is often updated. This is important because updates to your build file(s) will only be reloaded if you start a new msbuild process.\nThis setup breaks down when I (very rarely) move or change the dependencies of that clean-and-update build target to the extent that the msbuild process would need to reload for valid instructions to run the clean-and-update target. When this happens, I stop CC.Net before committing, go into the CC.Net server, and do an 'svn update' by hand.\nSidelight: It could well be that CC.Net has a natural clean-before-build operation by now. I've since moved to TeamCity, which is configurable to do this every build or only when the developer chooses (e.g., when you know you've made a change that would not update cleanly--svn moves of directories with build products comes to mind).\n" ]
[ 4, 0, 0, 0 ]
[]
[]
[ "cruisecontrol", "cruisecontrol.net" ]
stackoverflow_0000026925_cruisecontrol_cruisecontrol.net.txt
Q: How to represent cross-model information in MVC? I have an application, built using MVC, that produces a view which delivers summary information across a number of models. Further to that, some calculations are performed across the different sets of data. There's no clear single model (that maps to a table at least) that seems to make sense as the starting point for this, so the various summaries are pulled from the contributing models in the controller, passed into the view and the calculations are performed there. But that seems, well, dirty. But controllers are supposed to be lightweight, aren't they? And business logic shouldn't be in views, as I have it as present. So where should this information be assembled? A new model, that doesn't map to a table? A library function/module? Or something else? (Although I see this as mostly of an architectural/pattern question, I'm working in Rails, FWIW.) Edit: Good answers all round, and a lot of consensus, which is reassuring. I "accepted" the answer I did to keep the link to Railscasts at the top. I'm behind in my Railscast viewing - something I shall make strenuous attempts to rectify! A: As Brian said, you can create another model that marshals out the work that needs doing. There is a great Railscast on how to do this type of thing. HTH A: Why not create a model that doesn't inherit ActiveRecord::Base and execute the logic there (think the Cart class in Agile...With Rails). A: Controllers don't have to map to specific models or views. Your model doesn't have to map one-to-one to a database table. That's sort of the idea of the framework. Separation of concerns that can all be tested in isolation. A: Controllers don't have to be that lightweight. However if you have some calculations that only rely on the model/s then you probably just need some sort of model wrapper for the models to perform the calculation. You can then place that into the API for the view so the view gets the end result. A: You don't want the logic to be in the view. However you are free to create a database view. Except, rather than create it on the database side, create it as a new model. This will enable you to perform your calculations and your actual logic there, in one place. The pain of trying to keep your views in sync vs. the one time "pain" of creating the new model... I vote for a new model.
How to represent cross-model information in MVC?
I have an application, built using MVC, that produces a view which delivers summary information across a number of models. Further to that, some calculations are performed across the different sets of data. There's no clear single model (that maps to a table at least) that seems to make sense as the starting point for this, so the various summaries are pulled from the contributing models in the controller, passed into the view and the calculations are performed there. But that seems, well, dirty. But controllers are supposed to be lightweight, aren't they? And business logic shouldn't be in views, as I have it as present. So where should this information be assembled? A new model, that doesn't map to a table? A library function/module? Or something else? (Although I see this as mostly of an architectural/pattern question, I'm working in Rails, FWIW.) Edit: Good answers all round, and a lot of consensus, which is reassuring. I "accepted" the answer I did to keep the link to Railscasts at the top. I'm behind in my Railscast viewing - something I shall make strenuous attempts to rectify!
[ "As Brian said, you can create another model that marshals out the work that needs doing. There is a great Railscast on how to do this type of thing.\nHTH\n", "Why not create a model that doesn't inherit ActiveRecord::Base and execute the logic there (think the Cart class in Agile...With Rails).\n", "Controllers don't have to map to specific models or views. Your model doesn't have to map one-to-one to a database table. That's sort of the idea of the framework. Separation of concerns that can all be tested in isolation.\n", "Controllers don't have to be that lightweight.\nHowever if you have some calculations that only rely on the model/s then you probably just need some sort of model wrapper for the models to perform the calculation. You can then place that into the API for the view so the view gets the end result.\n", "You don't want the logic to be in the view. However you are free to create a database view. Except, rather than create it on the database side, create it as a new model. This will enable you to perform your calculations and your actual logic there, in one place. The pain of trying to keep your views in sync vs. the one time \"pain\" of creating the new model... I vote for a new model.\n" ]
[ 3, 1, 1, 0, 0 ]
[]
[]
[ "design_patterns", "model_view_controller", "ruby_on_rails" ]
stackoverflow_0000026834_design_patterns_model_view_controller_ruby_on_rails.txt
Q: Link from ASP.NET yellow error page directly to VS source code When an ASP.NET application errors out and generates the yellow-screen display, I'd like to create some kind of link from the error page which would jump directly to the correct line of code in Visual Studio. I'm not sure how to approach this, or if there are any tools already in existence which accomplish it - but I'd love some feedback on where to start. In the event that generating a new error page is necessary, is it possible to replace the standard yellow screen across an entire webserver, rather than having to configure the customized error output for each application? A: You would probably need to embed an ActiveX control in the page for something like that to be possible. A: The yellow screen of death is served by the default ASP.NET HTTPHandler. In order to intercept it, you would need to add another HTTPHandler in front of it that intercepts all uncaught exceptions. At that point, you could do whatever you want for your error layout. Creating a way to directly jump to Visual Studio would be tricky. I could see it done in IE via a COM/ActiveX object. A: The yellow screen of death is just a 500 error as far as the server is concerned, you can redirect to a custom screen using the error section of the web.config. To make a whole server change in the same manner you could probably override it at the iis level? Or perhaps even set the default behaviour in the machine.config file (not 100% sure about that one though) A: The yellow screen of death is just a 500 error as far as the server is concerned, you can redirect to a custom screen using the error section of the web.config. To make a whole server change in the same manner you could probably override it at the iis level? Or perhaps even set the default behaviour in the machine.config file (not 100% sure about that one though) If you let it bubble up all the way to IIS you will not have any way to access the Exception information. Its better to catch the Exception before the YSOD and serve your own. This can be done at the application level. A: Don't forget that you need the Program Debug Database (pdb) file to find the source code line number. An application in release mode won't have the same level of information as a debug release.
Link from ASP.NET yellow error page directly to VS source code
When an ASP.NET application errors out and generates the yellow-screen display, I'd like to create some kind of link from the error page which would jump directly to the correct line of code in Visual Studio. I'm not sure how to approach this, or if there are any tools already in existence which accomplish it - but I'd love some feedback on where to start. In the event that generating a new error page is necessary, is it possible to replace the standard yellow screen across an entire webserver, rather than having to configure the customized error output for each application?
[ "You would probably need to embed an ActiveX control in the page for something like that to be possible.\n", "The yellow screen of death is served by the default ASP.NET HTTPHandler.\nIn order to intercept it, you would need to add another HTTPHandler in front of it that intercepts all uncaught exceptions.\nAt that point, you could do whatever you want for your error layout.\nCreating a way to directly jump to Visual Studio would be tricky. I could see it done in IE via a COM/ActiveX object.\n", "The yellow screen of death is just a 500 error as far as the server is concerned, you can redirect to a custom screen using the error section of the web.config. To make a whole server change in the same manner you could probably override it at the iis level? Or perhaps even set the default behaviour in the machine.config file (not 100% sure about that one though)\n", "\nThe yellow screen of death is just a 500 error as far as the server is concerned, you can redirect to a custom screen using the error section of the web.config. To make a whole server change in the same manner you could probably override it at the iis level? Or perhaps even set the default behaviour in the machine.config file (not 100% sure about that one though)\n\nIf you let it bubble up all the way to IIS you will not have any way to access the Exception information. Its better to catch the Exception before the YSOD and serve your own.\nThis can be done at the application level.\n", "Don't forget that you need the Program Debug Database (pdb) file to find the source code line number. An application in release mode won't have the same level of information as a debug release.\n" ]
[ 1, 0, 0, 0, 0 ]
[ "The easiest, laziest thing I could think of would be to have the process happen thusly:\n\nThe yellow screen is modified so the line is source code is clickable. When clicked it delivers a small text file with the source file name and line number.\nA small program on the PC is tied to the extension of the small file the yellow screen let you download. The program uses visual studio's extensibility model to open the source file and goto that line. The program may need to know where your source code is.\n\nA simple Google search\ngives helpful pointers on how to manipulate VS with an external program such as this post on MSDN.\nIf you want to go snazzier, then there are certainly other methods, but I'd rather write out a quick and dirty program, and get it out of my way so I can be about my business.\nDon't let the tools become projects...\n-Adam\n" ]
[ -1 ]
[ "asp.net", "yellow_screen_of_death" ]
stackoverflow_0000020575_asp.net_yellow_screen_of_death.txt
Q: Keeping key value pairs together in HTML with jQuery? Given a select with multiple option's in jQuery. $select = $("<select></select>"); $select.append("<option>Jason</option>") //Key = 1 .append("<option>John</option>") //Key = 32 .append("<option>Paul</option>") //Key = 423 How should the key be stored and retrieved? The ID may be an OK place but would not be guaranteed unique if I had multiple select's sharing values (and other scenarios). Thanks and in the spirit of TMTOWTDI. $option = $("<option></option>"); $select = $("<select></select>"); $select.addOption = function(value,text){ $(this).append($("<option/>").val(value).text(text)); }; $select.append($option.val(1).text("Jason").clone()) .append("<option value=32>John</option>") .append($("<option/>").val(423).text("Paul")) .addOption("321","Lenny"); A: Like lucas said the value attribute is what you need. Using your code it would look something like this ( I added an id attribute to the select to make it fit ): $select = $('<select id="mySelect"></select>'); $select.append('<option value="1">Jason</option>') //Key = 1 .append('<option value="32">John</option>') //Key = 32 .append('<option value="423">Paul</option>') //Key = 423 jQuery lets you get the value using the val() method. Using it on the select tag you get the current selected option's value. $( '#mySelect' ).val(); //Gets the value for the current selected option $( '#mySelect > option' ).each( function( index, option ) { option.val(); //The value for each individual option } ); Just in case, the .each method loops throught every element the query matched. A: The HTML <option> tag has an attribute called "value", where you can store your key. e.g.: <option value=1>Jason</option> I don't know how this will play with jQuery (I don't use it), but I hope this is helpful nonetheless. A: If you are using HTML5, you can use a custom data attribute. It would look like this: $select = $("<select></select>"); $select.append("<option data-key=\"1\">Jason</option>") //Key = 1 .append("<option data-key=\"32\">John</option>") //Key = 32 .append("<option data-key=\"423\">Paul</option>") //Key = 423 Then to get the selected key you could do: var key = $('select option:selected').attr('data-key'); Or if you are using XHTML, then you can create a custom namespace. Since you say the keys can repeat, using the value attribute is probably not an option since then you wouldn't be able to tell which of the different options with the same value was selected on the form post.
Keeping key value pairs together in HTML with jQuery?
Given a select with multiple option's in jQuery. $select = $("<select></select>"); $select.append("<option>Jason</option>") //Key = 1 .append("<option>John</option>") //Key = 32 .append("<option>Paul</option>") //Key = 423 How should the key be stored and retrieved? The ID may be an OK place but would not be guaranteed unique if I had multiple select's sharing values (and other scenarios). Thanks and in the spirit of TMTOWTDI. $option = $("<option></option>"); $select = $("<select></select>"); $select.addOption = function(value,text){ $(this).append($("<option/>").val(value).text(text)); }; $select.append($option.val(1).text("Jason").clone()) .append("<option value=32>John</option>") .append($("<option/>").val(423).text("Paul")) .addOption("321","Lenny");
[ "Like lucas said the value attribute is what you need. Using your code it would look something like this ( I added an id attribute to the select to make it fit ):\n$select = $('<select id=\"mySelect\"></select>');\n$select.append('<option value=\"1\">Jason</option>') //Key = 1\n .append('<option value=\"32\">John</option>') //Key = 32\n .append('<option value=\"423\">Paul</option>') //Key = 423\n\njQuery lets you get the value using the val() method. Using it on the select tag you get the current selected option's value.\n$( '#mySelect' ).val(); //Gets the value for the current selected option\n\n$( '#mySelect > option' ).each( function( index, option ) {\n option.val(); //The value for each individual option\n} );\n\nJust in case, the .each method loops throught every element the query matched.\n", "The HTML <option> tag has an attribute called \"value\", where you can store your key.\ne.g.:\n<option value=1>Jason</option>\n\nI don't know how this will play with jQuery (I don't use it), but I hope this is helpful nonetheless.\n", "If you are using HTML5, you can use a custom data attribute. It would look like this:\n$select = $(\"<select></select>\");\n$select.append(\"<option data-key=\\\"1\\\">Jason</option>\") //Key = 1\n .append(\"<option data-key=\\\"32\\\">John</option>\") //Key = 32\n .append(\"<option data-key=\\\"423\\\">Paul</option>\") //Key = 423\n\nThen to get the selected key you could do:\nvar key = $('select option:selected').attr('data-key');\n\nOr if you are using XHTML, then you can create a custom namespace.\nSince you say the keys can repeat, using the value attribute is probably not an option since then you wouldn't be able to tell which of the different options with the same value was selected on the form post.\n" ]
[ 17, 6, 3 ]
[]
[]
[ "html", "javascript", "jquery" ]
stackoverflow_0000027219_html_javascript_jquery.txt
Q: Javascript: declaring a variable before the conditional result? My JavaScript is pretty nominal, so when I saw this construction, I was kind of baffled: var shareProxiesPref = document.getElementById("network.proxy.share_proxy_settings"); shareProxiesPref.disabled = proxyTypePref.value != 1; Isn't it better to do an if on proxyTypePref.value, and then declare the var inside the result, only if you need it? (Incidentally, I also found this form very hard to read in comparison to the normal usage. There were a set of two or three of these conditionals, instead of doing a single if with a block of statements in the result.) UPDATE: The responses were very helpful and asked for more context. The code fragment is from Firefox 3, so you can see the code here: http://mxr.mozilla.org/firefox/source/browser/components/preferences/connection.js Basically, when you look at the Connect preferences window in Firefox, clicking the proxy modes (radio buttons), causes various form elements to enable|disable. A: (Incidentally, I also found this form very hard to read in comparison to the normal usage. Not necessarily, although that was my first thought, too. A code should always emphasize its function, especially if it has side effects. If the writer's intention was to emphasize the assignment to sharedProxiesPref.disabled then hey, roll with it. On the other hand, it could have been clearer that the action taking place here is to disable the object, in which case the conditional block would have been better. A: It depends on the context of this code. If it's running on page load, then it would be better to put this code in an if block. But, if this is part of a validation function, and the field switches between enabled and disabled throughout the life of the page, then this code sort of makes sense. It's important to remember that setting disabled to false also alters page state. A: It's hard to say what's better to do without more context. If this code being executed every time that proxyTypePref changes, then you're always going to need set shareProxiesPref.disabled. I would agree than an if statement would be a bit more readable than the current code. Isn't it better to do an if on proxyTypePref.value, and then declare the var inside the result, only if you need it? If you're talking strictly about variable declaration, then it doesn't matter whether or not you put it inside an if statement. Any Javascript variable declared inside a function is in scope for the entire function, regardless of where it is declared. If you're talking about the execution of document.getElementById, then yes, it is much better to not make that call if you don't have to.
Javascript: declaring a variable before the conditional result?
My JavaScript is pretty nominal, so when I saw this construction, I was kind of baffled: var shareProxiesPref = document.getElementById("network.proxy.share_proxy_settings"); shareProxiesPref.disabled = proxyTypePref.value != 1; Isn't it better to do an if on proxyTypePref.value, and then declare the var inside the result, only if you need it? (Incidentally, I also found this form very hard to read in comparison to the normal usage. There were a set of two or three of these conditionals, instead of doing a single if with a block of statements in the result.) UPDATE: The responses were very helpful and asked for more context. The code fragment is from Firefox 3, so you can see the code here: http://mxr.mozilla.org/firefox/source/browser/components/preferences/connection.js Basically, when you look at the Connect preferences window in Firefox, clicking the proxy modes (radio buttons), causes various form elements to enable|disable.
[ "\n(Incidentally, I also found this form very hard to read in comparison to the normal usage.\n\nNot necessarily, although that was my first thought, too. A code should always emphasize its function, especially if it has side effects. If the writer's intention was to emphasize the assignment to sharedProxiesPref.disabled then hey, roll with it. On the other hand, it could have been clearer that the action taking place here is to disable the object, in which case the conditional block would have been better.\n", "It depends on the context of this code. If it's running on page load, then it would be better to put this code in an if block.\nBut, if this is part of a validation function, and the field switches between enabled and disabled throughout the life of the page, then this code sort of makes sense.\nIt's important to remember that setting disabled to false also alters page state.\n", "It's hard to say what's better to do without more context.\nIf this code being executed every time that proxyTypePref changes, then you're always going to need set shareProxiesPref.disabled.\nI would agree than an if statement would be a bit more readable than the current code.\n\nIsn't it better to do an if on proxyTypePref.value, and then declare the var inside the result, only if you need it?\n\nIf you're talking strictly about variable declaration, then it doesn't matter whether or not you put it inside an if statement. Any Javascript variable declared inside a function is in scope for the entire function, regardless of where it is declared.\nIf you're talking about the execution of document.getElementById, then yes, it is much better to not make that call if you don't have to.\n" ]
[ 2, 2, 1 ]
[]
[]
[ "javascript" ]
stackoverflow_0000027034_javascript.txt
Q: Upgrading Sharepoint 3.0 to SQL 2005 Backend? We're trying to get rid of all of our SQL Server 2000 databases to re purpose our old DB server... Sharepoint 3.0 is being a showstopper. I've looked at a lot of guides from Microsoft and tried the instructions in those. I've also just tried the good ol' exec sp_detach_db / sp_attach_db with no luck. Has anyone actually done this? A: my boss has. it was a real pain. permissions issues. he used the built in sharepoint backup tool. I can more details tomorrow if need. I'll check back. I'm back. Here's the steps he used. install an instance of sql server 2005 on the sql 2000 box (side-by-side) back up the sharepoint site using the sharepoint admin tools. This will create a one mother of a large xml file w/ the whole kit and kaboodle (the site & all it's content) delete the old-n-busted sharepoint site create a new hotness sharepoint site using the sql server 2005 as the database. do a restore from the xml backup using the admin tools - this will take hours to run (thank you xml ...) Bingo! P.S. I forgot, the account you use to do the restore must be an 'sa' account.
Upgrading Sharepoint 3.0 to SQL 2005 Backend?
We're trying to get rid of all of our SQL Server 2000 databases to re purpose our old DB server... Sharepoint 3.0 is being a showstopper. I've looked at a lot of guides from Microsoft and tried the instructions in those. I've also just tried the good ol' exec sp_detach_db / sp_attach_db with no luck. Has anyone actually done this?
[ "my boss has. it was a real pain. permissions issues. he used the built in sharepoint backup tool. I can more details tomorrow if need. I'll check back. \nI'm back. Here's the steps he used.\n\ninstall an instance of sql server\n2005 on the sql 2000 box\n(side-by-side)\nback up the sharepoint site using the sharepoint admin tools. This will create a one mother of a large xml file w/ the whole kit and kaboodle (the site & all it's content)\ndelete the old-n-busted sharepoint site\ncreate a new hotness sharepoint site using the sql server 2005 as the database.\ndo a restore from the xml backup using the admin tools - this will take hours to run (thank you xml ...) \nBingo!\nP.S. I forgot, the account you use to do the restore must be an 'sa' account. \n\n" ]
[ 1 ]
[]
[]
[ "sharepoint", "sql_server_2000", "sql_server_2005" ]
stackoverflow_0000026028_sharepoint_sql_server_2000_sql_server_2005.txt
Q: IE6 security login (debugging via VirtualPC) I am debugging my ASP.NET application on my Windows XP box with a virtual directory set up in IIS (5.1). I am also running VirtualPC with XP and IE6 for testing purposes. When I connect to my real machine from the virtual machine, I enter the URL: http://machinename/projectname. I get a security popup to connect to my machine (which I expect), but the User name field is disabled. I cannot change it from machinename\Guest to machinename\username in order to connect. How do I get this to enable so I can enter the correct credentials. A: It sounds like you need to allow anonymous users. Can you connect from other machines on your network? Try changing your virtual directory's authentication settings, so that anonymous users are allowed (MyVirtualDir > Properties > Authentication). A: uncheck allow anonymous on the virtual dir and check integrated authentication. also make sure you are not logging into the virtual xp box as guest or a user w/o a password.
IE6 security login (debugging via VirtualPC)
I am debugging my ASP.NET application on my Windows XP box with a virtual directory set up in IIS (5.1). I am also running VirtualPC with XP and IE6 for testing purposes. When I connect to my real machine from the virtual machine, I enter the URL: http://machinename/projectname. I get a security popup to connect to my machine (which I expect), but the User name field is disabled. I cannot change it from machinename\Guest to machinename\username in order to connect. How do I get this to enable so I can enter the correct credentials.
[ "It sounds like you need to allow anonymous users. Can you connect from other machines on your network?\nTry changing your virtual directory's authentication settings, so that anonymous users are allowed (MyVirtualDir > Properties > Authentication).\n", "uncheck allow anonymous on the virtual dir and check integrated authentication. also make sure you are not logging into the virtual xp box as guest or a user w/o a password. \n" ]
[ 2, 2 ]
[]
[]
[ "asp.net", "iis", "internet_explorer" ]
stackoverflow_0000027078_asp.net_iis_internet_explorer.txt
Q: Bandwith throttling in IIS 6 by IP Address I am writing an application that downloads large files in the background. All clients are logged in locally, or through a VPN. When they are logged in locally, I do not want to throttle downloads. However, I would like to limit downloads to 10 KBps when the user is connected via VPN. I can differentiate between these users by IP Address range. Since this is an AIR Application, I figure I will throttle via server-side since I can do it from either the server itself (IIS 6) or the web service (asp.net / C#). Throttling through IIS 6 seems to work fine, but it seems like it has to be done across the entire web site. Is there anyway to do this via IP? Or will I have to rig this up in .NET? A: My first thought is this. I don't know if it would work but it would only take a few minutes to try. Create two IIS web sites on the same server. The first site is bound to the public IP, but the second site is bound to the private IP. Both point to the same folder on the file system. Your VPN users will be accessing via the private IP, so you can setup a "site-wide" rule on that site that will only affect VPN users. This should work for almost any IIS6 setting, including bandwidth throttling. Worth a try, at least. -- Edit: Tried this and it worked flawlessly.
Bandwith throttling in IIS 6 by IP Address
I am writing an application that downloads large files in the background. All clients are logged in locally, or through a VPN. When they are logged in locally, I do not want to throttle downloads. However, I would like to limit downloads to 10 KBps when the user is connected via VPN. I can differentiate between these users by IP Address range. Since this is an AIR Application, I figure I will throttle via server-side since I can do it from either the server itself (IIS 6) or the web service (asp.net / C#). Throttling through IIS 6 seems to work fine, but it seems like it has to be done across the entire web site. Is there anyway to do this via IP? Or will I have to rig this up in .NET?
[ "My first thought is this. I don't know if it would work but it would only take a few minutes to try.\nCreate two IIS web sites on the same server. The first site is bound to the public IP, but the second site is bound to the private IP. Both point to the same folder on the file system.\nYour VPN users will be accessing via the private IP, so you can setup a \"site-wide\" rule on that site that will only affect VPN users. This should work for almost any IIS6 setting, including bandwidth throttling.\nWorth a try, at least.\n-- \nEdit: Tried this and it worked flawlessly.\n" ]
[ 11 ]
[]
[]
[ "asp.net", "iis" ]
stackoverflow_0000001409_asp.net_iis.txt
Q: Word Automation: Write RTF text without going through clipboard I am trying to replace the current selection in Word (2003/2007) by some RTF string stored in a variable. Here is the current code: Clipboard.SetText(strRTFString, TextDataFormat.Rtf) oWord.ActiveDocument.ActiveWindow.Selection.PasteAndFormat(0) Is there any way to do the same thing without going through the clipboard. Or is there any way to push the clipboard data to a safe place and restore it after? A: Put the RTF in a file instead of the clipboard, then insert from the file, e.g. Selection.InsertFile FileName:="myfile.rtf", Range :="", _ ConfirmConversions:=False, Link:=False, Attachment:=False
Word Automation: Write RTF text without going through clipboard
I am trying to replace the current selection in Word (2003/2007) by some RTF string stored in a variable. Here is the current code: Clipboard.SetText(strRTFString, TextDataFormat.Rtf) oWord.ActiveDocument.ActiveWindow.Selection.PasteAndFormat(0) Is there any way to do the same thing without going through the clipboard. Or is there any way to push the clipboard data to a safe place and restore it after?
[ "Put the RTF in a file instead of the clipboard, then insert from the file, e.g.\n\nSelection.InsertFile FileName:=\"myfile.rtf\", Range :=\"\", _\n ConfirmConversions:=False, Link:=False, Attachment:=False\n\n" ]
[ 14 ]
[ "You can use a RichTextbox to convert RTF to text or vice versa.\nRichTextBox r = new RichTextBox();\nr.Rtf = strRTFString;\nConsole.WriteLine(r.Text);\n\n" ]
[ -3 ]
[ "automation", "ms_word", "vba" ]
stackoverflow_0000022326_automation_ms_word_vba.txt
Q: How to send out email at a user's local time in .NET / Sql Server? I am writing a program that needs to send out an email every hour on the hour, but at a time local to the user. Say I have 2 users in different time zones. John is in New York and Fred is in Los Angeles. The server is in Chicago. If I want to send an email at 6 PM local to each user, I'd have to send the email to John at 7 PM Server time and Fred at 4 PM Server time. What's a good approach to this in .NET / Sql Server? I have found an xml file with all of the time zone information, so I am considering writing a script to import it into the database, then querying off of it. Edit: I used “t4znet.dll” and did all comparisons on the .NET side. A: I'm a PHP developer so I'll share what I know from PHP. I'm sure .NET will include something similar. In PHP you can get timezone differences for the server time - as you've suggested you'd send the emails at different times on the server. Every time you add a user save their time offset from the server time (or their timezone in case the server timezone changes). Then when you specify an update, have an automated task (Cron for LAMP people) that runs each hour checking to see if an email needs to be sent. Do this until there are no emails left to send. A: You have two options: Store the adjusted time for the mail action into the database for each user. Then just compare server time with stored time. To avoid confusion and portability issues, I would store all times in UTC. So, send mail when SERVER_UTC_TIME() == storedUtcTime. Store the local time for each mail action into the database, then convert on-the-fly. Send mail when SERVER_UTC_TIME() == TO_UTC_TIME(storedLocalTime, userTimeZone). You should decide what makes most sense for your application. For example if the mailing time is always the same for all users, it makes more sense to go with option (2). If the events times can change between users and even per user, it may make development and debugging easier if you choose option (1). Either way you will need to know the user's time zone. *These function calls are obviously pseudo, since I don't know their invocations in T-SQL, but they should exist. A: You can complement your solution with this excellent article "World Clock and the TimeZoneInformation class", I made a webservice that sent a file with information that included the local and receiver time, what I did was to modify this class so I could handle that issue and it worked perfect, exactly as I needed. I think you could take this class and obtain from the table "Users" the time zone of them and "calculate" the appropiate time, my code went like this; //Get correct destination time DateTime thedate = DateTime.Now; string destinationtimezone = null; //Load the time zone where the file is going TimeZoneInformation tzi = TimeZoneInformation.FromName(this.m_destinationtimezone); //Calculate destinationtimezone = tzi.FromUniversalTime(thedate.ToUniversalTime()).ToString(); This class has an issue in Windows Vista that crashes the "FromIndex(int index)" function but you can modify the code, instead of using the function: public static TimeZoneInformation FromIndex(int index) { TimeZoneInformation[] zones = EnumZones(); for (int i = 0; i < zones.Length; ++i) { if (zones[i].Index == index) return zones[i]; } throw new ArgumentOutOfRangeException("index", index, "Unknown time zone index"); } You can change it to; public static TimeZoneInformation FromName(string name) { TimeZoneInformation[] zones = EnumZones(); foreach (TimeZoneInformation tzi in zones) { if (tzi.DisplayName.Equals(name)) return tzi; } throw new ArgumentOutOfRangeException("name", name, "Unknown time zone name"); }
How to send out email at a user's local time in .NET / Sql Server?
I am writing a program that needs to send out an email every hour on the hour, but at a time local to the user. Say I have 2 users in different time zones. John is in New York and Fred is in Los Angeles. The server is in Chicago. If I want to send an email at 6 PM local to each user, I'd have to send the email to John at 7 PM Server time and Fred at 4 PM Server time. What's a good approach to this in .NET / Sql Server? I have found an xml file with all of the time zone information, so I am considering writing a script to import it into the database, then querying off of it. Edit: I used “t4znet.dll” and did all comparisons on the .NET side.
[ "I'm a PHP developer so I'll share what I know from PHP. I'm sure .NET will include something similar.\nIn PHP you can get timezone differences for the server time - as you've suggested you'd send the emails at different times on the server.\nEvery time you add a user save their time offset from the server time (or their timezone in case the server timezone changes).\nThen when you specify an update, have an automated task (Cron for LAMP people) that runs each hour checking to see if an email needs to be sent. Do this until there are no emails left to send.\n", "You have two options:\n\nStore the adjusted time for the mail action into the database for each user. Then just compare server time with stored time. To avoid confusion and portability issues, I would store all times in UTC. So, send mail when SERVER_UTC_TIME() == storedUtcTime.\nStore the local time for each mail action into the database, then convert on-the-fly. Send mail when SERVER_UTC_TIME() == TO_UTC_TIME(storedLocalTime, userTimeZone).\n\nYou should decide what makes most sense for your application. For example if the mailing time is always the same for all users, it makes more sense to go with option (2). If the events times can change between users and even per user, it may make development and debugging easier if you choose option (1). Either way you will need to know the user's time zone.\n*These function calls are obviously pseudo, since I don't know their invocations in T-SQL, but they should exist.\n", "You can complement your solution with this excellent article \"World Clock and the TimeZoneInformation class\", I made a webservice that sent a file with information that included the local and receiver time, what I did was to modify this class so I could handle that issue and it worked perfect, exactly as I needed.\nI think you could take this class and obtain from the table \"Users\" the time zone of them and \"calculate\" the appropiate time, my code went like this;\n//Get correct destination time\nDateTime thedate = DateTime.Now;\n\nstring destinationtimezone = null;\n\n//Load the time zone where the file is going\nTimeZoneInformation tzi = TimeZoneInformation.FromName(this.m_destinationtimezone);\n\n//Calculate\ndestinationtimezone = tzi.FromUniversalTime(thedate.ToUniversalTime()).ToString();\n\nThis class has an issue in Windows Vista that crashes the \"FromIndex(int index)\" function but you can modify the code, instead of using the function:\n public static TimeZoneInformation FromIndex(int index)\n {\n TimeZoneInformation[] zones = EnumZones();\n\n for (int i = 0; i < zones.Length; ++i)\n {\n if (zones[i].Index == index)\n return zones[i];\n }\n\n throw new ArgumentOutOfRangeException(\"index\", index, \"Unknown time zone index\");\n }\n\nYou can change it to;\n public static TimeZoneInformation FromName(string name)\n {\n TimeZoneInformation[] zones = EnumZones();\n\n foreach (TimeZoneInformation tzi in zones)\n {\n if (tzi.DisplayName.Equals(name))\n return tzi;\n }\n\n throw new ArgumentOutOfRangeException(\"name\", name, \"Unknown time zone name\");\n }\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ ".net", "sql", "sql_server", "timezone" ]
stackoverflow_0000022319_.net_sql_sql_server_timezone.txt
Q: What's the simplest way to connect to a .NET remote server object Given that my client code knows everything it needs to about the remoting object, what's the simplest way to connect to it? This is what I'm doing at the moment: ChannelServices.RegisterChannel(new HttpChannel(), false); RemotingConfiguration.RegisterWellKnownServiceType( typeof(IRemoteServer), "RemoteServer.rem", WellKnownObjectMode.Singleton); MyServerObject = (IRemoteServer)Activator.GetObject( typeof(IRemoteServer), String.Format("tcp://{0}:{1}/RemoteServer.rem", server, port)); A: The first two lines are in the server-side code, for marshaling out the server object, yes? In that case, yes, the third line is the simplest you can get at client-side. In addition, you can serve out additional server-side objects from the MyServerObject instance, if you include public accessors for them in IRemoteServer interface, so, accessing those objects become the simple matter of method calls or property accesses on your main server object, so you don't have to use activator for every single thing: //obtain another marshalbyref object of the type ISessionManager: ISessionManager = MyServerObject.GetSessionManager(); A: WCF. I have used IPC before there was a WCF, and believe me, IPC is a bear. And it isn't documented fully/correctly. What’s the simplest way to connect to a .NET remote server object? WCF.
What's the simplest way to connect to a .NET remote server object
Given that my client code knows everything it needs to about the remoting object, what's the simplest way to connect to it? This is what I'm doing at the moment: ChannelServices.RegisterChannel(new HttpChannel(), false); RemotingConfiguration.RegisterWellKnownServiceType( typeof(IRemoteServer), "RemoteServer.rem", WellKnownObjectMode.Singleton); MyServerObject = (IRemoteServer)Activator.GetObject( typeof(IRemoteServer), String.Format("tcp://{0}:{1}/RemoteServer.rem", server, port));
[ "The first two lines are in the server-side code, for marshaling out the server object, yes?\nIn that case, yes, the third line is the simplest you can get at client-side.\nIn addition, you can serve out additional server-side objects from the MyServerObject instance, if you include public accessors for them in IRemoteServer interface, so, accessing those objects become the simple matter of method calls or property accesses on your main server object, so you don't have to use activator for every single thing:\n//obtain another marshalbyref object of the type ISessionManager:\nISessionManager = MyServerObject.GetSessionManager();\n\n", "WCF. \nI have used IPC before there was a WCF, and believe me, IPC is a bear. And it isn't documented fully/correctly.\nWhat’s the simplest way to connect to a .NET remote server object? WCF.\n" ]
[ 1, 0 ]
[]
[]
[ ".net", "c#", "remote_server", "remoting" ]
stackoverflow_0000025982_.net_c#_remote_server_remoting.txt
Q: Does Mono support System.Drawing and System.Drawing.Printing? I'm attempting to use Mono to load a bitmap and print it on Linux but I'm getting an exception. Does Mono support printing on Linux? The code/exception are below: EDIT: No longer getting the exception, but I'm still curious what kind of support there is. Leaving the code for posterity or something. private void btnPrintTest_Click(object sender, EventArgs e) { _printDocTest.DefaultPageSettings.Landscape = true; _printDocTest.DefaultPageSettings.Margins = new Margins(50,50,50,50); _printDocTest.Print(); } void _printDocTest_PrintPage(object sender, PrintPageEventArgs e) { var bmp = new Bitmap("test.bmp"); // Determine center of graph var xCenter = e.MarginBounds.X + (e.MarginBounds.Width - bmp.Width) / 2; var yCenter = e.MarginBounds.Y + (e.MarginBounds.Height - bmp.Height) / 2; e.Graphics.DrawImage(bmp, xCenter, yCenter); e.HasMorePages = false; } A: From the Mono docs, I think yes: Managed.Windows.Forms (aka System.Windows.Forms): A complete and cross platform, System.Drawing based Winforms implementation. It also useful if you run the Mono Migration Analyzer first. A: According to System.Drawing is now complete, and in addition to being the underlying rendering engine for Windows.Forms, it has also been tested for using third party controls that heavily depend on it.
Does Mono support System.Drawing and System.Drawing.Printing?
I'm attempting to use Mono to load a bitmap and print it on Linux but I'm getting an exception. Does Mono support printing on Linux? The code/exception are below: EDIT: No longer getting the exception, but I'm still curious what kind of support there is. Leaving the code for posterity or something. private void btnPrintTest_Click(object sender, EventArgs e) { _printDocTest.DefaultPageSettings.Landscape = true; _printDocTest.DefaultPageSettings.Margins = new Margins(50,50,50,50); _printDocTest.Print(); } void _printDocTest_PrintPage(object sender, PrintPageEventArgs e) { var bmp = new Bitmap("test.bmp"); // Determine center of graph var xCenter = e.MarginBounds.X + (e.MarginBounds.Width - bmp.Width) / 2; var yCenter = e.MarginBounds.Y + (e.MarginBounds.Height - bmp.Height) / 2; e.Graphics.DrawImage(bmp, xCenter, yCenter); e.HasMorePages = false; }
[ "From the Mono docs, I think yes:\n\nManaged.Windows.Forms (aka\n System.Windows.Forms): A complete and\n cross platform, System.Drawing based\n Winforms implementation.\n\nIt also useful if you run the Mono Migration Analyzer first.\n", "According to\nSystem.Drawing is now complete, and in addition to being the underlying rendering engine for Windows.Forms, it has also been tested for using third party controls that heavily depend on it.\n" ]
[ 7, 5 ]
[]
[]
[ ".net", "c#", "linux", "mono", "printing" ]
stackoverflow_0000027455_.net_c#_linux_mono_printing.txt
Q: Avoid traffic shaping by using ssh on port 443 I heard that if you use port 443 (the port usually used for https) for ssh, the encrypted packets look the same to your isp. Could this be a way to avoid traffic shaping/throttling? A: I'm not sure it's true that any given ssh packet "looks" the same as any given https packet. However, over their lifetime they don't behave the same way. The session set up and tear down don't look alike (SSH offer a plain text banner during initial connect, for one thing). Also, typically wouldn't an https session be short lived? Connect, get your data, disconnect, whereas ssh would connect and persist for long periods of time? I think perhaps using 443 instead of 22 might get past naive filters, but I don't think it would fool someone specifically looking for active attempts to bypass their filters. Is throttling ssh a common occurrence? I've experienced people blocking it, but I don't think I've experienced throttling. Heck, I usually use ssh tunnels to bypass other blocks since people don't usually care about it. A: 443, when used for HTTPS, relies on SSL (not SSH) for its encryption. SSH looks different than SSL, so it would depend on what your ISP was actually looking for, but it is entirely possible that they could detect the difference. In my experience, though, you'd be more likely to see some personal firewall software block that sort of behavior since it's nonstandard. Fortunately, it's pretty easy to write an SSL tunnel using a SecureSocket of some type. In general, they can see how much bandwidth you are using, whether or not the traffic is encrypted. They'll still know the endpoints of the connection, how long it's been open, and how many packets have been sent, so if they base their shaping metrics on this sort of data, there's really nothing you can do to prevent them from throttling your connection. A: Your ISP is probably more likely to traffic shape port 443 over 22, seeing as 22 requires more real-time responsiveness. Not really a programming question though, maybe you'll get a more accurate response somewhere else..
Avoid traffic shaping by using ssh on port 443
I heard that if you use port 443 (the port usually used for https) for ssh, the encrypted packets look the same to your isp. Could this be a way to avoid traffic shaping/throttling?
[ "I'm not sure it's true that any given ssh packet \"looks\" the same as any given https packet.\nHowever, over their lifetime they don't behave the same way. The session set up and tear down don't look alike (SSH offer a plain text banner during initial connect, for one thing). Also, typically wouldn't an https session be short lived? Connect, get your data, disconnect, whereas ssh would connect and persist for long periods of time? I think perhaps using 443 instead of 22 might get past naive filters, but I don't think it would fool someone specifically looking for active attempts to bypass their filters.\nIs throttling ssh a common occurrence? I've experienced people blocking it, but I don't think I've experienced throttling. Heck, I usually use ssh tunnels to bypass other blocks since people don't usually care about it.\n", "443, when used for HTTPS, relies on SSL (not SSH) for its encryption. SSH looks different than SSL, so it would depend on what your ISP was actually looking for, but it is entirely possible that they could detect the difference. In my experience, though, you'd be more likely to see some personal firewall software block that sort of behavior since it's nonstandard. Fortunately, it's pretty easy to write an SSL tunnel using a SecureSocket of some type.\nIn general, they can see how much bandwidth you are using, whether or not the traffic is encrypted. They'll still know the endpoints of the connection, how long it's been open, and how many packets have been sent, so if they base their shaping metrics on this sort of data, there's really nothing you can do to prevent them from throttling your connection.\n", "Your ISP is probably more likely to traffic shape port 443 over 22, seeing as 22 requires more real-time responsiveness.\nNot really a programming question though, maybe you'll get a more accurate response somewhere else..\n" ]
[ 5, 4, 2 ]
[]
[]
[ "https", "linux", "ssh", "trafficshaping" ]
stackoverflow_0000027266_https_linux_ssh_trafficshaping.txt
Q: Timeout not being honoured in connection string I have a long running SQL statement that I want to run, and no matter what I put in the "timeout=" clause of my connection string, it always seems to end after 30 seconds. I'm just using SqlHelper.ExecuteNonQuery() to execute it, and letting it take care of opening connections, etc. Is there something else that could be overriding my timeout, or causing sql server to ignore it? I have run profiler over the query, and the trace doesn't look any different when I run it in management studio, versus in my code. Management studio completes the query in roughly a minute, but even with a timeout set to 300, or 30000, my code still times out after 30 seconds. A: What are you using to set the timeout in your connection string? From memory that's "ConnectionTimeout" and only affects the time it takes to actually connect to the server. Each individual command has a separate "CommandTimeout" which would be what you're looking for. Not sure how SqlHelper implements that though. A: In addition to timeout in connection string, try using the timeout property of the SQL command. Below is a C# sample, using the SqlCommand class. Its equivalent should be applicable to what you are using. SqlCommand command = new SqlCommand(sqlQuery, _Database.Connection); command.CommandTimeout = 0; int rows = command.ExecuteNonQuery();
Timeout not being honoured in connection string
I have a long running SQL statement that I want to run, and no matter what I put in the "timeout=" clause of my connection string, it always seems to end after 30 seconds. I'm just using SqlHelper.ExecuteNonQuery() to execute it, and letting it take care of opening connections, etc. Is there something else that could be overriding my timeout, or causing sql server to ignore it? I have run profiler over the query, and the trace doesn't look any different when I run it in management studio, versus in my code. Management studio completes the query in roughly a minute, but even with a timeout set to 300, or 30000, my code still times out after 30 seconds.
[ "What are you using to set the timeout in your connection string? From memory that's \"ConnectionTimeout\" and only affects the time it takes to actually connect to the server.\nEach individual command has a separate \"CommandTimeout\" which would be what you're looking for. Not sure how SqlHelper implements that though.\n", "In addition to timeout in connection string, try using the timeout property of the SQL command. Below is a C# sample, using the SqlCommand class. Its equivalent should be applicable to what you are using.\nSqlCommand command = new SqlCommand(sqlQuery, _Database.Connection);\ncommand.CommandTimeout = 0;\nint rows = command.ExecuteNonQuery();\n\n" ]
[ 44, 15 ]
[]
[]
[ "database", "sql_server", "timeout" ]
stackoverflow_0000027472_database_sql_server_timeout.txt
Q: Databind RenderTransform Scaling in Silverlight 2 Beta 2 Anyone know if it's possible to databind the ScaleX and ScaleY of a render transform in Silverlight 2 Beta 2? Binding transforms is possible in WPF - But I'm getting an error when setting up my binding in Silverlight through XAML. Perhaps it's possible to do it through code? <Image Height="60" HorizontalAlignment="Right" Margin="0,122,11,0" VerticalAlignment="Top" Width="60" Source="Images/Fish128x128.png" Stretch="Fill" RenderTransformOrigin="0.5,0.5" x:Name="fishImage"> <Image.RenderTransform> <TransformGroup> <ScaleTransform ScaleX="1" ScaleY="1"/> <SkewTransform/> <RotateTransform/> <TranslateTransform/> </TransformGroup> </Image.RenderTransform> </Image> I want to bind the ScaleX and ScaleY of the ScaleTransform element. I'm getting a runtime error when I try to bind against a double property on my data context: Message="AG_E_PARSER_BAD_PROPERTY_VALUE [Line: 1570 Position: 108]" My binding looks like this: <ScaleTransform ScaleX="{Binding Path=SelectedDive.Visibility}" ScaleY="{Binding Path=SelectedDive.Visibility}"/> I have triple verified that the binding path is correct - I'm binding a slidebar against the same value and that works just fine... Visibility is of type double and is a number between 0.0 and 30.0. I have a value converter that scales that number down to 0.5 and 1 - I want to scale the size of the fish depending on the clarity of the water. So I don't think it's a problem with the type I'm binding against... A: Is it a runtime error or compile-time, Jonas? Looking at the documentation, ScaleX and ScaleY are dependency properties, so you should be able to write <ScaleTransform ScaleX="{Binding Foo}" ScaleY="{Binding Bar}" /> ... where Foo and Bar are of the appropriate type. Edit: Of course, that's the WPF documentation. I suppose it's possible that they've changed ScaleX and ScaleY to be standard properties rather than dependency properties in Silverlight. I'd love to hear more about the error you're seeing. A: ScaleTransform doesn't have a data context so most likely the binding is looking for SelectedDive.Visibility off it's self and not finding it. There is much in Silverlight xaml and databinding that is different from WPF... Anyway to solve this you will want to set up the binding in code**, or manually listen for the PropertyChanged event of your data object and set the Scale in code behind. I would choose the latter if you wanted to do an animation/storyboard for the scale change. ** i need to check but you may not be able to bind to it. as i recall if the RenderTransform is not part of an animation it gets turned into a matrix transform and all bets are off. A: Ah I think I see your problem. You're attempting to bind a property of type Visibility (SelectedDive.Visibility) to a property of type Double (ScaleTransform.ScaleX). WPF/Silverlight can't convert between those two types. What are you trying to accomplish? Maybe I can help you with the XAML. What is "SelectedDive" and what do you want to happen when its Visibility changes? A: Sorry - was looking for the answer count to go up so I didn't realise you'd edited the question with more information. OK, so Visibility is of type Double, so the binding should work in that regard. As a workaround, could you try binding your ScaleX and ScaleY values directly to the slider control that SelectedDive.Visibility is bound to? Something like: <ScaleTransform ScaleX="{Binding ElementName=slider1,Path=Value}" ... /> If that works then it'll at least get you going. Edit: Ah, I just remembered that I read once that Silverlight doesn't support the ElementName syntax in bindings, so that might not work. A: Yeah maybe the embedded render transforms aren't inheriting the DataContext from the object they apply to. Can you force the DataContext into them? For example, give the transform a name: <ScaleTransform x:Name="myScaler" ... /> ... and then in your code-behind: myScaler.DataContext = fishImage.DataContext; ... so that the scaler definitely shares its DataContext with the Image. A: Ok, is the Image itself picking up the DataContext properly? Try adding this: <Image Tooltip="{Binding SelectedDive.Visibility}" ... /> If that compiles and runs, hover over the image and see if it displays the right value. A: I was hoping to solve this through XAML, but turns out Brian's suggestion was the way to go. I used Matt's suggestion to give the scale transform a name, so that I can access it from code. Then I hooked the value changed event of the slider, and manually updates the ScaleX and ScaleY property. I kept my value converter to convert from the visibility range (0-30m) to scale (0.5 to 1). The code looks like this: private ScaleConverter converter; public DiveLog() { InitializeComponent(); converter = new ScaleConverter(); visibilitySlider.ValueChanged += new RoutedPropertyChangedEventHandler<double>(visibilitySlider_ValueChanged); } private void visibilitySlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { fishScale.ScaleX = (double)converter.Convert(e.NewValue, typeof(double), null, CultureInfo.CurrentCulture); fishScale.ScaleY = fishScale.ScaleX; }
Databind RenderTransform Scaling in Silverlight 2 Beta 2
Anyone know if it's possible to databind the ScaleX and ScaleY of a render transform in Silverlight 2 Beta 2? Binding transforms is possible in WPF - But I'm getting an error when setting up my binding in Silverlight through XAML. Perhaps it's possible to do it through code? <Image Height="60" HorizontalAlignment="Right" Margin="0,122,11,0" VerticalAlignment="Top" Width="60" Source="Images/Fish128x128.png" Stretch="Fill" RenderTransformOrigin="0.5,0.5" x:Name="fishImage"> <Image.RenderTransform> <TransformGroup> <ScaleTransform ScaleX="1" ScaleY="1"/> <SkewTransform/> <RotateTransform/> <TranslateTransform/> </TransformGroup> </Image.RenderTransform> </Image> I want to bind the ScaleX and ScaleY of the ScaleTransform element. I'm getting a runtime error when I try to bind against a double property on my data context: Message="AG_E_PARSER_BAD_PROPERTY_VALUE [Line: 1570 Position: 108]" My binding looks like this: <ScaleTransform ScaleX="{Binding Path=SelectedDive.Visibility}" ScaleY="{Binding Path=SelectedDive.Visibility}"/> I have triple verified that the binding path is correct - I'm binding a slidebar against the same value and that works just fine... Visibility is of type double and is a number between 0.0 and 30.0. I have a value converter that scales that number down to 0.5 and 1 - I want to scale the size of the fish depending on the clarity of the water. So I don't think it's a problem with the type I'm binding against...
[ "Is it a runtime error or compile-time, Jonas? Looking at the documentation, ScaleX and ScaleY are dependency properties, so you should be able to write\n<ScaleTransform ScaleX=\"{Binding Foo}\" ScaleY=\"{Binding Bar}\" />\n\n... where Foo and Bar are of the appropriate type.\nEdit: Of course, that's the WPF documentation. I suppose it's possible that they've changed ScaleX and ScaleY to be standard properties rather than dependency properties in Silverlight. I'd love to hear more about the error you're seeing.\n", "ScaleTransform doesn't have a data context so most likely the binding is looking for SelectedDive.Visibility off it's self and not finding it. There is much in Silverlight xaml and databinding that is different from WPF... \nAnyway to solve this you will want to set up the binding in code**, or manually listen for the PropertyChanged event of your data object and set the Scale in code behind.\nI would choose the latter if you wanted to do an animation/storyboard for the scale change.\n** i need to check but you may not be able to bind to it. as i recall if the RenderTransform is not part of an animation it gets turned into a matrix transform and all bets are off. \n", "Ah I think I see your problem. You're attempting to bind a property of type Visibility (SelectedDive.Visibility) to a property of type Double (ScaleTransform.ScaleX). WPF/Silverlight can't convert between those two types.\nWhat are you trying to accomplish? Maybe I can help you with the XAML. What is \"SelectedDive\" and what do you want to happen when its Visibility changes?\n", "Sorry - was looking for the answer count to go up so I didn't realise you'd edited the question with more information.\nOK, so Visibility is of type Double, so the binding should work in that regard.\nAs a workaround, could you try binding your ScaleX and ScaleY values directly to the slider control that SelectedDive.Visibility is bound to? Something like:\n<ScaleTransform ScaleX=\"{Binding ElementName=slider1,Path=Value}\" ... />\n\nIf that works then it'll at least get you going.\nEdit: Ah, I just remembered that I read once that Silverlight doesn't support the ElementName syntax in bindings, so that might not work.\n", "Yeah maybe the embedded render transforms aren't inheriting the DataContext from the object they apply to. Can you force the DataContext into them? For example, give the transform a name:\n<ScaleTransform x:Name=\"myScaler\" ... />\n\n... and then in your code-behind:\nmyScaler.DataContext = fishImage.DataContext;\n\n... so that the scaler definitely shares its DataContext with the Image.\n", "Ok, is the Image itself picking up the DataContext properly?\nTry adding this:\n<Image Tooltip=\"{Binding SelectedDive.Visibility}\" ... />\n\nIf that compiles and runs, hover over the image and see if it displays the right value.\n", "I was hoping to solve this through XAML, but turns out Brian's suggestion was the way to go. I used Matt's suggestion to give the scale transform a name, so that I can access it from code. Then I hooked the value changed event of the slider, and manually updates the ScaleX and ScaleY property. I kept my value converter to convert from the visibility range (0-30m) to scale (0.5 to 1). The code looks like this:\n private ScaleConverter converter;\n\n public DiveLog()\n { \n InitializeComponent();\n\n converter = new ScaleConverter();\n visibilitySlider.ValueChanged += new \n RoutedPropertyChangedEventHandler<double>(visibilitySlider_ValueChanged);\n } \n\n private void visibilitySlider_ValueChanged(object sender, \n RoutedPropertyChangedEventArgs<double> e)\n {\n fishScale.ScaleX = (double)converter.Convert(e.NewValue, \n typeof(double), null, CultureInfo.CurrentCulture);\n fishScale.ScaleY = fishScale.ScaleX;\n }\n\n" ]
[ 1, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "data_binding", "silverlight" ]
stackoverflow_0000027303_data_binding_silverlight.txt
Q: How do you deal with the light side and dark side of distributed version control systems? I've had some discussions recently at work about switching from Subversion to a DVCS like bazaar, and I would like to get other people's opinion. I've managed to crystallize my reluctance to do so into a simple parallel. Version Control can be used well or badly. The 'light side' of version control is when you use it to keep track of your changes, are able to go back to older versions when you break stuff, and when you publish your changes so your peers can see your work-in-progress. The 'dark side' of version control is when you don't use it properly so you don't 'checkpoint' your work by committing regularly, you keep a bunch of changes in your local checkout, and you don't share your changes with others as you make them. Subversion makes both the light side and the dark side relatively hard. All the basics work, but few people really use branching in Subversion (beyond tagging and releasing) because merging is not straightforward at all. The support for it in Subversion itself is terrible, and there are scripts like svnmerge that make it better, but it's still not very good. So, these days, with good branching and merging support considered more and more like the necessity it is for collaborative development, Subversion doesn't match up. On the other hand, the 'dark side' is pretty tough to follow too. You only need to be bitten once by not having your local changes commited once in a while to the online repository, and breaking your code with a simple edit you don't even remember making. So you end up making regular commits and people can see the work you're doing. So, in the end Subversion ends up being a good middle-of-the-road VCS that, while a bit cumbersome for implementing the best practices, still makes it hard to get things very wrong. In contrast, with a DVCS the cost of either going completely light side or dark side is a lot lower. Branching and merging is a lot simpler with these modern VCS systems. But the distributed aspect makes it easy to work in a set of local branches on your own machine, giving you the granular commits you need to checkpoint your work, possibly without ever publishing your changes so others can see, review, and collaborate. The friction of keeping your changes in your local branches and not publishing them is typically lower than publishing them in some branch on a publically available server. So in a nutshell, here's the question: if I give our developers at work a DVCS, how can I make sure they use it to go to the 'light side', still publish their changes in a central location regularly, and make them understand that their one week local hack they didn't want to share yet might be just the thing some other developer could use to finish a feature while the first one is on holiday? If both the light side and the dark side of DVCS are so easy to get to, how do I keep them away from the dark side? A: If there are developers on your team that don't want to share their "one week local hack" then thats the problem, not the source control tool you are using. A better term for the "dark side" you are describing is "the wrong way" of coding for a team. Source control is a tool used to facilitate collaborative work. If your team is not clear about the fact that the goal is to share the work, then the best reason to use source control is not even applicable. Also, I think you might be a little confused about distributed source control. There is no publishing to a central locations. Some branches are more important than others and there exists many many branches. Keeping that in mind, I think that distributed source control really works best for popular open source projects. I'm under the perception that centralized source control is still better for development withing a company or some other clearly defined entity. A: Nick, while I agree that the problem is 'not sharing your work', the main argument is that tools promote a certain work flow and not all tools apply to all problems with equal friction. My concern is that a DVCS makes it easier to not share your work since you don't have the drawbacks of not sharing your work you get with SVN. If the friction of not sharing is lower than the friction of not sharing (which it is in DVCS), a developer, all else being equal, might easily choose the path of least friction. I don't think I'm confused about distributed source control. I know that there is no 'central location' by default. But most projects using DVCS still have the concept of a 'master' branch at a 'central location' that they release from. For the purpose of my question though, I only make the distinction between 'private' (only accessible by the developer) and 'public' (accessible by all other developers) branches. A: You make a distinction between 'private' and 'public' branches, but the only real difference between these cases is whether the branch's repository is only available locally or company-wide. A central repository is only one way to have company-wide availability. Instead, why not say that all repositories must be publically available throughout the company? For example, you could make all developer run their own local VCS server, and share their branches via zeroconf. A: I believe svn's merging has been somewhat overhauled in the latest release.
How do you deal with the light side and dark side of distributed version control systems?
I've had some discussions recently at work about switching from Subversion to a DVCS like bazaar, and I would like to get other people's opinion. I've managed to crystallize my reluctance to do so into a simple parallel. Version Control can be used well or badly. The 'light side' of version control is when you use it to keep track of your changes, are able to go back to older versions when you break stuff, and when you publish your changes so your peers can see your work-in-progress. The 'dark side' of version control is when you don't use it properly so you don't 'checkpoint' your work by committing regularly, you keep a bunch of changes in your local checkout, and you don't share your changes with others as you make them. Subversion makes both the light side and the dark side relatively hard. All the basics work, but few people really use branching in Subversion (beyond tagging and releasing) because merging is not straightforward at all. The support for it in Subversion itself is terrible, and there are scripts like svnmerge that make it better, but it's still not very good. So, these days, with good branching and merging support considered more and more like the necessity it is for collaborative development, Subversion doesn't match up. On the other hand, the 'dark side' is pretty tough to follow too. You only need to be bitten once by not having your local changes commited once in a while to the online repository, and breaking your code with a simple edit you don't even remember making. So you end up making regular commits and people can see the work you're doing. So, in the end Subversion ends up being a good middle-of-the-road VCS that, while a bit cumbersome for implementing the best practices, still makes it hard to get things very wrong. In contrast, with a DVCS the cost of either going completely light side or dark side is a lot lower. Branching and merging is a lot simpler with these modern VCS systems. But the distributed aspect makes it easy to work in a set of local branches on your own machine, giving you the granular commits you need to checkpoint your work, possibly without ever publishing your changes so others can see, review, and collaborate. The friction of keeping your changes in your local branches and not publishing them is typically lower than publishing them in some branch on a publically available server. So in a nutshell, here's the question: if I give our developers at work a DVCS, how can I make sure they use it to go to the 'light side', still publish their changes in a central location regularly, and make them understand that their one week local hack they didn't want to share yet might be just the thing some other developer could use to finish a feature while the first one is on holiday? If both the light side and the dark side of DVCS are so easy to get to, how do I keep them away from the dark side?
[ "If there are developers on your team that don't want to share their \"one week local hack\" then thats the problem, not the source control tool you are using. A better term for the \"dark side\" you are describing is \"the wrong way\" of coding for a team. Source control is a tool used to facilitate collaborative work. If your team is not clear about the fact that the goal is to share the work, then the best reason to use source control is not even applicable.\nAlso, I think you might be a little confused about distributed source control. There is no publishing to a central locations. Some branches are more important than others and there exists many many branches. Keeping that in mind, I think that distributed source control really works best for popular open source projects. I'm under the perception that centralized source control is still better for development withing a company or some other clearly defined entity.\n", "Nick,\nwhile I agree that the problem is 'not sharing your work', the main argument is that tools promote a certain work flow and not all tools apply to all problems with equal friction. My concern is that a DVCS makes it easier to not share your work since you don't have the drawbacks of not sharing your work you get with SVN. If the friction of not sharing is lower than the friction of not sharing (which it is in DVCS), a developer, all else being equal, might easily choose the path of least friction.\nI don't think I'm confused about distributed source control. I know that there is no 'central location' by default. But most projects using DVCS still have the concept of a 'master' branch at a 'central location' that they release from. For the purpose of my question though, I only make the distinction between 'private' (only accessible by the developer) and 'public' (accessible by all other developers) branches.\n", "You make a distinction between 'private' and 'public' branches, but the only real difference between these cases is whether the branch's repository is only available locally or company-wide. A central repository is only one way to have company-wide availability.\nInstead, why not say that all repositories must be publically available throughout the company? For example, you could make all developer run their own local VCS server, and share their branches via zeroconf.\n", "I believe svn's merging has been somewhat overhauled in the latest release.\n" ]
[ 3, 2, 1, 0 ]
[]
[]
[ "svn", "version_control" ]
stackoverflow_0000027054_svn_version_control.txt
Q: Cannot delete, a file with that name may already exist This is starting to vex me. I recently decided to clear out my FTP, and stumbled across an old Wordpress install I forgot I had (oh yes, very security conscious me). Anyway, for some reason deleting the directory failed so I investigated to see what was causing the blockage and I've narrowed it down to a file in wp-content. Now when I try to delete this file I can get two errors. I've tried in Windowx Explorer (FTP) and the Web Control Panel's File Manager. Here's some error shots: As you can see my File manager thinks the file is a Symbolic Link. While it scares me that my web server is host to an obviously religoious artifact I'm also heavily confused by the situation. I've tried renaming the file. I've refreshed the FTP view. I've tried moving the file to another dir (which worked, no success on deletion though). I've tried editing the file and then deletion. And I'm at a loss. Is there a special way to delete SymLinks? I've never heard of them, until now. edit Oho Windows you really are a magician of sorts. I decided to take a look at my FTP via command prompt and guess what? The file doesn't exist. Whether ftp ignores symlinks I don't know but I'm about to give up :P A: First of all, try emailing your webhost either for SSH-access or to remove the symlink for you. If you get SSH-access, use: unlink index.php Or if neither works: Create a PHP file there (for instance remove.php) that contains: <?php unlink("./index.php") ?> Then open that file in your browser, afterwards remove the remove.php file.
Cannot delete, a file with that name may already exist
This is starting to vex me. I recently decided to clear out my FTP, and stumbled across an old Wordpress install I forgot I had (oh yes, very security conscious me). Anyway, for some reason deleting the directory failed so I investigated to see what was causing the blockage and I've narrowed it down to a file in wp-content. Now when I try to delete this file I can get two errors. I've tried in Windowx Explorer (FTP) and the Web Control Panel's File Manager. Here's some error shots: As you can see my File manager thinks the file is a Symbolic Link. While it scares me that my web server is host to an obviously religoious artifact I'm also heavily confused by the situation. I've tried renaming the file. I've refreshed the FTP view. I've tried moving the file to another dir (which worked, no success on deletion though). I've tried editing the file and then deletion. And I'm at a loss. Is there a special way to delete SymLinks? I've never heard of them, until now. edit Oho Windows you really are a magician of sorts. I decided to take a look at my FTP via command prompt and guess what? The file doesn't exist. Whether ftp ignores symlinks I don't know but I'm about to give up :P
[ "First of all, try emailing your webhost either for SSH-access or to remove the symlink for you.\nIf you get SSH-access, use:\nunlink index.php\n\nOr if neither works: Create a PHP file there (for instance remove.php) that contains:\n<?php unlink(\"./index.php\") ?>\n\nThen open that file in your browser, afterwards remove the remove.php file.\n" ]
[ 2 ]
[]
[]
[ "file", "ftp", "symlink" ]
stackoverflow_0000027655_file_ftp_symlink.txt
Q: SVN Client Ignore Pattern for VB.NET Solutions What is the best SVN Ignore Pattern should TortoiseSVN have for a VB.NET solution? A: this is what I use for C# w/resharper, should work just the same with vb.net: build deploy */bin */bin/* obj *.dll *.pdb *.user *.suo _ReSharper* *.resharper* bin A: I always add Thumbs.db in as well, because I hate having those files versioned. Probably more of an issue for web developers
SVN Client Ignore Pattern for VB.NET Solutions
What is the best SVN Ignore Pattern should TortoiseSVN have for a VB.NET solution?
[ "this is what I use for C# w/resharper, should work just the same with vb.net:\nbuild deploy */bin */bin/* obj *.dll *.pdb *.user *.suo _ReSharper* *.resharper* bin\n\n", "I always add Thumbs.db in as well, because I hate having those files versioned. Probably more of an issue for web developers \n" ]
[ 17, 4 ]
[]
[]
[ "svn", "tortoisesvn", "vb.net" ]
stackoverflow_0000004138_svn_tortoisesvn_vb.net.txt
Q: Executing JavaScript to Render HTML for Server-Side Caching There are lots of widgets provided by sites that are effectively bits of JavaScript that generate HTML through DOM manipulation or document.write(). Rather than slow the browser down even more with additional requests and trust yet another provider to be fast, reliable and not change the widget output, I want to execute* the JavaScript to generate the rendered HTML, and then save that HTML source.­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­ Things I've looked into that seem unworkable or way too difficult: The Links Browser (not lynx!) Headless use of Xvfb plus Firefox plus Greasemonkey (yikes) The all-Java browser toolkit Cobra (the best bet!) Any ideas? ** Obviously you can't really execute the JavaScript completely, as it doesn't necessarily have an exit path, but you get the idea. A: Wikipedia's "Server-side JavaScript" article lists numerous implementations, many of which are based on Mozilla's Rhino JavaScript-to-Java converter, or its cousin SpiderMonkey (the same engine as found in Firefox and other Gecko-based browsers). In particular, something simple like mod_js for Apache may suit your needs. A: If you're just using plain JS, Rhino should do the trick. But if the JS code is actually calling DOM methods and so on, you're going to need a full-blown browser. Crowbar might help you. Is this really going to make things faster for users without causing compatibility issues? A: There's John Resig's project Bringing the Browser to the Server: "browser/DOM environment, written in JavaScript, that runs on top of Rhino; capable of running jQuery, Prototype, and MochiKit (at the very least)."
Executing JavaScript to Render HTML for Server-Side Caching
There are lots of widgets provided by sites that are effectively bits of JavaScript that generate HTML through DOM manipulation or document.write(). Rather than slow the browser down even more with additional requests and trust yet another provider to be fast, reliable and not change the widget output, I want to execute* the JavaScript to generate the rendered HTML, and then save that HTML source.­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­ Things I've looked into that seem unworkable or way too difficult: The Links Browser (not lynx!) Headless use of Xvfb plus Firefox plus Greasemonkey (yikes) The all-Java browser toolkit Cobra (the best bet!) Any ideas? ** Obviously you can't really execute the JavaScript completely, as it doesn't necessarily have an exit path, but you get the idea.
[ "Wikipedia's \"Server-side JavaScript\" article lists numerous implementations, many of which are based on Mozilla's Rhino JavaScript-to-Java converter, or its cousin SpiderMonkey (the same engine as found in Firefox and other Gecko-based browsers). In particular, something simple like mod_js for Apache may suit your needs.\n", "If you're just using plain JS, Rhino should do the trick. But if the JS code is actually calling DOM methods and so on, you're going to need a full-blown browser. Crowbar might help you.\nIs this really going to make things faster for users without causing compatibility issues?\n", "There's John Resig's project Bringing the Browser to the Server: \"browser/DOM environment, written in JavaScript, that runs on top of Rhino; capable of running jQuery, Prototype, and MochiKit (at the very least).\"\n" ]
[ 4, 2, 2 ]
[]
[]
[ "greasemonkey", "html", "javascript", "rendering" ]
stackoverflow_0000015007_greasemonkey_html_javascript_rendering.txt
Q: TClientDataSet Aggregates specification aren't added automatically when creating an Aggregate field I need to create an Aggregate Field in a TClientDataSet, but as said in the docs: Choose OK. The newly defined aggregate field is automatically added to the client dataset and its Aggregates property is automatically updated to include the appropriate aggregate specification. When I add a new aggregate field, the aggregate specification isn't added to the TClientDataSet's Aggregates, therefore I can't use its OnUpdateMethod. I also tried handling the OnChange event of my new Aggregate Field, but it isn't fired at all. Am I doing something wrong? I just want to have an aggregated field and fire an event everything it's value change. Is this broken on delphi? Because what is in the documentation doesn't reflect the actual behavior. edit: @Michal Sznajder I'm using Delphi 2007 A: I think you may be getting confused between TAggregate and TAggregateField objects, and the Delphi documentation probably isn't helping. AFAICT, TAggregateField objects are automatically 'recalculated' and can be bound to data-aware controls like TDBText, but don't have any OnUpdate event. "TAggregate" objects, on the other hand, do have an OnUpdate event, but can't be bound to data-aware controls. This may be enlightening: http://dn.codegear.com/article/29272 A: Which version of Delphi ? I just tried clean D7 application and TAggregateField was added.
TClientDataSet Aggregates specification aren't added automatically when creating an Aggregate field
I need to create an Aggregate Field in a TClientDataSet, but as said in the docs: Choose OK. The newly defined aggregate field is automatically added to the client dataset and its Aggregates property is automatically updated to include the appropriate aggregate specification. When I add a new aggregate field, the aggregate specification isn't added to the TClientDataSet's Aggregates, therefore I can't use its OnUpdateMethod. I also tried handling the OnChange event of my new Aggregate Field, but it isn't fired at all. Am I doing something wrong? I just want to have an aggregated field and fire an event everything it's value change. Is this broken on delphi? Because what is in the documentation doesn't reflect the actual behavior. edit: @Michal Sznajder I'm using Delphi 2007
[ "I think you may be getting confused between TAggregate and TAggregateField objects, and the Delphi documentation probably isn't helping.\nAFAICT, TAggregateField objects are automatically 'recalculated' and can be bound to data-aware controls like TDBText, but don't have any OnUpdate event. \n\"TAggregate\" objects, on the other hand, do have an OnUpdate event, but can't be bound to data-aware controls.\nThis may be enlightening: http://dn.codegear.com/article/29272\n", "Which version of Delphi ? I just tried clean D7 application and TAggregateField was added. \n" ]
[ 4, 1 ]
[]
[]
[ "delphi" ]
stackoverflow_0000022212_delphi.txt
Q: How print Flex components in FireFox3? Thanks to FireFox's buggy implementation of ActiveX components (it really should take an image of them when printing) Flex components (in our case charts) don't print in FX. They print fine in IE7, even IE6. We need these charts to print, but they also have dynamic content. I don't really want to draw them again as images when the user prints - the Flex component should do it. We've found a potential workaround, but unfortunately it doesn't work in FireFox3 (in FireFox2 it sort-of works, but not well enough). Anyone know a workaround? A: Using the ACPrintManager I was able to get firefox 3 to print perfectly! The one thing I had to add to the example was to check if stage was null, and callLater if the stage was null. private function initPrint():void { //if we don't have a stage, wait until the next frame and try again if ( stage == null ) { callLater(initPrint); return; } PrintManager.init(stage); var data:BitmapData = new BitmapData(stage.stageWidth, stage.stageHeight); data.draw(myDataGrid); PrintManager.setPrintableContent(data); } A: Thanks. A load of callLater-s added to our custom chart code seems to have done it.
How print Flex components in FireFox3?
Thanks to FireFox's buggy implementation of ActiveX components (it really should take an image of them when printing) Flex components (in our case charts) don't print in FX. They print fine in IE7, even IE6. We need these charts to print, but they also have dynamic content. I don't really want to draw them again as images when the user prints - the Flex component should do it. We've found a potential workaround, but unfortunately it doesn't work in FireFox3 (in FireFox2 it sort-of works, but not well enough). Anyone know a workaround?
[ "Using the ACPrintManager I was able to get firefox 3 to print perfectly!\nThe one thing I had to add to the example was to check if stage was null, and callLater if the stage was null.\nprivate function initPrint():void {\n //if we don't have a stage, wait until the next frame and try again\n if ( stage == null ) {\n callLater(initPrint);\n return;\n }\n\n PrintManager.init(stage);\n\n var data:BitmapData = new BitmapData(stage.stageWidth, stage.stageHeight);\n data.draw(myDataGrid);\n\n PrintManager.setPrintableContent(data);\n}\n\n", "Thanks. A load of callLater-s added to our custom chart code seems to have done it.\n" ]
[ 3, 0 ]
[]
[]
[ "actionscript_3", "apache_flex", "firefox" ]
stackoverflow_0000009256_actionscript_3_apache_flex_firefox.txt
Q: Finding the crash dump files for a C# app An app I'm writing always crashes on a clients computer, but I don't get an exception description, or a stack trace. The only thing I get is a crash report that windows wants to send to Microsoft. I would like to get that dump file and investigate it myself, but I cannot find it. When I "View the contents of the error report" I can see the different memory dumps, but I cannot copy it or save it. A: You can use the Windows debugging tools to view the crash dump. To get the most use out of it, you'll need an exact copy of the symbols for that application (i.e. same version). Have a look at Tess's blog for tutorials on how to use the Windows debugging tools. I refer to her blog constantly whenever I'm in need of analysing crash dumps. A: Tess' blog was a great resource. Eventually I managed to figure out how to do remote debugging which means I didn't have to look at the crash dump. For the general community, here are some links I found useful: Remote debugging, how to set up and run it. Crash dumps, how to save and debug them.
Finding the crash dump files for a C# app
An app I'm writing always crashes on a clients computer, but I don't get an exception description, or a stack trace. The only thing I get is a crash report that windows wants to send to Microsoft. I would like to get that dump file and investigate it myself, but I cannot find it. When I "View the contents of the error report" I can see the different memory dumps, but I cannot copy it or save it.
[ "You can use the Windows debugging tools to view the crash dump. To get the most use out of it, you'll need an exact copy of the symbols for that application (i.e. same version).\nHave a look at Tess's blog for tutorials on how to use the Windows debugging tools. I refer to her blog constantly whenever I'm in need of analysing crash dumps.\n", "Tess' blog was a great resource. Eventually I managed to figure out how to do remote debugging which means I didn't have to look at the crash dump.\nFor the general community, here are some links I found useful:\n\nRemote debugging, how to set up and run it.\nCrash dumps, how to save and debug them.\n\n" ]
[ 8, 6 ]
[]
[]
[ "c#", "crash", "memory_dump" ]
stackoverflow_0000027742_c#_crash_memory_dump.txt
Q: Dynamic Element Names I want to transform an XML document. The source XML looks like this: <svc:ElementList> <svc:Element> <Year>2007</Year> </svc:Element> <svc:Element> <Year>2006</Year> </svc:Element> <svc:Element> <Year>2005</Year> </svc:Element> </svc:ElementList> I want to turn that into: <ElementList> <NewTag2007/> <NewTag2006/> <NewTag2005/> </ElementList> The following line of code isn't working: <xsl:element name="{concat('NewTag',Element/Year)}"/> The output is a series of elements that look like this: < NewTag >. (Without the spaces...) "//Element/Year", "./Element/Year", and "//svc:Element/Year" don't work either. One complication is that the "Element" tag is in the "svc" namespace while the "Year" tag is in the default namespace. So anyway, am I facing a namespace issue or am I mis-using the "concat()" function? A: Probably namespace issues and maybe one with current context. For source (with added namespace declaration to make it well-formed xml) <svc:ElementList xmlns:svc="svc"> <svc:Element> <Year>2007</Year> </svc:Element> <svc:Element> <Year>2006</Year> </svc:Element> <svc:Element> <Year>2005</Year> </svc:Element> </svc:ElementList> the stylesheet <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:svc="svc" version="1.0"> <xsl:template match="svc:ElementList"> <xsl:element name="{local-name()}"> <xsl:for-each select="svc:Element"> <xsl:element name="{concat('NewTag', Year)}"/> </xsl:for-each> </xsl:element> </xsl:template> </xsl:stylesheet> will give you the output you need. Note that svc:Element needs to be selected using namespace prefixed and that the context when generating the new tags is svc:Element, not svc:ElementList.
Dynamic Element Names
I want to transform an XML document. The source XML looks like this: <svc:ElementList> <svc:Element> <Year>2007</Year> </svc:Element> <svc:Element> <Year>2006</Year> </svc:Element> <svc:Element> <Year>2005</Year> </svc:Element> </svc:ElementList> I want to turn that into: <ElementList> <NewTag2007/> <NewTag2006/> <NewTag2005/> </ElementList> The following line of code isn't working: <xsl:element name="{concat('NewTag',Element/Year)}"/> The output is a series of elements that look like this: < NewTag >. (Without the spaces...) "//Element/Year", "./Element/Year", and "//svc:Element/Year" don't work either. One complication is that the "Element" tag is in the "svc" namespace while the "Year" tag is in the default namespace. So anyway, am I facing a namespace issue or am I mis-using the "concat()" function?
[ "Probably namespace issues and maybe one with current context. For source (with added namespace declaration to make it well-formed xml)\n<svc:ElementList xmlns:svc=\"svc\">\n <svc:Element>\n <Year>2007</Year>\n </svc:Element>\n <svc:Element>\n <Year>2006</Year>\n </svc:Element>\n <svc:Element>\n <Year>2005</Year>\n </svc:Element>\n</svc:ElementList>\n\nthe stylesheet\n<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n xmlns:svc=\"svc\"\n version=\"1.0\">\n <xsl:template match=\"svc:ElementList\">\n <xsl:element name=\"{local-name()}\">\n <xsl:for-each select=\"svc:Element\">\n <xsl:element name=\"{concat('NewTag', Year)}\"/>\n </xsl:for-each>\n </xsl:element>\n </xsl:template> \n</xsl:stylesheet>\n\nwill give you the output you need. Note that svc:Element needs to be selected using namespace prefixed and that the context when generating the new tags is svc:Element, not svc:ElementList.\n" ]
[ 13 ]
[]
[]
[ "namespaces", "xml", "xslt" ]
stackoverflow_0000027931_namespaces_xml_xslt.txt
Q: Reverse Find in a string I need to be able to find the last occurrence of a character within an element. For example: <mediaurl>http://www.blah.com/path/to/file/media.jpg</mediaurl> If I try to locate it through using substring-before(mediaurl, '.') and substring-after(mediaurl, '.') then it will, of course, match on the first dot. How would I get the file extension? Essentially, I need to get the file name and the extension from a path like this, but I am quite stumped as to how to do it using XSLT. A: The following is an example of a template that would produce the required output in XSLT 1.0: <xsl:template name="getExtension"> <xsl:param name="filename"/> <xsl:choose> <xsl:when test="contains($filename, '.')"> <xsl:call-template name="getExtension"> <xsl:with-param name="filename" select="substring-after($filename, '.')"/> </xsl:call-template> </xsl:when> <xsl:otherwise> <xsl:value-of select="$filename"/> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template match="/"> <xsl:call-template name="getExtension"> <xsl:with-param name="filename" select="'http://www.blah.com/path/to/file/media.jpg'"/> </xsl:call-template> </xsl:template> A: If you're using XSLT 2.0, it's easy: <xsl:variable name="extension" select="tokenize($filename, '\.')[last()]"/> If you're not, it's a bit harder. There's a good example from the O'Reilly XSLT Cookbook. Search for "Tokenizing a String." I believe there's also an EXSLT function, if you have that available. A: How about tokenize with "/" and take the last element from the array ? Example: tokenize("XPath is fun", "\s+") Result: ("XPath", "is", "fun") Was an XSLT fiddler sometime back... lost touch now. But HTH A: For reference, this problem is usually called "substring-after-last" in XSLT.
Reverse Find in a string
I need to be able to find the last occurrence of a character within an element. For example: <mediaurl>http://www.blah.com/path/to/file/media.jpg</mediaurl> If I try to locate it through using substring-before(mediaurl, '.') and substring-after(mediaurl, '.') then it will, of course, match on the first dot. How would I get the file extension? Essentially, I need to get the file name and the extension from a path like this, but I am quite stumped as to how to do it using XSLT.
[ "The following is an example of a template that would produce the required output in XSLT 1.0:\n<xsl:template name=\"getExtension\">\n<xsl:param name=\"filename\"/>\n\n <xsl:choose>\n <xsl:when test=\"contains($filename, '.')\">\n <xsl:call-template name=\"getExtension\">\n <xsl:with-param name=\"filename\" select=\"substring-after($filename, '.')\"/>\n </xsl:call-template>\n </xsl:when>\n <xsl:otherwise>\n <xsl:value-of select=\"$filename\"/>\n </xsl:otherwise>\n </xsl:choose>\n</xsl:template>\n\n<xsl:template match=\"/\">\n <xsl:call-template name=\"getExtension\">\n <xsl:with-param name=\"filename\" select=\"'http://www.blah.com/path/to/file/media.jpg'\"/>\n </xsl:call-template>\n</xsl:template>\n\n", "If you're using XSLT 2.0, it's easy:\n <xsl:variable name=\"extension\" select=\"tokenize($filename, '\\.')[last()]\"/>\n\nIf you're not, it's a bit harder. There's a good example from the O'Reilly XSLT Cookbook. Search for \"Tokenizing a String.\"\nI believe there's also an EXSLT function, if you have that available.\n", "How about tokenize with \"/\" and take the last element from the array ?\nExample: tokenize(\"XPath is fun\", \"\\s+\")\nResult: (\"XPath\", \"is\", \"fun\")\n\nWas an XSLT fiddler sometime back... lost touch now. But HTH\n", "For reference, this problem is usually called \"substring-after-last\" in XSLT.\n" ]
[ 14, 4, 0, 0 ]
[]
[]
[ "xml", "xslt" ]
stackoverflow_0000014527_xml_xslt.txt
Q: Use table metadata for select statement in SQL Server? I have a large database and would like to select table names that have a certain column name. I have done something like this in MySQL, but can't find any info on SQL Server. I want to do something like: select [table] from [db] where table [has column 'classtypeid'] How can I do something like this? A: Use the ANSI information_schema views, this will also work in MySQL select table_name from information_schema.columns where column_name = 'classtypeid' A: Here you go: SELECT C.TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS AS C INNER JOIN INFORMATION_SCHEMA.TABLES AS T ON C.TABLE_NAME = T.TABLE_NAME AND C.TABLE_SCHEMA = T.TABLE_SCHEMA WHERE C.COLUMN_NAME = 'classtypeid' AND T.TABLE_TYPE = 'BASE TABLE' Edit: Note that this will not list views based on any tables with that column. If you only query INFORMATION_SCHEMA.COLUMNS you will also get back views.
Use table metadata for select statement in SQL Server?
I have a large database and would like to select table names that have a certain column name. I have done something like this in MySQL, but can't find any info on SQL Server. I want to do something like: select [table] from [db] where table [has column 'classtypeid'] How can I do something like this?
[ "Use the ANSI information_schema views, this will also work in MySQL\nselect table_name \nfrom information_schema.columns \nwhere column_name = 'classtypeid'\n\n", "Here you go:\nSELECT C.TABLE_NAME\nFROM INFORMATION_SCHEMA.COLUMNS AS C\n INNER JOIN INFORMATION_SCHEMA.TABLES AS T ON C.TABLE_NAME = T.TABLE_NAME\n AND C.TABLE_SCHEMA = T.TABLE_SCHEMA\nWHERE C.COLUMN_NAME = 'classtypeid'\n AND T.TABLE_TYPE = 'BASE TABLE'\n\n\nEdit: Note that this will not list views based on any tables with that column. If you only query INFORMATION_SCHEMA.COLUMNS you will also get back views.\n" ]
[ 5, 2 ]
[]
[]
[ "sql", "sql_server" ]
stackoverflow_0000028003_sql_sql_server.txt
Q: SQL Server to MySQL I have a backup of an SQL Server DB in .bak format which I've successfully managed to restore to a local instance of SQL Server Express. I now want to export both the structure and data in a format that MySQL will accept. The tools that I use for MySQL management typically allow me to import/export .sql files, but unfortunately Microsoft didn't see fit to make my life this easy! I can't believe I'm the first to run into this, but Google hasn't been a great deal of help. Has anybody managed this before? A: There will be 2 issues: 1) Datatypes. There isn't always a direct analog between an MS SQL type and a MySQL type. For example, MySQL handles timestamps very differently and has the cut-off for when you need to switch between varchar(n) and varchar(max)/text at a different value of n. There are also some small differences in the numeric types. 2) Query syntax. There are a few differences in the query syntax that, again, don't always have a 1:1 analog replacement. The one that comes to the top of my mind is SELECT TOP N * FROM T in MS SQL becomes SELECT * FROM T LIMIT N in MySQL (MySQL makes paging loads easier).
SQL Server to MySQL
I have a backup of an SQL Server DB in .bak format which I've successfully managed to restore to a local instance of SQL Server Express. I now want to export both the structure and data in a format that MySQL will accept. The tools that I use for MySQL management typically allow me to import/export .sql files, but unfortunately Microsoft didn't see fit to make my life this easy! I can't believe I'm the first to run into this, but Google hasn't been a great deal of help. Has anybody managed this before?
[ "There will be 2 issues:\n1) Datatypes. There isn't always a direct analog between an MS SQL type and a MySQL type. For example, MySQL handles timestamps very differently and has the cut-off for when you need to switch between varchar(n) and varchar(max)/text at a different value of n. There are also some small differences in the numeric types. \n2) Query syntax. There are a few differences in the query syntax that, again, don't always have a 1:1 analog replacement. The one that comes to the top of my mind is SELECT TOP N * FROM T in MS SQL becomes SELECT * FROM T LIMIT N in MySQL (MySQL makes paging loads easier).\n" ]
[ 1 ]
[]
[]
[ "database", "sql_server" ]
stackoverflow_0000028033_database_sql_server.txt
Q: Print a barcode to a Intermec PB20 via the LinePrinter API Does anyone know how to print a barcode to the Intermec PB20 bluetooth printer from a Windows Compact Framework application? We are currently using the Intermec LinePrinter API but have been unable to find a way to print a barcode. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­ A: Thank you all for your thoughts. Printing directly to the serial port is likely the most flexible method. In this case we didn't want to replicate all of the work that was already built into the Intermec dll for handling the port, printer errors, etc. We were able to get this working by sending the printer the appropriate codes to switch it into a different mode and then pass direct printer commands that way. Here was our solution in case anyone else happens to encounter a similar issue working with Intermec Printers. The following code is a test case that doesn't catch printer errors and retry, etc. (See Intermec code examples.) Intermec.Print.LinePrinter lp; int escapeCharacter = int.Parse("1b", NumberStyles.HexNumber); char[] toEzPrintMode = new char[] { Convert.ToChar(num2), 'E', 'Z' }; lp = new Intermec.Print.LinePrinter("Printer_Config.XML", "PrinterPB20_40COL"); lp.Open(); lp.Write(charArray2); //switch to ez print mode string testBarcode = "{PRINT:@75,10:PD417,YDIM 6,XDIM 2,COLUMNS 2, SECURITY 3|ABCDEFGHIJKL|}"; lp.Write(testBarcode); lp.Write("{LP}"); //switch from ez print mode back to line printer mode lp.NewLine(); lp.Write("Test"); //verify line printer mode is working There is a technical document on Intermec's support site called the "Technical Manual" that describes the code for directly controlling the printer. The section about Easy Print describes how to print a variety of barcodes. A: Last time I had to print Barcode (despite the printer or framework) I resorted to use a True Type font with the Barcode I needed. (In my case was EAN-13 something), an european barcode. There are fonts where you simply write numbers (and/or letters when supported) and you get a perfect barcode any scanner can read :) Google is your friend. I don't know if there are free ones. A: Thank you for your answer. There are free fonts available -- However, the PB20 is a handheld printer with a few built-in fonts. It has the capability to print barcodes and can be manipulated directly via the serial port. Intermec provides a .Net CF API to make printing "easy", and it is using this API that we have been unable to figure out how to tell the printer to print a barcode. A: Ditch all API's and use a serial port API directly. Talk the printers language and you can get decent results. Every other approach leads to frustration. Not so pretty, but that is the way my old factory worked. 4k print jobs per day, and none ever missed. A: Free 3 of 9 This is 3 of 9 (sometimes called "code 39"), a widely used barcode standard that includes capital letters, numbers, and several symbols. This is not the barcode for UPC's (universal price codes) found on products at the store. However, most kinds of barcode scanners will recognize 3 of 9 just fine.
Print a barcode to a Intermec PB20 via the LinePrinter API
Does anyone know how to print a barcode to the Intermec PB20 bluetooth printer from a Windows Compact Framework application? We are currently using the Intermec LinePrinter API but have been unable to find a way to print a barcode. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
[ "Thank you all for your thoughts. Printing directly to the serial port is likely the most flexible method. In this case we didn't want to replicate all of the work that was already built into the Intermec dll for handling the port, printer errors, etc. We were able to get this working by sending the printer the appropriate codes to switch it into a different mode and then pass direct printer commands that way.\nHere was our solution in case anyone else happens to encounter a similar issue working with Intermec Printers. The following code is a test case that doesn't catch printer errors and retry, etc. (See Intermec code examples.)\nIntermec.Print.LinePrinter lp;\n\nint escapeCharacter = int.Parse(\"1b\", NumberStyles.HexNumber);\nchar[] toEzPrintMode = new char[] { Convert.ToChar(num2), 'E', 'Z' };\n\nlp = new Intermec.Print.LinePrinter(\"Printer_Config.XML\", \"PrinterPB20_40COL\");\nlp.Open();\n\nlp.Write(charArray2); //switch to ez print mode\n\nstring testBarcode = \"{PRINT:@75,10:PD417,YDIM 6,XDIM 2,COLUMNS 2, SECURITY 3|ABCDEFGHIJKL|}\";\nlp.Write(testBarcode);\n\nlp.Write(\"{LP}\"); //switch from ez print mode back to line printer mode\n\nlp.NewLine();\nlp.Write(\"Test\"); //verify line printer mode is working\n\nThere is a technical document on Intermec's support site called the \"Technical Manual\" that describes the code for directly controlling the printer. The section about Easy Print describes how to print a variety of barcodes.\n", "Last time I had to print Barcode (despite the printer or framework) I resorted to use a True Type font with the Barcode I needed. (In my case was EAN-13 something), an european barcode.\nThere are fonts where you simply write numbers (and/or letters when supported) and you get a perfect barcode any scanner can read :)\nGoogle is your friend. I don't know if there are free ones.\n", "Thank you for your answer. There are free fonts available -- However, the PB20 is a handheld printer with a few built-in fonts. It has the capability to print barcodes and can be manipulated directly via the serial port. Intermec provides a .Net CF API to make printing \"easy\", and it is using this API that we have been unable to figure out how to tell the printer to print a barcode.\n", "Ditch all API's and use a serial port API directly.\nTalk the printers language and you can get decent results.\nEvery other approach leads to frustration.\nNot so pretty, but that is the way my old factory worked.\n4k print jobs per day, and none ever missed.\n", "Free 3 of 9\n\nThis is 3 of 9 (sometimes called \"code\n 39\"), a widely used barcode standard\n that includes capital letters,\n numbers, and several symbols. This is\n not the barcode for UPC's (universal\n price codes) found on products at the\n store. However, most kinds of barcode\n scanners will recognize 3 of 9 just\n fine.\n\n" ]
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "c#", "windows_mobile" ]
stackoverflow_0000026354_c#_windows_mobile.txt
Q: Form post doesn't contain textbox data [ASP.NET C#] I have several "ASP:TextBox" controls on a form (about 20). When the form loads, the text boxes are populated from a database. The user can change the populated values, and when they submit the form, I take the values posted to the server and conditionally save them (determined by some business logic). All but 1 of the text boxes work as intended. The odd box out, upon postback, does not contain the updated value that the user typed into the box. When debugging the application, it is clear that myTextBox.Text reflects the old, pre-populated value, not the new, user-supplied value. Every other box properly shows their respective user-supplied values. I did find a workaround. My solution was to basically extract the text box's value out of the Request.Form object: Request.Form[myTextBox.UniqueID], which does contain the user-supplied value. What could be going on, here? As I mentioned, the other text boxes receive the user-supplied values just fine, and this particular problematic text box doesn't have any logic associated to it -- it just takes the value and saves it. The main difference between this text box and the others is that this is a multi-line box (for inputting notes), which I believe is rendered as an HTML "textarea" tag instead of an "input" tag in ASP.NET. A: Are you initially loading the data only when !Page.IsPostBack? Also, is view state enabled for the text box? A: this happens to me all the time. protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { // populate text boxes from database } } A: I would second Jonathan's response I would check your databinding settings. If you do not need ViewState for the textboxes (i.e. no postback occurs until form submit) then you should disable it. It sounds like you are not having problems saving the data (since you said you have managed to get the control to read the correct data back). Therefore, I would say the problem loads in your databinding code. A: Remember the order of the page lifecycle, and where you are databinding your form. PreInit Init Load Your Control Event Handler If you are reading the value in the Control Event handler, yet databinding in Init or Load, you'll have the old value. The trick is to always databind in the correct event, or check for postback and don't databind then. A: Are you initially loading the data only when !Page.IsPostBack? Also, is view state enabled for the text box? I had almost forgotten to check the ViewState, but ended up remembering to verify that it wasn't disabled before making my post here on SO. I even set EnableViewState="true" to make sure. I did find the solution, and it coincided with most of the answers here. The form was indeed loading its data more than once (which is intentional behavior). I implemented some special code for this field, and all is well. Thanks for your replies, all!
Form post doesn't contain textbox data [ASP.NET C#]
I have several "ASP:TextBox" controls on a form (about 20). When the form loads, the text boxes are populated from a database. The user can change the populated values, and when they submit the form, I take the values posted to the server and conditionally save them (determined by some business logic). All but 1 of the text boxes work as intended. The odd box out, upon postback, does not contain the updated value that the user typed into the box. When debugging the application, it is clear that myTextBox.Text reflects the old, pre-populated value, not the new, user-supplied value. Every other box properly shows their respective user-supplied values. I did find a workaround. My solution was to basically extract the text box's value out of the Request.Form object: Request.Form[myTextBox.UniqueID], which does contain the user-supplied value. What could be going on, here? As I mentioned, the other text boxes receive the user-supplied values just fine, and this particular problematic text box doesn't have any logic associated to it -- it just takes the value and saves it. The main difference between this text box and the others is that this is a multi-line box (for inputting notes), which I believe is rendered as an HTML "textarea" tag instead of an "input" tag in ASP.NET.
[ "Are you initially loading the data only when !Page.IsPostBack? Also, is view state enabled for the text box?\n", "this happens to me all the time.\nprotected void Page_Load(object sender, EventArgs e)\n{\n if (!Page.IsPostBack)\n {\n // populate text boxes from database\n }\n}\n\n", "I would second Jonathan's response I would check your databinding settings.\nIf you do not need ViewState for the textboxes (i.e. no postback occurs until form submit) then you should disable it.\nIt sounds like you are not having problems saving the data (since you said you have managed to get the control to read the correct data back). Therefore, I would say the problem loads in your databinding code.\n", "Remember the order of the page lifecycle, and where you are databinding your form.\n\nPreInit\nInit\nLoad\nYour Control Event Handler\n\nIf you are reading the value in the Control Event handler, yet databinding in Init or Load, you'll have the old value.\nThe trick is to always databind in the correct event, or check for postback and don't databind then.\n", "\nAre you initially loading the data only when !Page.IsPostBack? Also, is view state enabled for the text box?\n\nI had almost forgotten to check the ViewState, but ended up remembering to verify that it wasn't disabled before making my post here on SO. I even set EnableViewState=\"true\" to make sure.\nI did find the solution, and it coincided with most of the answers here. The form was indeed loading its data more than once (which is intentional behavior). I implemented some special code for this field, and all is well.\nThanks for your replies, all!\n" ]
[ 9, 7, 2, 1, 1 ]
[]
[]
[ "asp.net", "c#" ]
stackoverflow_0000022988_asp.net_c#.txt
Q: What are models for storing tree structures and what are their characteristics? So far I have encountered adjacency list, nested sets and nested intervals as models for storing tree structures in a database. I know these well enough and have migrated trees from one to another. What are other popular models? What are their characteristics? What are good resources (books, web, etc) on this topic? I'm not only looking for db storage but would like to expand my knowledge on trees in general. For example, I understand that nested sets/intervals are especially favorable for relational database storage and have asked myself, are they actually a bad choice in other contexts? A: A variation is where you use a direct hierarchical representation (ie. parent link in node), but also store a path value. ie. for a directory tree consisting of the following: C:\ Temp Windows System32 You would have the following nodes Key Name Parent Path 1 C: *1* 2 Temp 1 *1*2* 3 Windows 1 *1*3* 4 System32 3 *1*3*4* Path is indexed, and will allow you to quickly do a query that picks up a node and all its children, without having to manipulate ranges. ie. to find C:\Temp and all its children: WHERE Path LIKE '*1*2*%' This representation is the only place I can think of where storing id's in a string like this is ok. A: The seminal resource for this are chapters 28-30 of SQL for Smarties. (I've recommended this book so much I figure Celko owes me royalties by now!)
What are models for storing tree structures and what are their characteristics?
So far I have encountered adjacency list, nested sets and nested intervals as models for storing tree structures in a database. I know these well enough and have migrated trees from one to another. What are other popular models? What are their characteristics? What are good resources (books, web, etc) on this topic? I'm not only looking for db storage but would like to expand my knowledge on trees in general. For example, I understand that nested sets/intervals are especially favorable for relational database storage and have asked myself, are they actually a bad choice in other contexts?
[ "A variation is where you use a direct hierarchical representation (ie. parent link in node), but also store a path value.\nie. for a directory tree consisting of the following:\nC:\\\n Temp\n Windows\n System32\n\nYou would have the following nodes\nKey Name Parent Path\n1 C: *1*\n2 Temp 1 *1*2*\n3 Windows 1 *1*3*\n4 System32 3 *1*3*4*\n\nPath is indexed, and will allow you to quickly do a query that picks up a node and all its children, without having to manipulate ranges.\nie. to find C:\\Temp and all its children:\nWHERE Path LIKE '*1*2*%'\n\nThis representation is the only place I can think of where storing id's in a string like this is ok.\n", "The seminal resource for this are chapters 28-30 of SQL for Smarties.\n(I've recommended this book so much I figure Celko owes me royalties by now!)\n" ]
[ 2, 1 ]
[]
[]
[ "data_structures", "modeling" ]
stackoverflow_0000027850_data_structures_modeling.txt
Q: How can I convert types in C++? I'm using two different libraries in my project, and both of them supply a basic rectangle struct. The problem with this is that there seems to be no way to insert a conversion between the types, so I can't call a function in one library with the result from a function in the other. If I was the author of either of these, I could create conversions, from the outside, I can't. library a: typedef struct rectangle { sint16 x; sint16 y; uint16 w; uint16 h; } rectangle; library b: class Rect { int x; int y; int width; int height; /* ... */ }; Now, I can't make a converter class, because C++ will only look for a conversion in one step. This is probably a good thing, because there would be a lot of possibilities involving creating new objects of all kinds of types. I can't make an operator that takes the struct from a and supplies an object of the class from b: foo.cpp:123 error: ‘operator b::Rect(const rectangle&)’ must be a nonstatic member function So, is there a sensible way around this? edit: I should perhaps also point out that I'd really like some solution that makes working with the result seamless, since I don't expect to be that coder. (Though I agree, old-school, explicit, conversion would have been a good choice. The other branch, reinterpret_cast has the same problem..) edit2: Actually, none of the suggestions really answer my actual question, Konrad Rudolph seems to be correct. C++ actually can't do this. Sucks, but true. (If it makes any difference, I'm going to try subclassing as suggested by CodingTheWheel. A: Create an intermediate shim type "RectangleEx", and define custom conversions to/from the 3rd-party string types. Whenever you speak to either API, do so through the shim class. Another way would be to derive a class from either rect or Rectangle, and insert conversions/constructors there. A: Not sure how sensible this is, but how about something like this: class R { public: R(const rectangle& r) { ... }; R(const Rect& r) { ... }; operator rectangle() const { return ...; } operator Rect() const { return ...; } private: ... }; Then you can just wrap every rectangle in R() and the "right thing" will happen. A: If you can't modify the structures then you have no alternative to writing a manual conversion function because overloading conversion operators only works within the class body. There's no other way. A: It may not be feasible in your case, but I've seen people employ a little preprocessor-foo to massage the types into compatibility. Even this assumes that you are building one or both libraries. It is also possible that you don't want to do this at all, but want to re-evaulate some early decision. Or not. A: If the structs were the same internally, you could do a reinterpret_cast; however, since it looks like you have 16-bit vs 32-bit fields, you're probably stuck converting on each call, or writing wrappers for all functions of one of the libraries. A: Why not something simple like this: (note this may/probably won't compile) but you get the idea... private Rect* convert(const rectangle& src) { return new Rect(src.x,src.y,src.w,src.h); } int main() { rectangle r; r.x = 1; r.y = 2; r.w = 3; r.h = 4; Rect* foo = convert(&r); ... delete foo; } EDIT: Looks like koko's and I have the same idea.
How can I convert types in C++?
I'm using two different libraries in my project, and both of them supply a basic rectangle struct. The problem with this is that there seems to be no way to insert a conversion between the types, so I can't call a function in one library with the result from a function in the other. If I was the author of either of these, I could create conversions, from the outside, I can't. library a: typedef struct rectangle { sint16 x; sint16 y; uint16 w; uint16 h; } rectangle; library b: class Rect { int x; int y; int width; int height; /* ... */ }; Now, I can't make a converter class, because C++ will only look for a conversion in one step. This is probably a good thing, because there would be a lot of possibilities involving creating new objects of all kinds of types. I can't make an operator that takes the struct from a and supplies an object of the class from b: foo.cpp:123 error: ‘operator b::Rect(const rectangle&)’ must be a nonstatic member function So, is there a sensible way around this? edit: I should perhaps also point out that I'd really like some solution that makes working with the result seamless, since I don't expect to be that coder. (Though I agree, old-school, explicit, conversion would have been a good choice. The other branch, reinterpret_cast has the same problem..) edit2: Actually, none of the suggestions really answer my actual question, Konrad Rudolph seems to be correct. C++ actually can't do this. Sucks, but true. (If it makes any difference, I'm going to try subclassing as suggested by CodingTheWheel.
[ "Create an intermediate shim type \"RectangleEx\", and define custom conversions to/from the 3rd-party string types. Whenever you speak to either API, do so through the shim class.\nAnother way would be to derive a class from either rect or Rectangle, and insert conversions/constructors there.\n", "Not sure how sensible this is, but how about something like this:\nclass R\n{\npublic:\n R(const rectangle& r) { ... };\n R(const Rect& r) { ... };\n\n operator rectangle() const { return ...; }\n operator Rect() const { return ...; }\n\nprivate:\n ...\n};\n\nThen you can just wrap every rectangle in R() and the \"right thing\" will happen.\n", "If you can't modify the structures then you have no alternative to writing a manual conversion function because overloading conversion operators only works within the class body. There's no other way.\n", "It may not be feasible in your case, but I've seen people employ a little preprocessor-foo to massage the types into compatibility.\nEven this assumes that you are building one or both libraries.\nIt is also possible that you don't want to do this at all, but want to re-evaulate some early decision. Or not.\n", "If the structs were the same internally, you could do a reinterpret_cast; however, since it looks like you have 16-bit vs 32-bit fields, you're probably stuck converting on each call, or writing wrappers for all functions of one of the libraries.\n", "Why not something simple like this: (note this may/probably won't compile) but you get the idea...\n\n\nprivate Rect* convert(const rectangle& src)\n{\n return new Rect(src.x,src.y,src.w,src.h);\n}\nint main()\n{\n rectangle r;\n r.x = 1;\n r.y = 2;\n r.w = 3;\n r.h = 4;\n\n Rect* foo = convert(&r);\n ...\n delete foo;\n\n}\n\n\nEDIT: Looks like koko's and I have the same idea.\n" ]
[ 4, 3, 2, 0, 0, 0 ]
[ "Maybe you could try it with operator overloading ? (Maybe a = operator which is not a method of your class) ?\nRect operator= (const Rect&,const rectangle&)\nMore about this in the C++ programming language by Bjarne Stroustrup or maybe on this page: http://www.cs.caltech.edu/courses/cs11/material/cpp/donnie/cpp-ops.html\n" ]
[ -1 ]
[ "c++", "oop", "types" ]
stackoverflow_0000028212_c++_oop_types.txt
Q: Is there any way to prevent find from digging down recursively into subdirectories? When I do: $ find / It searches the entire system. How do I prevent that? (This question comes from an "answer" to another question.) A: Consider: -maxdepth n True if the depth of the current file into the tree is less than or equal to n. -mindepth n True if the depth of the current file into the tree is greater than or equal to n. A: G'day, Just wanted to expand on the suggestion from Jon to use -prune. It isn't the easiest of find options to use, for example to just search in the current directory the find command looks like: find . \( -type d ! -name . -prune \) -o \( <the bit you want to look for> \) this will stop find from descending into sub-directories within this directory. Basically, it says, "prune anything that is a directory, whose name isn't ".", i.e. current dir." The find command evals left to right for each item found in the current directory so after completion of the first element, i.e. the prune segment, it will then continue on with the matched item in your second -o (OR'd) expression. HTH. cheers, Rob A: You might be better off using wildcards. For instance, if you want to find all ksh scripts in the current directory: $ ls *.ksh A: Use the -prune option. A: You may even do echo /specific/dir/*.jpg as it's your shell that expands the wildcard. Typing ls *.jpg is equivalent to typing ls foo.jpg bar.jpg given foo.jpg and bar.jpg are all the files that end with ".jpg" in the current directory.
Is there any way to prevent find from digging down recursively into subdirectories?
When I do: $ find / It searches the entire system. How do I prevent that? (This question comes from an "answer" to another question.)
[ "Consider:\n-maxdepth n\n True if the depth of the current file into the tree is less than\n or equal to n.\n\n-mindepth n\n True if the depth of the current file into the tree is greater\n than or equal to n.\n\n", "G'day,\nJust wanted to expand on the suggestion from Jon to use -prune. It isn't the easiest of find options to use, for example to just search in the current directory the find command looks like:\nfind . \\( -type d ! -name . -prune \\) -o \\( <the bit you want to look for> \\)\n\nthis will stop find from descending into sub-directories within this directory.\nBasically, it says, \"prune anything that is a directory, whose name isn't \".\", i.e. current dir.\"\nThe find command evals left to right for each item found in the current directory so after completion of the first element, i.e. the prune segment, it will then continue on with the matched item in your second -o (OR'd) expression.\nHTH.\ncheers,\nRob\n", "You might be better off using wildcards. For instance, if you want to find all ksh scripts in the current directory:\n$ ls *.ksh\n\n", "Use the -prune option.\n", "You may even do\necho /specific/dir/*.jpg\n\nas it's your shell that expands the wildcard. Typing\nls *.jpg\n\nis equivalent to typing\nls foo.jpg bar.jpg\n\ngiven foo.jpg and bar.jpg are all the files that end with \".jpg\" in the current directory.\n" ]
[ 10, 4, 3, 0, 0 ]
[]
[]
[ "bash", "ksh", "shell", "unix" ]
stackoverflow_0000027077_bash_ksh_shell_unix.txt
Q: How to get SpecUnit to run within a TeamCity CI build I am trying to get SpecUnit to run in a continuous integration build using Nant. At the moment the files are in the correct place but no output is generated from SpecUnit.Report.exe. Here is the relevant task from the nant build script: <echo message="**** Starting SpecUnit report generation ****" /> <copy file="${specunit.exe}" tofile="${output.dir}SpecUnit.Report.exe" /> <exec program="${output.dir}SpecUnit.Report.exe" failonerror="false"> <arg value="${acceptance.tests.assembly}" /> </exec> Please note: ${specunit.exe} is the full path to where “SpecUnit.Report.exe” is located. ${output.dir} is the teamcity output directory for the current build agent. ${acceptance.tests.assembly} is "AcceptanceTests.dll" Anyone tried this before? A: You need to specify the full path to the assembly argument I think... <exec program="${output.dir}SpecUnit.Report.exe" verbose="true"> <arg value="${output.dir}${acceptance.tests.assembly}" /> </exec>
How to get SpecUnit to run within a TeamCity CI build
I am trying to get SpecUnit to run in a continuous integration build using Nant. At the moment the files are in the correct place but no output is generated from SpecUnit.Report.exe. Here is the relevant task from the nant build script: <echo message="**** Starting SpecUnit report generation ****" /> <copy file="${specunit.exe}" tofile="${output.dir}SpecUnit.Report.exe" /> <exec program="${output.dir}SpecUnit.Report.exe" failonerror="false"> <arg value="${acceptance.tests.assembly}" /> </exec> Please note: ${specunit.exe} is the full path to where “SpecUnit.Report.exe” is located. ${output.dir} is the teamcity output directory for the current build agent. ${acceptance.tests.assembly} is "AcceptanceTests.dll" Anyone tried this before?
[ "You need to specify the full path to the assembly argument I think...\n <exec program=\"${output.dir}SpecUnit.Report.exe\" verbose=\"true\">\n <arg value=\"${output.dir}${acceptance.tests.assembly}\" />\n </exec>\n\n" ]
[ 0 ]
[]
[]
[ "c#", "nant", "teamcity" ]
stackoverflow_0000027889_c#_nant_teamcity.txt
Q: Does PHP have an equivalent to this type of Python string substitution? Python has this wonderful way of handling string substitutions using dictionaries: >>> 'The %(site)s site %(adj)s because it %(adj)s' % {'site':'Stackoverflow', 'adj':'rocks'} 'The Stackoverflow site rocks because it rocks' I love this because you can specify a value once in the dictionary and then replace it all over the place in the string. I've tried to achieve something similar in PHP using various string replace functions but everything I've come up with feels awkward. Does anybody have a nice clean way to do this kind of string substitution in PHP? Edit Here's the code from the sprintf page that I liked best. <?php function sprintf3($str, $vars, $char = '%') { $tmp = array(); foreach($vars as $k => $v) { $tmp[$char . $k . $char] = $v; } return str_replace(array_keys($tmp), array_values($tmp), $str); } echo sprintf3( 'The %site% site %adj% because it %adj%', array('site'=>'Stackoverflow', 'adj'=>'rocks')); ?> A: function subst($str, $dict){ return preg_replace(array_map(create_function('$a', 'return "/%\\($a\\)s/";'), array_keys($dict)), array_values($dict), $str); } You call it like so: echo subst('The %(site)s site %(adj)s because it %(adj)s', array('site'=>'Stackoverflow', 'adj'=>'rocks')); A: @Marius I don't know if it's faster, but you can do it without regexes: function subst($str, $dict) { foreach ($dict AS $key, $value) { $str = str_replace($key, $value, $str); } return $str; } A: Some of the user-contributed notes and functions in PHP's documentation for sprintf come quite close. Note: search the page for "sprintf2".
Does PHP have an equivalent to this type of Python string substitution?
Python has this wonderful way of handling string substitutions using dictionaries: >>> 'The %(site)s site %(adj)s because it %(adj)s' % {'site':'Stackoverflow', 'adj':'rocks'} 'The Stackoverflow site rocks because it rocks' I love this because you can specify a value once in the dictionary and then replace it all over the place in the string. I've tried to achieve something similar in PHP using various string replace functions but everything I've come up with feels awkward. Does anybody have a nice clean way to do this kind of string substitution in PHP? Edit Here's the code from the sprintf page that I liked best. <?php function sprintf3($str, $vars, $char = '%') { $tmp = array(); foreach($vars as $k => $v) { $tmp[$char . $k . $char] = $v; } return str_replace(array_keys($tmp), array_values($tmp), $str); } echo sprintf3( 'The %site% site %adj% because it %adj%', array('site'=>'Stackoverflow', 'adj'=>'rocks')); ?>
[ "function subst($str, $dict){\n return preg_replace(array_map(create_function('$a', 'return \"/%\\\\($a\\\\)s/\";'), array_keys($dict)), array_values($dict), $str);\n }\n\nYou call it like so:\necho subst('The %(site)s site %(adj)s because it %(adj)s', array('site'=>'Stackoverflow', 'adj'=>'rocks'));\n\n", "@Marius\nI don't know if it's faster, but you can do it without regexes:\nfunction subst($str, $dict)\n{\n foreach ($dict AS $key, $value)\n {\n $str = str_replace($key, $value, $str);\n }\n\n return $str;\n}\n\n", "Some of the user-contributed notes and functions in PHP's documentation for sprintf come quite close.\nNote: search the page for \"sprintf2\".\n" ]
[ 5, 4, 1 ]
[]
[]
[ "php", "python", "string" ]
stackoverflow_0000028165_php_python_string.txt
Q: Comparing two XML Schemas Are there any tools to effectively compare two XML schema's? I have seen some generic XML diff tools, but I was wondering if there is anything that knows more about schemas. A: I would look into DeltaXML. It seems to have the features you're looking for. They even have a guide on how to compare schemas.
Comparing two XML Schemas
Are there any tools to effectively compare two XML schema's? I have seen some generic XML diff tools, but I was wondering if there is anything that knows more about schemas.
[ "I would look into DeltaXML. It seems to have the features you're looking for. They even have a guide on how to compare schemas.\n" ]
[ 6 ]
[]
[]
[ "comparison", "xml", "xsd" ]
stackoverflow_0000028433_comparison_xml_xsd.txt