content
stringlengths
86
88.9k
title
stringlengths
0
150
question
stringlengths
1
35.8k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
30
130
Q: Clean builds in continuous integration We use a CruiseControl.Net/NAnt/Subversion stack for CI. Doing a fresh checkout for every build is way too time-consuming, so currently we just do an update on a working copy. However, this leaves the possibility that orphaned files may remain in the working copy, after being deleted in source control. We have tried using the NAnt delete task just to remove all code source files before an update, but this can corrupt the working copy. Does anyone know a fast way to run a build on a clean and up-to-date working copy? EDIT: We are on SVN 1.3.2 A: If you do just 'update', SVN will delete all the files that were deleted in the source control. However files that were created during build process might still be there and might interfere with new build. I'm not sure if SVN has a command to delete them but I guess you could do that with a little script, SVN definitely could tell you which files are under source control and which aren't. A: We had a similar issue with our CC implementation. Our solution... We had already crafted a 3:00 AM nightly build that executed longer running integration tests in addition to the base unit tests. We simply decided to make that 3:00 AM build a fully clean build on a fresh tree. As it was the middle of the night, it rarely affected anyone. All other "normal" check-ins ran incremental builds. A: If there are orphaned files left in your working copy having done an svn update then there's a bug in your Subversion version. A: You might do a daily full build, and leave the build on check-in as is. Also, for deployment builds, it is probably a good idea to always use a clean complete build. A: The only way I can think of is having two copies on the build server. First you update on the first location. You delete the second location. Copy first to second and then build in the second location. That way you always start from a clean build. You might want to look at why your checkout is taking so long. I've used the same buildserver stack and never had problems with this. Subversion usually took less time than the build itself.
Clean builds in continuous integration
We use a CruiseControl.Net/NAnt/Subversion stack for CI. Doing a fresh checkout for every build is way too time-consuming, so currently we just do an update on a working copy. However, this leaves the possibility that orphaned files may remain in the working copy, after being deleted in source control. We have tried using the NAnt delete task just to remove all code source files before an update, but this can corrupt the working copy. Does anyone know a fast way to run a build on a clean and up-to-date working copy? EDIT: We are on SVN 1.3.2
[ "If you do just 'update', SVN will delete all the files that were deleted in the source control. However files that were created during build process might still be there and might interfere with new build. I'm not sure if SVN has a command to delete them but I guess you could do that with a little script, SVN definitely could tell you which files are under source control and which aren't.\n", "We had a similar issue with our CC implementation. \nOur solution... We had already crafted a 3:00 AM nightly build that executed longer running integration tests in addition to the base unit tests. We simply decided to make that 3:00 AM build a fully clean build on a fresh tree. As it was the middle of the night, it rarely affected anyone. All other \"normal\" check-ins ran incremental builds.\n", "If there are orphaned files left in your working copy having done an svn update then there's a bug in your Subversion version.\n", "You might do a daily full build, and leave the build on check-in as is. Also, for deployment builds, it is probably a good idea to always use a clean complete build.\n", "The only way I can think of is having two copies on the build server. First you update on the first location. You delete the second location. Copy first to second and then build in the second location. That way you always start from a clean build.\nYou might want to look at why your checkout is taking so long. I've used the same buildserver stack and never had problems with this. Subversion usually took less time than the build itself.\n" ]
[ 5, 3, 1, 1, 1 ]
[]
[]
[ "cruisecontrol.net", "nant", "svn" ]
stackoverflow_0000092329_cruisecontrol.net_nant_svn.txt
Q: Working with .qr2 reports in .NET? We use an ERP that has a bunch of reports in QuickReport format (.qr2). From what I could search, Quickreports has an interface for Delphi but not for .NET. Anyone know if there's a (preferably free/OSS) solution for converting .qr2 reports to something I could work with in C#? Or a component for reading these reports directly? A: There is a .NET version of QuickReports supported in Delphi 2005 and Delphi 2006. You have to get the (non-free) "professional" version of QuickReports to get the .NET support, however. It's not included in the "standard" edition. Delphi 2005 and Delphi 2006 both support C#, but I have never tried the .NET version of QuickReports, with either Delphi for .NET or C#. I can't tell you how well it works. Also, Qsoft is planning to release a C# version of their tool, though it appears to be behind schedule.
Working with .qr2 reports in .NET?
We use an ERP that has a bunch of reports in QuickReport format (.qr2). From what I could search, Quickreports has an interface for Delphi but not for .NET. Anyone know if there's a (preferably free/OSS) solution for converting .qr2 reports to something I could work with in C#? Or a component for reading these reports directly?
[ "There is a .NET version of QuickReports supported in Delphi 2005 and Delphi 2006. You have to get the (non-free) \"professional\" version of QuickReports to get the .NET support, however. It's not included in the \"standard\" edition. Delphi 2005 and Delphi 2006 both support C#, but I have never tried the .NET version of QuickReports, with either Delphi for .NET or C#. I can't tell you how well it works.\nAlso, Qsoft is planning to release a C# version of their tool, though it appears to be behind schedule.\n" ]
[ 2 ]
[]
[]
[ ".net", "quickreports", "reporting" ]
stackoverflow_0000089221_.net_quickreports_reporting.txt
Q: MS SQL Server 2005 - How to Auto Increment a field (not primary key) I would like to automatically increment a field named `incrementID' anytime any field in any row within the table named 'tb_users' is updated. Currently I am doing it via the sql update statement. i.e "UPDATE tb_users SET name = @name, incrementID = incrementID + 1 .....WHERE id = @id; I'm wondering how I can do this automatically. for example, by changing the way sql server treats the field - kind of like the increment setting of 'Identity'. Before I update a row, I wish to check whether the incrementID of the object to be updated is different to the incrementID of the row of the db. A: Columns in the Table can have an Identity Specification set. Simply expand the node in the property window and fill in the details (Is Identity, Increment, Seed). The IDENTITYCOL keyword can be used for operations on Identity Specifications. A: You could use a trigger for this (if I've read you correctly and you want the value incremented each time you update the row). A: If you just need to know that it changed, rather than specifically that this is a later version or how many changes there have been, consider using a rowversion column. A: This trigger should do the trick: create trigger update_increment for update as if not update(incrementID) UPDATE tb_users SET incrementID = incrementID + 1 from inserted WHERE tb_users.id = inserted.id
MS SQL Server 2005 - How to Auto Increment a field (not primary key)
I would like to automatically increment a field named `incrementID' anytime any field in any row within the table named 'tb_users' is updated. Currently I am doing it via the sql update statement. i.e "UPDATE tb_users SET name = @name, incrementID = incrementID + 1 .....WHERE id = @id; I'm wondering how I can do this automatically. for example, by changing the way sql server treats the field - kind of like the increment setting of 'Identity'. Before I update a row, I wish to check whether the incrementID of the object to be updated is different to the incrementID of the row of the db.
[ "Columns in the Table can have an Identity Specification set. Simply expand the node in the property window and fill in the details (Is Identity, Increment, Seed).\nThe IDENTITYCOL keyword can be used for operations on Identity Specifications.\n", "You could use a trigger for this (if I've read you correctly and you want the value incremented each time you update the row).\n", "If you just need to know that it changed, rather than specifically that this is a later version or how many changes there have been, consider using a rowversion column.\n", "This trigger should do the trick:\ncreate trigger update_increment for update as\nif not update(incrementID) \n UPDATE tb_users SET incrementID = incrementID + 1 \n from inserted WHERE tb_users.id = inserted.id\n\n" ]
[ 4, 2, 2, 2 ]
[]
[]
[ "sql_server" ]
stackoverflow_0000091628_sql_server.txt
Q: How can I use classes from VisualBasic-Express in VBA for Excel or Access projects? I saved my VB-Express code as .dll and registered it with regasm and made a .tlb file. But when I try to run a function from it in an Excel-modul I get: Run-time error ‘453’: Can’t find DLL entry point RegisterServiceProcess in kernel32 What step did I miss? A: See http://richnewman.wordpress.com/2007/04/15/a-beginner’s-guide-to-calling-a-net-library-from-excel/ or better still try out ExcelDNA ( http://groups.google.com/group/ExcelDna ) A: I think you're creating a .Net dll and trying to call it from a COM-oriented environment (VBA), which isn't going to work without help. If I'm guessing right, then you need to investigate the COM Interop elements of .Net: Google throws up lots of promising-looking links, one of which is this article. It looks a bit unpleasant, but I expect the nastiness can be tucked away somewhere... A: Try this Microsoft Knowledge Base article: Can't Run Macro That Calls 16-bit DLL in 32-bit MS Excel. Do you have the proper rights to access the DLL? A: Thanks for the input to everybody, you helped me a big step further. After following the guides you provided I got: Run-time error: '-2147024894' (80070002)': File or assembly name AssemblyName, or one of its dependencies, was not found. But I could fix that with this Workaround.
How can I use classes from VisualBasic-Express in VBA for Excel or Access projects?
I saved my VB-Express code as .dll and registered it with regasm and made a .tlb file. But when I try to run a function from it in an Excel-modul I get: Run-time error ‘453’: Can’t find DLL entry point RegisterServiceProcess in kernel32 What step did I miss?
[ "See http://richnewman.wordpress.com/2007/04/15/a-beginner’s-guide-to-calling-a-net-library-from-excel/ \nor better still try out ExcelDNA ( http://groups.google.com/group/ExcelDna )\n", "I think you're creating a .Net dll and trying to call it from a COM-oriented environment (VBA), which isn't going to work without help. If I'm guessing right, then you need to investigate the COM Interop elements of .Net: Google throws up lots of promising-looking links, one of which is this article.\nIt looks a bit unpleasant, but I expect the nastiness can be tucked away somewhere...\n", "Try this Microsoft Knowledge Base article: Can't Run Macro That Calls 16-bit DLL in 32-bit MS Excel.\nDo you have the proper rights to access the DLL?\n", "Thanks for the input to everybody, you helped me a big step further.\nAfter following the guides you provided I got: Run-time error: '-2147024894' (80070002)': File or assembly name AssemblyName, or one of its dependencies, was not found.\nBut I could fix that with this Workaround.\n" ]
[ 2, 1, 0, 0 ]
[]
[]
[ "com_interop", "dll", "excel", "vba" ]
stackoverflow_0000086027_com_interop_dll_excel_vba.txt
Q: Entity Framework - Can you map the result type of an imported stored procedure to a custom entity type? I already have an entity model in a separate dll that contains various objects that I need to use. I don't really want to create or duplicate entities using the EF designer. Instead I would like to configure it so that when I call a stored procedure it will map certain columns to specific properties. I know you can do something VERY close to this using a custom DataContext in LinqToSql. The problem is you can't assign columns to complex property types. For example: I might have a columns returned that contain the address for a user. I would like to store the address details for the user in an Address object that is a property of a User object. So, Column STREET should map to User.Address.Street. Any ideas? A: There are a couple of options here. You can create a "Complex Type" and map that to the procedure result. However, you have to do that in your EDMX; it's not supported by the designer. Read this article for details. Note that Complex Types are not entity types per se, so this may or may not fit your needs. But you can find examples for stored procs which use "Address". You can change the visibility of your procedure to private, and then write a public interface for it in any manually-written partial class file which does the mapping that you want. Or just overload the procedure.
Entity Framework - Can you map the result type of an imported stored procedure to a custom entity type?
I already have an entity model in a separate dll that contains various objects that I need to use. I don't really want to create or duplicate entities using the EF designer. Instead I would like to configure it so that when I call a stored procedure it will map certain columns to specific properties. I know you can do something VERY close to this using a custom DataContext in LinqToSql. The problem is you can't assign columns to complex property types. For example: I might have a columns returned that contain the address for a user. I would like to store the address details for the user in an Address object that is a property of a User object. So, Column STREET should map to User.Address.Street. Any ideas?
[ "There are a couple of options here.\n\nYou can create a \"Complex Type\" and map that to the procedure result. However, you have to do that in your EDMX; it's not supported by the designer. Read this article for details. Note that Complex Types are not entity types per se, so this may or may not fit your needs. But you can find examples for stored procs which use \"Address\".\nYou can change the visibility of your procedure to private, and then write a public interface for it in any manually-written partial class file which does the mapping that you want. Or just overload the procedure.\n\n" ]
[ 1 ]
[]
[]
[ "c#", "entity_framework", "linq_to_sql", "orm" ]
stackoverflow_0000089950_c#_entity_framework_linq_to_sql_orm.txt
Q: Has anyone migrated from Struts 1 to another web framework? On my current project, we've been using Struts 1 for the last few years, and ... ahem ... Struts is showing its age. We're slowly migrating our front-end code to an Ajax client that consumes XML from the servers. I'm wondering if any of you have migrated a legacy Struts application to a different framework, and what challenges you faced in doing so. A: Sure. Moving from Struts to an AJAX framework is a very liberating experience. (Though we used JSON rather than XML. Much easier to parse.) However, you need to be aware that it's effectively a full rewrite of your application. Instead of the classic Database/JSP/Actions scheme for MVC, you'll find yourself moving to a Servlet/Javascript scheme whereby the model is represented by HTTP GET requests, actions are represented by POST/PUT/DELETE requests, and the view is rendered on the fly by the web browser. This leads to interesting challenges in each area: Server Side - On the server side you will need to develop a standard for exposing data to the client. The simplest and easiest method is to adopt a REST methodology that best matches your data's hierarchy. This is fairly simple to implement with servlets, but Sun also has developed a Java 1.6 scheme using attributes that looks pretty cool. Another aspect of the server side is to choose a transmission protocol. I know you mentioned XML already, but you might want to reconsider. XML parsers vary greatly between browsers. One browser might make the document root the first child, another one might add a special content object, and they all parse whitespace differently. Even worse, the normalize() function doesn't seem to be correctly implemented by the major browsers. Which means that XML parsing is liable to be full of hacks. JSON is much easier to parse and more consistent in its results. Javascript and Actionscript (Flash) can both translate JSON directly to objects. This makes accessing the data a simple matter of x.y or x[y]. There are also plenty of APIs to handle JSON in every language imaginable. Because it's so easy to parse, it's almost supported BETTER than XML! Client Side - The first issue you're going to run into is the fact that no one understands how to write Javascript. ESPECIALLY those who think they do. If you have any books on Javascript, throw them out the window NOW. There are practically no good books on the language as they all follow the same "hacking" pattern without really diving into what they are doing. From the lowest level, your team is going to need remedial training on Javascript development. Start with the Javascript Client Guide. It's the de facto source of information on the language. The next stop is Douglas Crockford's videos on Javascript. I don't agree with everything he has to say, but he's one of the few experts on the language. Once you've got that down, consider what frameworks, if any, you want to use. Generally speaking, I dislike stuff like Prototype and Mootools. They tend to take a simple problem and make it worse. None the less, you can feel free to evaluate these tools and decide if they'll work for you. If you absolutely feel that you cannot live without a framework because your team is too inexperienced, then GWT might fit the bill. GWT allows you to quickly write DHTML web apps in Java code, then compile them to Javascript. The PROBLEM is that you're giving up massive amounts of flexibility by doing this. The Javascript language is far more powerful than GWT exposes. However, GWT does let Java developers get up to speed faster. So pick your battles. Those are the key areas I can think of. I can say that you'll heave a sigh of relief once you get struts out of your application. It can be a bit of a beast. Especially if you've had inexperienced developers working on your Struts model. :-) Any questions? Edit 1: I forgot to add that your team should study the W3C specs religiously. These are the APIs available to you in modern browsers. If you catch anyone using the DOM 0 APIs (e.g. document.forms['myform'].blah.value instead of document.getElementById("blah").value) force them to transcribe the entire DOM 1 specification until they understand it top to bottom. Edit 2: Another key issue to consider is how to document your fancy new AJAX application. REST style interfaces lend themselves well to being documented in a Wiki. What I did was a had a top level page that listed each of the services and a description. By clicking on the service path, you would be taken to a document with detailed information on each of the sub-paths. In theory, this scheme can document as deep as you need the tree to go. If you go with JSON, you will need to develop a scheme to document the objects. I just listed out the possible properties in the Wiki as documentation. That works well for simple object trees, but can get complex with larger, more sophisticated objects. You can consider supplementing with something like IDL or WebIDL in that case. (Can't be much worse than XML DTDs and Schemas. ;-)) The DHTML code is a bit more classical in its documentation. You can use a tool like JSDoc to create JavaDoc-style documentation. There's just one caveat. Javascript code does not lend itself well to being documented in-code. If for no other reason that the fact that it bloats the download. However, you may find yourself regularly writing code that operates as a cohesive object, but is not coded behind the scenes as such an object. Thus the best solution is to create JSDoc skeleton files that represent and document the Javascript objects. If you're using GWT, documentation should be a no-brainer. A: Check out the Stripes Framework. If you are familiar with struts then stripes will make sense to you, but it's so much better. They have a Stripes vs Struts section on their website. You could check that out and see if it interests you. It allows you to work with any ajax framework you want, and I don't think it would take long to migrate from struts to stripes.
Has anyone migrated from Struts 1 to another web framework?
On my current project, we've been using Struts 1 for the last few years, and ... ahem ... Struts is showing its age. We're slowly migrating our front-end code to an Ajax client that consumes XML from the servers. I'm wondering if any of you have migrated a legacy Struts application to a different framework, and what challenges you faced in doing so.
[ "Sure. Moving from Struts to an AJAX framework is a very liberating experience. (Though we used JSON rather than XML. Much easier to parse.) However, you need to be aware that it's effectively a full rewrite of your application. \nInstead of the classic Database/JSP/Actions scheme for MVC, you'll find yourself moving to a Servlet/Javascript scheme whereby the model is represented by HTTP GET requests, actions are represented by POST/PUT/DELETE requests, and the view is rendered on the fly by the web browser. This leads to interesting challenges in each area:\nServer Side - On the server side you will need to develop a standard for exposing data to the client. The simplest and easiest method is to adopt a REST methodology that best matches your data's hierarchy. This is fairly simple to implement with servlets, but Sun also has developed a Java 1.6 scheme using attributes that looks pretty cool. \nAnother aspect of the server side is to choose a transmission protocol. I know you mentioned XML already, but you might want to reconsider. XML parsers vary greatly between browsers. One browser might make the document root the first child, another one might add a special content object, and they all parse whitespace differently. Even worse, the normalize() function doesn't seem to be correctly implemented by the major browsers. Which means that XML parsing is liable to be full of hacks.\nJSON is much easier to parse and more consistent in its results. Javascript and Actionscript (Flash) can both translate JSON directly to objects. This makes accessing the data a simple matter of x.y or x[y]. There are also plenty of APIs to handle JSON in every language imaginable. Because it's so easy to parse, it's almost supported BETTER than XML!\nClient Side - The first issue you're going to run into is the fact that no one understands how to write Javascript. ESPECIALLY those who think they do. If you have any books on Javascript, throw them out the window NOW. There are practically no good books on the language as they all follow the same \"hacking\" pattern without really diving into what they are doing. \nFrom the lowest level, your team is going to need remedial training on Javascript development. Start with the Javascript Client Guide. It's the de facto source of information on the language. The next stop is Douglas Crockford's videos on Javascript. I don't agree with everything he has to say, but he's one of the few experts on the language.\nOnce you've got that down, consider what frameworks, if any, you want to use. Generally speaking, I dislike stuff like Prototype and Mootools. They tend to take a simple problem and make it worse. None the less, you can feel free to evaluate these tools and decide if they'll work for you.\nIf you absolutely feel that you cannot live without a framework because your team is too inexperienced, then GWT might fit the bill. GWT allows you to quickly write DHTML web apps in Java code, then compile them to Javascript. The PROBLEM is that you're giving up massive amounts of flexibility by doing this. The Javascript language is far more powerful than GWT exposes. However, GWT does let Java developers get up to speed faster. So pick your battles.\nThose are the key areas I can think of. I can say that you'll heave a sigh of relief once you get struts out of your application. It can be a bit of a beast. Especially if you've had inexperienced developers working on your Struts model. :-)\nAny questions?\nEdit 1: I forgot to add that your team should study the W3C specs religiously. These are the APIs available to you in modern browsers. If you catch anyone using the DOM 0 APIs (e.g. document.forms['myform'].blah.value instead of document.getElementById(\"blah\").value) force them to transcribe the entire DOM 1 specification until they understand it top to bottom.\nEdit 2: Another key issue to consider is how to document your fancy new AJAX application. REST style interfaces lend themselves well to being documented in a Wiki. What I did was a had a top level page that listed each of the services and a description. By clicking on the service path, you would be taken to a document with detailed information on each of the sub-paths. In theory, this scheme can document as deep as you need the tree to go.\nIf you go with JSON, you will need to develop a scheme to document the objects. I just listed out the possible properties in the Wiki as documentation. That works well for simple object trees, but can get complex with larger, more sophisticated objects. You can consider supplementing with something like IDL or WebIDL in that case. (Can't be much worse than XML DTDs and Schemas. ;-))\nThe DHTML code is a bit more classical in its documentation. You can use a tool like JSDoc to create JavaDoc-style documentation. There's just one caveat. Javascript code does not lend itself well to being documented in-code. If for no other reason that the fact that it bloats the download. However, you may find yourself regularly writing code that operates as a cohesive object, but is not coded behind the scenes as such an object. Thus the best solution is to create JSDoc skeleton files that represent and document the Javascript objects.\nIf you're using GWT, documentation should be a no-brainer. \n", "Check out the Stripes Framework. If you are familiar with struts then stripes will make sense to you, but it's so much better. They have a Stripes vs Struts section on their website. You could check that out and see if it interests you. It allows you to work with any ajax framework you want, and I don't think it would take long to migrate from struts to stripes. \n" ]
[ 7, 2 ]
[]
[]
[ "ajax", "java", "struts" ]
stackoverflow_0000090078_ajax_java_struts.txt
Q: session variable mixup in ASP.NET? Is it possible for ASP.NET to mix up which user is associated with which session variable on the server? Are session variables immutably tied to the original user that created them across time, space & dimension? A: It depends on your session provider, if you have overriden the session key generation in a way that is no longer unique, then multiple users may be accessing the same session. What behavior are you seeing? And are you sure there's no static in play with the variables you are talking about? A: To answer your original question: Sessions are keyed to an id that is placed in a cookie. This id is generated using some random number crypto routines. It is not guaranteed to be unique but it is highly unlikely that it will ever be duplicated in the span of the life of a session. Even if your sessions run for full work days. It would probably take years for a really popular site to even generate a duplicate key (No stats or facts to back that up). Having said all that it doesn't appear that your problem is with session values getting mixed up. The first thing that I would start to look at is connection pooling. ADO pools connections by default but if you request a connection with a username/password that is not in the pool it should give you a new connection. Hint that may be a performance bottleneck in the future if your site is very large. It has been a while since I worked with SQL Server, in Oracle there is a call that can be made to switch the identity of the user. I would be surprised if there was no equivalent in SQL Server. You might try connecting to your DB with a generic username/password and then executing that identity switch call before you hand back the connection to the rest of your code. A: while anything is possible. . . . No, unless you are storing session state in sql server or some other out of process storage and then messing with it. . . A: The session is bound to a user cookie, the chances of that messing up in a normal scenario is very unlikely, however there could be issues if using distributed session state. A: It's not possible. Sessions are tied to the creator. Do you want to mix up, or do you have a case when it looks like mixed up? A: More information: I've got an app that takes the userid/password from the login page and stores it in a session variable. I plop it into my connection string for making calls to SQL Server. When a table gets updated, we're using 'system_user' in the database to identify the 'last updated by' user. We're seeing some odd behavior in which the user we're expecting to be listed is incorrect, and it's showing someone else. A: Can you pop in the debugger and see if the correct value is indeed being passed on that connection string? It would quickly help you idenfity which side the problem is on. Also make sure that none of the connection code has static properties for connection or user, or one user may have their connection replaced with that of the most recent user before the update fires off. A: My guess is that you're re-using a static field on a class to hold the connection string. Those static fields are re-used across multiple IIS requests so you're probably only ever seeing the most recently logged in user in the 'last updated by'. BTW, unless you have a REALLY good reason for doing so then you shouldn't be connecting to the DB like this. You're preventing yourself from using connection pooling which is going to hurt performance under high loads.
session variable mixup in ASP.NET?
Is it possible for ASP.NET to mix up which user is associated with which session variable on the server? Are session variables immutably tied to the original user that created them across time, space & dimension?
[ "It depends on your session provider, if you have overriden the session key generation in a way that is no longer unique, then multiple users may be accessing the same session. \nWhat behavior are you seeing? And are you sure there's no static in play with the variables you are talking about?\n", "To answer your original question: Sessions are keyed to an id that is placed in a cookie. This id is generated using some random number crypto routines. It is not guaranteed to be unique but it is highly unlikely that it will ever be duplicated in the span of the life of a session. Even if your sessions run for full work days. It would probably take years for a really popular site to even generate a duplicate key (No stats or facts to back that up).\nHaving said all that it doesn't appear that your problem is with session values getting mixed up. The first thing that I would start to look at is connection pooling. ADO pools connections by default but if you request a connection with a username/password that is not in the pool it should give you a new connection. Hint that may be a performance bottleneck in the future if your site is very large. It has been a while since I worked with SQL Server, in Oracle there is a call that can be made to switch the identity of the user. I would be surprised if there was no equivalent in SQL Server. You might try connecting to your DB with a generic username/password and then executing that identity switch call before you hand back the connection to the rest of your code.\n", "while anything is possible. . . .\nNo, unless you are storing session state in sql server or some other out of process storage and then messing with it. . .\n", "The session is bound to a user cookie, the chances of that messing up in a normal scenario is very unlikely, however there could be issues if using distributed session state.\n", "It's not possible. Sessions are tied to the creator.\nDo you want to mix up, or do you have a case when it looks like mixed up?\n", "More information:\nI've got an app that takes the userid/password from the login page and stores it in a session variable. I plop it into my connection string for making calls to SQL Server. \nWhen a table gets updated, we're using 'system_user' in the database to identify the 'last updated by' user. We're seeing some odd behavior in which the user we're expecting to be listed is incorrect, and it's showing someone else. \n", "Can you pop in the debugger and see if the correct value is indeed being passed on that connection string? It would quickly help you idenfity which side the problem is on. \nAlso make sure that none of the connection code has static properties for connection or user, or one user may have their connection replaced with that of the most recent user before the update fires off.\n", "My guess is that you're re-using a static field on a class to hold the connection string. Those static fields are re-used across multiple IIS requests so you're probably only ever seeing the most recently logged in user in the 'last updated by'.\nBTW, unless you have a REALLY good reason for doing so then you shouldn't be connecting to the DB like this. You're preventing yourself from using connection pooling which is going to hurt performance under high loads.\n" ]
[ 2, 2, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "asp.net", "session", "variables" ]
stackoverflow_0000092052_asp.net_session_variables.txt
Q: Multiple web-sites running in IIS simulatenously At work, we have multiple branches that we may be working on at any time. Our solution so far as been to create multiple web-sites but you can only run one web-site at a time. This makes switching between branches more of a pain that in should be. I just want to go to the URL, mapped in my hosts file, for that branch and it just work. Our client machines are XP machines with IIS 5.1. Is there any way to make IIS 5.1 run more than one web-site simultaneously? A: Yes, it is a restriction and this one website can have only 10 simultanious connections. Buy a Windows 2003 or 2008 Small Business Edition, it is quite cost-effective in this scenario. A: Are virtual directories an option for you? I run multiple versions of the same website this way. A: I believe it is a restriction of IIS that you can only run more than one website on server versions of the windows OS. A: Oddly enough, this is something I remember Jeff covering ages ago, but I guess it's still relevant if you're on IIS 5.1: http://www.codinghorror.com/blog/archives/000329.html A: One way you could solve this without reinstalling your computer is to create each branch in a virtual subdirectory under you current web-root. Then at the top-level website, create a default.asp(x) the reads Request.ServerVariables["SERVER-NAME"] (should be underscore) and redirects the browser to whatever virtual directory/application you want to access. That way you can create all the "virtual" domains you want in your hosts file. A: With Windows XP and IIS 5.1 you cannot run moultiple web sites. You can however run multiple ASP.NET hosts. You would probably have to write the host your self. Something like this should get you started: string FileLoction = "..Path to the branch.."; HttpListenerWrapper lw = (HttpListenerWrapper)ApplicationHost.CreateApplicationHost( typeof(HttpListenerWrapper), "/", FileLocation); string[] prefixes = new string[] { "http://localhost:8081/", "http://127.0.0.1:8081/" }; lw.Configure(prefixes, "/", FileLocation); lw.Start(); A: Picking up on Biri's answer rather than choose SBS there is a specific Windows Server Web edition which is the cheapest of all, around $399 and doesn't require CALs. Otherwise, if it's just for developer machines Vista Ultimate allows multiple IIS sites hosted simultaneously.
Multiple web-sites running in IIS simulatenously
At work, we have multiple branches that we may be working on at any time. Our solution so far as been to create multiple web-sites but you can only run one web-site at a time. This makes switching between branches more of a pain that in should be. I just want to go to the URL, mapped in my hosts file, for that branch and it just work. Our client machines are XP machines with IIS 5.1. Is there any way to make IIS 5.1 run more than one web-site simultaneously?
[ "Yes, it is a restriction and this one website can have only 10 simultanious connections.\nBuy a Windows 2003 or 2008 Small Business Edition, it is quite cost-effective in this scenario.\n", "Are virtual directories an option for you? I run multiple versions of the same website this way.\n", "I believe it is a restriction of IIS that you can only run more than one website on server versions of the windows OS.\n", "Oddly enough, this is something I remember Jeff covering ages ago, but I guess it's still relevant if you're on IIS 5.1:\nhttp://www.codinghorror.com/blog/archives/000329.html\n", "One way you could solve this without reinstalling your computer is to create each branch in a virtual subdirectory under you current web-root. Then at the top-level website, create a default.asp(x) the reads Request.ServerVariables[\"SERVER-NAME\"] (should be underscore) and redirects the browser to whatever virtual directory/application you want to access. That way you can create all the \"virtual\" domains you want in your hosts file.\n", "With Windows XP and IIS 5.1 you cannot run moultiple web sites.\nYou can however run multiple ASP.NET hosts. You would probably have to write the host your self.\nSomething like this should get you started:\n\nstring FileLoction = \"..Path to the branch..\";\nHttpListenerWrapper lw = (HttpListenerWrapper)ApplicationHost.CreateApplicationHost(\n typeof(HttpListenerWrapper), \"/\", FileLocation);\n\nstring[] prefixes = new string[] \n{\n \"http://localhost:8081/\",\n \"http://127.0.0.1:8081/\"\n};\n\nlw.Configure(prefixes, \"/\", FileLocation);\nlw.Start();\n\n", "Picking up on Biri's answer rather than choose SBS there is a specific Windows Server Web edition which is the cheapest of all, around $399 and doesn't require CALs.\nOtherwise, if it's just for developer machines Vista Ultimate allows multiple IIS sites hosted simultaneously.\n" ]
[ 3, 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "iis" ]
stackoverflow_0000034301_iis.txt
Q: What's the best way to serialize a HashTable for SOAP/XML? What's the best way to serialize a HashTable (or a data best navigated through a string indexer) with SOAP/XML? Let's say I have a Foo that has an property Bar[] Bars. A Bar object has a key and a value. By default, this serializes to the following XML: <Foo> <Bars> <Bar key="key0" value="value0"/> ... </Bars> </Foo> For JSON, this serializes to: {"Foo":["Bars":[{"Key":"key0","Value":"key1} ... ]}]} What I'd really like to have is this serialize to better reflect the underlying relationship. E.g., <Foo> <Bars> <Key0 value="value0"/> <Key1 value="value1"/> ... </Bars> </Foo> I realize there are some challenges with serializing to SOAP in this way, but what's the best approach to providing a schema that better reflects this? I've tried creating a BarsCollection object and defining custom serialization on that, but it doesn't seem to actually invoke the serialization on that object. E.g. void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { foreach (Bar bar in Bars){ info.AddValue(bar.Key. bar); } } Any suggestions? What's the best practice here? A: I really don't think that what you want reflects the structure better. To define a schema (think XSD) for this you would have to know all of the potential keys in advance since you indicate that you want each one to be a separate custom type. Conceptually Bars would be an array of objects holding objects of type Key0, Key1, with each of the KeyN class containing a value property. I believe that the first serialization actually is the best reflection of the underlying structure. The reason it "works" more like you want in JSON is that you lose the typing -- everything is just an object. If you don't care about the types why not just use JSON? A: ISerializable isn't used for xml serialization; its used for binary serialization. You would be better implementing IXmlSerializable. But I think that the KeyedCollection serializes more like you're thinking. Except you'll never get <key0 ... /> <key1 ... /> since the elements map to classes. A: You could pass the hashtable in a SOAP Extension. That way, you can serialize it whichever way you would like. Although there is custom code for this that has to be on the client and server. A: I think you're missing a fundamental key of the SOAP protocol. One of the things I really like about the SOAP protocol is that you can define arbitrary objects (along with methods) in your WSDL file and pass these objects around from one end to the other using the SOAP protocol. You don't have to serialize the data on one end and then unserialize it on the other end.
What's the best way to serialize a HashTable for SOAP/XML?
What's the best way to serialize a HashTable (or a data best navigated through a string indexer) with SOAP/XML? Let's say I have a Foo that has an property Bar[] Bars. A Bar object has a key and a value. By default, this serializes to the following XML: <Foo> <Bars> <Bar key="key0" value="value0"/> ... </Bars> </Foo> For JSON, this serializes to: {"Foo":["Bars":[{"Key":"key0","Value":"key1} ... ]}]} What I'd really like to have is this serialize to better reflect the underlying relationship. E.g., <Foo> <Bars> <Key0 value="value0"/> <Key1 value="value1"/> ... </Bars> </Foo> I realize there are some challenges with serializing to SOAP in this way, but what's the best approach to providing a schema that better reflects this? I've tried creating a BarsCollection object and defining custom serialization on that, but it doesn't seem to actually invoke the serialization on that object. E.g. void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { foreach (Bar bar in Bars){ info.AddValue(bar.Key. bar); } } Any suggestions? What's the best practice here?
[ "I really don't think that what you want reflects the structure better. To define a schema (think XSD) for this you would have to know all of the potential keys in advance since you indicate that you want each one to be a separate custom type. Conceptually Bars would be an array of objects holding objects of type Key0, Key1, with each of the KeyN class containing a value property. I believe that the first serialization actually is the best reflection of the underlying structure. The reason it \"works\" more like you want in JSON is that you lose the typing -- everything is just an object. If you don't care about the types why not just use JSON?\n", "ISerializable isn't used for xml serialization; its used for binary serialization. You would be better implementing IXmlSerializable.\nBut I think that the KeyedCollection serializes more like you're thinking. Except you'll never get <key0 ... /> <key1 ... /> since the elements map to classes.\n", "You could pass the hashtable in a SOAP Extension. That way, you can serialize it whichever way you would like. Although there is custom code for this that has to be on the client and server.\n", "I think you're missing a fundamental key of the SOAP protocol.\nOne of the things I really like about the SOAP protocol is that you can define arbitrary objects (along with methods) in your WSDL file and pass these objects around from one end to the other using the SOAP protocol. You don't have to serialize the data on one end and then unserialize it on the other end.\n" ]
[ 1, 0, 0, 0 ]
[]
[]
[ ".net", "c#", "serialization", "xml" ]
stackoverflow_0000088682_.net_c#_serialization_xml.txt
Q: WebClient.DownloadFileAsync fails to raise exception An odd issue that I have been trying to address in a project - my calls to WebClient.DownloadFileAsync seem to be getting ignored and no exceptions are being raised. So far I have been able to determine this might be due to destination folder not existing, but from the looks of the MSDN documentation for Webclient.DownloadFileAsync this should still cause an exception to be raised. I did find one MSDN forum thread that seems to imply that this has been known to happen, but there doesn't seem to be any resolution for it. Any ideas what might be going on? A: In an Async method, Exceptions aren't thrown, but rather passed through to the callback in the EventArgs object. A: This issue was resolved after reviewing MSDN and the source code involved. Previously the application was only implementing the DownloadProgressChangedEventHandler to track how much of a download remained. This turned out to be the root cause of the issue as AsyncCompletedEventHandler is what is invoked when an exception occurs and not implementing this event handler leaves you with no notification of errors.
WebClient.DownloadFileAsync fails to raise exception
An odd issue that I have been trying to address in a project - my calls to WebClient.DownloadFileAsync seem to be getting ignored and no exceptions are being raised. So far I have been able to determine this might be due to destination folder not existing, but from the looks of the MSDN documentation for Webclient.DownloadFileAsync this should still cause an exception to be raised. I did find one MSDN forum thread that seems to imply that this has been known to happen, but there doesn't seem to be any resolution for it. Any ideas what might be going on?
[ "In an Async method, Exceptions aren't thrown, but rather passed through to the callback in the EventArgs object.\n", "This issue was resolved after reviewing MSDN and the source code involved. Previously the application was only implementing the DownloadProgressChangedEventHandler to track how much of a download remained. This turned out to be the root cause of the issue as AsyncCompletedEventHandler is what is invoked when an exception occurs and not implementing this event handler leaves you with no notification of errors.\n" ]
[ 2, 2 ]
[]
[]
[ ".net", "webclient" ]
stackoverflow_0000038726_.net_webclient.txt
Q: Limiting results of System.Data.Linq.Table I am trying to inherit from my generated datacontext in LinqToSQL - something like this public class myContext : dbDataContext { public System.Data.Linq.Table<User>() Users { return (from x in base.Users() where x.DeletedOn.HasValue == false select x); } } But my Linq statement returns IQueryable which cannot cast to Table - does anyone know a way to limit the contents of a Linq.Table - I am trying to be certain that anywhere my Users table is accessed, it doesn't return those marked deleted. Perhaps I am going about this all wrong - any suggestions would be greatly appreciated. Hal A: Another approach would to be use views.. CREATE VIEW ActiveUsers as SELECT * FROM Users WHERE IsDeleted = 0 As far as linq to sql is concerned, that is just the same as a table. For any table that you needed the DeletedOn filtering, just create a view that uses the filter and use that in place of the table in your data context. A: You could use discriminator column inheritance on the table, ie. a DeletedUsers table and ActiveUsers table where the discriminator column says which goes to which. Then in your code, just reference the Users.OfType ActiveUsers, which will never include anything deleted. As a side note, how the heck do you do this with markdown? Users.OfType<ActiveUsers> I can get it in code, but not inline A: Encapsulate your DataContext so that developers don't use Table in their queries. I have an 'All' property on my repositories that does a similar filtering to what you need. So then queries are like: from item in All where ... select item and all might be: public IQueryable<T> All { get { return MyDataContext.GetTable<T>.Where(entity => !entity.DeletedOn.HasValue); } } A: You can use a stored procedure that returns all the mapped columns in the table for all the records that are not marked deleted, then map the LINQ to SQL class to the stored procedure's results. I think you just drag-drop the stored proc in Server Explorer on to the class in the LINQ to SQL designer. A: What I did in this circumstance is I created a repository class that passes back IQueryable but basically is just from t in _db.Table select t; this is usually referenced by tableRepository.GetAllXXX(); but you could have a tableRepository.GetAllNonDeletedXXX(); that puts in that preliminary where clause to take out the deleted rows. This would allow you to get back the deleted ones, the undeleted ones and all rows using different methods. A: Perhaps my comment to Keven sheffield's response may shed some light on what I am trying to accomplish: I have a similar repository for most of my data access, but I am trying to be able to traverse my relationships and maintain the DeletedOn logic, without actually calling any additional methods. The objects are interrogated (spelling fixed) by a StringTemplate processor which can't call methods (just props/fields). I will ultimately need this DeletedOn filtering for all of the tables in my application. The inherited class solution from Scott Nichols should work (although I will need to derive a class and relationships for around 30 tables - ouch), although I need to figure out how to check for a null value in my Derived Class Discriminator Value property. I may just end up extended all my classes specifically for the StringTemplate processing, explicitly adding properties for the relationships I need, I would just love to be able to throw StringTemplate a [user] and have it walk through everything. A: There are a couple of views we use in associations and they still appear just like any other relationship. We did need to add the associations manually. The only thing I can think to suggest is to take a look at the properties and decorated attributes generated for those classes and associations. Add a couple tables that have the same relationship and compare those to the view that isn't showing up. Also, sometimes the refresh on the server explorer connection doesn't seem to work correctly and the entities aren't created correctly initially, unless we remove them from the designer, close the project, then reopen the project and add them again from the server explorer. This is assuming you are using Visual Studio 2008 with the linq to sql .dbml designer. A: I found the problem that I had with the relationships/associations not showing in the views. It seems that you have to go through each class in the dbml and set a primary key for views as it is unable to extract that information from the schema. I am in the process of setting the primary keys now and am planning to go the view route to isolate only non-deleted items. Thanks and I will update more later.
Limiting results of System.Data.Linq.Table
I am trying to inherit from my generated datacontext in LinqToSQL - something like this public class myContext : dbDataContext { public System.Data.Linq.Table<User>() Users { return (from x in base.Users() where x.DeletedOn.HasValue == false select x); } } But my Linq statement returns IQueryable which cannot cast to Table - does anyone know a way to limit the contents of a Linq.Table - I am trying to be certain that anywhere my Users table is accessed, it doesn't return those marked deleted. Perhaps I am going about this all wrong - any suggestions would be greatly appreciated. Hal
[ "Another approach would to be use views..\nCREATE VIEW ActiveUsers as SELECT * FROM Users WHERE IsDeleted = 0\n\nAs far as linq to sql is concerned, that is just the same as a table. For any table that you needed the DeletedOn filtering, just create a view that uses the filter and use that in place of the table in your data context.\n", "You could use discriminator column inheritance on the table, ie. a DeletedUsers table and ActiveUsers table where the discriminator column says which goes to which. Then in your code, just reference the Users.OfType ActiveUsers, which will never include anything deleted.\nAs a side note, how the heck do you do this with markdown?\nUsers.OfType<ActiveUsers>\n\nI can get it in code, but not inline\n", "Encapsulate your DataContext so that developers don't use Table in their queries. I have an 'All' property on my repositories that does a similar filtering to what you need. So then queries are like:\nfrom item in All\nwhere ...\nselect item\n\nand all might be:\npublic IQueryable<T> All\n{\n get { return MyDataContext.GetTable<T>.Where(entity => !entity.DeletedOn.HasValue); }\n}\n\n", "You can use a stored procedure that returns all the mapped columns in the table for all the records that are not marked deleted, then map the LINQ to SQL class to the stored procedure's results. I think you just drag-drop the stored proc in Server Explorer on to the class in the LINQ to SQL designer.\n", "What I did in this circumstance is I created a repository class that passes back IQueryable but basically is just \n\nfrom t in _db.Table\n select t;\n\nthis is usually referenced by tableRepository.GetAllXXX(); but you could have a tableRepository.GetAllNonDeletedXXX(); that puts in that preliminary where clause to take out the deleted rows. This would allow you to get back the deleted ones, the undeleted ones and all rows using different methods.\n", "Perhaps my comment to Keven sheffield's response may shed some light on what I am trying to accomplish:\n\nI have a similar repository for most\n of my data access, but I am trying to\n be able to traverse my relationships\n and maintain the DeletedOn logic,\n without actually calling any\n additional methods. The objects are\n interrogated (spelling fixed) by a StringTemplate\n processor which can't call methods\n (just props/fields).\n\nI will ultimately need this DeletedOn filtering for all of the tables in my application. The inherited class solution from Scott Nichols should work (although I will need to derive a class and relationships for around 30 tables - ouch), although I need to figure out how to check for a null value in my Derived Class Discriminator Value property.\nI may just end up extended all my classes specifically for the StringTemplate processing, explicitly adding properties for the relationships I need, I would just love to be able to throw StringTemplate a [user] and have it walk through everything.\n", "There are a couple of views we use in associations and they still appear just like any other relationship. We did need to add the associations manually. The only thing I can think to suggest is to take a look at the properties and decorated attributes generated for those classes and associations. \nAdd a couple tables that have the same relationship and compare those to the view that isn't showing up. \nAlso, sometimes the refresh on the server explorer connection doesn't seem to work correctly and the entities aren't created correctly initially, unless we remove them from the designer, close the project, then reopen the project and add them again from the server explorer. This is assuming you are using Visual Studio 2008 with the linq to sql .dbml designer.\n", "I found the problem that I had with the relationships/associations not showing in the views. It seems that you have to go through each class in the dbml and set a primary key for views as it is unable to extract that information from the schema. I am in the process of setting the primary keys now and am planning to go the view route to isolate only non-deleted items.\nThanks and I will update more later.\n" ]
[ 2, 1, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "linq_to_sql" ]
stackoverflow_0000085457_linq_to_sql.txt
Q: How do I preserve line feeds, tabs, and spaces in data while still wrapping text? I had data in XML that had line feeds, spaces, and tabs that I wanted to preserve in the output HTML (so I couldn't use <p>) but I also wanted the lines to wrap when the side of the screen was reached (so I couldn't use <pre>). A: Another way of putting this is that you want to turn all pairs of spaces into two non-breaking spaces, tabs into four non-breaking spaces and all line breaks into <br> elements. In XSLT 1.0, I'd do: <xsl:template name="replace-spaces"> <xsl:param name="text" /> <xsl:choose> <xsl:when test="contains($text, ' ')"> <xsl:call-template name="replace-spaces"> <xsl:with-param name="text" select="substring-before($text, ' ')"/> </xsl:call-template> <xsl:text>&#xA0;&#xA0;</xsl:text> <xsl:call-template name="replace-spaces"> <xsl:with-param name="text" select="substring-before($text, ' ')" /> </xsl:call-template> </xsl:when> <xsl:when test="contains($text, '&#x9;')"> <xsl:call-template name="replace-spaces"> <xsl:with-param name="text" select="substring-before($text, '&#x9;')"/> </xsl:call-template> <xsl:text>&#xA0;&#xA0;&#xA0;&#xA0;</xsl:text> <xsl:call-template name="replace-spaces"> <xsl:with-param name="text" select="substring-before($text, '&#x9;')" /> </xsl:call-template> </xsl:when> <xsl:when test="contains($text, '&#xA;')"> <xsl:call-template name="replace-spaces"> <xsl:with-param name="text" select="substring-before($text, '&#xA;')" /> </xsl:call-template> <br /> <xsl:call-template name="replace-spaces"> <xsl:with-param name="text" select="substring-after($text, '&#xA;')" /> </xsl:call-template> </xsl:when> <xsl:otherwise> <xsl:value-of select="$text" /> </xsl:otherwise> </xsl:choose> </xsl:template> Not being able to use tail recursion is a bit of a pain, but it shouldn't be a real problem unless the text is very long. An XSLT 2.0 solution would use <xsl:analyze-string>. A: I and a co-worker (Patricia Eromosele) came up with the following solution: (Is there a better solution?) <p> <xsl:call-template name="prewrap"> <xsl:with-param name="text" select="text"/> </xsl:call-template> </p> <xsl:template name="prewrap"> <xsl:param name="text" select="."/> <xsl:variable name="spaceIndex" select="string-length(substring-before($text, ' '))"/> <xsl:variable name="tabIndex" select="string-length(substring-before($text, '&#x09;'))"/> <xsl:variable name="lineFeedIndex" select="string-length(substring-before($text, '&#xA;'))"/> <xsl:choose> <xsl:when test="$spaceIndex = 0 and $tabIndex = 0 and $lineFeedIndex = 0"><!-- no special characters left --> <xsl:value-of select="$text"/> </xsl:when> <xsl:when test="$spaceIndex > $tabIndex and $lineFeedIndex > $tabIndex"><!-- tab --> <xsl:value-of select="substring-before($text, '&#x09;')"/> <xsl:text disable-output-escaping="yes">&amp;nbsp;</xsl:text> <xsl:text disable-output-escaping="yes">&amp;nbsp;</xsl:text> <xsl:text disable-output-escaping="yes">&amp;nbsp;</xsl:text> <xsl:text disable-output-escaping="yes">&amp;nbsp;</xsl:text> <xsl:call-template name="prewrap"> <xsl:with-param name="text" select="substring-after($text,'&#x09;')"/> </xsl:call-template> </xsl:when> <xsl:when test="$spaceIndex > $lineFeedIndex and $tabIndex > $lineFeedIndex"><!-- line feed --> <xsl:value-of select="substring-before($text, '&#xA;')"/> <br/> <xsl:call-template name="prewrap"> <xsl:with-param name="text" select="substring-after($text,'&#xA;')"/> </xsl:call-template> </xsl:when> <xsl:when test="$lineFeedIndex > $spaceIndex and $tabIndex > $spaceIndex"><!-- two spaces --> <xsl:value-of select="substring-before($text, ' ')"/> <xsl:text disable-output-escaping="yes">&amp;nbsp;</xsl:text> <xsl:text disable-output-escaping="yes">&amp;nbsp;</xsl:text> <xsl:call-template name="prewrap"> <xsl:with-param name="text" select="substring-after($text,' ')"/> </xsl:call-template> </xsl:when> <xsl:otherwise><!-- should never happen --> <xsl:value-of select="$text"/> </xsl:otherwise> </xsl:choose> </xsl:template> Source: http://jamesjava.blogspot.com/2008/06/xsl-preserving-line-feeds-tabs-and.html A: Really, I'd choose an editor which supports this correctly, rather than wrangling it through more XML. A: Not sure if this relevant, but isn't there a preservespace attribute and whatnot for xml?
How do I preserve line feeds, tabs, and spaces in data while still wrapping text?
I had data in XML that had line feeds, spaces, and tabs that I wanted to preserve in the output HTML (so I couldn't use <p>) but I also wanted the lines to wrap when the side of the screen was reached (so I couldn't use <pre>).
[ "Another way of putting this is that you want to turn all pairs of spaces into two non-breaking spaces, tabs into four non-breaking spaces and all line breaks into <br> elements. In XSLT 1.0, I'd do:\n<xsl:template name=\"replace-spaces\">\n <xsl:param name=\"text\" />\n <xsl:choose>\n <xsl:when test=\"contains($text, ' ')\">\n <xsl:call-template name=\"replace-spaces\">\n <xsl:with-param name=\"text\" select=\"substring-before($text, ' ')\"/>\n </xsl:call-template>\n <xsl:text>&#xA0;&#xA0;</xsl:text>\n <xsl:call-template name=\"replace-spaces\">\n <xsl:with-param name=\"text\" select=\"substring-before($text, ' ')\" />\n </xsl:call-template>\n </xsl:when>\n <xsl:when test=\"contains($text, '&#x9;')\">\n <xsl:call-template name=\"replace-spaces\">\n <xsl:with-param name=\"text\" select=\"substring-before($text, '&#x9;')\"/>\n </xsl:call-template>\n <xsl:text>&#xA0;&#xA0;&#xA0;&#xA0;</xsl:text>\n <xsl:call-template name=\"replace-spaces\">\n <xsl:with-param name=\"text\" select=\"substring-before($text, '&#x9;')\" />\n </xsl:call-template>\n </xsl:when>\n <xsl:when test=\"contains($text, '&#xA;')\">\n <xsl:call-template name=\"replace-spaces\">\n <xsl:with-param name=\"text\" select=\"substring-before($text, '&#xA;')\" />\n </xsl:call-template>\n <br />\n <xsl:call-template name=\"replace-spaces\">\n <xsl:with-param name=\"text\" select=\"substring-after($text, '&#xA;')\" />\n </xsl:call-template>\n </xsl:when>\n <xsl:otherwise>\n <xsl:value-of select=\"$text\" />\n </xsl:otherwise>\n </xsl:choose>\n</xsl:template>\n\nNot being able to use tail recursion is a bit of a pain, but it shouldn't be a real problem unless the text is very long.\nAn XSLT 2.0 solution would use <xsl:analyze-string>.\n", "I and a co-worker (Patricia Eromosele) came up with the following solution: (Is there a better solution?)\n <p> <xsl:call-template name=\"prewrap\"> <xsl:with-param name=\"text\" select=\"text\"/> </xsl:call-template> </p> <xsl:template name=\"prewrap\"> <xsl:param name=\"text\" select=\".\"/> <xsl:variable name=\"spaceIndex\" select=\"string-length(substring-before($text, ' '))\"/> <xsl:variable name=\"tabIndex\" select=\"string-length(substring-before($text, '&#x09;'))\"/> <xsl:variable name=\"lineFeedIndex\" select=\"string-length(substring-before($text, '&#xA;'))\"/> <xsl:choose> <xsl:when test=\"$spaceIndex = 0 and $tabIndex = 0 and $lineFeedIndex = 0\"><!-- no special characters left --> <xsl:value-of select=\"$text\"/> </xsl:when> <xsl:when test=\"$spaceIndex > $tabIndex and $lineFeedIndex > $tabIndex\"><!-- tab --> <xsl:value-of select=\"substring-before($text, '&#x09;')\"/> <xsl:text disable-output-escaping=\"yes\">&amp;nbsp;</xsl:text> <xsl:text disable-output-escaping=\"yes\">&amp;nbsp;</xsl:text> <xsl:text disable-output-escaping=\"yes\">&amp;nbsp;</xsl:text> <xsl:text disable-output-escaping=\"yes\">&amp;nbsp;</xsl:text> <xsl:call-template name=\"prewrap\"> <xsl:with-param name=\"text\" select=\"substring-after($text,'&#x09;')\"/> </xsl:call-template> </xsl:when> <xsl:when test=\"$spaceIndex > $lineFeedIndex and $tabIndex > $lineFeedIndex\"><!-- line feed --> <xsl:value-of select=\"substring-before($text, '&#xA;')\"/> <br/> <xsl:call-template name=\"prewrap\"> <xsl:with-param name=\"text\" select=\"substring-after($text,'&#xA;')\"/> </xsl:call-template> </xsl:when> <xsl:when test=\"$lineFeedIndex > $spaceIndex and $tabIndex > $spaceIndex\"><!-- two spaces --> <xsl:value-of select=\"substring-before($text, ' ')\"/> <xsl:text disable-output-escaping=\"yes\">&amp;nbsp;</xsl:text> <xsl:text disable-output-escaping=\"yes\">&amp;nbsp;</xsl:text> <xsl:call-template name=\"prewrap\"> <xsl:with-param name=\"text\" select=\"substring-after($text,' ')\"/> </xsl:call-template> </xsl:when> <xsl:otherwise><!-- should never happen --> <xsl:value-of select=\"$text\"/> </xsl:otherwise> </xsl:choose> </xsl:template>\nSource: http://jamesjava.blogspot.com/2008/06/xsl-preserving-line-feeds-tabs-and.html\n", "Really, I'd choose an editor which supports this correctly, rather than wrangling it through more XML.\n", "Not sure if this relevant, but isn't there a preservespace attribute and whatnot for xml?\n" ]
[ 1, 0, 0, 0 ]
[]
[]
[ "xslt" ]
stackoverflow_0000087177_xslt.txt
Q: C# Datatype for large sorted collection with position? I am trying to compare two large datasets from a SQL query. Right now the SQL query is done externally and the results from each dataset is saved into its own csv file. My little C# console application loads up the two text/csv files and compares them for differences and saves the differences to a text file. Its a very simple application that just loads all the data from the first file into an arraylist and does a .compare() on the arraylist as each line is read from the second csv file. Then saves the records that don't match. The application works but I would like to improve the performance. I figure I can greatly improve performance if I can take advantage of the fact that both files are sorted, but I don't know a datatype in C# that keeps order and would allow me to select a specific position. Theres a basic array, but I don't know how many items are going to be in each list. I could have over a million records. Is there a data type available that I should be looking at? A: If data in both of your CSV files is already sorted and have the same number of records, you could skip the data structure entirely and do in-place analysis. StreamReader one = new StreamReader("C:\file1.csv"); StreamReader two = new StreamReader("C:\file2.csv"); String lineOne; String lineTwo; StreamWriter differences = new StreamWriter("Output.csv"); while (!one.EndOfStream) { lineOne = one.ReadLine(); lineTwo = two.ReadLine(); // do your comparison. bool areDifferent = true; if (areDifferent) differences.WriteLine(lineOne + lineTwo); } one.Close(); two.Close(); differences.Close(); A: System.Collections.Specialized.StringCollection allows you to add a range of values and, using the .IndexOf(string) method, allows you to retrieve the index of that item. That being said, you could likely just load up a couple of byte[] from a filestream and do byte comparison... don't even worry about loading that stuff into a formal datastructure like StringCollection or string[]; if all you're doing is checking for differences, and you want speed, I would wreckon byte differences are where it's at. A: This is an adaptation of David Sokol's code to work with varying number of lines, outputing the lines that are in one file but not the other: StreamReader one = new StreamReader("C:\file1.csv"); StreamReader two = new StreamReader("C:\file2.csv"); String lineOne; String lineTwo; StreamWriter differences = new StreamWriter("Output.csv"); lineOne = one.ReadLine(); lineTwo = two.ReadLine(); while (!one.EndOfStream || !two.EndOfStream) { if(lineOne == lineTwo) { // lines match, read next line from each and continue lineOne = one.ReadLine(); lineTwo = two.ReadLine(); continue; } if(two.EndOfStream || lineOne < lineTwo) { differences.WriteLine(lineOne); lineOne = one.ReadLine(); } if(one.EndOfStream || lineTwo < lineOne) { differences.WriteLine(lineTwo); lineTwo = two.ReadLine(); } } Standard caveat about code written off the top of my head applies -- you may need to special-case running out of lines in one while the other still has lines, but I think this basic approach should do what you're looking for. A: Well, there are several approaches that would work. You could write your own data structure that did this. Or you can try and use SortedList. You can also return the DataSets in code, and then use .Select() on the table. Granted, you would have to do this on both tables. A: You can easily use a SortedList to do fast lookups. If the data you are loading is already sorted, insertions into the SortedList should not be slow. A: If you are looking simply to see if all lines in FileA are included in FileB you could read it in and just compare streams inside a loop. File 1 Entry1 Entry2 Entry3 File 2 Entry1 Entry3 You could loop through with two counters and find omissions, going line by line through each file and see if you get what you need. A: Maybe I misunderstand, but the ArrayList will maintain its elements in the same order by which you added them. This means you can compare the two ArrayLists within one pass only - just increment the two scanning indices according to the comparison results. A: One question I have is have you considered "out-sourcing" your comparison. There are plenty of good diff tools that you could just call out to. I'd be surprised if there wasn't one that let you specify two files and get only the differences. Just a thought. A: I think the reason everyone has so many different answers is that you haven't quite got your problem specified well enough to be answered. First off, it depends what kind of differences you want to track. Are you wanting the differences to be output like in a WinDiff where the first file is the "original" and second file is the "modified" so you can list changes as INSERT, UPDATE or DELETE? Do you have a primary key that will allow you to match up two lines as different versions of the same record (when fields other than the primary key are different)? Or is is this some sort of reconciliation where you just want your difference output to say something like "RECORD IN FILE 1 AND NOT FILE 2"? I think the asnwers to these questions will help everyone to give you a suitable answer to your problem. A: If you have two files that are each a million lines as mentioned in your post, you might be using up a lot of memory. Some of the performance problem might be that you are swapping from disk. If you are simply comparing line 1 of file A to line one of file B, line2 file A -> line 2 file B, etc, I would recommend a technique that does not store so much in memory. You could either read write off of two file streams as a previous commenter posted and write out your results "in real time" as you find them. This would not explicitly store anything in memory. You could also dump chunks of each file into memory, say one thousand lines at a time, into something like a List. This could be fine tuned to meet your needs. A: To resolve question #1 I'd recommend looking into creating a hash of each line. That way you can compare hashes quick and easy using a dictionary. To resolve question #2 one quick and dirty solution would be to use an IDictionary. Using itemId as your first string type and the rest of the line as your second string type. You can then quickly find if an itemId exists and compare the lines. This of course assumes .Net 2.0+
C# Datatype for large sorted collection with position?
I am trying to compare two large datasets from a SQL query. Right now the SQL query is done externally and the results from each dataset is saved into its own csv file. My little C# console application loads up the two text/csv files and compares them for differences and saves the differences to a text file. Its a very simple application that just loads all the data from the first file into an arraylist and does a .compare() on the arraylist as each line is read from the second csv file. Then saves the records that don't match. The application works but I would like to improve the performance. I figure I can greatly improve performance if I can take advantage of the fact that both files are sorted, but I don't know a datatype in C# that keeps order and would allow me to select a specific position. Theres a basic array, but I don't know how many items are going to be in each list. I could have over a million records. Is there a data type available that I should be looking at?
[ "If data in both of your CSV files is already sorted and have the same number of records, you could skip the data structure entirely and do in-place analysis.\nStreamReader one = new StreamReader(\"C:\\file1.csv\");\nStreamReader two = new StreamReader(\"C:\\file2.csv\");\nString lineOne;\nString lineTwo;\n\nStreamWriter differences = new StreamWriter(\"Output.csv\");\nwhile (!one.EndOfStream)\n{\n lineOne = one.ReadLine();\n lineTwo = two.ReadLine();\n // do your comparison.\n bool areDifferent = true;\n\n if (areDifferent)\n differences.WriteLine(lineOne + lineTwo);\n}\n\none.Close();\ntwo.Close();\ndifferences.Close();\n\n", "System.Collections.Specialized.StringCollection allows you to add a range of values and, using the .IndexOf(string) method, allows you to retrieve the index of that item.\nThat being said, you could likely just load up a couple of byte[] from a filestream and do byte comparison... don't even worry about loading that stuff into a formal datastructure like StringCollection or string[]; if all you're doing is checking for differences, and you want speed, I would wreckon byte differences are where it's at.\n", "This is an adaptation of David Sokol's code to work with varying number of lines, outputing the lines that are in one file but not the other:\nStreamReader one = new StreamReader(\"C:\\file1.csv\");\nStreamReader two = new StreamReader(\"C:\\file2.csv\");\nString lineOne;\nString lineTwo;\nStreamWriter differences = new StreamWriter(\"Output.csv\");\nlineOne = one.ReadLine();\nlineTwo = two.ReadLine();\nwhile (!one.EndOfStream || !two.EndOfStream)\n{\n if(lineOne == lineTwo)\n {\n // lines match, read next line from each and continue\n lineOne = one.ReadLine();\n lineTwo = two.ReadLine();\n continue;\n }\n if(two.EndOfStream || lineOne < lineTwo)\n {\n differences.WriteLine(lineOne);\n lineOne = one.ReadLine();\n }\n if(one.EndOfStream || lineTwo < lineOne)\n {\n differences.WriteLine(lineTwo);\n lineTwo = two.ReadLine();\n }\n}\n\nStandard caveat about code written off the top of my head applies -- you may need to special-case running out of lines in one while the other still has lines, but I think this basic approach should do what you're looking for.\n", "Well, there are several approaches that would work. You could write your own data structure that did this. Or you can try and use SortedList. You can also return the DataSets in code, and then use .Select() on the table. Granted, you would have to do this on both tables.\n", "You can easily use a SortedList to do fast lookups. If the data you are loading is already sorted, insertions into the SortedList should not be slow.\n", "If you are looking simply to see if all lines in FileA are included in FileB you could read it in and just compare streams inside a loop.\nFile 1\nEntry1\nEntry2\nEntry3\nFile 2\nEntry1\nEntry3\nYou could loop through with two counters and find omissions, going line by line through each file and see if you get what you need.\n", "Maybe I misunderstand, but the ArrayList will maintain its elements in the same order by which you added them. This means you can compare the two ArrayLists within one pass only - just increment the two scanning indices according to the comparison results.\n", "One question I have is have you considered \"out-sourcing\" your comparison. There are plenty of good diff tools that you could just call out to. I'd be surprised if there wasn't one that let you specify two files and get only the differences. Just a thought.\n", "I think the reason everyone has so many different answers is that you haven't quite got your problem specified well enough to be answered. First off, it depends what kind of differences you want to track. Are you wanting the differences to be output like in a WinDiff where the first file is the \"original\" and second file is the \"modified\" so you can list changes as INSERT, UPDATE or DELETE? Do you have a primary key that will allow you to match up two lines as different versions of the same record (when fields other than the primary key are different)? Or is is this some sort of reconciliation where you just want your difference output to say something like \"RECORD IN FILE 1 AND NOT FILE 2\"?\nI think the asnwers to these questions will help everyone to give you a suitable answer to your problem.\n", "If you have two files that are each a million lines as mentioned in your post, you might be using up a lot of memory. Some of the performance problem might be that you are swapping from disk. If you are simply comparing line 1 of file A to line one of file B, line2 file A -> line 2 file B, etc, I would recommend a technique that does not store so much in memory. You could either read write off of two file streams as a previous commenter posted and write out your results \"in real time\" as you find them. This would not explicitly store anything in memory. You could also dump chunks of each file into memory, say one thousand lines at a time, into something like a List. This could be fine tuned to meet your needs.\n", "To resolve question #1 I'd recommend looking into creating a hash of each line. That way you can compare hashes quick and easy using a dictionary. \nTo resolve question #2 one quick and dirty solution would be to use an IDictionary. Using itemId as your first string type and the rest of the line as your second string type. You can then quickly find if an itemId exists and compare the lines. This of course assumes .Net 2.0+\n" ]
[ 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "c#", "comparison", "sorting", "types" ]
stackoverflow_0000077503_c#_comparison_sorting_types.txt
Q: What should be done to make TFS send e-mails for events? Our Tfs server (Tfs2008) has smtp server installed. But we could not make Tfs send e-mails after events to the subscribers (we are using EventSubscriptionTool). Our appsettings includes these lines: <add key="emailNotificationFromAddress" value="[email protected]" /> <add key="smtpServer" value="localhost" /> Is there any other tricks for this task...? A: You sound like you have common part fixed - setting the appropriate appSettings in the web.config in %ProgramFile%\Microsoft Visual Studio 2008 Team Foundation Server\Web Services\Services. The following post from Pete Sheill might help you debug what's going wrong. http://blogs.msdn.com/psheill/archive/2005/11/28/497662.aspx It was written with TFS2005 in mind, but if you replace 2005 in the paths for 2008 you'll get the gist. Good luck, Martin.
What should be done to make TFS send e-mails for events?
Our Tfs server (Tfs2008) has smtp server installed. But we could not make Tfs send e-mails after events to the subscribers (we are using EventSubscriptionTool). Our appsettings includes these lines: <add key="emailNotificationFromAddress" value="[email protected]" /> <add key="smtpServer" value="localhost" /> Is there any other tricks for this task...?
[ "You sound like you have common part fixed - setting the appropriate appSettings in the web.config in %ProgramFile%\\Microsoft Visual Studio 2008 Team Foundation Server\\Web Services\\Services.\nThe following post from Pete Sheill might help you debug what's going wrong.\n\nhttp://blogs.msdn.com/psheill/archive/2005/11/28/497662.aspx\n\nIt was written with TFS2005 in mind, but if you replace 2005 in the paths for 2008 you'll get the gist.\nGood luck,\nMartin.\n" ]
[ 3 ]
[]
[]
[ "tfs" ]
stackoverflow_0000092467_tfs.txt
Q: How do you use WebServiceMessageDrivenBean in Spring-WS? How do you use the the org.springframework.ws.transport.jms.WebServiceMessageDrivenBean class from the Java Spring Framework - Spring-WS project? There is very little documentation or examples available on the web. A: From what I gather from reading the javadocs it looks like this allows a Spring WebServiceMessageReceiver to be invoked using a JMS client instead of a web services client. Hopefully that's right, because the rest of this is based on that assumption. The basics of is should match with how you create a regular Spring message driven bean. There is a little bit of documentation on how to do that in the Spring Reference Manual. Also see the AbstractEnterpriseBean Javadoc for some additional information about how the Spring context is retrieved. The extra configuration required for a WebServiceMessageDrivenBean appear to be a ConnectionFactory, a WebServiceMessageFactory, and your WebServiceMessageReceiver. These need to use the bean names specified in the Javadoc for the WebServiceMessageDrivenBean. The bean names are "connectionFactory", "messageFactory", and "messageReceiver" respectively. A: Using the WebServiceMessageDrivenBean is very similar to the Spring support for Message Driven Beans (MDBS). First you create a MDB: public class HelloWorldMessageDrivenBean extends WebServiceMessageDrivenBean { private static final long serialVersionUID = -2905491432314736668L; } That is it as far as the MDB goes! Next you configure the MDB by adding the following following to the MDB definition in the ejb-jar.xml: <env-entry> <description></description> <env-entry-name>ejb/BeanFactoryPath</env-entry-name> <env-entry-type>java.lang.String</env-entry-type> <env-entry-value> application-context.xml </env-entry-value> </env-entry> This tells the Spring MDB support classes where to pick up your Spring configuration file. You can now configure your endpoints either in the application-context.xml file or in addition using the annotation support.
How do you use WebServiceMessageDrivenBean in Spring-WS?
How do you use the the org.springframework.ws.transport.jms.WebServiceMessageDrivenBean class from the Java Spring Framework - Spring-WS project? There is very little documentation or examples available on the web.
[ "From what I gather from reading the javadocs it looks like this allows a Spring WebServiceMessageReceiver to be invoked using a JMS client instead of a web services client. Hopefully that's right, because the rest of this is based on that assumption.\nThe basics of is should match with how you create a regular Spring message driven bean. There is a little bit of documentation on how to do that in the Spring Reference Manual. Also see the AbstractEnterpriseBean Javadoc for some additional information about how the Spring context is retrieved. \nThe extra configuration required for a WebServiceMessageDrivenBean appear to be a ConnectionFactory, a WebServiceMessageFactory, and your WebServiceMessageReceiver. These need to use the bean names specified in the Javadoc for the WebServiceMessageDrivenBean. The bean names are \"connectionFactory\", \"messageFactory\", and \"messageReceiver\" respectively. \n", "Using the WebServiceMessageDrivenBean is very similar to the Spring support for Message Driven Beans (MDBS).\nFirst you create a MDB:\npublic class HelloWorldMessageDrivenBean extends WebServiceMessageDrivenBean {\n private static final long serialVersionUID = -2905491432314736668L;\n}\n\nThat is it as far as the MDB goes!\nNext you configure the MDB by adding the following following to the MDB definition in the ejb-jar.xml:\n<env-entry> \n <description></description> \n <env-entry-name>ejb/BeanFactoryPath</env-entry-name> \n <env-entry-type>java.lang.String</env-entry-type> \n <env-entry-value> \n application-context.xml \n </env-entry-value> \n</env-entry>\n\nThis tells the Spring MDB support classes where to pick up your Spring configuration file.\nYou can now configure your endpoints either in the application-context.xml file or in addition using the annotation support.\n" ]
[ 2, 0 ]
[]
[]
[ "java", "spring", "spring_ws" ]
stackoverflow_0000037912_java_spring_spring_ws.txt
Q: Casting array of objects (which implement interface IFoo) to IFoo[] in C# class A : IFoo { } ... A[] arrayOfA = new A[10]; if(arrayOfA is IFoo[]) { // this is not called } Q1: Why is arrayOfA not an array of IFoos? Q2: Why can't I cast arrayOfA to IFoo[]? A: arrayOfA is IFoo[]. There must be something else wrong with your program. You seem to have mocked up some code to show the problem, but in fact your code (see below) works as you expect. Try updating this question with the real code - or as close to real as you can - and we can take another look. using System; public class oink { public static void Main() { A[] aOa = new A[10]; if (aOa is IFoo[]) { Console.WriteLine("aOa is IFoo[]"); } } public interface IFoo {} public class A : IFoo {} } PS D:\> csc test.cs Microsoft (R) Visual C# 2008 Compiler version 3.5.30729.1 for Microsoft (R) .NET Framework version 3.5 Copyright (C) Microsoft Corporation. All rights reserved. PS D:\> D:\test.exe aOa is IFoo[] PS D:\>
Casting array of objects (which implement interface IFoo) to IFoo[] in C#
class A : IFoo { } ... A[] arrayOfA = new A[10]; if(arrayOfA is IFoo[]) { // this is not called } Q1: Why is arrayOfA not an array of IFoos? Q2: Why can't I cast arrayOfA to IFoo[]?
[ "arrayOfA is IFoo[]. \nThere must be something else wrong with your program.\nYou seem to have mocked up some code to show the problem, but in fact your code (see below) works as you expect. Try updating this question with the real code - or as close to real as you can - and we can take another look.\nusing System;\npublic class oink {\n public static void Main() {\n A[] aOa = new A[10];\n\n if (aOa is IFoo[]) { Console.WriteLine(\"aOa is IFoo[]\"); }\n\n }\n public interface IFoo {}\n public class A : IFoo {}\n}\n\nPS D:\\> csc test.cs\nMicrosoft (R) Visual C# 2008 Compiler version 3.5.30729.1\nfor Microsoft (R) .NET Framework version 3.5\nCopyright (C) Microsoft Corporation. All rights reserved.\n\nPS D:\\> D:\\test.exe\naOa is IFoo[]\nPS D:\\>\n\n" ]
[ 6 ]
[ "You could try\nif (arrayofA[0] is IFoo) {.....}\n\nwhich sort of answers your question. arrayOfA is an array. An array is an object which implements ICloneable, IList, ICollection, & IEnumerable. IFoo isn't among them.\n" ]
[ -3 ]
[ "c#" ]
stackoverflow_0000092820_c#.txt
Q: Django + FCGID on Fedora Core 9 -- what am I missing? Fedora Core 9 seems to have FCGID instead of FastCGI as a pre-built, YUM-managed module. [I'd rather not have to maintain a module outside of YUM; so no manual builds for me or my sysadmins.] I'm trying to launch Django through the runfastcgi interface (per the FastCGI deployment docs). What I'm seeing is the resulting page written to error_log. It does not come back through Apache to my browser. Further, there are a bunch of messages -- apparently from flup and WSGIServer -- that indicate that the WSGI environment isn't defined properly. Is FastCGI available for FC9, and I just overlooked it? Does FCGID and flup actually create the necessary WSGI environment for Django? If so, can you share the .fcgi interface script you're using? Mine is copied from mysite.fcgi in the Django docs. The FCGID Documentations page drops hints that PHP and Ruby are supported -- PHP directly, and Ruby through dispatch.fcgi -- and Python is not supported. Update. The error messages are... WSGIServer: missing FastCGI param REQUEST_METHOD required by WSGI! WSGIServer: missing FastCGI param SERVER_NAME required by WSGI! WSGIServer: missing FastCGI param SERVER_PORT required by WSGI! WSGIServer: missing FastCGI param SERVER_PROTOCOL required by WSGI! Should I abandon ship and switch to mod_python and give up on this approach? A: Why don't you try modwsgi? It sounds as the preffered way these days for WSGI applications such as Django. If you don't wan't to compile stuff for Fedora Core, that might be trickier. Regarding to your first question, this seems to solve the fcgid configuration problem. Note that you don't want to run the django application manually like this: python manage.py runfcgi, the fcgi is run by apache automatically if the setup is correct and restarted by touch your.fcgi.
Django + FCGID on Fedora Core 9 -- what am I missing?
Fedora Core 9 seems to have FCGID instead of FastCGI as a pre-built, YUM-managed module. [I'd rather not have to maintain a module outside of YUM; so no manual builds for me or my sysadmins.] I'm trying to launch Django through the runfastcgi interface (per the FastCGI deployment docs). What I'm seeing is the resulting page written to error_log. It does not come back through Apache to my browser. Further, there are a bunch of messages -- apparently from flup and WSGIServer -- that indicate that the WSGI environment isn't defined properly. Is FastCGI available for FC9, and I just overlooked it? Does FCGID and flup actually create the necessary WSGI environment for Django? If so, can you share the .fcgi interface script you're using? Mine is copied from mysite.fcgi in the Django docs. The FCGID Documentations page drops hints that PHP and Ruby are supported -- PHP directly, and Ruby through dispatch.fcgi -- and Python is not supported. Update. The error messages are... WSGIServer: missing FastCGI param REQUEST_METHOD required by WSGI! WSGIServer: missing FastCGI param SERVER_NAME required by WSGI! WSGIServer: missing FastCGI param SERVER_PORT required by WSGI! WSGIServer: missing FastCGI param SERVER_PROTOCOL required by WSGI! Should I abandon ship and switch to mod_python and give up on this approach?
[ "Why don't you try modwsgi? It sounds as the preffered way these days for WSGI applications such as Django.\nIf you don't wan't to compile stuff for Fedora Core, that might be trickier.\nRegarding to your first question, this seems to solve the fcgid configuration problem. \nNote that you don't want to run the django application manually like this: python manage.py runfcgi, the fcgi is run by apache automatically if the setup is correct and restarted by touch your.fcgi.\n" ]
[ 3 ]
[]
[]
[ "apache2", "django", "fastcgi", "fcgid", "python" ]
stackoverflow_0000092373_apache2_django_fastcgi_fcgid_python.txt
Q: How do I reserve caret position in CEdit control? I'm programming an application in MFC (don't ask) and I have a CEdit box that holds a number. When that number is edited, I would like to act on the change, and then replace the caret where it was before I acted on the change - if the user was just before the "." in "35.40", I would like it to still be placed before the dot if they change it to "345.40". I'm currently catching the CHANGE message, but that can be switched to something else (UPDATE?). How can I accomplish this? A: Use the GetSel() function before your change to store the location of the cursor, then use SelSel() to set it back. You can use these functions to get/set the location of the caret, not just to get/set the selection the user has made. A: Could you explain the reason why you would want to change the behavior of the CEdit box? As a user I would have a problem with the caret being changed every time I enter some character. Or is it what you would like to prevent if you change that value programmatically?
How do I reserve caret position in CEdit control?
I'm programming an application in MFC (don't ask) and I have a CEdit box that holds a number. When that number is edited, I would like to act on the change, and then replace the caret where it was before I acted on the change - if the user was just before the "." in "35.40", I would like it to still be placed before the dot if they change it to "345.40". I'm currently catching the CHANGE message, but that can be switched to something else (UPDATE?). How can I accomplish this?
[ "Use the GetSel() function before your change to store the location of the cursor, then use SelSel() to set it back. You can use these functions to get/set the location of the caret, not just to get/set the selection the user has made.\n", "Could you explain the reason why you would want to change the behavior of the CEdit box?\nAs a user I would have a problem with the caret being changed every time I enter some character. Or is it what you would like to prevent if you change that value programmatically?\n" ]
[ 1, 0 ]
[]
[]
[ "c++", "mfc", "user_interface" ]
stackoverflow_0000092671_c++_mfc_user_interface.txt
Q: Tidy Converting to I am using the PHP 5 Tidy class to format html. Everything is fine except when it gets passed a style attribute, when it changes it into a class attribute. As I am only formatting the body of a document, not the head, there is no class defined in the head for the attribute to read. I have looked through all the Tidy options but can't work out how to stop this behaviour. Thanks A: Try switching the clean option off.
Tidy Converting to
I am using the PHP 5 Tidy class to format html. Everything is fine except when it gets passed a style attribute, when it changes it into a class attribute. As I am only formatting the body of a document, not the head, there is no class defined in the head for the attribute to read. I have looked through all the Tidy options but can't work out how to stop this behaviour. Thanks
[ "Try switching the clean option off.\n" ]
[ 3 ]
[]
[]
[ "php", "tidy" ]
stackoverflow_0000092672_php_tidy.txt
Q: Multiple keyboards and low-level hooks I have a system where I have multiple keyboards and really need to know which keyboard the key stroke is coming from. To explain the set up: I have a normal PC and USB keyboard I have an external VGA screen with some hard-keys The hard keys are mapped as a standard USB keyboard, sending a limited number of key-codes (F1, F2, Return, + and -) I have a low-level hook (in C# but actually calling upon Win32 functionality) which is able to deal with the input even when my application is not focused. The problem is that when using the normal keyboard, some of the mapped key-codes at picked up by the application being driven on the external screen. One of the key-presses sent by the external screen and used for confirmation is VK_RETURN. Unless I can identify the "device" and filter upon it, the user could be performing actions and confirming them on a screen their not even looking at. How do I know which keyboard was responsible for the key-press? A: Yes I stand corrected, my bad, learning something new every day. Here's my attempt at making up for it :) : Register the devices you want to use for raw input (the two keyboards) with ::RegisterRawInputDevices(). You can get these devices from GetRawInputDeviceList() After you've registered your devices, you will start getting WM_INPUT messages. The lParam of the WM_INPUT message contains a RAWKEYBOARD structure that you can use to determine the keyboard where the input came from, plus the virtual keycode and the type of message (WM_KEYDOWN, WM_KEYUP, ...) So you can set a flag of where the last message came from and then dispatch it to the regular keyboard input handlers.
Multiple keyboards and low-level hooks
I have a system where I have multiple keyboards and really need to know which keyboard the key stroke is coming from. To explain the set up: I have a normal PC and USB keyboard I have an external VGA screen with some hard-keys The hard keys are mapped as a standard USB keyboard, sending a limited number of key-codes (F1, F2, Return, + and -) I have a low-level hook (in C# but actually calling upon Win32 functionality) which is able to deal with the input even when my application is not focused. The problem is that when using the normal keyboard, some of the mapped key-codes at picked up by the application being driven on the external screen. One of the key-presses sent by the external screen and used for confirmation is VK_RETURN. Unless I can identify the "device" and filter upon it, the user could be performing actions and confirming them on a screen their not even looking at. How do I know which keyboard was responsible for the key-press?
[ "Yes I stand corrected, my bad, learning something new every day.\nHere's my attempt at making up for it :) :\n\nRegister the devices you want to use for raw input (the two keyboards) with ::RegisterRawInputDevices().\nYou can get these devices from GetRawInputDeviceList()\nAfter you've registered your devices, you will start getting WM_INPUT messages.\nThe lParam of the WM_INPUT message contains a RAWKEYBOARD structure that you can use to determine the keyboard where the input came from, plus the virtual keycode and the type of message (WM_KEYDOWN, WM_KEYUP, ...)\nSo you can set a flag of where the last message came from and then dispatch it to the regular keyboard input handlers.\n\n" ]
[ 16 ]
[ "No way to do this. Windows abstracts this for you. As mentioned, you need to write/modify a device driver.\n" ]
[ -3 ]
[ "c#", "hardware", "hook", "keyboard", "winapi" ]
stackoverflow_0000091234_c#_hardware_hook_keyboard_winapi.txt
Q: Is it worth the effort to move from a hand crafted hibernate mapping file to annotaions? I've got a webapp whose original code base was developed with a hand crafted hibernate mapping file. Since then, I've become fairly proficient at 'coding' my hbm.xml file. But all the cool kids are using annotations these days. So, the question is: Is it worth the effort to refactor my code to use hibernate annotations? Will I gain anything, other than being hip and modern? Will I lose any of the control I have in my existing hand coded mapping file? A sub-question is, how much effort will it be? I like my databases lean and mean. The mapping covers only a dozen domain objects, including two sets, some subclassing, and about 8 tables. Thanks, dear SOpedians, in advance for your informed opinions. A: "If it ain't broke - don't fix it!" I'm an old fashioned POJO/POCO kind of guy anyway, but why change to annotations just to be cool? To the best of my knowledge you can do most of the stuff as annotations, but the more complex mappings are sometimes expressed more clearly as XML. A: One thing you'll gain from using annotations instead of an external mapping file is that your mapping information will be on classes and fields which improves maintainability. You add a field, you immediately add the annotation. You remove one, you also remove the annotation. you rename a class or a field, the annotation is right there and you can rename the table or column as well. you make changes in class inheritance, it's taken into account. You don't have to go and edit an external file some time later. this makes the whole thing more efficient and less error prone. On the other side, you'll lose the global view your mapping file used to give you. A: I've recently done both in a project and found: I prefer writing annotations to XML (plays well with static typing of Java, auto-complete in IDE, refactoring, etc). I like seeing the stuff all woven together rather than going back and forth between code and XML. Encodes db information in your classes. Some people find that gross and unacceptable. I can't say it bothered me. It has to go somewhere and we're going to rebuild the WAR for a change regardless. We actually went all the way to JPA annotations but there are definitely cases where the JPA annotations are not enough, so then had to use either Hibernate annotations or config to tweak. Note that you can actually use both annotations AND hbm files. Might be a nice hybrid that specifies the O part in annotations and R part in hbm files but sounds like more trouble than it's worth. A: As much as I like to move on to new and potentially better things I need to remember to not mess with things that aren't broken. So if having the hibernate mappings in a separate file is working for you now I wouldn't change it. A: I definitely prefer annotations, having used them both. They are much more maintainable and since you aren't dealing with that many classes to re-map, I would say it's worth it. The annotations make refactoring much easier. A: All the features are supported both in the XML and in annotations. You will still be able to override your annotations with xml declaration. As for the effort, i think it is worth it as you will be able to see all in one place and not switch between your code and the xml file (unless of-course you are using two monitors ;) ) A: The only thing you'll gain from using annotations I would probably argue that this is the thing you want to gain from using annotations. Because you don't get compile time safety with NHibernate this is the next best thing. A: "If it ain't broke - don't fix it!" @Macka - Thanks, I needed to hear that. And thanks to everyone for your answers. While I am in the very fortunate position of having an insane amount of professional and creative control over my work, and can bring in just about any technology, library, or tool for just about any reason (baring expensive stuff) including "because all the cool kids are using it"...It does not really make sense to port what amounts to a significant portion of the core of an existing project. I'll try out Hibernate or JPA annotations with a green-field project some time. Unfortunately, I rarely get new completely independent projects.
Is it worth the effort to move from a hand crafted hibernate mapping file to annotaions?
I've got a webapp whose original code base was developed with a hand crafted hibernate mapping file. Since then, I've become fairly proficient at 'coding' my hbm.xml file. But all the cool kids are using annotations these days. So, the question is: Is it worth the effort to refactor my code to use hibernate annotations? Will I gain anything, other than being hip and modern? Will I lose any of the control I have in my existing hand coded mapping file? A sub-question is, how much effort will it be? I like my databases lean and mean. The mapping covers only a dozen domain objects, including two sets, some subclassing, and about 8 tables. Thanks, dear SOpedians, in advance for your informed opinions.
[ "\"If it ain't broke - don't fix it!\"\nI'm an old fashioned POJO/POCO kind of guy anyway, but why change to annotations just to be cool? To the best of my knowledge you can do most of the stuff as annotations, but the more complex mappings are sometimes expressed more clearly as XML.\n", "One thing you'll gain from using annotations instead of an external mapping file is that your mapping information will be on classes and fields which improves maintainability. You add a field, you immediately add the annotation. You remove one, you also remove the annotation. you rename a class or a field, the annotation is right there and you can rename the table or column as well. you make changes in class inheritance, it's taken into account. You don't have to go and edit an external file some time later. this makes the whole thing more efficient and less error prone.\nOn the other side, you'll lose the global view your mapping file used to give you.\n", "I've recently done both in a project and found:\n\nI prefer writing annotations to XML (plays well with static typing of Java, auto-complete in IDE, refactoring, etc). I like seeing the stuff all woven together rather than going back and forth between code and XML. \nEncodes db information in your classes. Some people find that gross and unacceptable. I can't say it bothered me. It has to go somewhere and we're going to rebuild the WAR for a change regardless. \nWe actually went all the way to JPA annotations but there are definitely cases where the JPA annotations are not enough, so then had to use either Hibernate annotations or config to tweak.\nNote that you can actually use both annotations AND hbm files. Might be a nice hybrid that specifies the O part in annotations and R part in hbm files but sounds like more trouble than it's worth.\n\n", "As much as I like to move on to new and potentially better things I need to remember to not mess with things that aren't broken. So if having the hibernate mappings in a separate file is working for you now I wouldn't change it.\n", "I definitely prefer annotations, having used them both. They are much more maintainable and since you aren't dealing with that many classes to re-map, I would say it's worth it. The annotations make refactoring much easier.\n", "All the features are supported both in the XML and in annotations.\nYou will still be able to override your annotations with xml declaration.\nAs for the effort, i think it is worth it as you will be able to see all in one place and not switch between your code and the xml file (unless of-course you are using two monitors ;) )\n", "\nThe only thing you'll gain from using\n annotations\n\nI would probably argue that this is the thing you want to gain from using annotations. Because you don't get compile time safety with NHibernate this is the next best thing.\n", "\n\"If it ain't broke - don't fix it!\"\n\n@Macka - Thanks, I needed to hear that. And thanks to everyone for your answers. \nWhile I am in the very fortunate position of having an insane amount of professional and creative control over my work, and can bring in just about any technology, library, or tool for just about any reason (baring expensive stuff) including \"because all the cool kids are using it\"...It does not really make sense to port what amounts to a significant portion of the core of an existing project. \nI'll try out Hibernate or JPA annotations with a green-field project some time. Unfortunately, I rarely get new completely independent projects. \n" ]
[ 7, 4, 3, 2, 1, 0, 0, 0 ]
[]
[]
[ "annotations", "hibernate", "java" ]
stackoverflow_0000082223_annotations_hibernate_java.txt
Q: Flash animations editor What application should I use for creating Flash animations for a website? A: Adobe Flash (http://www.adobe.com/products/flash/) A: For other options (free software), check out this question or this question. A: I've used SWiSH Max2 for a few years now (well, SWiSH Max then the second one). It's very much the "FrontPage" of Flash editing but it's got the advantage of being reasonably professional and easy to use and relatively inexpensive ($149 compared to $699 for Adobe Flash CS3, though I think I paid $99 for it so it's gone up in price). It has a free 30-day trial.
Flash animations editor
What application should I use for creating Flash animations for a website?
[ "Adobe Flash (http://www.adobe.com/products/flash/)\n", "For other options (free software), check out this question or this question.\n", "I've used SWiSH Max2 for a few years now (well, SWiSH Max then the second one). It's very much the \"FrontPage\" of Flash editing but it's got the advantage of being reasonably professional and easy to use and relatively inexpensive ($149 compared to $699 for Adobe Flash CS3, though I think I paid $99 for it so it's gone up in price). \nIt has a free 30-day trial.\n" ]
[ 5, 2, 1 ]
[]
[]
[ "flash" ]
stackoverflow_0000092925_flash.txt
Q: Easiest cross platform widget toolkit? What is the easiest cross platform widget toolkit? I'm looking for one that minimally covers Windows, OSX, and Linux with a C or C++ interface. A: I don't know of any I've personally used with a C API, but wxWidgets is C++. It runs on Windows, Linux, and Mac OS X. And if you're looking for easy, wxPython is a Python wrapper around wxWidgets and it is pretty easy to use. A: I really like Qt. Have been working with it in several projects now. Although the project, I am currently working on, will be released for windows only, some of our developers code under Mac OS X using the gcc. And using different compilers and environments is an extra benefit for locating errors & bugs. I forgot to mention that Qt has a really good documentation including lots of practical examples that help for a quick start. A: I've used both wxWidgets and QT professionally. Both are certainly capable of meeting your goals. Which one is easiest is hard to say. You don't tell us whether you're looking for easy to use, or easy to learn. Qt is easier for big programs. WxWidgets is easier to learn. This for a large part due to the signal/slot mechanism in QT, which is a good but non-intuitive architecture for large applications. Both libraries are actually so good that I'd recommend them for non-crossplatform programming too. A: Are we talking GUI Widgets? If so, I can suggest 3 FLTK: http://www.fltk.org/ GTK: http://www.gtk.org/ QT: http://trolltech.com/products/qt/ A: As with the other posters, I strongly recommend looking at C++ toolkits. GTK will work on Windows and the Mac OS, but will only give you truly good results on Linux. And even some of the GTK maintainers are inventing their their own object-oriented C dialect to avoid writing GUIs against the native GTK API. As for C++, it depends on what you want. Ease of development? Native GUIs on every platform? Commercial support? If you want native-looking GUIs on Win32 and Linux (and something semi-reasonable on the Mac), one excellent choice is wxWidgets. Here's a longer article with real-world wxWidgets experiences. The Mac port has improved substantially since 2002, when that article was written, but it still has some soft spots. A: The easiest to write a new program in would be the one you're most familiar with. The easiest to use, test or distribute would probably be the most cross-platform, most distributed or the most supported one, so GTK+/wx/Qt/Tk? Note that C itself isn't a particularly easy language, especially with the growing object-oriented approach to GUIs. The easiest one to cook up a prototype in a scripting language, then convert to a compiled one might be any toolkit with a scripting language binding (pyGTK, wxPython, etc.) That being said, of the "big" ones, only GTK+ and Tk have a C bindings. wxWidgets, Qt and FLTK were all written in C++ and don't have any C bindings as far as I know. I suggest you look into learning C++ and then comparing the available options. Coding in C++ might feel like coding in a scripting language with great conveniences such as automatic pointers, utility classes and overloaded operators, non-invasive garbage collectors and easy to inherit parent classes all brought to your fingertips by the language itself and your widget toolkit. Then my personal suggestion would be wxWidgets; quite easy to use, better documented than GTKmm and "freer" than Qt.
Easiest cross platform widget toolkit?
What is the easiest cross platform widget toolkit? I'm looking for one that minimally covers Windows, OSX, and Linux with a C or C++ interface.
[ "I don't know of any I've personally used with a C API, but wxWidgets is C++. It runs on Windows, Linux, and Mac OS X. And if you're looking for easy, wxPython is a Python wrapper around wxWidgets and it is pretty easy to use.\n", "I really like Qt. Have been working with it in several projects now.\nAlthough the project, I am currently working on, will be released for windows only, some of our developers code under Mac OS X using the gcc. And using different compilers and environments is an extra benefit for locating errors & bugs.\nI forgot to mention that Qt has a really good documentation including lots of practical examples that help for a quick start.\n", "I've used both wxWidgets and QT professionally. Both are certainly capable of meeting your goals. Which one is easiest is hard to say. You don't tell us whether you're looking for easy to use, or easy to learn. Qt is easier for big programs. WxWidgets is easier to learn. This for a large part due to the signal/slot mechanism in QT, which is a good but non-intuitive architecture for large applications. \nBoth libraries are actually so good that I'd recommend them for non-crossplatform programming too.\n", "Are we talking GUI Widgets? If so, I can suggest 3\nFLTK:\nhttp://www.fltk.org/\nGTK:\nhttp://www.gtk.org/\nQT:\nhttp://trolltech.com/products/qt/\n", "As with the other posters, I strongly recommend looking at C++ toolkits. GTK will work on Windows and the Mac OS, but will only give you truly good results on Linux. And even some of the GTK maintainers are inventing their their own object-oriented C dialect to avoid writing GUIs against the native GTK API.\nAs for C++, it depends on what you want. Ease of development? Native GUIs on every platform? Commercial support?\nIf you want native-looking GUIs on Win32 and Linux (and something semi-reasonable on the Mac), one excellent choice is wxWidgets. Here's a longer article with real-world wxWidgets experiences. The Mac port has improved substantially since 2002, when that article was written, but it still has some soft spots.\n", "The easiest to write a new program in would be the one you're most familiar with.\nThe easiest to use, test or distribute would probably be the most cross-platform, most distributed or the most supported one, so GTK+/wx/Qt/Tk?\nNote that C itself isn't a particularly easy language, especially with the growing object-oriented approach to GUIs.\nThe easiest one to cook up a prototype in a scripting language, then convert to a compiled one might be any toolkit with a scripting language binding (pyGTK, wxPython, etc.)\nThat being said, of the \"big\" ones, only GTK+ and Tk have a C bindings. wxWidgets, Qt and FLTK were all written in C++ and don't have any C bindings as far as I know.\nI suggest you look into learning C++ and then comparing the available options. Coding in C++ might feel like coding in a scripting language with great conveniences such as automatic pointers, utility classes and overloaded operators, non-invasive garbage collectors and easy to inherit parent classes all brought to your fingertips by the language itself and your widget toolkit.\nThen my personal suggestion would be wxWidgets; quite easy to use, better documented than GTKmm and \"freer\" than Qt.\n" ]
[ 11, 9, 6, 5, 5, 1 ]
[]
[]
[ "c", "c++", "cross_platform", "gui_toolkit" ]
stackoverflow_0000091616_c_c++_cross_platform_gui_toolkit.txt
Q: How can I avoid duplicate copies of an object in a cache? I'm using memcache to design a cache for the model layer of a web application, one of my biggest problems is data consistency. It came to my mind caching data like this: (key=query, value=list of object ids result of the query) for each id of the list: (key=object.id, value=object) So, every time a query is done: If the query already exists I retrieve the objects signaled in the list from the cache. If it doesn't, all the objects of the lists are stored in the cache replacing any other old value. Has someone use this alternative, is it god? any other ideas? A: Caching is one of those topics where there is no one right answer - it depends on your domain. The caching policy that you describe may be sufficient for your domain. However, you don't appear to be worried about stale data. Often I would expect to see a timestamp against some of the entities - if the cached value is older than some system defined parameter, then it would be considered stale and re-fetched. For more discussion on caching algorithms, see Wikipedia (for starters) A: Welcome to the world of concurrency programming. You'll want to learn a bit about mutual exclusion. If you tell us what language/platform you are developing for we can describe more specifically your options.
How can I avoid duplicate copies of an object in a cache?
I'm using memcache to design a cache for the model layer of a web application, one of my biggest problems is data consistency. It came to my mind caching data like this: (key=query, value=list of object ids result of the query) for each id of the list: (key=object.id, value=object) So, every time a query is done: If the query already exists I retrieve the objects signaled in the list from the cache. If it doesn't, all the objects of the lists are stored in the cache replacing any other old value. Has someone use this alternative, is it god? any other ideas?
[ "Caching is one of those topics where there is no one right answer - it depends on your domain.\nThe caching policy that you describe may be sufficient for your domain. However, you don't appear to be worried about stale data. Often I would expect to see a timestamp against some of the entities - if the cached value is older than some system defined parameter, then it would be considered stale and re-fetched.\nFor more discussion on caching algorithms, see Wikipedia (for starters)\n", "Welcome to the world of concurrency programming. You'll want to learn a bit about mutual exclusion. If you tell us what language/platform you are developing for we can describe more specifically your options.\n" ]
[ 1, 0 ]
[]
[]
[ "caching", "memcached", "php" ]
stackoverflow_0000092927_caching_memcached_php.txt
Q: Using boost-python with C++ in Linux My development shop has put together a fairly useful Python-based test suite, and we'd like to test some Linux-based C++ code with it. We've gotten the test project they ship with Boost to compile (type 'bjam' in the directory and it works), but we're having issues with our actual project. Building the boost libraries and bjam from source (v1.35.0), when I run bjam I get a .so in the bin/gcc-4.1.2/debug directory. I run python and "import " and I get: ImportError: libboost_python-gcc41-d-1_35.so.1.35.0: cannot open shared object file: No such file or directory Looking in the library directory, I have the following: libboost_python-gcc41-mt-1_35.so libboost_python-gcc41-mt-1_35.so.1.35.0 libboost_python-gcc41-mt.so Obviously I need the -d instead of the -mt libraries, or to point at the -mt libraries instead of -d, but I can't figure out how to make my Jamroot file do that. When I install Debian Etch's versions of the libraries, I get "No Jamfile in /usr/include" - and there's a debian bug that says they left out the system-level jamfile. I'm more hopeful about getting it working from source, so if anyone has any suggestions to resolve the library issues, I'd like to hear them. Response to answer 1: Thanks for the tip. So, do you know how I'd go about getting it to use the MT libraries instead? It appears to be more of a problem with bjam or the Jamfile I am using thinking I am in debug mode, even though I can't find any flags for that. While I know how to include specific libraries in a call to GCC, I don't see a way to configure that from the Boost end. A: One important Point: -d means debug of course, and should only be linked to a debug build of your project and can only be used with a debug build of python (OR NOT, SEE BELOW). If you try to link a debug lib to a non-debug build, or you try to import a debug pyd into a non-debug python, bad things will happen. mt means multi-threaded and is orthogonal to d. You probably want to use a mt non-d for your project. I am afraid I don't know how to tell gcc what to link against (I have been using Visual Studio). One thing to try: man gcc Somewhere that should tell you how to force specific libs on the linker. EDIT: Actually you can import a debug version of you project into a non-debug build of python. Wherever you included python.h, include boost/python/detail/wrap_python.hpp instead. A: If you want to build the debug variants of the boost libraries as well, you have to invoke bjam with the option --build-type=complete. On Debian, you get the debug Python interpreter in the python2.x-dbg packages. Debug builds of the Boost libraries are in libboost1.xy-dbg, if you want to use the system Boost. A: Found the solution! Boost builds a debug build by default. Typing "bjam release" builds the release configuration. (This isn't listed in any documentation anywhere, as far as I can tell.) Note that this is not the same as changing your build-type to release, as that doesn't build a release configuration. Doing a 'complete' build as Torsten suggests also does not stop it from building only a debug version. It's also worth noting that the -d libraries were in <boost-version>/bin.v2/libs/python/build/<gcc version>/debug/ and the release libraries were in <gcc-version>/release, and not installed into the top-level 'libs' directory. Thanks for the other suggestions!
Using boost-python with C++ in Linux
My development shop has put together a fairly useful Python-based test suite, and we'd like to test some Linux-based C++ code with it. We've gotten the test project they ship with Boost to compile (type 'bjam' in the directory and it works), but we're having issues with our actual project. Building the boost libraries and bjam from source (v1.35.0), when I run bjam I get a .so in the bin/gcc-4.1.2/debug directory. I run python and "import " and I get: ImportError: libboost_python-gcc41-d-1_35.so.1.35.0: cannot open shared object file: No such file or directory Looking in the library directory, I have the following: libboost_python-gcc41-mt-1_35.so libboost_python-gcc41-mt-1_35.so.1.35.0 libboost_python-gcc41-mt.so Obviously I need the -d instead of the -mt libraries, or to point at the -mt libraries instead of -d, but I can't figure out how to make my Jamroot file do that. When I install Debian Etch's versions of the libraries, I get "No Jamfile in /usr/include" - and there's a debian bug that says they left out the system-level jamfile. I'm more hopeful about getting it working from source, so if anyone has any suggestions to resolve the library issues, I'd like to hear them. Response to answer 1: Thanks for the tip. So, do you know how I'd go about getting it to use the MT libraries instead? It appears to be more of a problem with bjam or the Jamfile I am using thinking I am in debug mode, even though I can't find any flags for that. While I know how to include specific libraries in a call to GCC, I don't see a way to configure that from the Boost end.
[ "One important Point: -d means debug of course, and should only be linked to a debug build of your project and can only be used with a debug build of python (OR NOT, SEE BELOW). If you try to link a debug lib to a non-debug build, or you try to import a debug pyd into a non-debug python, bad things will happen.\nmt means multi-threaded and is orthogonal to d. You probably want to use a mt non-d for your project.\nI am afraid I don't know how to tell gcc what to link against (I have been using Visual Studio). One thing to try:\nman gcc\n\nSomewhere that should tell you how to force specific libs on the linker. \nEDIT: Actually you can import a debug version of you project into a non-debug build of python. Wherever you included python.h, include boost/python/detail/wrap_python.hpp instead.\n", "If you want to build the debug variants of the boost libraries as well, you have to invoke bjam with the option --build-type=complete. \nOn Debian, you get the debug Python interpreter in the python2.x-dbg packages. Debug builds of the Boost libraries are in libboost1.xy-dbg, if you want to use the system Boost.\n", "Found the solution! Boost builds a debug build by default. Typing \"bjam release\" builds the release configuration. (This isn't listed in any documentation anywhere, as far as I can tell.) Note that this is not the same as changing your build-type to release, as that doesn't build a release configuration. Doing a 'complete' build as Torsten suggests also does not stop it from building only a debug version.\nIt's also worth noting that the -d libraries were in <boost-version>/bin.v2/libs/python/build/<gcc version>/debug/ and the release libraries were in <gcc-version>/release, and not installed into the top-level 'libs' directory.\nThanks for the other suggestions!\n" ]
[ 2, 2, 2 ]
[]
[]
[ "boost_python", "c++" ]
stackoverflow_0000067015_boost_python_c++.txt
Q: Loading DLLs into a separate AppDomain I want to load one or more DLLs dynamically so that they run with a different security or basepath than my main application. How do I load these DLLs into a separate AppDomain and instantiate objects from them? A: More specifically AppDomain domain = AppDomain.CreateDomain("New domain name"); //Do other things to the domain like set the security policy string pathToDll = @"C:\myDll.dll"; //Full path to dll you want to load Type t = typeof(TypeIWantToLoad); TypeIWantToLoad myObject = (TypeIWantToLoad)domain.CreateInstanceFromAndUnwrap(pathToDll, t.FullName); If all that goes properly (no exceptions thrown) you now have an instance of TypeIWantToLoad loaded into your new domain. The instance you have is actually a proxy (since the actual object is in the new domain) but you can use it just like your normal object. Note: As far as I know TypeIWantToLoad has to inherit from MarshalByRefObject. A: If you're targeting 3.5, you can take advantage of the new managed extensibility framework to handle all the heavy lifting for you. A: You can use the AppDomain.CreateInstance method to do this. You'll need to call the Unwrap method of the ObjectHandle that is returned to get at the actual object. A: Create a new Appdomain with AppDomain.Create( ... ). After creating the AppDomain load the DLLs into that AppDomain. Look into all the methods that Appdomain has with Create*. There are certain things like CreateInstanceAndUnwrap, etc. A: As previously stated, use AppDomain.CreateDomain to create a new app domain. You can then load an assembly into it using the Load method, or even execute an assembly using the ExecuteAssembly method. You can use GetAssemblies to see if an assembly has already been loaded. Be aware too that you cannot unload an assembly once it's loaded. You will need to unload the domain.
Loading DLLs into a separate AppDomain
I want to load one or more DLLs dynamically so that they run with a different security or basepath than my main application. How do I load these DLLs into a separate AppDomain and instantiate objects from them?
[ "More specifically\nAppDomain domain = AppDomain.CreateDomain(\"New domain name\");\n//Do other things to the domain like set the security policy\n\nstring pathToDll = @\"C:\\myDll.dll\"; //Full path to dll you want to load\nType t = typeof(TypeIWantToLoad);\nTypeIWantToLoad myObject = (TypeIWantToLoad)domain.CreateInstanceFromAndUnwrap(pathToDll, t.FullName);\n\nIf all that goes properly (no exceptions thrown) you now have an instance of TypeIWantToLoad loaded into your new domain. The instance you have is actually a proxy (since the actual object is in the new domain) but you can use it just like your normal object.\nNote: As far as I know TypeIWantToLoad has to inherit from MarshalByRefObject.\n", "If you're targeting 3.5, you can take advantage of the new managed extensibility framework to handle all the heavy lifting for you.\n", "You can use the AppDomain.CreateInstance method to do this. You'll need to call the Unwrap method of the ObjectHandle that is returned to get at the actual object.\n", "Create a new Appdomain with AppDomain.Create( ... ).\nAfter creating the AppDomain load the DLLs into that AppDomain.\nLook into all the methods that Appdomain has with Create*. There are certain things like CreateInstanceAndUnwrap, etc.\n", "As previously stated, use AppDomain.CreateDomain to create a new app domain. You can then load an assembly into it using the Load method, or even execute an assembly using the ExecuteAssembly method. You can use GetAssemblies to see if an assembly has already been loaded. Be aware too that you cannot unload an assembly once it's loaded. You will need to unload the domain.\n" ]
[ 35, 4, 2, 0, 0 ]
[]
[]
[ ".net", "appdomain", "c#" ]
stackoverflow_0000088717_.net_appdomain_c#.txt
Q: Separating user table from people table in a relational database I've done many web apps where the first thing you do is make a user table with usernames, passwords, names, e-mails and all of the other usual flotsam. My current project presents a situation where non-users records need to function similarly to users, but do not need to the ability to be a first order user. Is it reasonable to create a second table, people_tb, that is the main relational table and data store, and only use the users_tb for authentication? Does separating user_tb from people_tb present any problems? If this is commonly done, what are some strategies and solutions as well as drawbacks? A: This is certainly a good idea, as you are normalizing the database. I have done a similar design in an app that I am writing, where I have an employee table and a user table. Users may a from an external company or an employee, so I have separate tables because an employee is always a user, but a user may not be an employee. The issues that you'll run into is that whenever you use the user table, you'll nearly always want the person table to get the name or other common attributes you would want to show up. From a coding standpoint, if you're using straight SQL, it will take a little more effort to mentally parse the select statement. It may be a little more complicated if you're using an ORM library. I don't have enough experience with those. In my application, I'm writing it in Ruby on Rails, so I'm constantly doing things like employee.user.name, where if I kept them together, it would be just employee.name or user.name. From a performance standpoint, you are hitting two tables instead of one, but given proper indexes, it should be negligible. If you had an index that contained the primary key and the person name, for instance, the database would hit the user table, then the index for the person table (with a nearly direct hit), so the performance would be nearly the same as having one table. You could also create a view in the database to keep both tables joined together to give you additional performance enhancements. I know in the later versions of Oracle you can even put an index on a view if needed to increase performance. A: I routinely do that because for me the concept of "user" (username, password, create date, last login date) is different from "person" (name, address, phone, email). One of the drawbacks that you may find is that your queries will often require more joins to get the info you're looking for. If all you have is a login name, you'll need to join the "people" table to get the first and last name for example. If you base everything around the user id primary key, this is mitigated a bit, but still pops up. A: If user_tb has auth info, I would very much keep it separate from people_tb. I would however keep a relationship between the two, and most of users' info would be stored in people_tb except all of the info needed for auth (which i guess will not be used for much else) Its a nice tradeoff between design and efficiency i think. A: That is definitely what we do as we have millions of people records and only thousands of users. We also separate address, phones and emails into relational tables as many people have more than one of each of these things. Critial is to not rely on name as the identifier as name is not unique. Make sure the tables are joined through some type of surrogate key (an integer or a GUID is preferable) not name. A: I always try to avoid as much data repetition as possible. If not all people need to login, you can have a generic people table with the information that applies to both people and users (eg. firstname, lastname, etc). Then for people that login, you can have a users table that has a 1~1 relationship with people. This table can store the username and password. A: I'd say go for the normalized design (two tables) and only denormalize (go down to one user/person table) if it will really make your life easier down the line. If however practically all people are also users it may be simpler to denormalize up front. Its up to you; I have used the normalized approach without problems. A: Very reasonable. As an example, take a look at the aspnet_* services tables here. Their built in schema has a aspnet_Users and aspnet_Membership with the later table having more extended information about a given user (hashed passwords, etc) but the aspnet_User.UserID is used in the other portions of the schema for referential integrity etc. Bottom line, it's very common, and good design, to have attributes in a separate table if they are different entities, as in your case.
Separating user table from people table in a relational database
I've done many web apps where the first thing you do is make a user table with usernames, passwords, names, e-mails and all of the other usual flotsam. My current project presents a situation where non-users records need to function similarly to users, but do not need to the ability to be a first order user. Is it reasonable to create a second table, people_tb, that is the main relational table and data store, and only use the users_tb for authentication? Does separating user_tb from people_tb present any problems? If this is commonly done, what are some strategies and solutions as well as drawbacks?
[ "This is certainly a good idea, as you are normalizing the database. I have done a similar design in an app that I am writing, where I have an employee table and a user table. Users may a from an external company or an employee, so I have separate tables because an employee is always a user, but a user may not be an employee.\nThe issues that you'll run into is that whenever you use the user table, you'll nearly always want the person table to get the name or other common attributes you would want to show up. \nFrom a coding standpoint, if you're using straight SQL, it will take a little more effort to mentally parse the select statement. It may be a little more complicated if you're using an ORM library. I don't have enough experience with those.\nIn my application, I'm writing it in Ruby on Rails, so I'm constantly doing things like employee.user.name, where if I kept them together, it would be just employee.name or user.name.\nFrom a performance standpoint, you are hitting two tables instead of one, but given proper indexes, it should be negligible. If you had an index that contained the primary key and the person name, for instance, the database would hit the user table, then the index for the person table (with a nearly direct hit), so the performance would be nearly the same as having one table.\nYou could also create a view in the database to keep both tables joined together to give you additional performance enhancements. I know in the later versions of Oracle you can even put an index on a view if needed to increase performance.\n", "I routinely do that because for me the concept of \"user\" (username, password, create date, last login date) is different from \"person\" (name, address, phone, email). One of the drawbacks that you may find is that your queries will often require more joins to get the info you're looking for. If all you have is a login name, you'll need to join the \"people\" table to get the first and last name for example. If you base everything around the user id primary key, this is mitigated a bit, but still pops up.\n", "If user_tb has auth info, I would very much keep it separate from people_tb. I would however keep a relationship between the two, and most of users' info would be stored in people_tb except all of the info needed for auth (which i guess will not be used for much else) Its a nice tradeoff between design and efficiency i think.\n", "That is definitely what we do as we have millions of people records and only thousands of users. We also separate address, phones and emails into relational tables as many people have more than one of each of these things. Critial is to not rely on name as the identifier as name is not unique. Make sure the tables are joined through some type of surrogate key (an integer or a GUID is preferable) not name.\n", "I always try to avoid as much data repetition as possible. If not all people need to login, you can have a generic people table with the information that applies to both people and users (eg. firstname, lastname, etc).\nThen for people that login, you can have a users table that has a 1~1 relationship with people. This table can store the username and password.\n", "I'd say go for the normalized design (two tables) and only denormalize (go down to one user/person table) if it will really make your life easier down the line. If however practically all people are also users it may be simpler to denormalize up front. Its up to you; I have used the normalized approach without problems.\n", "Very reasonable. \nAs an example, take a look at the aspnet_* services tables here.\nTheir built in schema has a aspnet_Users and aspnet_Membership with the later table having more extended information about a given user (hashed passwords, etc) but the aspnet_User.UserID is used in the other portions of the schema for referential integrity etc.\nBottom line, it's very common, and good design, to have attributes in a separate table if they are different entities, as in your case.\n" ]
[ 10, 3, 1, 1, 0, 0, 0 ]
[]
[]
[ "database", "database_design", "rdbms" ]
stackoverflow_0000092894_database_database_design_rdbms.txt
Q: C++ class design from database schema I am writing a perl script to parse a mysql database schema and create C++ classes when necessary. My question is a pretty easy one, but us something I haven't really done before and don't know common practice. Any object of any of classes created will need to have "get" methods to populate this information. So my questions are twofold: Does it make sense to call all of the get methods in the constructor so that the object has data right away? Some classes will have a lot of them, so as needed might make sense too. I have two constrcutors now. One that populates the data and one that does not. Should I also have a another "get" method that retrieves the object's copy of the data rather that the db copy. I could go both ways on #1 and am leaning towards yes on #2. Any advice, pointers would be much appreciated. A: Ususally, the most costly part of an application is round trips to the database, so it would me much more efficient to populate all your data members from a single query than to do them one at a time, either on an as needed basis or from your constructor. Once you've paid for the round trip, you may as well get your money's worth. Also, in general, your get* methods should be declared as const, meaning they don't change the underlying object, so having them go out to the database to populate the object would break that (which you could allow by making the member variables mutable, but that would basically defeat the purpose of const). To break things down into concrete steps, I would recommend: Have your constructor call a separate init() method that queries the database and populates your object's data members. Declare your get* methods as const, and just have them return the data members. A: First realize that you're re-inventing the wheel here. There are a number of decent object-relational mapping libraries for database access in just about every language. For C/C++ you might look at: http://trac.butterfat.net/public/StactiveRecord http://debea.net/trac Ok, with that out of the way, you probably want to create a static method in your class called find or search which is a factory for constructing objects and selecting them from the database: Artist MJ = Artist::Find("Michael Jackson"); MJ->set("relevant", "no"); MJ->save(); Note the save method which then takes the modified object and stores it back into the database. If you actually want to create a new record, then you'd use the new method which would instantiate an empty object: Artist StackOverflow = Artist->new(); StackOverflow->set("relevant", "yes"); StackOverflow->save(); Note the set and get methods here just set and get the values from the object, not the database. To actually store elements in the database you'd need to use the static Find method or the object's save method. A: there are existing tools that reverse db's into java (and probably other languages). consider using one of them and converting that to c++. A: I would not recommend having your get methods go to the database at all, unless absolutely necessary for your particular problem. It makes for a lot more places something could go wrong, and probably a lot of unnecessary reads on your DB, and could inadvertently tie your objects to db-specific features, losing a lot of the benefits of a tiered architecture. As far as your domain model is concerned, the database does not exist. edit - this is for #2 (obviously). For #1 I would say no, for many of the same reasons. A: Another alternative would be to not automate creating the classes, and instead create separate classes that only contain the data members that individual executables are interested in, so that those classes only pull the necessary data. Don't know how many tables we're talking about, though, so that may explode the scope of your project.
C++ class design from database schema
I am writing a perl script to parse a mysql database schema and create C++ classes when necessary. My question is a pretty easy one, but us something I haven't really done before and don't know common practice. Any object of any of classes created will need to have "get" methods to populate this information. So my questions are twofold: Does it make sense to call all of the get methods in the constructor so that the object has data right away? Some classes will have a lot of them, so as needed might make sense too. I have two constrcutors now. One that populates the data and one that does not. Should I also have a another "get" method that retrieves the object's copy of the data rather that the db copy. I could go both ways on #1 and am leaning towards yes on #2. Any advice, pointers would be much appreciated.
[ "Ususally, the most costly part of an application is round trips to the database, so it would me much more efficient to populate all your data members from a single query than to do them one at a time, either on an as needed basis or from your constructor. Once you've paid for the round trip, you may as well get your money's worth.\nAlso, in general, your get* methods should be declared as const, meaning they don't change the underlying object, so having them go out to the database to populate the object would break that (which you could allow by making the member variables mutable, but that would basically defeat the purpose of const).\nTo break things down into concrete steps, I would recommend:\n\nHave your constructor call a separate init() method that queries the database and populates your object's data members.\nDeclare your get* methods as const, and just have them return the data members.\n\n", "First realize that you're re-inventing the wheel here. There are a number of decent object-relational mapping libraries for database access in just about every language. For C/C++ you might look at:\nhttp://trac.butterfat.net/public/StactiveRecord\nhttp://debea.net/trac\nOk, with that out of the way, you probably want to create a static method in your class called find or search which is a factory for constructing objects and selecting them from the database:\nArtist MJ = Artist::Find(\"Michael Jackson\");\nMJ->set(\"relevant\", \"no\");\nMJ->save();\n\nNote the save method which then takes the modified object and stores it back into the database. If you actually want to create a new record, then you'd use the new method which would instantiate an empty object:\nArtist StackOverflow = Artist->new();\nStackOverflow->set(\"relevant\", \"yes\");\nStackOverflow->save();\n\nNote the set and get methods here just set and get the values from the object, not the database. To actually store elements in the database you'd need to use the static Find method or the object's save method.\n", "there are existing tools that reverse db's into java (and probably other languages). consider using one of them and converting that to c++.\n", "I would not recommend having your get methods go to the database at all, unless absolutely necessary for your particular problem. It makes for a lot more places something could go wrong, and probably a lot of unnecessary reads on your DB, and could inadvertently tie your objects to db-specific features, losing a lot of the benefits of a tiered architecture. As far as your domain model is concerned, the database does not exist. \nedit - this is for #2 (obviously). For #1 I would say no, for many of the same reasons.\n", "Another alternative would be to not automate creating the classes, and instead create separate classes that only contain the data members that individual executables are interested in, so that those classes only pull the necessary data.\nDon't know how many tables we're talking about, though, so that may explode the scope of your project.\n" ]
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "c++", "class", "database", "mysql", "oop" ]
stackoverflow_0000083512_c++_class_database_mysql_oop.txt
Q: Built in unit-testing in VS I'm looking for advice on the built-in unit testing feature provided in VS08. Can any body please tell me if they know of any reasons NOT to use this feature over any of the other packages available (I'm vaguely familiar with NUnit)? I'm planning on applying unit testing to an older project just to learn the ropes of unit testing and some of the newer features in the .NET 3.5 framework. I like the look of the built in feature as from the quick demo I ran it seemed incredibly easy to use and I generally find Microsoft documentation very helpful. I'd be very grateful if anyone who is familiar with this feature could alert me to any issues I should be aware of or any reasons to avoid this in favour of another package. Note: I've tried raking through this (excellent) site for details specific to VS's built in unit testing feature. It has been mentioned a few times but I couldn't an exact match but please accept my apologies if this has been answered elsewhere. Thank you, Eric A: It looks like the discussion here can answer your question. A: The syntax can be a little clumsy, but if you're only trying to get to grips with unit testing, then there will be no harm in using the built-in stuff
Built in unit-testing in VS
I'm looking for advice on the built-in unit testing feature provided in VS08. Can any body please tell me if they know of any reasons NOT to use this feature over any of the other packages available (I'm vaguely familiar with NUnit)? I'm planning on applying unit testing to an older project just to learn the ropes of unit testing and some of the newer features in the .NET 3.5 framework. I like the look of the built in feature as from the quick demo I ran it seemed incredibly easy to use and I generally find Microsoft documentation very helpful. I'd be very grateful if anyone who is familiar with this feature could alert me to any issues I should be aware of or any reasons to avoid this in favour of another package. Note: I've tried raking through this (excellent) site for details specific to VS's built in unit testing feature. It has been mentioned a few times but I couldn't an exact match but please accept my apologies if this has been answered elsewhere. Thank you, Eric
[ "It looks like the discussion here can answer your question.\n", "The syntax can be a little clumsy, but if you're only trying to get to grips with unit testing, then there will be no harm in using the built-in stuff\n" ]
[ 1, 0 ]
[]
[]
[ ".net", "unit_testing" ]
stackoverflow_0000093060_.net_unit_testing.txt
Q: Using openssl encryption with Java I have a legacy C++ module that offers encryption/decryption using the openssl library (DES encryption). I'm trying to translate that code into java, and I don't want to rely on a DLL, JNI, etc... C++ code looks like: des_string_to_key(reinterpret_cast<const char *>(key1), &initkey); des_string_to_key(reinterpret_cast<const char *>(key2), &key); key_sched(&key, ks); // ... des_ncbc_encrypt(reinterpret_cast<const unsigned char *>(tmp.c_str()), reinterpret_cast< unsigned char *>(encrypted_buffer), tmp.length(), ks, &initkey, DES_ENCRYPT); return base64(reinterpret_cast<const unsigned char *>(encrypted_buffer), strlen(encrypted_buffer)); Java code looks like: Cipher ecipher; try { ecipher = Cipher.getInstance("DES"); SecretKeySpec keySpec = new SecretKeySpec(key, "DES"); ecipher.init(Cipher.ENCRYPT_MODE, keySpec); byte[] utf8 = password.getBytes("UTF8"); byte[] enc = ecipher.doFinal(utf8); return new sun.misc.BASE64Encoder().encode(enc); } catch { // ... } So I can do DES encryption in Java pretty easily, but how can I get the same result as with the above code with methods that are completely different? What bothers me in particular is the fact that the C++ version uses 2 keys while the Java version uses only 1 key. The answer about DES in CBC mode is quite satisfying but I can't get it to work yet. Here are more details about the original code: unsigned char key1[10]= {0}; unsigned char key2[50]= {0}; int i; for (i=0;i<8;i++) key1[i] = 31+int((i*sqrt((double)i*5)))%100; key1[9]=0; for (i=0;i<48;i++) key2[i] = 31+int((i*i*sqrt((double)i*2)))%100; key2[49]=0; ... // Initialize encrypted buffer memset(encrypted_buffer, 0, sizeof(encrypted_buffer)); // Add begin Text and End Text to the encrypted message std::string input; const char beginText = 2; const char endText = 3; input.append(1,beginText); input.append(bufferToEncrypt); input.append(1,endText); // Add padding tmp.assign(desPad(input)); des_ncbc_encrypt(reinterpret_cast<const unsigned char *>(tmp.c_str()), reinterpret_cast< unsigned char *>(encrypted_buffer), tmp.length(), ks, &initkey, DES_ENCRYPT); ... From what I've read, the key should be 56 (or 64, it's not clear to me) bits long, but here it's 48 bytes long. A: I'm not an OpenSSL expert, but I'd guess the C++ code is using DES in CBC mode thus needing an IV (that's what the initKey probably is, and that's why you think you need two keys). If I'm right, you need to change your Java code to use DES in CBC mode too, then the Java code too will require an encryption key and an IV. A: Also, keep in mind that you really shouldn't use sun.misc.* classes in your code. This could break in other VMs as these are not public APIs. Apache Commons Codecs (among others) have implementations of Base64 that don't bear this problem. I'm not really sure why single DES would ever use multiple keys. Even if you were using Triple-DES, I believe you would use a single key (with more bytes of data) rather than using separate keys with the Java Cryptography API. A: The algorithms should match; if you're getting different results it may have to do with the way you're handling the keys and the text. Also keep in mind that Java characters are 2 bytes long, which C++ chars are 1 byte, so that may have something to do with it.
Using openssl encryption with Java
I have a legacy C++ module that offers encryption/decryption using the openssl library (DES encryption). I'm trying to translate that code into java, and I don't want to rely on a DLL, JNI, etc... C++ code looks like: des_string_to_key(reinterpret_cast<const char *>(key1), &initkey); des_string_to_key(reinterpret_cast<const char *>(key2), &key); key_sched(&key, ks); // ... des_ncbc_encrypt(reinterpret_cast<const unsigned char *>(tmp.c_str()), reinterpret_cast< unsigned char *>(encrypted_buffer), tmp.length(), ks, &initkey, DES_ENCRYPT); return base64(reinterpret_cast<const unsigned char *>(encrypted_buffer), strlen(encrypted_buffer)); Java code looks like: Cipher ecipher; try { ecipher = Cipher.getInstance("DES"); SecretKeySpec keySpec = new SecretKeySpec(key, "DES"); ecipher.init(Cipher.ENCRYPT_MODE, keySpec); byte[] utf8 = password.getBytes("UTF8"); byte[] enc = ecipher.doFinal(utf8); return new sun.misc.BASE64Encoder().encode(enc); } catch { // ... } So I can do DES encryption in Java pretty easily, but how can I get the same result as with the above code with methods that are completely different? What bothers me in particular is the fact that the C++ version uses 2 keys while the Java version uses only 1 key. The answer about DES in CBC mode is quite satisfying but I can't get it to work yet. Here are more details about the original code: unsigned char key1[10]= {0}; unsigned char key2[50]= {0}; int i; for (i=0;i<8;i++) key1[i] = 31+int((i*sqrt((double)i*5)))%100; key1[9]=0; for (i=0;i<48;i++) key2[i] = 31+int((i*i*sqrt((double)i*2)))%100; key2[49]=0; ... // Initialize encrypted buffer memset(encrypted_buffer, 0, sizeof(encrypted_buffer)); // Add begin Text and End Text to the encrypted message std::string input; const char beginText = 2; const char endText = 3; input.append(1,beginText); input.append(bufferToEncrypt); input.append(1,endText); // Add padding tmp.assign(desPad(input)); des_ncbc_encrypt(reinterpret_cast<const unsigned char *>(tmp.c_str()), reinterpret_cast< unsigned char *>(encrypted_buffer), tmp.length(), ks, &initkey, DES_ENCRYPT); ... From what I've read, the key should be 56 (or 64, it's not clear to me) bits long, but here it's 48 bytes long.
[ "I'm not an OpenSSL expert, but I'd guess the C++ code is using DES in CBC mode thus needing an IV (that's what the initKey probably is, and that's why you think you need two keys). If I'm right, you need to change your Java code to use DES in CBC mode too, then the Java code too will require an encryption key and an IV.\n", "Also, keep in mind that you really shouldn't use sun.misc.* classes in your code. This could break in other VMs as these are not public APIs. Apache Commons Codecs (among others) have implementations of Base64 that don't bear this problem.\nI'm not really sure why single DES would ever use multiple keys. Even if you were using Triple-DES, I believe you would use a single key (with more bytes of data) rather than using separate keys with the Java Cryptography API.\n", "The algorithms should match; if you're getting different results it may have to do with the way you're handling the keys and the text. Also keep in mind that Java characters are 2 bytes long, which C++ chars are 1 byte, so that may have something to do with it.\n" ]
[ 1, 1, 0 ]
[]
[]
[ "encryption", "java", "openssl" ]
stackoverflow_0000092456_encryption_java_openssl.txt
Q: Unix Proc Directory I am trying to find the virtual file that contains the current users id. I was told that I could find it in the proc directory, but not quite sure which file. A: You actually want /proc/self/status, which will give you information about the currently executed process. Here is an example: $ cat /proc/self/status Name: cat State: R (running) Tgid: 17618 Pid: 17618 PPid: 3083 TracerPid: 0 Uid: 500 500 500 500 Gid: 500 500 500 500 FDSize: 32 Groups: 10 488 500 VmPeak: 4792 kB VmSize: 4792 kB VmLck: 0 kB VmHWM: 432 kB VmRSS: 432 kB VmData: 156 kB VmStk: 84 kB VmExe: 32 kB VmLib: 1532 kB VmPTE: 24 kB Threads: 1 SigQ: 0/32268 SigPnd: 0000000000000000 ShdPnd: 0000000000000000 SigBlk: 0000000000000000 SigIgn: 0000000000000000 SigCgt: 0000000000000000 CapInh: 0000000000000000 CapPrm: 0000000000000000 CapEff: 0000000000000000 Cpus_allowed: 00000003 Mems_allowed: 1 voluntary_ctxt_switches: 0 nonvoluntary_ctxt_switches: 3 You probably want to look at the first numbers on the Uid and Gid lines. You can look up which uid numbers map to what username by looking at /etc/passwd, or calling the relevant functions for mapping uid to username in whatever language you're using. Ideally, you would just call the system call getuid() to look up this information, doing it by looking at /proc/ is counterproductive. A: Why not just use "id -u"? A: I'm not sure that can be found in /proc. You could try using the getuid() function or the $USER environment variable. A: As far as I know, /proc is specific to Linux, it's not in UNIX in general. If you really just want the current UID, use the getuid() or geteuid() function. If you know you'll be on Linux only, you can explore the hierarchy under /proc/self/*, it contains various information about the current process. Remember that /proc is "magical", it's a virtual filesystem the kernel serves and the contents is dynamically generated at the point you request it. Therefore it can return information specific for the current process. For example, try this command: cat /proc/self/status A: Most likely, you either want to check the $USER environment variable. Other options include getuid and id -u, but searching /proc is certainly not the best method of action. A: In /proc/process_id/status (at least on Linux) you'll find a line like this: Uid: 1000 1000 1000 1000 This tells you the uid of the user under whose account the process is running. However, to find out the process id of the current process you would need a system call, and then you might as well call getuid to get the uid directly. Edit: ah, /proc/self/status... learning something new every day! A: The things you are looking for may be in environment variables. You need to be careful about what shell you are using when you check environment variables. bash uses "UID" while tcsh uses "uid" and in *nix case matters. I've also found that tcsh sets "gid" but I wasn't able to find a matching variable in bash.
Unix Proc Directory
I am trying to find the virtual file that contains the current users id. I was told that I could find it in the proc directory, but not quite sure which file.
[ "You actually want /proc/self/status, which will give you information about the currently executed process.\nHere is an example:\n$ cat /proc/self/status\nName: cat\nState: R (running)\nTgid: 17618\nPid: 17618\nPPid: 3083\nTracerPid: 0\nUid: 500 500 500 500\nGid: 500 500 500 500\nFDSize: 32\nGroups: 10 488 500 \nVmPeak: 4792 kB\nVmSize: 4792 kB\nVmLck: 0 kB\nVmHWM: 432 kB\nVmRSS: 432 kB\nVmData: 156 kB\nVmStk: 84 kB\nVmExe: 32 kB\nVmLib: 1532 kB\nVmPTE: 24 kB\nThreads: 1\nSigQ: 0/32268\nSigPnd: 0000000000000000\nShdPnd: 0000000000000000\nSigBlk: 0000000000000000\nSigIgn: 0000000000000000\nSigCgt: 0000000000000000\nCapInh: 0000000000000000\nCapPrm: 0000000000000000\nCapEff: 0000000000000000\nCpus_allowed: 00000003\nMems_allowed: 1\nvoluntary_ctxt_switches: 0\nnonvoluntary_ctxt_switches: 3\n\nYou probably want to look at the first numbers on the Uid and Gid lines. You can look up which uid numbers map to what username by looking at /etc/passwd, or calling the relevant functions for mapping uid to username in whatever language you're using.\nIdeally, you would just call the system call getuid() to look up this information, doing it by looking at /proc/ is counterproductive.\n", "Why not just use \"id -u\"?\n", "I'm not sure that can be found in /proc. You could try using the getuid() function or the $USER environment variable.\n", "As far as I know, /proc is specific to Linux, it's not in UNIX in general. If you really just want the current UID, use the getuid() or geteuid() function.\nIf you know you'll be on Linux only, you can explore the hierarchy under /proc/self/*, it contains various information about the current process. Remember that /proc is \"magical\", it's a virtual filesystem the kernel serves and the contents is dynamically generated at the point you request it. Therefore it can return information specific for the current process.\nFor example, try this command: cat /proc/self/status\n", "Most likely, you either want to check the $USER environment variable. Other options include getuid and id -u, but searching /proc is certainly not the best method of action.\n", "In /proc/process_id/status (at least on Linux) you'll find a line like this:\nUid: 1000 1000 1000 1000\nThis tells you the uid of the user under whose account the process is running.\nHowever, to find out the process id of the current process you would need a system call, and then you might as well call getuid to get the uid directly.\nEdit: ah, /proc/self/status... learning something new every day!\n", "The things you are looking for may be in environment variables. You need to be careful about what shell you are using when you check environment variables. bash uses \"UID\" while tcsh uses \"uid\" and in *nix case matters. I've also found that tcsh sets \"gid\" but I wasn't able to find a matching variable in bash.\n" ]
[ 8, 6, 3, 3, 1, 1, 0 ]
[]
[]
[ "linux", "procfs", "unix" ]
stackoverflow_0000089745_linux_procfs_unix.txt
Q: Are Java 6's performance improvements in the JDK, JVM, or both? I've been wondering about the performance improvements touted in Java SE 6 - is it in the compiler or the runtime? Put another way, would a Java 5 application compiled by JDK 6 see an improvement run under JSE 5 (indicating improved compiler optimization)? Would a Java 5 application compiled by JDK 5 see an improvement run under JSE 6 (indicating improved runtime optimization)? I've noticed that compiling under JDK 6 takes almost twice as long as it did under JDK 5 for the exact same codebase; I'm hoping that at least some of that extra time is being spent on compiler optimizations, hopefully leading to more performant JARs and WARs. Sun's JDK info doesn't really go into detail on the performance improvements they've made - I assume it's a little from column A, and a little from column B, but I wonder which is the greater influence. Does anyone know of any benchmarks done on JDK 6 vs. JDK 5? A: javac, which compiles from Java source to bytecodes, does almost no optimisation. Indeed optimisation would often make code actually run slower by being harder to analyse for later optimisation. The only significant difference between generated code for 1.5 and 1.6 is that with -target 1.6 extra information is added about the state of the stack to make verification easier and faster (Java ME does this as well). This only affects class loading speeds. The real optimising part is the hotspot compiler that compile bytecode to native code. This is even updated on some update releases. On Windows only the slower client C1 version of hotspot is distributed in the JRE by default. The server C2 hotspot runs faster (use -server on the java command line), but is slower to start up and uses more memory. Also the libraries and tools (including javac) sometimes have optimisation work done. I don't know why you are finding JDK 6 slower to compile code than JDK 5. Is there some subtle difference in set up? A: I have not heard about improvements in the compiler, but extensive information has been published on the runtime performance improvements. Migration guide: http://java.sun.com/javase/6/webnotes/adoption/adoptionguide.html Performance whitepaper: https://www.oracle.com/java/technologies/javase/6performance.html A: Its almost 100% the runtime. While it is possible for some basic compilation tricks to make it into the Java compiler itself, I don't believe there are any significant improvements between Java 1.5 and 1.6. A: There's been a lot of new improvements and optimization in the new java virtual machine. So the main part you'll see improved performance is while running java with the version 6 jvm. Compiling old java code using the Java 6 JDK will probably yield more efficient code, but the main improvements lie in the virtual machine, at least that's what I've noticed.
Are Java 6's performance improvements in the JDK, JVM, or both?
I've been wondering about the performance improvements touted in Java SE 6 - is it in the compiler or the runtime? Put another way, would a Java 5 application compiled by JDK 6 see an improvement run under JSE 5 (indicating improved compiler optimization)? Would a Java 5 application compiled by JDK 5 see an improvement run under JSE 6 (indicating improved runtime optimization)? I've noticed that compiling under JDK 6 takes almost twice as long as it did under JDK 5 for the exact same codebase; I'm hoping that at least some of that extra time is being spent on compiler optimizations, hopefully leading to more performant JARs and WARs. Sun's JDK info doesn't really go into detail on the performance improvements they've made - I assume it's a little from column A, and a little from column B, but I wonder which is the greater influence. Does anyone know of any benchmarks done on JDK 6 vs. JDK 5?
[ "javac, which compiles from Java source to bytecodes, does almost no optimisation. Indeed optimisation would often make code actually run slower by being harder to analyse for later optimisation.\nThe only significant difference between generated code for 1.5 and 1.6 is that with -target 1.6 extra information is added about the state of the stack to make verification easier and faster (Java ME does this as well). This only affects class loading speeds.\nThe real optimising part is the hotspot compiler that compile bytecode to native code. This is even updated on some update releases. On Windows only the slower client C1 version of hotspot is distributed in the JRE by default. The server C2 hotspot runs faster (use -server on the java command line), but is slower to start up and uses more memory.\nAlso the libraries and tools (including javac) sometimes have optimisation work done. \nI don't know why you are finding JDK 6 slower to compile code than JDK 5. Is there some subtle difference in set up?\n", "I have not heard about improvements in the compiler, but extensive information has been published on the runtime performance improvements.\nMigration guide:\nhttp://java.sun.com/javase/6/webnotes/adoption/adoptionguide.html\nPerformance whitepaper:\nhttps://www.oracle.com/java/technologies/javase/6performance.html\n", "Its almost 100% the runtime. While it is possible for some basic compilation tricks to make it into the Java compiler itself, I don't believe there are any significant improvements between Java 1.5 and 1.6.\n", "There's been a lot of new improvements and optimization in the new java virtual machine. So the main part you'll see improved performance is while running java with the version 6 jvm.\nCompiling old java code using the Java 6 JDK will probably yield more efficient code, but the main improvements lie in the virtual machine, at least that's what I've noticed.\n" ]
[ 7, 3, 1, 1 ]
[]
[]
[ "benchmarking", "comparison", "java", "performance", "versions" ]
stackoverflow_0000093049_benchmarking_comparison_java_performance_versions.txt
Q: Physics of a snooker game Anyone can point me to any info regarding physics of a snooker game, if possible more about the ball collisions? I would like to make a game and I need some help about the physics. A: There's a book online about this, "Amateur Physics for the Amateur Pool Player" by Ron Shepard (PDF Link) I haven't read it but I've heard it's good for game developers. A: Carom3D is a great one, they seem to have mastered the physics. See these links for more info: http://www.jimloy.com/billiard/phys.htm http://archive.ncsa.uiuc.edu/Classes/MATH198/townsend/math.html http://www2.swgc.mun.ca/physics/physlets/billiards.html http://www.regispetit.com/bil_praa.htm Good luck!
Physics of a snooker game
Anyone can point me to any info regarding physics of a snooker game, if possible more about the ball collisions? I would like to make a game and I need some help about the physics.
[ "There's a book online about this,\n\"Amateur Physics for the Amateur Pool Player\" by Ron Shepard (PDF Link)\nI haven't read it but I've heard it's good for game developers.\n", "Carom3D is a great one, they seem to have mastered the physics. See these links for more info:\nhttp://www.jimloy.com/billiard/phys.htm\nhttp://archive.ncsa.uiuc.edu/Classes/MATH198/townsend/math.html\nhttp://www2.swgc.mun.ca/physics/physlets/billiards.html\nhttp://www.regispetit.com/bil_praa.htm\nGood luck!\n" ]
[ 9, 1 ]
[]
[]
[ "physics" ]
stackoverflow_0000093085_physics.txt
Q: How to prevent the ObjectDisposedException in C# when drawing and application exits I'm a CompSci student, and fairly new at C#, and I was doing a "Josephus Problem" program for a class, and I created an Exit button that calls Application.Exit() to exit at anytime, but if C# is still working on painting and the button is pressed it throws an ObjectDisposedExeception for the Graphics object. Is there any way to prevent this?. I was thinking of try{}catch or change a boolean to tell the painting process to stop before exiting, but I want to know if there's another solution. A: You should be called the Close() method of the Form that contains the button in order to close down the form in an orderly manner. Closing the main form will cause the application to exit for you anyway. A: It shouldn't be possible for this to happen. If the button is created on the same thread as the window, they share a message pump and the Paint handler cannot be interrupted to handle the exit button. The message that the button has been clicked will be queued up on the thread's message queue until the Paint handler returns. Generally, you should defer painting to the Paint handler (or override OnPaint) and everywhere else that you need to update the screen, call the control's Invalidate method. That tells Windows that an area needs repainting and, once all other messages have been dealt with, it will generate a WM_PAINT message which ultimately will call OnPaint, which in turn will fire the Paint event. If animating, use a System.Windows.Forms.Timer to trigger each frame, rather than using a thread. System.Threading.Timer callbacks execute on the threadpool, so they're always on the wrong thread for manipulating the UI.
How to prevent the ObjectDisposedException in C# when drawing and application exits
I'm a CompSci student, and fairly new at C#, and I was doing a "Josephus Problem" program for a class, and I created an Exit button that calls Application.Exit() to exit at anytime, but if C# is still working on painting and the button is pressed it throws an ObjectDisposedExeception for the Graphics object. Is there any way to prevent this?. I was thinking of try{}catch or change a boolean to tell the painting process to stop before exiting, but I want to know if there's another solution.
[ "You should be called the Close() method of the Form that contains the button in order to close down the form in an orderly manner. Closing the main form will cause the application to exit for you anyway.\n", "It shouldn't be possible for this to happen. If the button is created on the same thread as the window, they share a message pump and the Paint handler cannot be interrupted to handle the exit button. The message that the button has been clicked will be queued up on the thread's message queue until the Paint handler returns.\nGenerally, you should defer painting to the Paint handler (or override OnPaint) and everywhere else that you need to update the screen, call the control's Invalidate method. That tells Windows that an area needs repainting and, once all other messages have been dealt with, it will generate a WM_PAINT message which ultimately will call OnPaint, which in turn will fire the Paint event.\nIf animating, use a System.Windows.Forms.Timer to trigger each frame, rather than using a thread. System.Threading.Timer callbacks execute on the threadpool, so they're always on the wrong thread for manipulating the UI.\n" ]
[ 2, 1 ]
[]
[]
[ "c#", "exception_handling", "graphics" ]
stackoverflow_0000090662_c#_exception_handling_graphics.txt
Q: Creating a workflow task generates an "Invalid field name" error I have a custom (code-based) workflow, deployed in WSS via features in a .wsp file. The workflow is configured with a custom task content type (ie, the Workflow element contains a TaskListContentTypeId attribute). This content type's declaration contains a FormUrls element pointing to a custom task edit page. When the workflow attempts to create a task, the workflow throws this exception: Invalid field name. {17ca3a22-fdfe-46eb-99b5-9646baed3f16 This is the ID of the FormURN site column. I thought FormURN is only used for InfoPath forms, not regular aspx forms... Does anyone have any idea how to solve this, so I can create tasks in my workflow? A: Are you using the CreateTaskWithContentTypeId activity in your workflow? If you are then you need to ensure that the content types have been added to the Workflow Tasks list. SharePoint will not add them automatically. Oisin A: It turns out that I was missing two things: My custom content type neeeded to be added to the workflow task list I needed to add an empty FieldRefs element to my content type definition; without it, the content type wasn't inheriting any workflow task fields.
Creating a workflow task generates an "Invalid field name" error
I have a custom (code-based) workflow, deployed in WSS via features in a .wsp file. The workflow is configured with a custom task content type (ie, the Workflow element contains a TaskListContentTypeId attribute). This content type's declaration contains a FormUrls element pointing to a custom task edit page. When the workflow attempts to create a task, the workflow throws this exception: Invalid field name. {17ca3a22-fdfe-46eb-99b5-9646baed3f16 This is the ID of the FormURN site column. I thought FormURN is only used for InfoPath forms, not regular aspx forms... Does anyone have any idea how to solve this, so I can create tasks in my workflow?
[ "Are you using the CreateTaskWithContentTypeId activity in your workflow? If you are then you need to ensure that the content types have been added to the Workflow Tasks list. SharePoint will not add them automatically.\nOisin\n", "It turns out that I was missing two things:\n\nMy custom content type neeeded to be\nadded to the workflow task list \nI needed to add an empty FieldRefs element to my content type definition; without it, the content type wasn't inheriting any workflow task fields.\n\n" ]
[ 2, 2 ]
[]
[]
[ "sharepoint", "workflow", "wss" ]
stackoverflow_0000086417_sharepoint_workflow_wss.txt
Q: Sending a 4 byte message header from C# client to a Java Server I am trying to write a C# client to a server that is written in Java. The server expects a 4 byte (DataInputStread readInt() in Java) message header followed by the actual message. I am absolutely new to C#, how can I send this message header over to the Java Server? I tried it several ways (mostly trial and error without getting too deep into the C# language), and nothing worked. The Java side ended up with the incorrect (very large) message length. A: It is, as other posters have pointed out, down to endianness. The Java DataInputStream expects the data to be big-endian (network byte order). Judging from the Mono documentation (for equivalents like BinaryWriter), C# tends toward being little-endian (the default for Win32/x86). So, when you use the standard class library to change the 32bit int '1' to bytes, they produce different results: //byte hex values Java: 00 00 00 01 C#: 01 00 00 00 You can alter the way you write ints in C#: private static void WriteInt(Stream stream, int n) { for(int i=3; i>=0; i--) { int shift = i * 8; //bits to shift byte b = (byte) (n >> shift); stream.WriteByte(b); } } EDIT: A safer way of doing this would be: private static void WriteToNetwork(System.IO.BinaryWriter stream, int n) { n = System.Net.IPAddress.HostToNetworkOrder(n); stream.Write(n); } A: It's simple, but have you checked endianness? It could easily be a mismatch between the endianness you have sent the data in and the endianness you are recieving in. A: As everyone here has already pointed out, the issue is most likely caused by the C# application sending ints in little-endian order whereas the Java app expects them in network order (big-endian). However, instead of explicitly rearranging bytes in the C# app, the correct way is to rely on built-in functions for converting from host to network order (htons and the likes) -- this way your code will continue working just fine even when run on a big-endian machine. In general, when troubleshooting such issues, I find it useful to record the correct traffic (e.g., Java to Java in your case) using tools like netcat or wireshark, and then compare it to the incorrect traffic to see where it's going wrong. As an added benefit, you can also use netcat to inject the captured/prerecorded requests into the server or inject captured/prerecorded responses into the client. Not to mention that you can also modify the requests/responses in a file and test the results before commencing with fixing the code. A: If you are going to be exchanging a lot of data, I would recommend implementing (or finding) a Stream-wrapper that can write and read ints in network-order. But if you really only need to write the length do something like this: using(Socket socket = ...){ NetworkStream ns = new NetworkStream(socket); ns.WriteByte((size>>24) & 0xFF); ns.WriteByte((size>>16) & 0xFF); ns.WriteByte((size>>8) & 0xFF); ns.WriteByte( size & 0xFF); // write the actual message } A: I dont know C# but you just need to do the equivalent of this: out.write((len >>> 24) & 0xFF); out.write((len >>> 16) & 0xFF); out.write((len >>> 8) & 0xFF); out.write((len >>> 0) & 0xFF); A: The Sysetm.Net.IPAddress class has two static helper methods: HostToNetworkOrder() and NetworkToHostOrder() that do the conversion for you. You can use it with a BinaryWriter over the stream to write the proper value: using (Socket socket = new Socket()) using (NetworkStream stream = new NetworkStream(socket)) using (BinaryWriter writer = new BinaryWriter(stream)) { int myValue = 42; writer.Write(IPAddress.HostToNetworkOrder(myValue)); }
Sending a 4 byte message header from C# client to a Java Server
I am trying to write a C# client to a server that is written in Java. The server expects a 4 byte (DataInputStread readInt() in Java) message header followed by the actual message. I am absolutely new to C#, how can I send this message header over to the Java Server? I tried it several ways (mostly trial and error without getting too deep into the C# language), and nothing worked. The Java side ended up with the incorrect (very large) message length.
[ "It is, as other posters have pointed out, down to endianness.\nThe Java DataInputStream expects the data to be big-endian (network byte order). Judging from the Mono documentation (for equivalents like BinaryWriter), C# tends toward being little-endian (the default for Win32/x86).\nSo, when you use the standard class library to change the 32bit int '1' to bytes, they produce different results:\n//byte hex values\nJava: 00 00 00 01\n C#: 01 00 00 00\n\nYou can alter the way you write ints in C#:\nprivate static void WriteInt(Stream stream, int n) {\n for(int i=3; i>=0; i--)\n {\n int shift = i * 8; //bits to shift\n byte b = (byte) (n >> shift);\n stream.WriteByte(b);\n }\n}\n\nEDIT:\nA safer way of doing this would be:\nprivate static void WriteToNetwork(System.IO.BinaryWriter stream, int n) {\n n = System.Net.IPAddress.HostToNetworkOrder(n);\n stream.Write(n);\n}\n\n", "It's simple, but have you checked endianness? It could easily be a mismatch between the endianness you have sent the data in and the endianness you are recieving in.\n", "As everyone here has already pointed out, the issue is most likely caused by the C# application sending ints in little-endian order whereas the Java app expects them in network order (big-endian). However, instead of explicitly rearranging bytes in the C# app, the correct way is to rely on built-in functions for converting from host to network order (htons and the likes) -- this way your code will continue working just fine even when run on a big-endian machine.\nIn general, when troubleshooting such issues, I find it useful to record the correct traffic (e.g., Java to Java in your case) using tools like netcat or wireshark, and then compare it to the incorrect traffic to see where it's going wrong. As an added benefit, you can also use netcat to inject the captured/prerecorded requests into the server or inject captured/prerecorded responses into the client. Not to mention that you can also modify the requests/responses in a file and test the results before commencing with fixing the code.\n", "If you are going to be exchanging a lot of data, I would recommend implementing (or finding) a Stream-wrapper that can write and read ints in network-order. But if you really only need to write the length do something like this:\nusing(Socket socket = ...){\n NetworkStream ns = new NetworkStream(socket); \n ns.WriteByte((size>>24) & 0xFF);\n ns.WriteByte((size>>16) & 0xFF);\n ns.WriteByte((size>>8) & 0xFF);\n ns.WriteByte( size & 0xFF);\n // write the actual message\n}\n\n", "I dont know C# but you just need to do the equivalent of this:\nout.write((len >>> 24) & 0xFF);\nout.write((len >>> 16) & 0xFF);\nout.write((len >>> 8) & 0xFF);\nout.write((len >>> 0) & 0xFF);\n\n", "The Sysetm.Net.IPAddress class has two static helper methods: HostToNetworkOrder() and NetworkToHostOrder() that do the conversion for you. You can use it with a BinaryWriter over the stream to write the proper value:\nusing (Socket socket = new Socket())\nusing (NetworkStream stream = new NetworkStream(socket))\nusing (BinaryWriter writer = new BinaryWriter(stream))\n{\n int myValue = 42;\n writer.Write(IPAddress.HostToNetworkOrder(myValue));\n}\n\n" ]
[ 11, 2, 2, 1, 0, 0 ]
[]
[]
[ "c#", "java", "sockets" ]
stackoverflow_0000092287_c#_java_sockets.txt
Q: How to protect yourself against shell DLLs loaded into your process? When you use a standard Windows "file open" dialog using GetOpenFileName(), the shell will load various DLLs that it requires to display the file list, including custom ones. In my application, I found that the DLL that TortoiseCVS uses to draw overlays on the icons was calling GdiPlusShutdown(), and so some time after displaying a "file open" dialog, the TortoiseCVS DLL would be unloaded, it would shut down GDI+ and my graphics functions would all fail! It seems quite bad that basically any old DLL could be loaded by my application at any time and start doing random things to its state. The workaround in my case was quite simple - just restart GDI+ if I detect that it's been shut down. However had this happened on a client's machine where I couldn't debug it, it would have been a lot more challenging to figure out what was going on. Can anybody offer any insight? What could I do to stop this from happening? A: I've had to deal with the crap that Dell puts on its machines, in particular wxVault. My solution was to "simply" patch the code. Slightly tricky with DEP, but still doable. You could have a peek at Microsoft Detours, which is a slightly more structured way to do the same. You'd still have the DLL load, but at least you can stop it calling functions that it should not be calling. At to why Windows has such a crappy mechanism, read Raymond Chen's "Old New Thing" blog or book.
How to protect yourself against shell DLLs loaded into your process?
When you use a standard Windows "file open" dialog using GetOpenFileName(), the shell will load various DLLs that it requires to display the file list, including custom ones. In my application, I found that the DLL that TortoiseCVS uses to draw overlays on the icons was calling GdiPlusShutdown(), and so some time after displaying a "file open" dialog, the TortoiseCVS DLL would be unloaded, it would shut down GDI+ and my graphics functions would all fail! It seems quite bad that basically any old DLL could be loaded by my application at any time and start doing random things to its state. The workaround in my case was quite simple - just restart GDI+ if I detect that it's been shut down. However had this happened on a client's machine where I couldn't debug it, it would have been a lot more challenging to figure out what was going on. Can anybody offer any insight? What could I do to stop this from happening?
[ "I've had to deal with the crap that Dell puts on its machines, in particular wxVault. My solution was to \"simply\" patch the code. Slightly tricky with DEP, but still doable. You could have a peek at Microsoft Detours, which is a slightly more structured way to do the same. You'd still have the DLL load, but at least you can stop it calling functions that it should not be calling.\nAt to why Windows has such a crappy mechanism, read Raymond Chen's \"Old New Thing\" blog or book.\n" ]
[ 1 ]
[]
[]
[ "dll", "shell", "winapi" ]
stackoverflow_0000093154_dll_shell_winapi.txt
Q: AssertionError with BIRT Runtime Engine API I'm new to BIRT and I'm trying to make the Report Engine running. I'm using the code snippets provided in http://www.eclipse.org/birt/phoenix/deploy/reportEngineAPI.php But I have a strange exception: java.lang.AssertionError at org.eclipse.birt.core.framework.Platform.startup(Platform.java:86) and nothing in the log file. Maybe I missed something in the configuration? Could somebody give me a hint about what I can try to make it running? Here is the code I'm using: public static void executeReport() { IReportEngine engine=null; EngineConfig config = null; try{ config = new EngineConfig( ); config.setBIRTHome("D:\\birt-runtime-2_3_0\\ReportEngine"); config.setLogConfig("d:/temp", Level.FINEST); Platform.startup( config ); IReportEngineFactory factory = (IReportEngineFactory) Platform .createFactoryObject( IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY ); engine = factory.createReportEngine( config ); IReportRunnable design = null; //Open the report design design = engine.openReportDesign("D:\\birt-runtime-2_3_0\\ReportEngine\\samples\\hello_world.rptdesign"); IRunAndRenderTask task = engine.createRunAndRenderTask(design); HTMLRenderOption options = new HTMLRenderOption(); options.setOutputFileName("output/resample/Parmdisp.html"); options.setOutputFormat("html"); task.setRenderOption(options); task.run(); task.close(); engine.destroy(); }catch( Exception ex){ ex.printStackTrace(); } finally { Platform.shutdown( ); } } A: I had the same mistake a couple of month ago. I'm not quite sure what actually fixed it but my code looks like the following: IDesignEngine engine = null; DesignConfig dConfig = new DesignConfig(); EngineConfig config = new EngineConfig(); IDesignEngineFactory factory = null; config.setLogConfig(LOG_DIRECTORY, Level.FINE); HttpServletRequest servletRequest = (HttpServletRequest) FacesContext.getCurrentInstance() .getExternalContext().getRequest(); String u = servletRequest.getSession().getServletContext().getRealPath("/"); File f = new File(u + PATH_TO_ENGINE_HOME); log.debug("setting engine home to:"+f.getAbsolutePath()); config.setEngineHome(f.getAbsolutePath()); Platform.startup(config); factory = (IDesignEngineFactory) Platform.createFactoryObject(IDesignEngineFactory.EXTENSION_DESIGN_ENGINE_FACTORY); engine = factory.createDesignEngine(dConfig); SessionHandle session = engine.newSessionHandle(null); this.design = session.openDesign(u + PATH_TO_MAIN_DESIGN); Perhaps you can solve your problem by comparing this code snippet and your own code. btw my PATH_TO_ENGINE_HOME is "/WEB-INF/platform". [edit]I used the complete "platform"-folder from the WebViewerExample of the birt-runtime-2_1_1. atm birt-runtime-2_3_0 is actual.[/edit] If this doesn't help please give a few more details (for example a code snippet). A: Just a thought, but I wonder if your use of a forward slash when setting the logger is causing a problem? instead of config.setLogConfig("d:/temp", Level.FINEST); you should use config.setLogConfig("/temp", Level.FINEST); or config.setLogConfig("d:\\temp", Level.FINEST); Finally, I realize that this is just some sample code, but you will certainly want to split your platform startup code out from your run and render task. The platform startup is very expensive and should only be done once per session. I have a couple of Eclipse projects that are setup in a Subversion server that demonstrate how to use the Report Engine API (REAPI) and the Design Engine API (DEAPI) that you may find useful as your code gets more complicated. To get the examples you will need either the Subclipse or the Subversive plugins and then you will need to connect to the following repository: http://longlake.minnovent.com/repos/birt_example The projects that you need are: birt_api_example birt_runtime_lib script.lib You may need to adjust some of the file locations in the BirtUtil class, but I think that most file locations are relative path. There is more information about how to use the examples projects on my blog at http:/birtworld.blogspot.com. In particular this article should help: Testing And Debug of Reports
AssertionError with BIRT Runtime Engine API
I'm new to BIRT and I'm trying to make the Report Engine running. I'm using the code snippets provided in http://www.eclipse.org/birt/phoenix/deploy/reportEngineAPI.php But I have a strange exception: java.lang.AssertionError at org.eclipse.birt.core.framework.Platform.startup(Platform.java:86) and nothing in the log file. Maybe I missed something in the configuration? Could somebody give me a hint about what I can try to make it running? Here is the code I'm using: public static void executeReport() { IReportEngine engine=null; EngineConfig config = null; try{ config = new EngineConfig( ); config.setBIRTHome("D:\\birt-runtime-2_3_0\\ReportEngine"); config.setLogConfig("d:/temp", Level.FINEST); Platform.startup( config ); IReportEngineFactory factory = (IReportEngineFactory) Platform .createFactoryObject( IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY ); engine = factory.createReportEngine( config ); IReportRunnable design = null; //Open the report design design = engine.openReportDesign("D:\\birt-runtime-2_3_0\\ReportEngine\\samples\\hello_world.rptdesign"); IRunAndRenderTask task = engine.createRunAndRenderTask(design); HTMLRenderOption options = new HTMLRenderOption(); options.setOutputFileName("output/resample/Parmdisp.html"); options.setOutputFormat("html"); task.setRenderOption(options); task.run(); task.close(); engine.destroy(); }catch( Exception ex){ ex.printStackTrace(); } finally { Platform.shutdown( ); } }
[ "I had the same mistake a couple of month ago. I'm not quite sure what actually fixed it but my code looks like the following:\n IDesignEngine engine = null;\n DesignConfig dConfig = new DesignConfig();\n EngineConfig config = new EngineConfig();\n IDesignEngineFactory factory = null;\n config.setLogConfig(LOG_DIRECTORY, Level.FINE);\n HttpServletRequest servletRequest = (HttpServletRequest) FacesContext.getCurrentInstance()\n .getExternalContext().getRequest();\n\n String u = servletRequest.getSession().getServletContext().getRealPath(\"/\");\n File f = new File(u + PATH_TO_ENGINE_HOME);\n\n log.debug(\"setting engine home to:\"+f.getAbsolutePath());\n config.setEngineHome(f.getAbsolutePath());\n\n Platform.startup(config);\n factory = (IDesignEngineFactory) Platform.createFactoryObject(IDesignEngineFactory.EXTENSION_DESIGN_ENGINE_FACTORY);\n engine = factory.createDesignEngine(dConfig);\n SessionHandle session = engine.newSessionHandle(null);\n\n this.design = session.openDesign(u + PATH_TO_MAIN_DESIGN);\n\nPerhaps you can solve your problem by comparing this code snippet and your own code. btw my PATH_TO_ENGINE_HOME is \"/WEB-INF/platform\". [edit]I used the complete \"platform\"-folder from the WebViewerExample of the birt-runtime-2_1_1. atm birt-runtime-2_3_0 is actual.[/edit]\nIf this doesn't help please give a few more details (for example a code snippet).\n", "Just a thought, but I wonder if your use of a forward slash when setting the logger is causing a problem? instead of\nconfig.setLogConfig(\"d:/temp\", Level.FINEST);\n\nyou should use \n config.setLogConfig(\"/temp\", Level.FINEST);\n\nor\n config.setLogConfig(\"d:\\\\temp\", Level.FINEST);\n\nFinally, I realize that this is just some sample code, but you will certainly want to split your platform startup code out from your run and render task. The platform startup is very expensive and should only be done once per session. \nI have a couple of Eclipse projects that are setup in a Subversion server that demonstrate how to use the Report Engine API (REAPI) and the Design Engine API (DEAPI) that you may find useful as your code gets more complicated. \nTo get the examples you will need either the Subclipse or the Subversive plugins and then you will need to connect to the following repository:\nhttp://longlake.minnovent.com/repos/birt_example\n\nThe projects that you need are:\nbirt_api_example\nbirt_runtime_lib\nscript.lib\n\nYou may need to adjust some of the file locations in the BirtUtil class, but I think that most file locations are relative path. There is more information about how to use the examples projects on my blog at http:/birtworld.blogspot.com. In particular this article should help: Testing And Debug of Reports\n" ]
[ 2, 1 ]
[]
[]
[ "birt", "java", "reporting" ]
stackoverflow_0000082123_birt_java_reporting.txt
Q: keep rsync from removing unfinished source files I have two machines, speed and mass. speed has a fast Internet connection and is running a crawler which downloads a lot of files to disk. mass has a lot of disk space. I want to move the files from speed to mass after they're done downloading. Ideally, I'd just run: $ rsync --remove-source-files speed:/var/crawldir . but I worry that rsync will unlink a source file that hasn't finished downloading yet. (I looked at the source code and I didn't see anything protecting against this.) Any suggestions? A: It seems to me the problem is transferring a file before it's complete, not that you're deleting it. If this is Linux, it's possible for a file to be open by process A and process B can unlink the file. There's no error, but of course A is wasting its time. Therefore, the fact that rsync deletes the source file is not a problem. The problem is rsync deletes the source file only after it's copied, and if it's still being written to disk you'll have a partial file. How about this: Mount mass as a remote file system (NFS would work) in speed. Then just web-crawl the files directly. A: How much control do you have over the download process? If you roll your own, you can have the file being downloaded go to a temp directory or have a temporary name until it's finished downloading, and then mv it to the correct name when it's done. If you're using third party software, then you don't have as much control, but you still might be able to do the temp directory thing. A: Rsync can exclude files matching certain patters. Even if you can't modify it to make it download files to a temporary directory, maybe it has a convention of naming the files differently during download (for example: foo.downloading while downloading for a file named foo) and you can use this property to exclude files which are still being downloaded from being copied. A: If you have control over the crawling process, or it has predictable output, the above solutions (storing in a tempfile until finished, then mv'ing to the completed-downloads place, or ignoring files with a '.downloading' kind of name) might work. If all of that is beyond your control, you can make sure that the file is not opened by any process by doing 'lsof $filename' and checking if there's a result. Clearly if no one has the file open, it's safe to move it over.
keep rsync from removing unfinished source files
I have two machines, speed and mass. speed has a fast Internet connection and is running a crawler which downloads a lot of files to disk. mass has a lot of disk space. I want to move the files from speed to mass after they're done downloading. Ideally, I'd just run: $ rsync --remove-source-files speed:/var/crawldir . but I worry that rsync will unlink a source file that hasn't finished downloading yet. (I looked at the source code and I didn't see anything protecting against this.) Any suggestions?
[ "It seems to me the problem is transferring a file before it's complete, not that you're deleting it.\nIf this is Linux, it's possible for a file to be open by process A and process B can unlink the file. There's no error, but of course A is wasting its time. Therefore, the fact that rsync deletes the source file is not a problem.\nThe problem is rsync deletes the source file only after it's copied, and if it's still being written to disk you'll have a partial file.\nHow about this: Mount mass as a remote file system (NFS would work) in speed. Then just web-crawl the files directly.\n", "How much control do you have over the download process? If you roll your own, you can have the file being downloaded go to a temp directory or have a temporary name until it's finished downloading, and then mv it to the correct name when it's done. If you're using third party software, then you don't have as much control, but you still might be able to do the temp directory thing.\n", "Rsync can exclude files matching certain patters. Even if you can't modify it to make it download files to a temporary directory, maybe it has a convention of naming the files differently during download (for example: foo.downloading while downloading for a file named foo) and you can use this property to exclude files which are still being downloaded from being copied.\n", "If you have control over the crawling process, or it has predictable output, the above solutions (storing in a tempfile until finished, then mv'ing to the completed-downloads place, or ignoring files with a '.downloading' kind of name) might work. If all of that is beyond your control, you can make sure that the file is not opened by any process by doing 'lsof $filename' and checking if there's a result. Clearly if no one has the file open, it's safe to move it over. \n" ]
[ 10, 9, 3, 3 ]
[]
[]
[ "rsync", "storage", "web_crawler" ]
stackoverflow_0000048491_rsync_storage_web_crawler.txt
Q: How to obtain Vista Edition programmatically? How to obtain Vista Edition programmatically, that is Home Basic, Home Premium, Business or Ultimate ? A: MSDN gives extensive answer: Getting the System Version A: [Environment.OSVersion][1] A: Brilliant! This is just what I need as well. Thanks aku. edg: Environment.OSVersion contains a version string but this doesn't generally give enough information to differentiate editions (also applies to XP Home/XP Pro). Also, there's the risk that this string will be localised so matching on it woudn't necessarily work.
How to obtain Vista Edition programmatically?
How to obtain Vista Edition programmatically, that is Home Basic, Home Premium, Business or Ultimate ?
[ "MSDN gives extensive answer:\nGetting the System Version\n", "[Environment.OSVersion][1]\n\n", "Brilliant! This is just what I need as well. Thanks aku.\nedg: Environment.OSVersion contains a version string but this doesn't generally give enough information to differentiate editions (also applies to XP Home/XP Pro). Also, there's the risk that this string will be localised so matching on it woudn't necessarily work.\n" ]
[ 5, 1, 0 ]
[]
[]
[ "windows_vista" ]
stackoverflow_0000056195_windows_vista.txt
Q: Can I automatically 'Generate Scripts' in a SQL Server 2005 task? I'd like to automatically generate database scripts on a regular basis. Is this possible. A: To generate script for an object you have to pass up to six parameters: exec proc_genscript @ServerName = 'Server Name', @DBName = 'Database Name', @ObjectName = 'Object Name to generate script for', @ObjectType = 'Object Type', @TableName = 'Parent table name for index and trigger', @ScriptFile = 'File name to save the script' http://www.databasejournal.com/features/mssql/article.php/2205291 A: You might want to look at the SQL Server Management Objects (SMO). There are objects for scripting that will assist in generating T-SQL scripts from database objects. A good reference for this is "Programming SQL Server 2005" by Bill Hamilton. Chapter 12 in particular references the SMO utility classes.
Can I automatically 'Generate Scripts' in a SQL Server 2005 task?
I'd like to automatically generate database scripts on a regular basis. Is this possible.
[ "To generate script for an object you have to pass up to six parameters:\nexec proc_genscript \n @ServerName = 'Server Name', \n @DBName = 'Database Name', \n @ObjectName = 'Object Name to generate script for', \n @ObjectType = 'Object Type', \n @TableName = 'Parent table name for index and trigger',\n @ScriptFile = 'File name to save the script'\n\nhttp://www.databasejournal.com/features/mssql/article.php/2205291\n", "You might want to look at the SQL Server Management Objects (SMO). There are objects for scripting that will assist in generating T-SQL scripts from database objects. A good reference for this is \"Programming SQL Server 2005\" by Bill Hamilton. Chapter 12 in particular references the SMO utility classes.\n" ]
[ 7, 0 ]
[]
[]
[ "scripting", "sql_server" ]
stackoverflow_0000093208_scripting_sql_server.txt
Q: Windsor Container: Registering things in Code vs Xml From what I've read about Windsor/Microkernel it is in theory possible to do everything that you can do using xml files with code. As a matter of fact - and please correct me if I'm wrong - it seems like the major contribution of the Windsor layer is to add xml configuration for things Microkernel can already do. However, I have been struggling lately with finding out how to implement some slightly more complicated functionality in code though (ie. how to assign a default constructor argument value). Now while I am going to use xml in my production release, I am registering components in code for my tests and this is getting to be quite problematic. This is not helped by the unfortunate state of their documentation and the fact that the only articles I can find focus on xml registration. Does anybody know a source which lists how to register things in code (preferably with the xml equivalent)? Baring the existence of that, does anyone simply know of an open source/sample project where there is significant non-xml use of Castle Windsor/Microkernel? A: I've always found looking at the unit test the best way to learn how to use an open source project. Castle has a fluent interface that will allow you to do everything in code. From the WindsorDotNet2Tests test case: [Test] public void ParentResolverIntercetorShouldNotAffectGenericComponentInterceptor() { WindsorContainer container = new WindsorContainer(); container.AddComponent<MyInterceptor>(); container.Register( Component.For<ISpecification>() .ImplementedBy<MySpecification>() .Interceptors(new InterceptorReference(typeof(MyInterceptor))) .Anywhere ); container.AddComponent("repos", typeof(IRepository<>), typeof(TransientRepository<>)); ISpecification specification = container.Resolve<ISpecification>(); bool isProxy = specification.Repository.GetType().FullName.Contains("Proxy"); Assert.IsFalse(isProxy); } And for more, check out the the ComponentRegistrationTestCase and AllTypesTestCase There is also a DSL for doing it, this is my prefered option, as it really simplifies things and offers alot of easy extensibility. The DSL is called Binsor, which you can read more about here: http://www.ayende.com/Blog/archive/7268.aspx But again, the best place for infor is the Unit Tests. This is a code example of whats possible with binsor: for type in AllTypesBased of IController("Company.Web.Controller"): component type Those two lines will register ever type that inherits the IController interface into the container :D
Windsor Container: Registering things in Code vs Xml
From what I've read about Windsor/Microkernel it is in theory possible to do everything that you can do using xml files with code. As a matter of fact - and please correct me if I'm wrong - it seems like the major contribution of the Windsor layer is to add xml configuration for things Microkernel can already do. However, I have been struggling lately with finding out how to implement some slightly more complicated functionality in code though (ie. how to assign a default constructor argument value). Now while I am going to use xml in my production release, I am registering components in code for my tests and this is getting to be quite problematic. This is not helped by the unfortunate state of their documentation and the fact that the only articles I can find focus on xml registration. Does anybody know a source which lists how to register things in code (preferably with the xml equivalent)? Baring the existence of that, does anyone simply know of an open source/sample project where there is significant non-xml use of Castle Windsor/Microkernel?
[ "I've always found looking at the unit test the best way to learn how to use an open source project. Castle has a fluent interface that will allow you to do everything in code. From the WindsorDotNet2Tests test case:\n[Test]\n public void ParentResolverIntercetorShouldNotAffectGenericComponentInterceptor()\n {\n WindsorContainer container = new WindsorContainer();\n container.AddComponent<MyInterceptor>();\n\n container.Register(\n Component.For<ISpecification>()\n .ImplementedBy<MySpecification>()\n .Interceptors(new InterceptorReference(typeof(MyInterceptor)))\n .Anywhere\n );\n container.AddComponent(\"repos\", typeof(IRepository<>), typeof(TransientRepository<>));\n\n ISpecification specification = container.Resolve<ISpecification>();\n bool isProxy = specification.Repository.GetType().FullName.Contains(\"Proxy\");\n Assert.IsFalse(isProxy);\n }\n\nAnd for more, check out the the ComponentRegistrationTestCase and AllTypesTestCase\nThere is also a DSL for doing it, this is my prefered option, as it really simplifies things and offers alot of easy extensibility. The DSL is called Binsor, which you can read more about here: http://www.ayende.com/Blog/archive/7268.aspx But again, the best place for infor is the Unit Tests. This is a code example of whats possible with binsor:\nfor type in AllTypesBased of IController(\"Company.Web.Controller\"):\n component type\n\nThose two lines will register ever type that inherits the IController interface into the container :D\n" ]
[ 6 ]
[]
[]
[ ".net", "castle_windsor", "inversion_of_control" ]
stackoverflow_0000093094_.net_castle_windsor_inversion_of_control.txt
Q: Is there a pretty printer for python data? Working with python interactively, it's sometimes necessary to display a result which is some arbitrarily complex data structure (like lists with embedded lists, etc.) The default way to display them is just one massive linear dump which just wraps over and over and you have to parse carefully to read it. Is there something that will take any python object and display it in a more rational manner. e.g. [0, 1, [a, b, c], 2, 3, 4] instead of: [0, 1, [a, b, c], 2, 3, 4] I know that's not a very good example, but I think you get the idea. A: from pprint import pprint a = [0, 1, ['a', 'b', 'c'], 2, 3, 4] pprint(a) Note that for a short list like my example, pprint will in fact print it all on one line. However, for more complex structures it does a pretty good job of pretty printing data. A: Somtimes YAML can be good for this. import yaml a = [0, 1, ['a', 'b', 'c'], 2, 3, 4] print yaml.dump(a) Produces: - 0 - 1 - [a, b, c] - 2 - 3 - 4 A: In addition to pprint.pprint, pprint.pformat is really useful for making readable __repr__s. My complex __repr__s usually look like so: def __repr__(self): from pprint import pformat return "<ClassName %s>" % pformat({"attrs":self.attrs, "that_i":self.that_i, "care_about":self.care_about}) A: Another good option is to use IPython, which is an interactive environment with a lot of extra features, including automatic pretty printing, tab-completion of methods, easy shell access, and a lot more. It's also very easy to install. IPython tutorial
Is there a pretty printer for python data?
Working with python interactively, it's sometimes necessary to display a result which is some arbitrarily complex data structure (like lists with embedded lists, etc.) The default way to display them is just one massive linear dump which just wraps over and over and you have to parse carefully to read it. Is there something that will take any python object and display it in a more rational manner. e.g. [0, 1, [a, b, c], 2, 3, 4] instead of: [0, 1, [a, b, c], 2, 3, 4] I know that's not a very good example, but I think you get the idea.
[ "from pprint import pprint\na = [0, 1, ['a', 'b', 'c'], 2, 3, 4]\npprint(a)\n\nNote that for a short list like my example, pprint will in fact print it all on one line. However, for more complex structures it does a pretty good job of pretty printing data.\n", "Somtimes YAML can be good for this.\nimport yaml\na = [0, 1, ['a', 'b', 'c'], 2, 3, 4]\nprint yaml.dump(a)\n\nProduces:\n- 0\n- 1\n- [a, b, c]\n- 2\n- 3\n- 4\n\n", "In addition to pprint.pprint, pprint.pformat is really useful for making readable __repr__s. My complex __repr__s usually look like so:\ndef __repr__(self):\n from pprint import pformat\n\n return \"<ClassName %s>\" % pformat({\"attrs\":self.attrs,\n \"that_i\":self.that_i,\n \"care_about\":self.care_about})\n\n", "Another good option is to use IPython, which is an interactive environment with a lot of extra features, including automatic pretty printing, tab-completion of methods, easy shell access, and a lot more. It's also very easy to install. \nIPython tutorial\n" ]
[ 29, 11, 8, 3 ]
[]
[]
[ "prettify", "python" ]
stackoverflow_0000091810_prettify_python.txt
Q: How to add a display name for a decorator in Visual Studio DSL (Domain Specific Language) Tools? In my DSL project I have a shape with a number of decorators that are linked to properties on my domain class. But even though ieach decorator has a DisplayName property (set to a meaningfull value) it does not appear in the generated DSL project. (I have not forgtten to use regenerate the t4 files.) Do I have to create another decorator for each property that only has the display name as a value that I wish to display or is there some other way that I can't figure out right now? A: I assume by a display name for the decorator you mean you want the element in the generated DSL to appear as "Example = a_value" where a_value is the actual value and Example is the property name. What I've done with this in the past is to create second property "ExampleDisplay" that's not browsable and is what the decorator actually points to. I then set the Kind property of the ExampleDisplay to "Calculated". You then need to provide the method that the toolkit tries to call to display the decorator which you can do a partial class. partial class ExampleElement { string GetExampleDisplayValue() { return "Example : " + this.Example; } } This is not ideal as you don't get a good way of setting the property on the DSL diagram you have to use the properties window. (There's sometime lags from the property window unless you hook into the update of the underlying property too). Getting the slick editing in the GUI that actual DSL toolkit does maybe possible but I haven't found out how. It maybe worth ask VSX forums if you haven't already done so.
How to add a display name for a decorator in Visual Studio DSL (Domain Specific Language) Tools?
In my DSL project I have a shape with a number of decorators that are linked to properties on my domain class. But even though ieach decorator has a DisplayName property (set to a meaningfull value) it does not appear in the generated DSL project. (I have not forgtten to use regenerate the t4 files.) Do I have to create another decorator for each property that only has the display name as a value that I wish to display or is there some other way that I can't figure out right now?
[ "I assume by a display name for the decorator you mean you want the element in the generated DSL to appear as \"Example = a_value\" where a_value is the actual value and Example is the property name.\nWhat I've done with this in the past is to create second property \"ExampleDisplay\" that's not browsable and is what the decorator actually points to. I then set the Kind property of the ExampleDisplay to \"Calculated\". You then need to provide the method that the toolkit tries to call to display the decorator which you can do a partial class.\npartial class ExampleElement\n{\n string GetExampleDisplayValue()\n {\n return \"Example : \" + this.Example;\n }\n}\n\nThis is not ideal as you don't get a good way of setting the property on the DSL diagram you have to use the properties window. (There's sometime lags from the property window unless you hook into the update of the underlying property too). Getting the slick editing in the GUI that actual DSL toolkit does maybe possible but I haven't found out how.\nIt maybe worth ask VSX forums if you haven't already done so.\n" ]
[ 1 ]
[]
[]
[ "dsl", "vsx" ]
stackoverflow_0000071843_dsl_vsx.txt
Q: Are properties accessed by fields still lazy-loaded? I'm using the field.camelcase in my mapping files to setting things like collections, dependant entities, etc. and exposing the collections as readonly arrays. I know the access strategy does not affect the lazy loading, I just want confirm that this will still be cached: private ISet<AttributeValue> attributes; public virtual AttributeValue[] Attributes { get { return attributes.ToArray(); } } A: The access value just tells it how to access the field and field.camelcase just tells it the naming strategy. This doesn't affect lazy loading. The lazy value will determine lazy loading in the mapping. See: https://nhibernate.info/doc/nhibernate-reference/mapping.html
Are properties accessed by fields still lazy-loaded?
I'm using the field.camelcase in my mapping files to setting things like collections, dependant entities, etc. and exposing the collections as readonly arrays. I know the access strategy does not affect the lazy loading, I just want confirm that this will still be cached: private ISet<AttributeValue> attributes; public virtual AttributeValue[] Attributes { get { return attributes.ToArray(); } }
[ "The access value just tells it how to access the field and field.camelcase just tells it the naming strategy. This doesn't affect lazy loading. The lazy value will determine lazy loading in the mapping.\nSee: https://nhibernate.info/doc/nhibernate-reference/mapping.html\n" ]
[ 0 ]
[]
[]
[ ".net", "c#", "lazy_loading", "nhibernate" ]
stackoverflow_0000093018_.net_c#_lazy_loading_nhibernate.txt
Q: Java Applet - Partially Signed? Is it possible to sign only part of an applet? Ie, have an applet that pops up no security warnings about being signed, but if some particular function is used (that requires privileges) then use the signed jar? From what I can tell, some (perhaps most) browsers will pop up the warning for a signed applet even if you don't request privileges at all at execution time. I'd rather avoid that if possible. A: Try splitting your code into an unsigned jar and a signed jar. A: In theory you can (signed + unsigned jar), but in practice it will result that your code will be handled as unsigned. The access decision should be made from the thread, not the immediate caller. If the thread contains in the stack a call made from an object from unsigned code, the whole call should be treated as unsigned. If you work around this you've found a bug. In other words... No. If I'm not being to curious, may I inquire why do you want to partially sign your code?
Java Applet - Partially Signed?
Is it possible to sign only part of an applet? Ie, have an applet that pops up no security warnings about being signed, but if some particular function is used (that requires privileges) then use the signed jar? From what I can tell, some (perhaps most) browsers will pop up the warning for a signed applet even if you don't request privileges at all at execution time. I'd rather avoid that if possible.
[ "Try splitting your code into an unsigned jar and a signed jar.\n", "In theory you can (signed + unsigned jar), but in practice it will result that your code will be handled as unsigned. The access decision should be made from the thread, not the immediate caller. If the thread contains in the stack a call made from an object from unsigned code, the whole call should be treated as unsigned. If you work around this you've found a bug.\nIn other words... No.\nIf I'm not being to curious, may I inquire why do you want to partially sign your code?\n" ]
[ 1, 1 ]
[ "I've been given the impression that Sun wants to discourage the creation of Applets and encourage the usage of Java Web Start. I think this issue of signing applets is part of the problem. See this documentation from Sun: Java Web start FAQ.\nI haven't tried this, but could you segment the features that need signing into separate jars that only require permission checks when the user needs the functionality in those jars?\n" ]
[ -1 ]
[ "applet", "java", "security", "signed_applet" ]
stackoverflow_0000077686_applet_java_security_signed_applet.txt
Q: What's the difference between Subclipse Get Contents and Get Revision? When using the Eclipse->Team->Show History view, what's the difference between using Subclipse "Get Contents" and "Get Revision" options on a revision of a file? Is there any way to see what svn commands Subclipse is issuing behind the scenes? A: From the Subclipse manual (Help > Help Contents): Get Contents Use this option to update the contents of the selected file in your working copy with the contents of the revision in the repository. The revision number of your local file is not changed by this option. This option is only valid when the resource history was launched for an individual file in a local working copy. Get Revision Use this option to replace the file in your working copy with the selected revision in the repository. The revision number of your local file is changed to the selected revision. This option is only valid when the resource history was launched for an individual file in a local working copy. Pretty self-explanatory. A: Get contents just shows you the file's contents, while get revision replaces your version of the file. To see the commands run by subclipse in the console view you should check the "Show SVN console automatically when command is run" option in tools/preferences/team/svn/console.
What's the difference between Subclipse Get Contents and Get Revision?
When using the Eclipse->Team->Show History view, what's the difference between using Subclipse "Get Contents" and "Get Revision" options on a revision of a file? Is there any way to see what svn commands Subclipse is issuing behind the scenes?
[ "From the Subclipse manual (Help > Help Contents):\n\nGet Contents\nUse this option to update the contents\n of the selected file in your working\n copy with the contents of the revision\n in the repository. The revision number\n of your local file is not changed by\n this option.\nThis option is only valid when the\n resource history was launched for an\n individual file in a local working\n copy. \nGet Revision\nUse this option to replace the file in\n your working copy with the selected\n revision in the repository. The\n revision number of your local file is\n changed to the selected revision.\nThis option is only valid when the\n resource history was launched for an\n individual file in a local working\n copy.\n\nPretty self-explanatory.\n", "Get contents just shows you the file's contents, while get revision replaces your version of the file.\nTo see the commands run by subclipse in the console view you should check the \"Show SVN console automatically when command is run\" option in tools/preferences/team/svn/console.\n" ]
[ 10, 1 ]
[]
[]
[ "eclipse_plugin", "revision", "subclipse", "svn", "version_control" ]
stackoverflow_0000093183_eclipse_plugin_revision_subclipse_svn_version_control.txt
Q: Self-owning web services, or services that can survive the death of the inventor I noticed a new web service today called a Dead man's switch, which dispatches email in the event that you don't respond to periodic "pings" that prove you're still alive. But it occurred to me that I might outlive the person or organization that pays the bills for the service, making the service useless. There are other kinds of services that we could be reluctant to use simply because the value is so high we don't trust it to an inventor who could lose interest, or an organization that could go insolvent. Like data repositories that could be used in many different programs and devices, but that would break them all if someone forgot to pay the hosting bill. But say the service "owned itself", and paid its own hosting bills? Like this: The host is Amazon EC2 or similar The bill is paid by debiting a bank account The bank account is replenished by interest returns and advertising revenue The bank account is in the name of the service itself, and once seeded is never touched for anything else again The creator declares the service "finished" and moves onto the next project To me, this is an engineering problem similar to those of building Mars rovers, bury-n-forget power generators, The Millenium Clock, and other artifacts that have their own homeostasis mechanisms and can be abandoned by their creators without ceasing to function. The question is: what are the gotchas? Must the bank account be in a real person's name? Can you prevent the govt. from considering the account "unclaimed" after n years? How could it recover from crashes? Is there an API for opening new hosting accounts at other companies so it could automatically scale itself and protect itself against the insolvency of any one host? A: You can't make a service robust in this way - if the bank account is a single point of failure then when (not if) it fails, you lose. A bank account can't exist without a legal entity to own it, but that's just a detail here - other failures are that Amazon might pull SC2, or raise the price, or make an incompatible API change, or be bribed by your rival or ordered by a court to remove your app. Ross Anderson has published an initial description of the requirements for an "eternity service" for data storage. The broad principle is to distribute it across as many people as possible, and ensure that they all have solid incentives to keep the service running, and to keep specific data live. It has to be resilient against as many as possible participants dropping out, and against as many as possible participants "going rogue" and trying to subvert it. He only gives broad outlines in the paper I read, and a few specific techniques that might be useful, but that was over 10 years ago. You might find further research if you look. http://www.cl.cam.ac.uk/~rja14/eternity/eternity.html A: One thing that pops into mind i Wikipedia. One of the co-inventors dropped out, another one is having an increasngly limited role in it, the editor turnover is mindboggling, and there are a large number of people trying to subvert it (vandalism, fake articles, putting in false information), and they have a constant influx of people who have no idea what they are doing. What they did do right was to have de-centralized the structure. Except for the servers that host it, everything on WP is spread out among thousands of admins and millions of contributors world wide. WP itself keeps on generating enough interest among new people to keep on replenishing the ones that leave - and they leave oh so often. If you looked into the innards of WP, you'd be shocked and appalled that it even works, but it works and does so rather usefully. A: I think you've been watching too many sci-fi movies. Why do I have the feeling you're the kind of guy who will bring about humanity's demise by letting loose the robots with deadly AI... Interesting thought though. I like it. :) A: The bank account must either be tied to a person (via SSN), or a corporation (via TIN). You'd have better luck tying it to a personal account because while a corporation sounds like what you're looking for, there are other costs involved such as state and federal taxes which would cause the corporation to be dissolved without human intervention to upkeep it. And as for the API, there is not currently a general API for this aside from "the creator" writing some sort of bot script that could sign up for some of the current host companies ... of course, this doesn't solve the "bury n forget" aspect. Very interesting idea though ... I'm very curious to see the other responses to this question :-) A: The service would need to gain an established legal identity of some description before a bank account could be opened in it's name. It could be a possibility once that occurs. A: Aside from the legal complexities. Your service would also need to know when it was time for it to delete itself. If it's no longer being used, and the information it contains is duplicated elsewhere in better/more efficient services (and how would you test for that?) - is it serving a purpose by continuing to consume resources? This is starting to sound awefully like the start of a large number of scifi stories, as others have said :)
Self-owning web services, or services that can survive the death of the inventor
I noticed a new web service today called a Dead man's switch, which dispatches email in the event that you don't respond to periodic "pings" that prove you're still alive. But it occurred to me that I might outlive the person or organization that pays the bills for the service, making the service useless. There are other kinds of services that we could be reluctant to use simply because the value is so high we don't trust it to an inventor who could lose interest, or an organization that could go insolvent. Like data repositories that could be used in many different programs and devices, but that would break them all if someone forgot to pay the hosting bill. But say the service "owned itself", and paid its own hosting bills? Like this: The host is Amazon EC2 or similar The bill is paid by debiting a bank account The bank account is replenished by interest returns and advertising revenue The bank account is in the name of the service itself, and once seeded is never touched for anything else again The creator declares the service "finished" and moves onto the next project To me, this is an engineering problem similar to those of building Mars rovers, bury-n-forget power generators, The Millenium Clock, and other artifacts that have their own homeostasis mechanisms and can be abandoned by their creators without ceasing to function. The question is: what are the gotchas? Must the bank account be in a real person's name? Can you prevent the govt. from considering the account "unclaimed" after n years? How could it recover from crashes? Is there an API for opening new hosting accounts at other companies so it could automatically scale itself and protect itself against the insolvency of any one host?
[ "You can't make a service robust in this way - if the bank account is a single point of failure then when (not if) it fails, you lose. A bank account can't exist without a legal entity to own it, but that's just a detail here - other failures are that Amazon might pull SC2, or raise the price, or make an incompatible API change, or be bribed by your rival or ordered by a court to remove your app.\nRoss Anderson has published an initial description of the requirements for an \"eternity service\" for data storage. The broad principle is to distribute it across as many people as possible, and ensure that they all have solid incentives to keep the service running, and to keep specific data live. It has to be resilient against as many as possible participants dropping out, and against as many as possible participants \"going rogue\" and trying to subvert it.\nHe only gives broad outlines in the paper I read, and a few specific techniques that might be useful, but that was over 10 years ago. You might find further research if you look.\nhttp://www.cl.cam.ac.uk/~rja14/eternity/eternity.html\n", "One thing that pops into mind i Wikipedia. One of the co-inventors dropped out, another one is having an increasngly limited role in it, the editor turnover is mindboggling, and there are a large number of people trying to subvert it (vandalism, fake articles, putting in false information), and they have a constant influx of people who have no idea what they are doing. \nWhat they did do right was to have de-centralized the structure. Except for the servers that host it, everything on WP is spread out among thousands of admins and millions of contributors world wide. WP itself keeps on generating enough interest among new people to keep on replenishing the ones that leave - and they leave oh so often. If you looked into the innards of WP, you'd be shocked and appalled that it even works, but it works and does so rather usefully.\n", "I think you've been watching too many sci-fi movies. Why do I have the feeling you're the kind of guy who will bring about humanity's demise by letting loose the robots with deadly AI...\nInteresting thought though. I like it. :)\n", "The bank account must either be tied to a person (via SSN), or a corporation (via TIN). You'd have better luck tying it to a personal account because while a corporation sounds like what you're looking for, there are other costs involved such as state and federal taxes which would cause the corporation to be dissolved without human intervention to upkeep it.\nAnd as for the API, there is not currently a general API for this aside from \"the creator\" writing some sort of bot script that could sign up for some of the current host companies ... of course, this doesn't solve the \"bury n forget\" aspect.\nVery interesting idea though ... I'm very curious to see the other responses to this question :-)\n", "The service would need to gain an established legal identity of some description before a bank account could be opened in it's name.\nIt could be a possibility once that occurs.\n", "Aside from the legal complexities. \nYour service would also need to know when it was time for it to delete itself. \nIf it's no longer being used, and the information it contains is duplicated elsewhere in better/more efficient services (and how would you test for that?) - is it serving a purpose by continuing to consume resources? \nThis is starting to sound awefully like the start of a large number of scifi stories, as others have said :)\n" ]
[ 4, 1, 0, 0, 0, 0 ]
[]
[]
[ "web_services" ]
stackoverflow_0000092638_web_services.txt
Q: Proving correctness of multithread algorithms Multithread algorithms are notably hard to design/debug/prove. Dekker's algorithm is a prime example of how hard it can be to design a correct synchronized algorithm. Tanenbaum's Modern operating systems is filled with examples in its IPC section. Does anyone have a good reference (books, articles) for this? Thanks! A: It is impossible to prove anything without building upon guarentees, so the first thing you want to do is to get familiar with the memory model of your target platform; Java and x86 both have solid and standardized memory models - I'm not so sure about CLR, but if all else fails, you'll have build upon the memory model of your target CPU architecture. The exception to this rule is if you intend to use a language that does does not allow any shared mutable state at all - I've heard Erlang is like that. The first problem of concurrency is shared mutable state. That can be fixed by: Making state immutable Not sharing state Guarding shared mutable state by the same lock (two different locks cannot guard the same piece of state, unless you always use exactly these two locks) The second problem of concurrency is safe publication. How do you make data available to other threads? How do you perform a hand-over? You'll the solution to this problem in the memory model, and (hopefully) in the API. Java, for instance, has many ways to publish state and the java.util.concurrent package contains tools specifically designed to handle inter-thread communication. The third (and harder) problem of concurrency is locking. Mismanaged lock-ordering is the source of dead-locks. You can analytically prove, building upon the memory model guarentees, whether or not dead-locks are possible in your code. However, you need to design and write your code with that in mind, otherwise the complexity of the code can quickly render such an analysis impossible to perform in practice. Then, once you have, or before you do, prove the correct use of concurrency, you will have to prove single-threaded correctness. The set of bugs that can occur in a concurrent code base is equal to the set of single-threaded program bugs, plus all the possible concurrency bugs. A: The Pi-Calculus, A Theory of Mobile Processes is a good place to begin. A: "Principles of Concurrent and Distributed Programming", M. Ben-Ari ISBN-13: 978-0-321-31283-9 They have in on safari books online for reading: http://my.safaribooksonline.com/9780321312839 A: Short answer: it's hard. There was some really good work in the DEC SRC Modula-3 and larch stuff from the late 1980's. e.g. Thread synchronization: A formal specification (1991) by A D Birrell, J V Guttag, J J Horning, R Levin System Programming with Modula-3, chapter 5 Extended static checking (1998) by David L. Detlefs, David L. Detlefs, K. Rustan, K. Rustan, M. Leino, M. Leino, Greg Nelson, Greg Nelson, James B. Saxe, James B. Saxe Some of the good ideas from Modula-3 are making it into the Java world, e.g. JML, though "JML is currently limited to sequential specification" says the intro. A: I don't have any concrete references, but you might want to look into the Owicki-Gries theory (if you like theorem proving) or process theory/algebra (for which there are also various model-checking tools available). A: @Just in case: I is. But from what i learnt, doing so for a non trivial algorithm is a major pain. I leave that sort of a thing for brainier people. I learnt what i know from Parallel Program Design: A Foundation (1988) by K M Chandy, J Misra
Proving correctness of multithread algorithms
Multithread algorithms are notably hard to design/debug/prove. Dekker's algorithm is a prime example of how hard it can be to design a correct synchronized algorithm. Tanenbaum's Modern operating systems is filled with examples in its IPC section. Does anyone have a good reference (books, articles) for this? Thanks!
[ "It is impossible to prove anything without building upon guarentees, so the first thing you want to do is to get familiar with the memory model of your target platform; Java and x86 both have solid and standardized memory models - I'm not so sure about CLR, but if all else fails, you'll have build upon the memory model of your target CPU architecture. The exception to this rule is if you intend to use a language that does does not allow any shared mutable state at all - I've heard Erlang is like that.\nThe first problem of concurrency is shared mutable state.\nThat can be fixed by:\n\nMaking state immutable\nNot sharing state\nGuarding shared mutable state by the same lock (two different locks cannot guard the same piece of state, unless you always use exactly these two locks)\n\nThe second problem of concurrency is safe publication. How do you make data available to other threads? How do you perform a hand-over? You'll the solution to this problem in the memory model, and (hopefully) in the API. Java, for instance, has many ways to publish state and the java.util.concurrent package contains tools specifically designed to handle inter-thread communication.\nThe third (and harder) problem of concurrency is locking. Mismanaged lock-ordering is the source of dead-locks. You can analytically prove, building upon the memory model guarentees, whether or not dead-locks are possible in your code. However, you need to design and write your code with that in mind, otherwise the complexity of the code can quickly render such an analysis impossible to perform in practice.\nThen, once you have, or before you do, prove the correct use of concurrency, you will have to prove single-threaded correctness. The set of bugs that can occur in a concurrent code base is equal to the set of single-threaded program bugs, plus all the possible concurrency bugs.\n", "The Pi-Calculus, A Theory of Mobile Processes is a good place to begin.\n", "\"Principles of Concurrent and Distributed Programming\", M. Ben-Ari\nISBN-13: 978-0-321-31283-9\nThey have in on safari books online for reading:\nhttp://my.safaribooksonline.com/9780321312839\n", "Short answer: it's hard.\nThere was some really good work in the DEC SRC Modula-3 and larch stuff from the late 1980's.\ne.g.\n\nThread synchronization: A formal specification (1991)\nby A D Birrell, J V Guttag, J J Horning, R Levin\nSystem Programming with Modula-3, chapter 5 \nExtended static checking (1998)\nby David L. Detlefs, David L. Detlefs, K. Rustan, K. Rustan, M. Leino, M. Leino, Greg Nelson, Greg Nelson, James B. Saxe, James B. Saxe\n\nSome of the good ideas from Modula-3 are making it into the Java world, e.g.\nJML, though \"JML is currently limited to sequential specification\" says the intro.\n", "I don't have any concrete references, but you might want to look into the Owicki-Gries theory (if you like theorem proving) or process theory/algebra (for which there are also various model-checking tools available).\n", "@Just in case: I is. But from what i learnt, doing so for a non trivial algorithm is a major pain. I leave that sort of a thing for brainier people. I learnt what i know from Parallel Program Design: A Foundation (1988)\nby K M Chandy, J Misra \n" ]
[ 13, 3, 3, 2, 1, 0 ]
[]
[]
[ "algorithm", "correctness", "multithreading", "proof", "theory" ]
stackoverflow_0000074391_algorithm_correctness_multithreading_proof_theory.txt
Q: How do you mock params when testing a Rails model's setter? Given the code from the Complex Form part III how would you go about testing the virtual attribute? def new_task_attributes=(task_attributes) task_attributes.each do |attributes| tasks.build(attributes) end end I am currently trying to test it like this: def test_adding_task_to_project p = Project.new params = {"new_tasks_attributes" => [{ "name" => "paint fence"}]} p.new_tasks_attributes=(params) p.save assert p.tasks.length == 1 end But I am getting the following error: NoMethodError: undefined method `stringify_keys!' for "new_tasks_attributes":String Any suggestions on improving this test would be greatly appreciated. A: It looks as if new_task_attributes= is expecting an array of hashes, but you're passing it a hash. Try this: def test_adding_task_to_project p = Project.new new_tasks_attributes = [{ "name" => "paint fence"}] p.new_tasks_attributes = (new_tasks_attributes) p.save assert p.tasks.length == 1 end A: Can we see the whole stack trace? Where does it think String#stringify_keys! is being called? Also, params looks odd to me. Is tasks.build() expecting input like this: ["new_tasks_attribute", {"name" => "paint fence"}] ? If not, maybe you actually want Hash#each_key() instead of Hash#each()? Need more data. Also, you might consider a Ruby tag to accompany your Rails tag.
How do you mock params when testing a Rails model's setter?
Given the code from the Complex Form part III how would you go about testing the virtual attribute? def new_task_attributes=(task_attributes) task_attributes.each do |attributes| tasks.build(attributes) end end I am currently trying to test it like this: def test_adding_task_to_project p = Project.new params = {"new_tasks_attributes" => [{ "name" => "paint fence"}]} p.new_tasks_attributes=(params) p.save assert p.tasks.length == 1 end But I am getting the following error: NoMethodError: undefined method `stringify_keys!' for "new_tasks_attributes":String Any suggestions on improving this test would be greatly appreciated.
[ "It looks as if new_task_attributes= is expecting an array of hashes, but you're passing it a hash. Try this:\ndef test_adding_task_to_project\n p = Project.new\n new_tasks_attributes = [{ \"name\" => \"paint fence\"}]\n p.new_tasks_attributes = (new_tasks_attributes)\n p.save\n assert p.tasks.length == 1\nend\n\n", "Can we see the whole stack trace? Where does it think String#stringify_keys! is being called?\nAlso, params looks odd to me. Is tasks.build() expecting input like this: [\"new_tasks_attribute\", {\"name\" => \"paint fence\"}] ?\nIf not, maybe you actually want Hash#each_key() instead of Hash#each()?\nNeed more data. Also, you might consider a Ruby tag to accompany your Rails tag.\n" ]
[ 3, 0 ]
[]
[]
[ "ruby_on_rails", "testing", "testing_strategies", "unit_testing" ]
stackoverflow_0000093214_ruby_on_rails_testing_testing_strategies_unit_testing.txt
Q: How do I best convert a string representation into a DbType? Suppose I have a string 'nvarchar(50)', which is for example the T-SQL string segment used in creating a table of that type. How do I best convert that to an enum representation of System.Data.DbType? Could it handle the many different possible ways of writing the type in T-SQL, such as: [nvarchar](50) nvarchar 50 @Jorge Table: Yes, that's handy, but isn't there a prebaked converter? Otherwise good answer. A: Hope this mapping table do the job. http://www.carlprothman.net/Default.aspx?tabid=97 A: My first attempt would involve using a regex to parse the two parts of the declaration (where the second part is only used for variably sized types.) Make sure that you convert the type-name to lower case when you've parsed it. You could make an enum with all the various types in it (lower-cased), then use Enum.Parse to get an instance of the enum value, and then use a switch-case to get the appropriate System.Data.DbType for each enum value. Kind of gross, I admit.
How do I best convert a string representation into a DbType?
Suppose I have a string 'nvarchar(50)', which is for example the T-SQL string segment used in creating a table of that type. How do I best convert that to an enum representation of System.Data.DbType? Could it handle the many different possible ways of writing the type in T-SQL, such as: [nvarchar](50) nvarchar 50 @Jorge Table: Yes, that's handy, but isn't there a prebaked converter? Otherwise good answer.
[ "Hope this mapping table do the job.\nhttp://www.carlprothman.net/Default.aspx?tabid=97\n", "My first attempt would involve using a regex to parse the two parts of the declaration (where the second part is only used for variably sized types.) Make sure that you convert the type-name to lower case when you've parsed it.\nYou could make an enum with all the various types in it (lower-cased), then use Enum.Parse to get an instance of the enum value, and then use a switch-case to get the appropriate System.Data.DbType for each enum value.\nKind of gross, I admit.\n" ]
[ 1, 1 ]
[]
[]
[ ".net", "converter", "database" ]
stackoverflow_0000091124_.net_converter_database.txt
Q: Map of Enums and dependency injection in Spring 2.5 Let's assume we've got the following Java code: public class Maintainer { private Map<Enum, List<Listener>> map; public Maintainer() { this.map = new java.util.ConcurrentHashMap<Enum, List<Listener>>(); } public void addListener( Listener listener, Enum eventType ) { List<Listener> listeners; if( ( listeners = map.get( eventType ) ) == null ) { listeners = new java.util.concurrent.CopyOnWriteArrayList<Listener>(); map.put( eventType, listeners ); } listeners.add( listener ); } } This code snippet is nothing but a bit improved listener pattern where each listener is telling what type of event it is interested in, and the provided method maintains a concurrent map of these relationships. Initially, I wanted this method to be called via my own annotation framework, but bumped into a brick wall of various annotation limitations (e.g. you can't have java.lang.Enum as annotation param, also there's a set of various classloader issues) therefore decided to use Spring. Could anyone tell me how do I Spring_ify_ this? What I want to achive is: 1. Define Maintainer class as a Spring bean. 2. Make it so that all sorts of listeners would be able to register themselves to Maintainer via XML by using addListener method. Spring doc nor Google are very generous in examples. Is there a way to achieve this easily? A: What would be wrong with doing something like the following: Defining a 'Maintainer' interface with the addListener(Listener, Enum) method. Create a DefaultMaintainer class (as above) which implements Maintainer. Then, in each Listener class, 'inject' the Maintainer interface (constructor injection might be a good choice). The listener can then register itself with the Maintainer. other than that, I'm not 100% clear on exactly what your difficulty is with Spring at the moment! :) A: Slightly offtopic (as this is not about Spring) but there is a race condition in your implementation of AddListener: if( ( listeners = map.get( eventType ) ) == null ) { listeners = new java.util.concurrent.CopyOnWriteArrayList<Listener>(); map.put( eventType, listeners ); } listeners.add( listener ); If two threads call this method at the same time (for an event type that previously had no listeners), map.get( eventType ) will return null in both threads, each thread will create its own CopyOnWriteArrayList (each containing a single listener), one thread will replace the list created by the other, and the first listener will be forgotten. To fix this, change: private Map<Enum, List<Listener>> map; ... map.put( eventType, listeners ); to: private ConcurrentMap<Enum, List<Listener>> map; ... map.putIfAbsent( eventType, listeners ); listeners = map.get( eventType ); A: 1) Define Maintainer class as a Spring bean. Standard Spring syntax applies: <bean id="maintainer" class="com.example.Maintainer"/> 2) Make it so that all sorts of listeners would be able to register themselves to Maintainer via XML by using addListener method. Spring doc nor Google are very generous in examples. This is trickier. You could use MethodInvokingFactoryBean to individually call maintainer#addListener, like so: <bean id="listener" class="com.example.Listener"/> <bean id="maintainer.addListener" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="targetObject" ref="maintainer"/> <property name="targetMethod" value="addListener"/> <property name="arguments"> <list> <ref>listener</ref> <value>com.example.MyEnum</value> </list> </property> </bean> However, this is unwieldy, and potentially error-prone. I attempted something similar on a project, and created a Spring utility class to help out instead. I don't have the source code available at the moment, so I'll describe how to implement what I did. 1) Refactor the event types listened to into a MyListener interface public interface MyListener extends Listener { public Enum[] getEventTypes() } Which changes the registration method to public void addListener(MyListener listener) 2) Create Spring helper class that finds all relevant listeners in the context, and calls maintainer#addListener for each listener found. I would start with BeanFilteringSupport, and also implement BeanPostProcessor (or ApplicationListener) to register the beans after all beans have been instantiated. A: You said "... you can't have java.lang.Enum as" annotation param ..." I think you are wrong on that. I have recently used on a project something like this : public @interface MyAnnotation { MyEnum value(); } A: Thank you all for the answers. First, A quick follow up on all answers. 1. (alexvictor) Yes, you can have concrete enum as annotation param, but not java.lang.Enum. 2. Answer provided by flicken is correct, but unfortunately a bit scary. I am not a Spring expert but doing things this way (creating methods for easier Spring access) this seems to be a bit overkill, as is the MethodInvokingFactoryBean solution. Although I wanted to express my sincere thanks for your time and effort. 3. The answer by Phill is a bit unusual (instead of injecting listener bean, inject its maintainer!), but, I believe, the cleanest of all available. I think I will go down this path. Again, a big thanks you for your help.
Map of Enums and dependency injection in Spring 2.5
Let's assume we've got the following Java code: public class Maintainer { private Map<Enum, List<Listener>> map; public Maintainer() { this.map = new java.util.ConcurrentHashMap<Enum, List<Listener>>(); } public void addListener( Listener listener, Enum eventType ) { List<Listener> listeners; if( ( listeners = map.get( eventType ) ) == null ) { listeners = new java.util.concurrent.CopyOnWriteArrayList<Listener>(); map.put( eventType, listeners ); } listeners.add( listener ); } } This code snippet is nothing but a bit improved listener pattern where each listener is telling what type of event it is interested in, and the provided method maintains a concurrent map of these relationships. Initially, I wanted this method to be called via my own annotation framework, but bumped into a brick wall of various annotation limitations (e.g. you can't have java.lang.Enum as annotation param, also there's a set of various classloader issues) therefore decided to use Spring. Could anyone tell me how do I Spring_ify_ this? What I want to achive is: 1. Define Maintainer class as a Spring bean. 2. Make it so that all sorts of listeners would be able to register themselves to Maintainer via XML by using addListener method. Spring doc nor Google are very generous in examples. Is there a way to achieve this easily?
[ "What would be wrong with doing something like the following:\nDefining a 'Maintainer' interface with the addListener(Listener, Enum) method.\nCreate a DefaultMaintainer class (as above) which implements Maintainer.\nThen, in each Listener class, 'inject' the Maintainer interface (constructor injection might be a good choice). The listener can then register itself with the Maintainer.\nother than that, I'm not 100% clear on exactly what your difficulty is with Spring at the moment! :)\n", "Slightly offtopic (as this is not about Spring) but there is a race condition in your implementation of AddListener:\n if( ( listeners = map.get( eventType ) ) == null ) {\n listeners = new java.util.concurrent.CopyOnWriteArrayList<Listener>();\n map.put( eventType, listeners );\n }\n listeners.add( listener );\n\nIf two threads call this method at the same time (for an event type that previously had no listeners), map.get( eventType ) will return null in both threads, each thread will create its own CopyOnWriteArrayList (each containing a single listener), one thread will replace the list created by the other, and the first listener will be forgotten.\nTo fix this, change:\nprivate Map<Enum, List<Listener>> map;\n\n...\n\nmap.put( eventType, listeners );\n\nto:\nprivate ConcurrentMap<Enum, List<Listener>> map;\n\n...\n\nmap.putIfAbsent( eventType, listeners );\nlisteners = map.get( eventType );\n\n", "\n1) Define Maintainer class as a Spring bean.\n\nStandard Spring syntax applies:\n<bean id=\"maintainer\" class=\"com.example.Maintainer\"/>\n\n\n2) Make it so that all sorts of listeners would be able to register themselves to Maintainer via XML by using addListener method. Spring doc nor Google are very generous in examples.\n\nThis is trickier. You could use MethodInvokingFactoryBean to individually call maintainer#addListener, like so:\n<bean id=\"listener\" class=\"com.example.Listener\"/>\n\n<bean id=\"maintainer.addListener\" class=\"org.springframework.beans.factory.config.MethodInvokingFactoryBean\">\n <property name=\"targetObject\" ref=\"maintainer\"/>\n <property name=\"targetMethod\" value=\"addListener\"/>\n <property name=\"arguments\">\n <list>\n <ref>listener</ref>\n <value>com.example.MyEnum</value>\n </list>\n </property>\n</bean>\n\nHowever, this is unwieldy, and potentially error-prone. I attempted something similar on a project, and created a Spring utility class to help out instead. I don't have the source code available at the moment, so I'll describe how to implement what I did. \n1) Refactor the event types listened to into a MyListener interface\npublic interface MyListener extends Listener {\n public Enum[] getEventTypes()\n}\n\nWhich changes the registration method to\npublic void addListener(MyListener listener)\n\n2) Create Spring helper class that finds all relevant listeners in the context, and calls maintainer#addListener for each listener found. I would start with BeanFilteringSupport, and also implement BeanPostProcessor (or ApplicationListener) to register the beans after all beans have been instantiated.\n", "\nYou said \"... you can't have java.lang.Enum as\"\n annotation param ...\"\n\nI think you are wrong on that. I have recently used on a project something like this :\npublic @interface MyAnnotation {\n MyEnum value();\n}\n\n", "Thank you all for the answers. First, A quick follow up on all answers.\n1. (alexvictor) Yes, you can have concrete enum as annotation param, but not java.lang.Enum.\n2. Answer provided by flicken is correct, but unfortunately a bit scary. I am not a Spring expert but doing things this way (creating methods for easier Spring access) this seems to be a bit overkill, as is the MethodInvokingFactoryBean solution. Although I wanted to express my sincere thanks for your time and effort.\n3. The answer by Phill is a bit unusual (instead of injecting listener bean, inject its maintainer!), but, I believe, the cleanest of all available. I think I will go down this path.\nAgain, a big thanks you for your help.\n" ]
[ 3, 2, 1, 0, 0 ]
[]
[]
[ "enums", "java", "maps", "spring" ]
stackoverflow_0000071469_enums_java_maps_spring.txt
Q: Classical ASP in IIS 6.0 not scaling The IIS 6.0 is serving my Classical ASP pages in a serial fashion (one at a time) The #2 request will be handled by the web server only when the #1 request ends. If the #1 request takes a little longer, the #2 request will have to wait for the #1 ends to starts being handled by IIS. Is this a missconfiguration in IIS? The operation system is Windows Server 2003 Standard Edition (Service Pack 2) A: Yes, IIS or the site is most likely configured for server-side debugging, which causes all requests to the site to go through a single thread. To check if this is the case/turn it off: In the Properties pages for any Web site or Web virtual directory, click the Home Directory or Virtual Directory tab. Under Application Settings, click Configuration. An application must be created for the button to be active. Click the Debugging tab. Un-check the Enable ASP server-side script debugging check box. (Above steps were copied from the Debugging ASP Applications in IIS KB article) A: Is this happening across machines? Like if you start loading a page on one computer, then another, the second is blocked? I've seen this on a single computer, but only because the browser is limiting connections to the server
Classical ASP in IIS 6.0 not scaling
The IIS 6.0 is serving my Classical ASP pages in a serial fashion (one at a time) The #2 request will be handled by the web server only when the #1 request ends. If the #1 request takes a little longer, the #2 request will have to wait for the #1 ends to starts being handled by IIS. Is this a missconfiguration in IIS? The operation system is Windows Server 2003 Standard Edition (Service Pack 2)
[ "Yes, IIS or the site is most likely configured for server-side debugging, which causes all requests to the site to go through a single thread.\nTo check if this is the case/turn it off:\n\nIn the Properties pages for any Web site or Web virtual directory, click the Home Directory or Virtual Directory tab.\nUnder Application Settings, click Configuration. An application must be created for the button to be active.\nClick the Debugging tab.\nUn-check the Enable ASP server-side script debugging check box. \n\n(Above steps were copied from the Debugging ASP Applications in IIS KB article)\n", "Is this happening across machines? Like if you start loading a page on one computer, then another, the second is blocked? I've seen this on a single computer, but only because the browser is limiting connections to the server\n" ]
[ 4, 0 ]
[]
[]
[ "asp_classic", "iis_6", "scalability" ]
stackoverflow_0000093474_asp_classic_iis_6_scalability.txt
Q: Persisting Checkbox State Across Postbacks I have a web form that binds a DataGrid to a, normally, different data source on each postback. I have a static CheckBox column that is always present to the left of the autogenerated columns. I achieve a TabControl effect with a horizontal Menu control above the grid, with each menu item being a tab that contains a different grid. Now I would like to persist the state of these checkboxes for a particular 'tab', when another tab is selected. I would welcome any imaginative solution for doing this without using session variables. A: I think the best bet for this is to have a different gridview for each of your "tabs". Use the MultiView control with a View control for each tab, and a gridview in each View. In the click event of your menu change to the correct view. Only bind each gridview once, and then your checkboxes will persist.
Persisting Checkbox State Across Postbacks
I have a web form that binds a DataGrid to a, normally, different data source on each postback. I have a static CheckBox column that is always present to the left of the autogenerated columns. I achieve a TabControl effect with a horizontal Menu control above the grid, with each menu item being a tab that contains a different grid. Now I would like to persist the state of these checkboxes for a particular 'tab', when another tab is selected. I would welcome any imaginative solution for doing this without using session variables.
[ "I think the best bet for this is to have a different gridview for each of your \"tabs\". Use the MultiView control with a View control for each tab, and a gridview in each View. In the click event of your menu change to the correct view. Only bind each gridview once, and then your checkboxes will persist.\n" ]
[ 3 ]
[]
[]
[ "asp.net" ]
stackoverflow_0000093482_asp.net.txt
Q: Assembly names and versions What is considered as best practice when it comes to assemblies and releases? I would like to be able to reference multiple versions of the same library - solution contains multiple projects that depend on different versions of a commonutils.dll library we build ourselves. As all dependencies are copied to the bin/debug or bin/release, only a single copy of commonutils.dll can exist there despite each of the DLL files having different assembly version numbers. Should I include version numbers in the assembly name to be able to reference multiple versions of a library or is there another way? A: Assemblies can coexist in the GAC (Global Assembly Cache) even if they have the same name given that the version is different. This is how .NET Framework shipped assemblies work. A requirement that must be meet in order for an assembly to be able to be GAC registered is to be signed. Adding version numbers to the name of the Assembly just defeats the whole purpose of the assembly ecosystem and is cumbersome IMHO. To know which version of a given assembly I have just open the Properties window and check the version. A: Here's what I've been living by -- It depends on what you are planning to use the DLL files for. I categorize them in two main groups: Dead-end Assemblies. These are EXE files and DLL files you really aren't planning on referencing from anywhere. Just weakly name these and make sure you have the version numbers you release tagged in source-control, so you can rollback whenever. Referenced Assemblies. Strong name these so you can have multiple versions of it being referenced by other assemblies. Use the full name to reference them (Assembly.Load). Keep a copy of the latest-and-greatest version of it in a place where other code can reference it. Next, you have a choice of whether to copy local or not your references. Basically, the tradeoff boils down to -- do you want to take in patches/upgrades from your references? There can be positive value in that from getting new functionality, but on the other hand, there could be breaking changes. The decision here, I believe, should be made on a case-by-case basis. While developing in Visual Studio, by default you will take the latest version to compile with, but once compiled the referencing assembly will require the specific version it was compiled with. Your last decision is to Copy Local or not. Basically, if you already have a mechanism in place to deploy the referenced assembly, set this to false. If you are planning a big release management system, you'll probably have to put a lot more thought and care into this. For me (small shop -- two people), this works fine. We know what's going on, and don't feel restrained from having to do things in a way that doesn't make sense. Once you reach runtime, you Assembly.Load whatever you want into the application domain. Then, you can use Assembly.GetType to reach the type you want. If you have a type that is present in multiple loaded assemblies (such as in multiple versions of the same project), you may get an AmbiguousMatchException exception. In order to resolve that, you will need to get the type out of an instance of an assembly variable, not the static Assembly.GetType method. A: Giving different names to different assembly versions is the easiest way and surely works. If your assembly (commonutils.dll) is strong-named (i.e. signed), you can think about installing it in the GAC (Global Assembly Cache - you can install different versions of the same assembly side-by-side in the GAC), therefore the calling application automatically gets the proper version from there because .NET Types include assembly version information. In your VS project you reference the correct version of the library, but you don't deploy it in the application folder; you install it in the GAC instead (during application setup).
Assembly names and versions
What is considered as best practice when it comes to assemblies and releases? I would like to be able to reference multiple versions of the same library - solution contains multiple projects that depend on different versions of a commonutils.dll library we build ourselves. As all dependencies are copied to the bin/debug or bin/release, only a single copy of commonutils.dll can exist there despite each of the DLL files having different assembly version numbers. Should I include version numbers in the assembly name to be able to reference multiple versions of a library or is there another way?
[ "Assemblies can coexist in the GAC (Global Assembly Cache) even if they have the same name given that the version is different. This is how .NET Framework shipped assemblies work. A requirement that must be meet in order for an assembly to be able to be GAC registered is to be signed.\nAdding version numbers to the name of the Assembly just defeats the whole purpose of the assembly ecosystem and is cumbersome IMHO. To know which version of a given assembly I have just open the Properties window and check the version.\n", "Here's what I've been living by --\nIt depends on what you are planning to use the DLL files for. I categorize them in two main groups:\n\nDead-end Assemblies. These are EXE files and DLL files you really aren't planning on referencing from anywhere. Just weakly name these and make sure you have the version numbers you release tagged in source-control, so you can rollback whenever.\nReferenced Assemblies. Strong name these so you can have multiple versions of it being referenced by other assemblies. Use the full name to reference them (Assembly.Load). Keep a copy of the latest-and-greatest version of it in a place where other code can reference it.\n\nNext, you have a choice of whether to copy local or not your references. Basically, the tradeoff boils down to -- do you want to take in patches/upgrades from your references? There can be positive value in that from getting new functionality, but on the other hand, there could be breaking changes. The decision here, I believe, should be made on a case-by-case basis.\nWhile developing in Visual Studio, by default you will take the latest version to compile with, but once compiled the referencing assembly will require the specific version it was compiled with.\nYour last decision is to Copy Local or not. Basically, if you already have a mechanism in place to deploy the referenced assembly, set this to false. \nIf you are planning a big release management system, you'll probably have to put a lot more thought and care into this. For me (small shop -- two people), this works fine. We know what's going on, and don't feel restrained from having to do things in a way that doesn't make sense.\nOnce you reach runtime, you Assembly.Load whatever you want into the application domain. Then, you can use Assembly.GetType to reach the type you want. If you have a type that is present in multiple loaded assemblies (such as in multiple versions of the same project), you may get an AmbiguousMatchException exception. In order to resolve that, you will need to get the type out of an instance of an assembly variable, not the static Assembly.GetType method.\n", "Giving different names to different assembly versions is the easiest way and surely works.\nIf your assembly (commonutils.dll) is strong-named (i.e. signed), you can think about installing it in the GAC (Global Assembly Cache - you can install different versions of the same assembly side-by-side in the GAC), therefore the calling application automatically gets the proper version from there because .NET Types include assembly version information. \nIn your VS project you reference the correct version of the library, but you don't deploy it in the application folder; you install it in the GAC instead (during application setup).\n" ]
[ 3, 1, 0 ]
[]
[]
[ "assemblies", "c#", "naming_conventions" ]
stackoverflow_0000093455_assemblies_c#_naming_conventions.txt
Q: Call .NET objects/dlls across virtual sites Site 1 has dll's for x amount of object and data calls. Can Site 2 (a separate .net web app) call the objects/dll's of Site 1 ? A: This may be more semantics: You can't call an object of another process. You can however potentially instantiate a class within a dll as long as there is a reference to that dll in the calling web application. If you GAC the dll, the classes (not objects) will be accessible to the entire machine. A: I never used .NET Remoting but isn't that the kind of problem it could solve? A: My understanding of the situation was that because you couldn't access the Bin directory cross site, you'd need to develop an api or web service. Your best bet is to have a local copy of the dll on each server.
Call .NET objects/dlls across virtual sites
Site 1 has dll's for x amount of object and data calls. Can Site 2 (a separate .net web app) call the objects/dll's of Site 1 ?
[ "This may be more semantics:\nYou can't call an object of another process. You can however potentially instantiate a class within a dll as long as there is a reference to that dll in the calling web application. \nIf you GAC the dll, the classes (not objects) will be accessible to the entire machine.\n", "I never used .NET Remoting but isn't that the kind of problem it could solve?\n", "My understanding of the situation was that because you couldn't access the Bin directory cross site, you'd need to develop an api or web service. Your best bet is to have a local copy of the dll on each server.\n" ]
[ 1, 0, 0 ]
[]
[]
[ ".net" ]
stackoverflow_0000093468_.net.txt
Q: Does AES (128 or 256) encryption expand the data? If so, by how much? I would like to add AES encryption to a software product, but am concerned by increasing the size of the data. I am guessing that the data does increase in size, and then I'll have to add a compression algorithm to compensate. A: AES does not expand data. Moreover, the output will not generally be compressible; if you intend to compress your data, do so before encrypting it. However, note that AES encryption is usually combined with padding, which will increase the size of the data (though only by a few bytes). A: AES does not expand the data, except for a few bytes of padding at the end of the last block. The resulting data are not compressible, at any rate, because they are basically random - no dictionary-based algorithm is able to effectively compress them. A best practice is to compress the data first, then encrypt them. A: It is common to compress data before encrypting. Compressing it afterwards doesn't work, because AES encrypted data appears random (as for any good cipher, apart from any headers and whatnot). However, compression can introduce side-channel attacks in some contexts, so you must analyse your own use. Such attacks have recently been reported against encrypted VOIP: the gist is that different syllables create characteristic variations in bitrate when compressed with VBR, because some sounds compress better than others. Some (or all) syllables may therefore be recoverable with sufficient analysis, since the data is transmitted at the rate it is generated. The fix is to either to use (less efficient) CBR compression, or to use a buffer to transmit at constant rate regardless of the data rate coming out of the encoder (increasing latency). AES turns 16 byte input blocks into 16 byte output blocks. The only expansion is to round the data up to a whole number of blocks. A: I am fairly sure AES encryption adds nothing to the data being encrypted, since that would give away information about the state variables, and that is a Bad Thing when it comes to cryptography. If you want to mix compression and encryption, do them in that order. The reason is encrypted data (ideally) looks like totally random data, and compression algorithms will end up making the data bigger, due to its inability to actually compress any of it and overhead of book keeping that comes with any compressed file format. A: If compression is necessary do it before you encrypt. A: No. The only change will be a small amount of padding to align the data to the size of a block However, if you are compressing the content note that you should do this before encrypting. Encrypted data should generally be indistinguishable from random data, which means that it will not compress. A: @freespace and others: One of the things I remember from my cryptography classes is that you should not compress your data before encryption, because some repeatable chunks of compressed stream (like section headers for example) may make it easier to crack your encryption.
Does AES (128 or 256) encryption expand the data? If so, by how much?
I would like to add AES encryption to a software product, but am concerned by increasing the size of the data. I am guessing that the data does increase in size, and then I'll have to add a compression algorithm to compensate.
[ "AES does not expand data. Moreover, the output will not generally be compressible; if you intend to compress your data, do so before encrypting it.\nHowever, note that AES encryption is usually combined with padding, which will increase the size of the data (though only by a few bytes).\n", "AES does not expand the data, except for a few bytes of padding at the end of the last block.\nThe resulting data are not compressible, at any rate, because they are basically random - no dictionary-based algorithm is able to effectively compress them. A best practice is to compress the data first, then encrypt them.\n", "It is common to compress data before encrypting. Compressing it afterwards doesn't work, because AES encrypted data appears random (as for any good cipher, apart from any headers and whatnot).\nHowever, compression can introduce side-channel attacks in some contexts, so you must analyse your own use. Such attacks have recently been reported against encrypted VOIP: the gist is that different syllables create characteristic variations in bitrate when compressed with VBR, because some sounds compress better than others. Some (or all) syllables may therefore be recoverable with sufficient analysis, since the data is transmitted at the rate it is generated. The fix is to either to use (less efficient) CBR compression, or to use a buffer to transmit at constant rate regardless of the data rate coming out of the encoder (increasing latency).\nAES turns 16 byte input blocks into 16 byte output blocks. The only expansion is to round the data up to a whole number of blocks.\n", "I am fairly sure AES encryption adds nothing to the data being encrypted, since that would give away information about the state variables, and that is a Bad Thing when it comes to cryptography. \nIf you want to mix compression and encryption, do them in that order. The reason is encrypted data (ideally) looks like totally random data, and compression algorithms will end up making the data bigger, due to its inability to actually compress any of it and overhead of book keeping that comes with any compressed file format.\n", "If compression is necessary do it before you encrypt.\n", "No. The only change will be a small amount of padding to align the data to the size of a block\nHowever, if you are compressing the content note that you should do this before encrypting. Encrypted data should generally be indistinguishable from random data, which means that it will not compress.\n", "@freespace and others: One of the things I remember from my cryptography classes is that you should not compress your data before encryption, because some repeatable chunks of compressed stream (like section headers for example) may make it easier to crack your encryption.\n" ]
[ 59, 25, 12, 4, 0, 0, 0 ]
[]
[]
[ "aes", "compression", "encryption" ]
stackoverflow_0000093451_aes_compression_encryption.txt
Q: Easy way to set CurrentCulture for the entire application? In a .net 2 winforms application, what's a good way to set the culture for the entire application? Setting CurrentThread.CurrentCulture for every new thread is repetitive and error-prone. Ideally I'd like to set it when the app starts and forget about it. A: The culture for a thread in .NET is the culture for the system (as viewed by a single application/process). There is no way to override that in .NET, you'll have to continue setting the CurrentCulture for each new thread. A: You can set application current culture this way: static void Main() { System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("fi-FI"); Application.CurrentCulture = cultureInfo; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } I'm not sure if it helps, because I have never tested it with threads. edit: it doesn't work. I think you have to set current culture in every thread.
Easy way to set CurrentCulture for the entire application?
In a .net 2 winforms application, what's a good way to set the culture for the entire application? Setting CurrentThread.CurrentCulture for every new thread is repetitive and error-prone. Ideally I'd like to set it when the app starts and forget about it.
[ "The culture for a thread in .NET is the culture for the system (as viewed by a single application/process). There is no way to override that in .NET, you'll have to continue setting the CurrentCulture for each new thread.\n", "You can set application current culture this way:\nstatic void Main()\n{\n System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo(\"fi-FI\");\n Application.CurrentCulture = cultureInfo;\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n Application.Run(new Form1());\n}\n\nI'm not sure if it helps, because I have never tested it with threads.\nedit: it doesn't work. I think you have to set current culture in every thread.\n" ]
[ 12, 1 ]
[]
[]
[ ".net", "localization", "winforms" ]
stackoverflow_0000093153_.net_localization_winforms.txt
Q: Perl: why is the if statement slower than "and"? In Perl, a conditional can be expressed either as if (condition) { do something } or as (condition) and do { do something } Interestingly, the second way seems to be about 10% faster. Does anyone know why? A: Some comments about the deparse below: First, don't use B::Terse, it's obsolete. B::Concise gives you much better information once you are used to it. Second, you've run it using the literal code given, so condition was taken as a bareword that happens to be true, so the boolean check was optimized away in both cases, which kind of defeats the purpose. Third, there isn't an extra opcode - the "null" indicates an opcode that's been optimized away (completely out of the execution tree, though still in the parse tree.) Here's the Concise execution tree for the two cases, which shows them as identical: $ perl -MO=Concise,-exec -e'($condition) and do { do something }' 1 <0> enter 2 <;> nextstate(main 2 -e:1) v 3 <#> gvsv[*condition] s 4 <|> and(other->5) vK/1 5 <$> const[PV "something"] s/BARE 6 <1> dofile vK/1 7 <@> leave[1 ref] vKP/REFC -e syntax OK $ perl -MO=Concise,-exec -e'if ($condition) { do something }' 1 <0> enter 2 <;> nextstate(main 3 -e:1) v 3 <#> gvsv[*condition] s 4 <|> and(other->5) vK/1 5 <$> const[PV "something"] s/BARE 6 <1> dofile vK/1 7 <@> leave[1 ref] vKP/REFC -e syntax OK A: I've deparsed it, and it really shouldn't be faster. The opcode tree for the first is LISTOP (0x8177a18) leave [1] OP (0x8176590) enter COP (0x8177a40) nextstate LISTOP (0x8177b20) scope OP (0x81779b8) null [174] UNOP (0x8177c40) dofile SVOP (0x8177b58) const [1] PV (0x81546e4) "something" The opcode tree for the second is LISTOP (0x8177b28) leave [1] OP (0x8176598) enter COP (0x8177a48) nextstate UNOP (0x8177980) null LISTOP (0x8177ca0) scope OP (0x81779c0) null [174] UNOP (0x8177c48) dofile SVOP (0x8177b60) const [1] PV (0x81546e4) "something" I really don't see how the latter could be faster. It does an opcode more! A: Which just goes to show, if you don't know how to do proper code profiling, don't be doing this stuff. The speed difference of these two methods are within the same Big O() speed (As proven by @Leon Timmermans opcode analyisis) - the benchmarks are just going to show differences based on other local conditions, not necessarily your code. @Svante said the "and" was faster, and @shelfoo said "if" was faster. I mean really... 7 hundredths of a second change for 10 million loops? That's not faster or slower, statistically.... that's equal. Instead of looking at miniscule timings like this, learn about code refactoring and Big O() notation... how to reduce the number of loops in your code... and most of all, how to use code profilers to see where the real bottlenecks are. Don't worry about the statistically insignificant stuff. ;) A: How many tests did you do before you averaged? Very, very small deviations are statistically insignificant! There are plenty of reasons for speed to vary slightly between tests. A: According to Benchmark, the second is slightly slower. Possibly it has something to do with the condition, but here's results for a very simple case: use Benchmark; timethese(10000000, { 'if' => '$m=5;if($m > 4){my $i=0;}', 'and' => '$m=5; $m > 4 and do {my $i =0}', }); Results: Benchmark: timing 10000000 iterations of Name1, Name2... if: 3 wallclock secs ( 2.94 usr + 0.01 sys = 2.95 CPU) @ 3389830.51/s (n=10000000) and: 3 wallclock secs ( 3.01 usr + 0.01 sys = 3.02 CPU) @ 3311258.28/s (n=10000000) A: It also could depend on the version of Perl. Which you haven't mentioned. And the difference is not enough to worry about anyway. So use whatever makes more sense.
Perl: why is the if statement slower than "and"?
In Perl, a conditional can be expressed either as if (condition) { do something } or as (condition) and do { do something } Interestingly, the second way seems to be about 10% faster. Does anyone know why?
[ "Some comments about the deparse below:\nFirst, don't use B::Terse, it's obsolete. B::Concise gives you much better information once you are used to it.\nSecond, you've run it using the literal code given, so condition was taken as a bareword that happens to be true, so the boolean check was optimized away in both cases, which kind of defeats the purpose.\nThird, there isn't an extra opcode - the \"null\" indicates an opcode that's been optimized away (completely out of the execution tree, though still in the parse tree.)\nHere's the Concise execution tree for the two cases, which shows them as identical:\n$ perl -MO=Concise,-exec -e'($condition) and do { do something }'\n1 <0> enter \n2 <;> nextstate(main 2 -e:1) v\n3 <#> gvsv[*condition] s\n4 <|> and(other->5) vK/1\n5 <$> const[PV \"something\"] s/BARE\n6 <1> dofile vK/1\n7 <@> leave[1 ref] vKP/REFC\n-e syntax OK\n$ perl -MO=Concise,-exec -e'if ($condition) { do something }'\n1 <0> enter \n2 <;> nextstate(main 3 -e:1) v\n3 <#> gvsv[*condition] s\n4 <|> and(other->5) vK/1\n5 <$> const[PV \"something\"] s/BARE\n6 <1> dofile vK/1\n7 <@> leave[1 ref] vKP/REFC\n-e syntax OK\n\n", "I've deparsed it, and it really shouldn't be faster. The opcode tree for the first is\nLISTOP (0x8177a18) leave [1] \n OP (0x8176590) enter \n COP (0x8177a40) nextstate \n LISTOP (0x8177b20) scope \n OP (0x81779b8) null [174] \n UNOP (0x8177c40) dofile \n SVOP (0x8177b58) const [1] PV (0x81546e4) \"something\" \n\nThe opcode tree for the second is \nLISTOP (0x8177b28) leave [1] \n OP (0x8176598) enter \n COP (0x8177a48) nextstate \n UNOP (0x8177980) null \n LISTOP (0x8177ca0) scope \n OP (0x81779c0) null [174] \n UNOP (0x8177c48) dofile \n SVOP (0x8177b60) const [1] PV (0x81546e4) \"something\"\n\nI really don't see how the latter could be faster. It does an opcode more!\n", "Which just goes to show, if you don't know how to do proper code profiling, don't be doing this stuff. The speed difference of these two methods are within the same Big O() speed (As proven by @Leon Timmermans opcode analyisis) - the benchmarks are just going to show differences based on other local conditions, not necessarily your code.\n@Svante said the \"and\" was faster, and @shelfoo said \"if\" was faster. \nI mean really... 7 hundredths of a second change for 10 million loops? That's not faster or slower, statistically.... that's equal.\nInstead of looking at miniscule timings like this, learn about code refactoring and Big O() notation... how to reduce the number of loops in your code... and most of all, how to use code profilers to see where the real bottlenecks are. Don't worry about the statistically insignificant stuff. ;)\n", "How many tests did you do before you averaged? Very, very small deviations are statistically insignificant! There are plenty of reasons for speed to vary slightly between tests.\n", "According to Benchmark, the second is slightly slower. Possibly it has something to do with the condition, but here's results for a very simple case:\n\n\nuse Benchmark;\n\ntimethese(10000000, {\n 'if' => '$m=5;if($m > 4){my $i=0;}',\n 'and' => '$m=5; $m > 4 and do {my $i =0}',\n});\n\n\nResults:\n\n\nBenchmark: timing 10000000 iterations of Name1, Name2...\n if: 3 wallclock secs ( 2.94 usr + 0.01 sys = 2.95 CPU) @ 3389830.51/s (n=10000000)\n and: 3 wallclock secs ( 3.01 usr + 0.01 sys = 3.02 CPU) @ 3311258.28/s (n=10000000)\n\n\n", "It also could depend on the version of Perl. Which you haven't mentioned. And the difference is not enough to worry about anyway. So use whatever makes more sense.\n" ]
[ 18, 11, 11, 3, 2, 0 ]
[]
[]
[ "performance", "perl" ]
stackoverflow_0000088546_performance_perl.txt
Q: Reading an ASCII file with FileChannel and ByteArrays I have the following code: String inputFile = "somefile.txt"; FileInputStream in = new FileInputStream(inputFile); FileChannel ch = in.getChannel(); ByteBuffer buf = ByteBuffer.allocateDirect(BUFSIZE); // BUFSIZE = 256 /* read the file into a buffer, 256 bytes at a time */ int rd; while ( (rd = ch.read( buf )) != -1 ) { buf.rewind(); for ( int i = 0; i < rd/2; i++ ) { /* print each character */ System.out.print(buf.getChar()); } buf.clear(); } But the characters get displayed at ?'s. Does this have something to do with Java using Unicode characters? How do I correct this? A: You have to know what the encoding of the file is, and then decode the ByteBuffer into a CharBuffer using that encoding. Assuming the file is ASCII: import java.util.*; import java.io.*; import java.nio.*; import java.nio.channels.*; import java.nio.charset.*; public class Buffer { public static void main(String args[]) throws Exception { String inputFile = "somefile"; FileInputStream in = new FileInputStream(inputFile); FileChannel ch = in.getChannel(); ByteBuffer buf = ByteBuffer.allocateDirect(BUFSIZE); // BUFSIZE = 256 Charset cs = Charset.forName("ASCII"); // Or whatever encoding you want /* read the file into a buffer, 256 bytes at a time */ int rd; while ( (rd = ch.read( buf )) != -1 ) { buf.rewind(); CharBuffer chbuf = cs.decode(buf); for ( int i = 0; i < chbuf.length(); i++ ) { /* print each character */ System.out.print(chbuf.get()); } buf.clear(); } } } A: buf.getChar() is expecting 2 bytes per character but you are only storing 1. Use: System.out.print((char) buf.get()); A: Changing your print statement to: System.out.print((char)buf.get()); Seems to help. A: Depending on the encoding of somefile.txt, a character may not actually be composed of two bytes. This page gives more information about how to read streams with the proper encoding. The bummer is, the file system doesn't tell you the encoding of the file, because it doesn't know. As far as it's concerned, it's just a bunch of bytes. You must either find some way to communicate the encoding to the program, detect it somehow, or (if possible) always ensure that the encoding is the same (such as UTF-8). A: Is there a particular reason why you are reading the file in the way that you do? If you're reading in an ASCII file you should really be using a Reader. I would do it something like: File inputFile = new File("somefile.txt"); BufferedReader reader = new BufferedReader(new FileReader(inputFile)); And then use either readLine or similar to actually read in the data! A: Yes, it is Unicode. If you have 14 Chars in your File, you only get 7 '?'. Solution pending. Still thinking.
Reading an ASCII file with FileChannel and ByteArrays
I have the following code: String inputFile = "somefile.txt"; FileInputStream in = new FileInputStream(inputFile); FileChannel ch = in.getChannel(); ByteBuffer buf = ByteBuffer.allocateDirect(BUFSIZE); // BUFSIZE = 256 /* read the file into a buffer, 256 bytes at a time */ int rd; while ( (rd = ch.read( buf )) != -1 ) { buf.rewind(); for ( int i = 0; i < rd/2; i++ ) { /* print each character */ System.out.print(buf.getChar()); } buf.clear(); } But the characters get displayed at ?'s. Does this have something to do with Java using Unicode characters? How do I correct this?
[ "You have to know what the encoding of the file is, and then decode the ByteBuffer into a CharBuffer using that encoding. Assuming the file is ASCII:\nimport java.util.*;\nimport java.io.*;\nimport java.nio.*;\nimport java.nio.channels.*;\nimport java.nio.charset.*;\n\npublic class Buffer\n{\n public static void main(String args[]) throws Exception\n {\n String inputFile = \"somefile\";\n FileInputStream in = new FileInputStream(inputFile);\n FileChannel ch = in.getChannel();\n ByteBuffer buf = ByteBuffer.allocateDirect(BUFSIZE); // BUFSIZE = 256\n\n Charset cs = Charset.forName(\"ASCII\"); // Or whatever encoding you want\n\n /* read the file into a buffer, 256 bytes at a time */\n int rd;\n while ( (rd = ch.read( buf )) != -1 ) {\n buf.rewind();\n CharBuffer chbuf = cs.decode(buf);\n for ( int i = 0; i < chbuf.length(); i++ ) {\n /* print each character */\n System.out.print(chbuf.get());\n }\n buf.clear();\n }\n }\n}\n\n", "buf.getChar() is expecting 2 bytes per character but you are only storing 1. Use:\n System.out.print((char) buf.get());\n\n", "Changing your print statement to:\nSystem.out.print((char)buf.get());\n\nSeems to help.\n", "Depending on the encoding of somefile.txt, a character may not actually be composed of two bytes. This page gives more information about how to read streams with the proper encoding.\nThe bummer is, the file system doesn't tell you the encoding of the file, because it doesn't know. As far as it's concerned, it's just a bunch of bytes. You must either find some way to communicate the encoding to the program, detect it somehow, or (if possible) always ensure that the encoding is the same (such as UTF-8).\n", "Is there a particular reason why you are reading the file in the way that you do?\nIf you're reading in an ASCII file you should really be using a Reader.\nI would do it something like:\nFile inputFile = new File(\"somefile.txt\");\nBufferedReader reader = new BufferedReader(new FileReader(inputFile));\n\nAnd then use either readLine or similar to actually read in the data!\n", "Yes, it is Unicode.\nIf you have 14 Chars in your File, you only get 7 '?'.\nSolution pending. Still thinking.\n" ]
[ 7, 3, 2, 2, 1, 0 ]
[]
[]
[ "bytearray", "file_io", "filechannel", "io", "java" ]
stackoverflow_0000093423_bytearray_file_io_filechannel_io_java.txt
Q: Is FileStream lazy-loaded in .NET? I have a question about using streams in .NET to load files from disk. I am trying to pinpoint a performance problem and want to be sure it's where I think it is. Dim provider1 As New MD5CryptoServiceProvider Dim stream1 As FileStream stream1 = New FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.Read) provider1.ComputeHash(stream1) Q: Are the bytes read from disk when I create the FileStream object, or when the object consuming the stream, in this case an MD5 Hash algorithm, actually reads it? I see significant performance problems on my web host when using the ComputeHash method, compared to my local test environment. I'm just trying to make sure that the performance problem is in the hashing and not in the disk access. A: FileStream simply exposes an IO.Stream around a file object, and uses buffers. It doesn't read the entire file in the constructor (the file could be larger than RAM). The performance issue is most likely in the hashing, and you can perform some simple benchmarks to prove whether it's because of file IO or the algorithm itself. But one of the first things you might try is: provider1.ComputeHash(stream1.ToArray()); This should make the FileStream read the entire file and return an array of bytes. .ToArray() may invoke a faster method than the .Read() method that ComputeHash will call. A: Yes content of the file will be read then you run ComputeHash method and not when you just open a FileStream. The best way to test where the performance problem is , it is to read data from file to memory stream hash it and measure performance of each of this steps. You can use System.Diagnostics.Stopwatch class for this. A: Bytes from disk should be read when the caller requests them by invoking Read or similar methods. At any rate, both the hard disk and the operating system perform some read-ahead to improve sequential read operations, but this is surely hard to predict. You could also try to play with the buffer size parameter that some constructor overloads provide for FileStream.
Is FileStream lazy-loaded in .NET?
I have a question about using streams in .NET to load files from disk. I am trying to pinpoint a performance problem and want to be sure it's where I think it is. Dim provider1 As New MD5CryptoServiceProvider Dim stream1 As FileStream stream1 = New FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.Read) provider1.ComputeHash(stream1) Q: Are the bytes read from disk when I create the FileStream object, or when the object consuming the stream, in this case an MD5 Hash algorithm, actually reads it? I see significant performance problems on my web host when using the ComputeHash method, compared to my local test environment. I'm just trying to make sure that the performance problem is in the hashing and not in the disk access.
[ "FileStream simply exposes an IO.Stream around a file object, and uses buffers. It doesn't read the entire file in the constructor (the file could be larger than RAM). \nThe performance issue is most likely in the hashing, and you can perform some simple benchmarks to prove whether it's because of file IO or the algorithm itself.\nBut one of the first things you might try is:\nprovider1.ComputeHash(stream1.ToArray());\n\nThis should make the FileStream read the entire file and return an array of bytes. .ToArray() may invoke a faster method than the .Read() method that ComputeHash will call.\n", "Yes content of the file will be read then you run ComputeHash method and not when you just open a FileStream.\nThe best way to test where the performance problem is , it is to read data from file to memory stream hash it and measure performance of each of this steps. You can use System.Diagnostics.Stopwatch class for this. \n", "Bytes from disk should be read when the caller requests them by invoking Read or similar methods. At any rate, both the hard disk and the operating system perform some read-ahead to improve sequential read operations, but this is surely hard to predict.\nYou could also try to play with the buffer size parameter that some constructor overloads provide for FileStream.\n" ]
[ 2, 0, 0 ]
[]
[]
[ ".net", "performance" ]
stackoverflow_0000093590_.net_performance.txt
Q: What's a good way to store raster data? I have a variety of time-series data stored on a more-or-less georeferenced grid, e.g. one value per 0.2 degrees of latitude and longitude. Currently the data are stored in text files, so at day-of-year 251 you might see: 251 12.76 12.55 12.55 12.34 [etc., 200 more values...] 13.02 12.95 12.70 12.40 [etc., 200 more values...] [etc., 250 more lines] 252 [etc., etc.] I'd like to raise the level of abstraction, improve performance, and reduce fragility (for example, the current code can't insert a day between two existing ones!). We'd messed around with BLOB-y RDBMS hacks and even replicating each line of the text file format as a row in a table (one row per timestamp/latitude pair, one column per longitude increment -- yecch!). We could go to a "real" geodatabase, but the overhead of tagging each individual value with a lat and long seems prohibitive. The size and resolution of the data haven't changed in ten years and are unlikely to do so. I've been noodling around with putting everything in NetCDF files, but think we need to get past the file mindset entirely -- I hate that all my software has to figure out filenames from dates, deal with multiple files for multiple years, etc.. The alternative, putting all ten years' (and counting) data into a single file, doesn't seem workable either. Any bright ideas or products? A: I've assembled your comments here: I'd like to do all this "w/o writing my own file I/O code" I need access from "Java Ruby MATLAB" and "FORTRAN routines" When you add these up, you definitely don't want a new file format. Stick with the one you've got. If we can get you to relax your first requirement - ie, if you'd be willing to write your own file I/O code, then there are some interesting options for you. I'd write C++ classes, and I'd use something like SWIG to make your new classes available to the multiple languages you need. (But I'm not sure you'd be able to use SWIG to give you access from Java, Ruby, MATLAB and FORTRAN. You might need something else. Not really sure how to do it, myself.) You also said, "Actually, if I have to have files, I prefer text because then I can just go in and hand-edit when necessary." My belief is that this is a misguided statement. If you'd be willing to make your own file I/O routines then there are very clever things you could do... And as an ultimate fallback, you could give yourself a tool that converts from the new file format to the same old text format you're used to... And another tool that converts back. I'll come back to this at the end of my post... You said something that I want to address: "leverage 40 yrs of DB optimization" Databases are meant for relational data, not raster data. You will not leverage anyone's DB optimizations with this kind of data. You might be able to cram your data into a DB, but that's hardly the same thing. Here's the most useful thing I can tell you, based on everything you've told us. You said this: "I am more interested in optimizing my time than the CPU's, though exec speed is good!" This is frankly going to require TOOLS. Stop thinking of it as a text file. Start thinking of the common tasks you do, and write small tools - in WHATEVER LANGAUGE(S) - to make those things TRIVIAL to do. And if your tools turn out to have lousy performance? Guess what - it's because your flat text file is a cruddy format. But that's just my opinion. :) A: I'd definitely change from text to binary but keep each day in a separate file still. You could name them in such a way that insertions in between don't cause any strangeness with indices, such as by including the date and possible time in the filename. You could also consider the file structure if you have several fields per location for example. Is it common to look for a small tile from a large number of timesteps? In that case you might want to store them as tiles containing data from several days. You didn't mention how the data is accessed which plays a big role in how to organise it efficiently. A: Clarifications: I'm surprised you added "database" as one of the tags, and considered it as an option. Why did you do this? Essentially, you have a 2D, single component floating point image at every time step. Would you agree with this way of viewing your data? You also mentioned the desire to insert a day between two existing ones - which seems to be a very odd thing to do. Why would you need to do that? Is there a new day between May 4 and May 5 that I don't know about? Is "compression" one of the things you care about, or are you just sick of flat files? Would a float or a double be sufficient to store your data, or do you feel you need more arbitrary precision? Also, what programming language(s) do you want to access this data with? A: your answer on how to store the data depends entirely on what you're going to do with the data. for example, if you only ever need to retrieve by specifying the date or a date range, then storing in a database as a BLOB makes some sense. but if you need to find records that have certain values, you'll need to do something different. please describe how you need to be able to access the data/ A: Matt, thanks very much, and likewise longneck and jirv. This post was partly an experiment, testing the quality of stackoverflow discourse. If you guys/gals/alien lifeforms are representative, I'm sold. And on point, you've clarified my thinking considerably. Mind, I still might not necessarily implement your advice, but know that I will be thinking about it very seriously. >;-) I may very well leave the file format the same, add to the extant C and/or Ruby routines to tack on the few low-level features I lack (e.g. inserting missing timesteps), and hang an HTTP front end on the whole thing so that the data can be consumed by whatever box needs it, in whatever language is currently hoopy. While it's mostly unchanging legacy software that construct these data, we're always coming up with new consumers for it, so the multi-language/multi-computer requirement (gee, did I forget that one?) applies to the reading side, not the writing side. That also obviates a whole slew of security issues. Thanks again, folks.
What's a good way to store raster data?
I have a variety of time-series data stored on a more-or-less georeferenced grid, e.g. one value per 0.2 degrees of latitude and longitude. Currently the data are stored in text files, so at day-of-year 251 you might see: 251 12.76 12.55 12.55 12.34 [etc., 200 more values...] 13.02 12.95 12.70 12.40 [etc., 200 more values...] [etc., 250 more lines] 252 [etc., etc.] I'd like to raise the level of abstraction, improve performance, and reduce fragility (for example, the current code can't insert a day between two existing ones!). We'd messed around with BLOB-y RDBMS hacks and even replicating each line of the text file format as a row in a table (one row per timestamp/latitude pair, one column per longitude increment -- yecch!). We could go to a "real" geodatabase, but the overhead of tagging each individual value with a lat and long seems prohibitive. The size and resolution of the data haven't changed in ten years and are unlikely to do so. I've been noodling around with putting everything in NetCDF files, but think we need to get past the file mindset entirely -- I hate that all my software has to figure out filenames from dates, deal with multiple files for multiple years, etc.. The alternative, putting all ten years' (and counting) data into a single file, doesn't seem workable either. Any bright ideas or products?
[ "I've assembled your comments here:\n\nI'd like to do all this \"w/o writing my own file I/O code\"\nI need access from \"Java Ruby MATLAB\" and \"FORTRAN routines\"\n\nWhen you add these up, you definitely don't want a new file format. Stick with the one you've got.\nIf we can get you to relax your first requirement - ie, if you'd be willing to write your own file I/O code, then there are some interesting options for you. I'd write C++ classes, and I'd use something like SWIG to make your new classes available to the multiple languages you need. (But I'm not sure you'd be able to use SWIG to give you access from Java, Ruby, MATLAB and FORTRAN. You might need something else. Not really sure how to do it, myself.)\nYou also said, \"Actually, if I have to have files, I prefer text because then I can just go in and hand-edit when necessary.\"\nMy belief is that this is a misguided statement. If you'd be willing to make your own file I/O routines then there are very clever things you could do... And as an ultimate fallback, you could give yourself a tool that converts from the new file format to the same old text format you're used to... And another tool that converts back. I'll come back to this at the end of my post...\nYou said something that I want to address:\n\"leverage 40 yrs of DB optimization\"\nDatabases are meant for relational data, not raster data. You will not leverage anyone's DB optimizations with this kind of data. You might be able to cram your data into a DB, but that's hardly the same thing.\nHere's the most useful thing I can tell you, based on everything you've told us. You said this:\n\"I am more interested in optimizing my time than the CPU's, though exec speed is good!\"\nThis is frankly going to require TOOLS. Stop thinking of it as a text file. Start thinking of the common tasks you do, and write small tools - in WHATEVER LANGAUGE(S) - to make those things TRIVIAL to do.\nAnd if your tools turn out to have lousy performance? Guess what - it's because your flat text file is a cruddy format. But that's just my opinion. :)\n", "I'd definitely change from text to binary but keep each day in a separate file still. You could name them in such a way that insertions in between don't cause any strangeness with indices, such as by including the date and possible time in the filename. You could also consider the file structure if you have several fields per location for example. Is it common to look for a small tile from a large number of timesteps? In that case you might want to store them as tiles containing data from several days. You didn't mention how the data is accessed which plays a big role in how to organise it efficiently.\n", "Clarifications:\nI'm surprised you added \"database\" as one of the tags, and considered it as an option. Why did you do this?\nEssentially, you have a 2D, single component floating point image at every time step. Would you agree with this way of viewing your data?\nYou also mentioned the desire to insert a day between two existing ones - which seems to be a very odd thing to do. Why would you need to do that? Is there a new day between May 4 and May 5 that I don't know about?\nIs \"compression\" one of the things you care about, or are you just sick of flat files?\nWould a float or a double be sufficient to store your data, or do you feel you need more arbitrary precision?\nAlso, what programming language(s) do you want to access this data with?\n", "your answer on how to store the data depends entirely on what you're going to do with the data. for example, if you only ever need to retrieve by specifying the date or a date range, then storing in a database as a BLOB makes some sense. but if you need to find records that have certain values, you'll need to do something different.\nplease describe how you need to be able to access the data/\n", "Matt, thanks very much, and likewise longneck and jirv.\nThis post was partly an experiment, testing the quality of stackoverflow discourse. If you guys/gals/alien lifeforms are representative, I'm sold. \nAnd on point, you've clarified my thinking considerably. Mind, I still might not necessarily implement your advice, but know that I will be thinking about it very seriously. >;-)\nI may very well leave the file format the same, add to the extant C and/or Ruby routines to tack on the few low-level features I lack (e.g. inserting missing timesteps), and hang an HTTP front end on the whole thing so that the data can be consumed by whatever box needs it, in whatever language is currently hoopy. While it's mostly unchanging legacy software that construct these data, we're always coming up with new consumers for it, so the multi-language/multi-computer requirement (gee, did I forget that one?) applies to the reading side, not the writing side. That also obviates a whole slew of security issues.\nThanks again, folks.\n" ]
[ 2, 0, 0, 0, 0 ]
[]
[]
[ "database", "geolocation", "raster", "time_series" ]
stackoverflow_0000086913_database_geolocation_raster_time_series.txt
Q: How do I check ClickOnce prerequisites after first install? If I understand correctly, ClickOnce only checks for prerequisites with the first install of an application through the setup.exe file that contains the prerequisite information. If the user opens the app in the future it will check for new versions, but it does not launch the setup.exe again, thus not checking for any NEW prerequisites that might have been added. Is there any way to force ClickOnce to check the prerequisites again or does anyone have a good solution without asking the user to run the setup.exe again? A: Unfortunately, your users will have to re-run the setup.exe to check and install all the new prerequisites that you have added. Applications deployed using ClickOnce only check for application updates (if enabled), not prerequisites as it's the bootstrapper's job to make sure all dependencies are installed before the application is installed. I found this at Microsoft's site: The Setup.exe (bootstrapper) is responsible for installing all dependencies before your application runs. This bootstrapper runs as a separate process that is independent of the ClickOnce run-time engine. A: HAdes is correct. However, as long as your app can start without the new prerequisite, you have the option of checking for it in code. I had the exact same situation with Crystal Reports and ended up writing code to check if it was installed, download the installation files, and run it in the background. Definitely a pain, but the end result worked well.
How do I check ClickOnce prerequisites after first install?
If I understand correctly, ClickOnce only checks for prerequisites with the first install of an application through the setup.exe file that contains the prerequisite information. If the user opens the app in the future it will check for new versions, but it does not launch the setup.exe again, thus not checking for any NEW prerequisites that might have been added. Is there any way to force ClickOnce to check the prerequisites again or does anyone have a good solution without asking the user to run the setup.exe again?
[ "Unfortunately, your users will have to re-run the setup.exe to check and install all the new prerequisites that you have added.\nApplications deployed using ClickOnce only check for application updates (if enabled), not prerequisites as it's the bootstrapper's job to make sure all dependencies are installed before the application is installed.\nI found this at Microsoft's site:\n\nThe Setup.exe (bootstrapper) is\n responsible for installing all\n dependencies before your application\n runs. This bootstrapper runs as a\n separate process that is independent\n of the ClickOnce run-time engine.\n\n", "HAdes is correct. However, as long as your app can start without the new prerequisite, you have the option of checking for it in code.\nI had the exact same situation with Crystal Reports and ended up writing code to check if it was installed, download the installation files, and run it in the background. Definitely a pain, but the end result worked well.\n" ]
[ 12, 2 ]
[]
[]
[ ".net", "clickonce" ]
stackoverflow_0000081459_.net_clickonce.txt
Q: Why is my programmatically created user missing from the Welcome screen? I have a program that creates a Windows user account using the NetUserAdd() API which is suggested by Microsoft. The user is created successfully, and I can log in as that user. However, on Windows XP, the newly-created user is missing from the Welcome screen. If I disable the Welcome screen, I can log in as the new user by typing the user name in direcly. What property of the account I create causes it to be omitted from the Welcome screen? A: One thing you could do is add the username as a value to the registry key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\SpecialAccounts\UserList Use the username (As a REG_DWORD) and a value of 1 to show the user and 0 to hide.
Why is my programmatically created user missing from the Welcome screen?
I have a program that creates a Windows user account using the NetUserAdd() API which is suggested by Microsoft. The user is created successfully, and I can log in as that user. However, on Windows XP, the newly-created user is missing from the Welcome screen. If I disable the Welcome screen, I can log in as the new user by typing the user name in direcly. What property of the account I create causes it to be omitted from the Welcome screen?
[ "One thing you could do is add the username as a value to the registry key:\nHKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\\SpecialAccounts\\UserList\nUse the username (As a REG_DWORD) and a value of 1 to show the user and 0 to hide.\n" ]
[ 4 ]
[]
[]
[ "security", "winapi" ]
stackoverflow_0000093771_security_winapi.txt
Q: How to mock object construction? Is there a way to mock object construction using JMock in Java? For example, if I have a method as such: public Object createObject(String objectType) { if(objectType.equals("Integer") { return new Integer(); } else if (objectType.equals("String") { return new String(); } } ...is there a way to mock out the expectation of the object construction in a test method? I'd like to be able to place expectations that certain constructors are being called, rather than having an extra bit of code to check the type (as it won't always be as convoluted and simple as my example). So instead of: assertTrue(a.createObject() instanceof Integer); I could have an expectation of the certain constructor being called. Just to make it a bit cleaner, and express what is actually being tested in a more readable way. Please excuse the simple example, the actual problem I'm working on is a bit more complicated, but having the expectation would simplify it. For a bit more background: I have a simple factory method, which creates wrapper objects. The objects being wrapped can require parameters which are difficult to obtain in a test class (it's pre-existing code), so it is difficult to construct them. Perhaps closer to what I'm actually looking for is: is there a way to mock an entire class (using CGLib) in one fell swoop, without specifying every method to stub out? So the mock is being wrapped in a constructor, so obviously methods can be called on it, is JMock capable of dynamically mocking out each method? My guess is no, as that would be pretty complicated. But knowing I'm barking up the wrong tree is valuable too :-) A: The only thing I can think of is to have the create method on at factory object, which you would than mock. But in terms of mocking a constructor call, no. Mock objects presuppose the existence of the object, whereas a constructor presuppose that the object doesn't exist. At least in java where allocation and initialization happen together. A: jmockit can do this. See my answer in https://stackoverflow.com/questions/22697#93675 A: Alas, I think I'm guilty of asking the wrong question. The simple factory I was trying to test looked something like: public Wrapper wrapObject(Object toWrap) { if(toWrap instanceof ClassA) { return new Wrapper((ClassA) toWrap); } else if (toWrap instanceof ClassB) { return new Wrapper((ClassB) toWrap); } // etc else { return null; } } I was asking the question how to find if "new ClassAWrapper( )" was called because the object toWrap was hard to obtain in an isolated test. And the wrapper (if it can even be called that) is kind of weird as it uses the same class to wrap different objects, just uses different constructors[1]. I suspect that if I had asked the question a bit better, I would have quickly received the answer: "You should mock Object toWrap to match the instances you're testing for in different test methods, and inspect the resulting Wrapper object to find the correct type is returned... and hope you're lucky enough that you don't have to mock out the world to create the different instances ;-)" I now have an okay solution to the immediate problem, thanks! [1] opening up the question of whether this should be refactored is well out of the scope of my current problem :-) A: Are you familiar with Dependency Injection? If no, then you ceartanly would benefit from learning about that concept. I guess the good-old Inversion of Control Containers and the Dependency Injection pattern by Martin Fowler will serve as a good introduction. With Dependency Injection (DI), you would have a DI container object, that is able to create all kinds of classes for you. Then your object would make use of the DI container to instanciate classes and you would mock the DI container to test that the class creates instances of expected classes. A: Dependency Injection or Inversion of Control. Alternatively, use the Abstract Factory design pattern for all the objects that you create. When you are in Unit Test mode, inject an Testing Factory which will tell you what are you creating, then include the assertion code in the Testing Factory to check the results (inversion of control). To leave your code as clean as possible create an internal protected interface, implement the interface (your factory) with the production code as an internal class. Add a static variable type of your interface initialized to your default factory. Add static setter for the factory and you are done. In your test code (must be in the same package, otherwise the internal interface must be public), create an anonymous or internal class with the assertion code and the test code. Then in your test, initialize the target class, assign (inject) the test factory, and run the methods of your target class.
How to mock object construction?
Is there a way to mock object construction using JMock in Java? For example, if I have a method as such: public Object createObject(String objectType) { if(objectType.equals("Integer") { return new Integer(); } else if (objectType.equals("String") { return new String(); } } ...is there a way to mock out the expectation of the object construction in a test method? I'd like to be able to place expectations that certain constructors are being called, rather than having an extra bit of code to check the type (as it won't always be as convoluted and simple as my example). So instead of: assertTrue(a.createObject() instanceof Integer); I could have an expectation of the certain constructor being called. Just to make it a bit cleaner, and express what is actually being tested in a more readable way. Please excuse the simple example, the actual problem I'm working on is a bit more complicated, but having the expectation would simplify it. For a bit more background: I have a simple factory method, which creates wrapper objects. The objects being wrapped can require parameters which are difficult to obtain in a test class (it's pre-existing code), so it is difficult to construct them. Perhaps closer to what I'm actually looking for is: is there a way to mock an entire class (using CGLib) in one fell swoop, without specifying every method to stub out? So the mock is being wrapped in a constructor, so obviously methods can be called on it, is JMock capable of dynamically mocking out each method? My guess is no, as that would be pretty complicated. But knowing I'm barking up the wrong tree is valuable too :-)
[ "The only thing I can think of is to have the create method on at factory object, which you would than mock. \nBut in terms of mocking a constructor call, no. Mock objects presuppose the existence of the object, whereas a constructor presuppose that the object doesn't exist. At least in java where allocation and initialization happen together. \n", "jmockit can do this.\nSee my answer in https://stackoverflow.com/questions/22697#93675\n", "Alas, I think I'm guilty of asking the wrong question.\nThe simple factory I was trying to test looked something like:\npublic Wrapper wrapObject(Object toWrap) {\n if(toWrap instanceof ClassA) {\n return new Wrapper((ClassA) toWrap);\n } else if (toWrap instanceof ClassB) {\n return new Wrapper((ClassB) toWrap);\n } // etc\n\n else {\n return null;\n }\n}\n\nI was asking the question how to find if \"new ClassAWrapper( )\" was called because the object toWrap was hard to obtain in an isolated test. And the wrapper (if it can even be called that) is kind of weird as it uses the same class to wrap different objects, just uses different constructors[1]. I suspect that if I had asked the question a bit better, I would have quickly received the answer:\n\"You should mock Object toWrap to match the instances you're testing for in different test methods, and inspect the resulting Wrapper object to find the correct type is returned... and hope you're lucky enough that you don't have to mock out the world to create the different instances ;-)\"\nI now have an okay solution to the immediate problem, thanks! \n[1] opening up the question of whether this should be refactored is well out of the scope of my current problem :-)\n", "Are you familiar with Dependency Injection?\nIf no, then you ceartanly would benefit from learning about that concept. I guess the good-old Inversion of Control Containers and the Dependency Injection pattern by Martin Fowler will serve as a good introduction.\nWith Dependency Injection (DI), you would have a DI container object, that is able to create all kinds of classes for you. Then your object would make use of the DI container to instanciate classes and you would mock the DI container to test that the class creates instances of expected classes.\n", "Dependency Injection or Inversion of Control.\nAlternatively, use the Abstract Factory design pattern for all the objects that you create. When you are in Unit Test mode, inject an Testing Factory which will tell you what are you creating, then include the assertion code in the Testing Factory to check the results (inversion of control).\nTo leave your code as clean as possible create an internal protected interface, implement the interface (your factory) with the production code as an internal class. Add a static variable type of your interface initialized to your default factory. Add static setter for the factory and you are done.\nIn your test code (must be in the same package, otherwise the internal interface must be public), create an anonymous or internal class with the assertion code and the test code. Then in your test, initialize the target class, assign (inject) the test factory, and run the methods of your target class.\n" ]
[ 7, 4, 1, 0, 0 ]
[ "I hope there is none. \nMocks are supposed to mock interfaces, which have no constructors... just methods. \nSomething seems to be amiss in your approach to testing here. Any reason why you need to test that explicit constructors are being called ?\nAsserting the type of returned object seems okay for testing factory implementations. Treat createObject as a blackbox.. examine what it returns but dont micromanage how it does it. No one likes that :)\nUpdate on the Update: Ouch! Desperate measures for desperate times eh? I'd be surprised if JMock allows that... as I said it works on interfaces.. not concrete types. \nSo \n\nEither try and expend some effort on getting those pesky input objects 'instantiable' under the test harness. Go Bottom up in your approach.\nIf that is infeasible, manually test it out with breakpoints (I know it sucks). Then stick a \"Touch it at your own risk\" comment in a visible zone in the source file and move ahead. Fight another day.\n\n" ]
[ -1 ]
[ "java", "junit", "mocking", "tdd" ]
stackoverflow_0000091981_java_junit_mocking_tdd.txt
Q: .NET Framework method to quickly build directories Is there a quick way to join paths like the Join-Path function in Powershell? For example, I have two parts of a path "C:\foo" and a subdirectory "bar". Join-Path will join these and take care of the backslash delimiters. Is there a built-in method for this in .NET, or do I need to handle this myself? A: This is your friend: http://msdn.microsoft.com/en-us/library/system.io.path.combine.aspx A: System.IO.Path.Combine is the one you're looking for. There's quite a few useful methods on the Path class. A: Path.Combine is the way to go. A: System.IO.Path.Combine
.NET Framework method to quickly build directories
Is there a quick way to join paths like the Join-Path function in Powershell? For example, I have two parts of a path "C:\foo" and a subdirectory "bar". Join-Path will join these and take care of the backslash delimiters. Is there a built-in method for this in .NET, or do I need to handle this myself?
[ "This is your friend: http://msdn.microsoft.com/en-us/library/system.io.path.combine.aspx\n", "System.IO.Path.Combine is the one you're looking for. There's quite a few useful methods on the Path class.\n", "Path.Combine is the way to go.\n", "System.IO.Path.Combine\n" ]
[ 7, 2, 1, 1 ]
[]
[]
[ ".net", "powershell" ]
stackoverflow_0000093821_.net_powershell.txt
Q: Combine rows / concatenate rows I'm looking for an Access 2007 equivalent to SQL Server's COALESCE function. In SQL Server you could do something like: Person John Steve Richard SQL DECLARE @PersonList nvarchar(1024) SELECT @PersonList = COALESCE(@PersonList + ',','') + Person FROM PersonTable PRINT @PersonList Which produces: John, Steve, Richard I want to do the same but in Access 2007. Does anyone know how to combine rows like this in Access 2007? A: Here is a sample User Defined Function (UDF) and possible usage. Function: Function Coalsce(strSQL As String, strDelim, ParamArray NameList() As Variant) Dim db As Database Dim rs As DAO.Recordset Dim strList As String Set db = CurrentDb If strSQL <> "" Then Set rs = db.OpenRecordset(strSQL) Do While Not rs.EOF strList = strList & strDelim & rs.Fields(0) rs.MoveNext Loop strList = Mid(strList, Len(strDelim)) Else strList = Join(NameList, strDelim) End If Coalsce = strList End Function Usage: SELECT documents.MembersOnly, Coalsce("SELECT FName From Persons WHERE Member=True",":") AS Who, Coalsce("",":","Mary","Joe","Pat?") AS Others FROM documents; An ADO version, inspired by a comment by onedaywhen Function ConcatADO(strSQL As String, strColDelim, strRowDelim, ParamArray NameList() As Variant) Dim rs As New ADODB.Recordset Dim strList As String On Error GoTo Proc_Err If strSQL <> "" Then rs.Open strSQL, CurrentProject.Connection strList = rs.GetString(, , strColDelim, strRowDelim) strList = Mid(strList, 1, Len(strList) - Len(strRowDelim)) Else strList = Join(NameList, strColDelim) End If ConcatADO = strList Exit Function Proc_Err: ConcatADO = "***" & UCase(Err.Description) End Function From: http://wiki.lessthandot.com/index.php/Concatenate_a_List_into_a_Single_Field_%28Column%29 A: I think Nz is what you're after, syntax is Nz(variant, [if null value]). Here's the documentation link: Nz Function ---Person--- John Steve Richard DECLARE @PersonList nvarchar(1024) SELECT @PersonList = Nz(@PersonList + ',','') + Person FROM PersonTable PRINT @PersonList A: Although Nz does a comparable thing to COALESCE, you can't use it in Access to do the operation you are performing. It's not the COALESCE that is building the list of row values, it's the concatenatiion into a variable. Unfortunately, this isn't possible inside an Access query which has to be a single SQL statement and where there is no facility to declare a variable. I think you would need to create a function that would open a resultset, iterate over it and concatenate the row values into a string. A: To combine rows in Access, you'll probably need code that looks something like this: Public Function Coalesce(pstrTableName As String, pstrFieldName As String) Dim rst As DAO.Recordset Dim str As String Set rst = CurrentDb.OpenRecordset(pstrTableName) Do While rst.EOF = False If Len(str) = 0 Then str = rst(pstrFieldName) Else str = str & "," & rst(pstrFieldName) End If rst.MoveNext Loop Coalesce = str End Function You'll want to add error-handling code and clean up your recordset, and this will change slightly if you use ADO instead of DAO, but the general idea is the same. A: I understand here that you have a table "person" with 3 records. There is nothing comparable to what you describe in Access. In "standard" Access (DAO recordset), you will have to open a recordset and use the getrows method to have your data Dim rs as DAO.recordset, _ personList as String, _ personArray() as variant set rs = currentDb.open("Person") set personArray = rs.getRows(rs.recordcount) rs.close once you have this array (it will be bidimensional), you can manipulate it to extract the "column" you'll need. There might be a smart way to extract a one-dimension array from this, so you can then use the "Join" instruction to concatenate each array value in one string.
Combine rows / concatenate rows
I'm looking for an Access 2007 equivalent to SQL Server's COALESCE function. In SQL Server you could do something like: Person John Steve Richard SQL DECLARE @PersonList nvarchar(1024) SELECT @PersonList = COALESCE(@PersonList + ',','') + Person FROM PersonTable PRINT @PersonList Which produces: John, Steve, Richard I want to do the same but in Access 2007. Does anyone know how to combine rows like this in Access 2007?
[ "Here is a sample User Defined Function (UDF) and possible usage.\nFunction:\nFunction Coalsce(strSQL As String, strDelim, ParamArray NameList() As Variant)\nDim db As Database\nDim rs As DAO.Recordset\nDim strList As String\n\n Set db = CurrentDb\n\n If strSQL <> \"\" Then\n Set rs = db.OpenRecordset(strSQL)\n\n Do While Not rs.EOF\n strList = strList & strDelim & rs.Fields(0)\n rs.MoveNext\n Loop\n\n strList = Mid(strList, Len(strDelim))\n Else\n\n strList = Join(NameList, strDelim)\n End If\n\n Coalsce = strList\n\nEnd Function\n\nUsage:\nSELECT documents.MembersOnly, \n Coalsce(\"SELECT FName From Persons WHERE Member=True\",\":\") AS Who, \n Coalsce(\"\",\":\",\"Mary\",\"Joe\",\"Pat?\") AS Others\nFROM documents;\n\nAn ADO version, inspired by a comment by onedaywhen\nFunction ConcatADO(strSQL As String, strColDelim, strRowDelim, ParamArray NameList() As Variant)\n Dim rs As New ADODB.Recordset\n Dim strList As String\n\n On Error GoTo Proc_Err\n\n If strSQL <> \"\" Then\n rs.Open strSQL, CurrentProject.Connection\n strList = rs.GetString(, , strColDelim, strRowDelim)\n strList = Mid(strList, 1, Len(strList) - Len(strRowDelim))\n Else\n strList = Join(NameList, strColDelim)\n End If\n\n ConcatADO = strList\n\n Exit Function\n\n Proc_Err:\n ConcatADO = \"***\" & UCase(Err.Description)\n End Function\n\nFrom: http://wiki.lessthandot.com/index.php/Concatenate_a_List_into_a_Single_Field_%28Column%29\n", "I think Nz is what you're after, syntax is Nz(variant, [if null value]). Here's the documentation link: Nz Function\n---Person--- \nJohn\nSteve\nRichard\n\nDECLARE @PersonList nvarchar(1024)\nSELECT @PersonList = Nz(@PersonList + ',','') + Person\nFROM PersonTable\n\nPRINT @PersonList\n\n", "Although Nz does a comparable thing to COALESCE, you can't use it in Access to do the operation you are performing. It's not the COALESCE that is building the list of row values, it's the concatenatiion into a variable. \nUnfortunately, this isn't possible inside an Access query which has to be a single SQL statement and where there is no facility to declare a variable. \nI think you would need to create a function that would open a resultset, iterate over it and concatenate the row values into a string. \n", "To combine rows in Access, you'll probably need code that looks something like this:\nPublic Function Coalesce(pstrTableName As String, pstrFieldName As String)\n\nDim rst As DAO.Recordset\nDim str As String\n\n Set rst = CurrentDb.OpenRecordset(pstrTableName)\n Do While rst.EOF = False\n If Len(str) = 0 Then\n str = rst(pstrFieldName)\n Else\n str = str & \",\" & rst(pstrFieldName)\n End If\n rst.MoveNext\n Loop\n\n Coalesce = str\n\nEnd Function\n\nYou'll want to add error-handling code and clean up your recordset, and this will change slightly if you use ADO instead of DAO, but the general idea is the same. \n", "I understand here that you have a table \"person\" with 3 records. There is nothing comparable to what you describe in Access. \nIn \"standard\" Access (DAO recordset), you will have to open a recordset and use the getrows method to have your data\nDim rs as DAO.recordset, _\n personList as String, _\n personArray() as variant\n\nset rs = currentDb.open(\"Person\")\nset personArray = rs.getRows(rs.recordcount)\n\nrs.close\n\nonce you have this array (it will be bidimensional), you can manipulate it to extract the \"column\" you'll need. There might be a smart way to extract a one-dimension array from this, so you can then use the \"Join\" instruction to concatenate each array value in one string.\n" ]
[ 14, 0, 0, 0, 0 ]
[]
[]
[ "coalesce", "ms_access", "vba" ]
stackoverflow_0000092698_coalesce_ms_access_vba.txt
Q: How does one load a URL from a .NET client application What is the preferred way to open a URL from a thick client application on Windows using C# and the .NET framework? I want it to use the default browser. A: The following code surely works: Process.Start("http://www.yoururl.com/Blah.aspx"); It opens the default browser (technically, the default program that handles HTTP URIs). A: I'd use the Process.Start method. A: private void launchURL_Click(object sender, System.EventArgs e){ string targetURL = "http://stackoverflow.com"; System.Diagnostics.Process.Start(targetURL); } A: System.Diagnostics.Process.Start("http://www.stackoverflow.com");
How does one load a URL from a .NET client application
What is the preferred way to open a URL from a thick client application on Windows using C# and the .NET framework? I want it to use the default browser.
[ "The following code surely works:\nProcess.Start(\"http://www.yoururl.com/Blah.aspx\");\n\nIt opens the default browser (technically, the default program that handles HTTP URIs).\n", "I'd use the Process.Start method.\n", "private void launchURL_Click(object sender, System.EventArgs e){\n string targetURL = \"http://stackoverflow.com\";\n System.Diagnostics.Process.Start(targetURL);\n}\n\n", "System.Diagnostics.Process.Start(\"http://www.stackoverflow.com\");\n\n" ]
[ 8, 4, 1, 0 ]
[]
[]
[ ".net", "c#", "client", "windows" ]
stackoverflow_0000093832_.net_c#_client_windows.txt
Q: Modal dialogs in IE gets hidden behind IE if user clicks on IE pane I have to write an applet that brings up a password dialog. The problem is that dialog is set to be always on top but when user clicks on IE window dialog gets hidden behind IE window nevertheless. And since dialog is modal and holds all IE threads IE pane does not refresh and dialog window is still painted on top of IE (but not refreshed). This behaviour confuses users (they see dialog on top of IE but it looks like it has hanged since it is not refreshe). So I need a way to keep that dialog on top of everything. But any other solution to this problem would be nice. Here's the code: PassDialog dialog = new PassDialog(parent); /* do some non gui related initialization */ dialog.pack(); dialog.setLocationRelativeTo(null); dialog.setAlwaysOnTop(true); dialog.setVisible(true); Resolution: As @shemnon noted I should make a window instead of (null, Frame, Applet) parent of modal dialog. So good way to initlialize parent was: parent = javax.swing.SwingUtilities.getWindowAncestor(theApplet); A: Make a background Thread that calls toFront on the Dialog every 2 seconds. Code that we use (I hope I got everything): class TestClass { protected void toFrontTimer(JFrame frame) { try { bringToFrontTimer = new java.util.Timer(); bringToFrontTask = new BringToFrontTask(frame); bringToFrontTimer.schedule( bringToFrontTask, 300, 300); } catch (Throwable t) { t.printStackTrace(); } } class BringToFrontTask extends TimerTask { private Frame frame; public BringToFrontTask(Frame frame) { this.frame = frame; } public void run() { if(count < 2) { frame.toFront(); } else { cancel(); } count ++; } private int count = 0; } public void cleanup() { if(bringToFrontTask != null) { bringToFrontTask.cancel(); bringToFrontTask = null; } if(bringToFrontTimer != null) { bringToFrontTimer = null; } } java.util.Timer bringToFrontTimer = null; java.util.TimerTask bringToFrontTask = null; } A: This is a shot in the dark as I'm not familiar with applets, but you could take a look at IE's built-in window.showModalDialog method. It's fairly easy to use. Maybe a combination of this and Noah's suggestion? A: What argument are you using for the parent? You may have better luck if you use the parent of the Applet. javax.swing.SwingUtilities.getWindowAncestor(theApplet) Using the getWindowAncestor will skip the applet parents (getRoot(component) will return applets). In at least some versions of Java there was a Frame that was equivalent to the IE window. YMMV. A: You might try launching a modal from JavaScript using the JavaScript integration (see http://www.raditha.com/java/mayscript.php for an example). The JavaScript you would need would be something like: function getPassword() { return prompt("Enter Password"); } And the Java would be: password = jso.call("getPassword", new String[0]); Unfortunately that means giving up all hope of having a nice looking modal. Good luck!
Modal dialogs in IE gets hidden behind IE if user clicks on IE pane
I have to write an applet that brings up a password dialog. The problem is that dialog is set to be always on top but when user clicks on IE window dialog gets hidden behind IE window nevertheless. And since dialog is modal and holds all IE threads IE pane does not refresh and dialog window is still painted on top of IE (but not refreshed). This behaviour confuses users (they see dialog on top of IE but it looks like it has hanged since it is not refreshe). So I need a way to keep that dialog on top of everything. But any other solution to this problem would be nice. Here's the code: PassDialog dialog = new PassDialog(parent); /* do some non gui related initialization */ dialog.pack(); dialog.setLocationRelativeTo(null); dialog.setAlwaysOnTop(true); dialog.setVisible(true); Resolution: As @shemnon noted I should make a window instead of (null, Frame, Applet) parent of modal dialog. So good way to initlialize parent was: parent = javax.swing.SwingUtilities.getWindowAncestor(theApplet);
[ "Make a background Thread that calls toFront on the Dialog every 2 seconds.\nCode that we use (I hope I got everything):\nclass TestClass {\nprotected void toFrontTimer(JFrame frame) {\n try {\n bringToFrontTimer = new java.util.Timer();\n bringToFrontTask = new BringToFrontTask(frame);\n bringToFrontTimer.schedule( bringToFrontTask, 300, 300);\n } catch (Throwable t) {\n t.printStackTrace();\n }\n}\n\nclass BringToFrontTask extends TimerTask {\n private Frame frame;\n public BringToFrontTask(Frame frame) {\n this.frame = frame;\n }\n public void run()\n {\n if(count < 2) {\n frame.toFront();\n } else {\n cancel();\n }\n count ++;\n }\n private int count = 0;\n}\n\npublic void cleanup() {\n if(bringToFrontTask != null) {\n bringToFrontTask.cancel();\n bringToFrontTask = null;\n }\n if(bringToFrontTimer != null) {\n bringToFrontTimer = null;\n }\n}\n\njava.util.Timer bringToFrontTimer = null;\njava.util.TimerTask bringToFrontTask = null;\n}\n\n", "This is a shot in the dark as I'm not familiar with applets, but you could take a look at IE's built-in window.showModalDialog method. It's fairly easy to use. Maybe a combination of this and Noah's suggestion?\n", "What argument are you using for the parent?\nYou may have better luck if you use the parent of the Applet.\njavax.swing.SwingUtilities.getWindowAncestor(theApplet)\n\nUsing the getWindowAncestor will skip the applet parents (getRoot(component) will return applets). In at least some versions of Java there was a Frame that was equivalent to the IE window. YMMV.\n", "You might try launching a modal from JavaScript using the JavaScript integration (see http://www.raditha.com/java/mayscript.php for an example). \nThe JavaScript you would need would be something like:\nfunction getPassword() {\n return prompt(\"Enter Password\");\n}\n\nAnd the Java would be:\npassword = jso.call(\"getPassword\", new String[0]);\n\nUnfortunately that means giving up all hope of having a nice looking modal. Good luck!\n" ]
[ 1, 1, 1, 0 ]
[]
[]
[ "applet", "internet_explorer", "java", "modal_dialog", "swing" ]
stackoverflow_0000073000_applet_internet_explorer_java_modal_dialog_swing.txt
Q: Is there a .NET function to validate a class name? I am using CodeDom to generate dynamic code based on user values. One of those values controls what the name of the class I'm generating is. I know I could sterilize the name based on language rules about valid class names using regular expressions, but I'd like to know if there is a specific method built into the framework to validate and/or sterilize a class name. A: An easy way to determine if a string is a valid identifier for a class or variable is to call the static method System.CodeDom.Compiler.CodeGenerator.IsValidLanguageIndependentIdentifier(string value) A: Use the CreateValidIdentifier method on the CSharpCodeProvider class. CSharpCodeProvider codeProvider = new CSharpCodeProvider(); string sFixedName = codeProvider.CreateValidIdentifier("somePossiblyInvalidName"); CodeTypeDeclaration codeType = new CodeTypeDeclaration(sFixedName); It returns a valid name given some input. If you just want to validate the name and not fix it, compare the input and output. It won't alter valid input so the output will be equivalent. A: I found an answer to my question. I can call CodeCompiler.ValidateIdentifiers(class1); where class1 is a CodeObject to validate all identifiers in that CodeDom tree and below. So I can call this right after I create my CodeTypeDeclaration class1 to validate just the class name, or I can build up my CodeDom and then call this at the end to validate all the identifiers in my tree. Just what I needed! A: public static bool IsReservedKeyWord(string identifier) { Microsoft.CSharp.CSharpCodeProvider csharpProvider = new Microsoft.CSharp.CSharpCodeProvider(); return csharpProvider.IsValidIdentifier(identifier); }
Is there a .NET function to validate a class name?
I am using CodeDom to generate dynamic code based on user values. One of those values controls what the name of the class I'm generating is. I know I could sterilize the name based on language rules about valid class names using regular expressions, but I'd like to know if there is a specific method built into the framework to validate and/or sterilize a class name.
[ "An easy way to determine if a string is a valid identifier for a class or variable is to call the static method \nSystem.CodeDom.Compiler.CodeGenerator.IsValidLanguageIndependentIdentifier(string value)\n\n", "Use the CreateValidIdentifier method on the CSharpCodeProvider class. \nCSharpCodeProvider codeProvider = new CSharpCodeProvider(); \nstring sFixedName = codeProvider.CreateValidIdentifier(\"somePossiblyInvalidName\"); \nCodeTypeDeclaration codeType = new CodeTypeDeclaration(sFixedName); \n\nIt returns a valid name given some input. If you just want to validate the name and not fix it, compare the input and output. It won't alter valid input so the output will be equivalent. \n", "I found an answer to my question. I can call\nCodeCompiler.ValidateIdentifiers(class1);\n\nwhere class1 is a CodeObject to validate all identifiers in that CodeDom tree and below. So I can call this right after I create my CodeTypeDeclaration class1 to validate just the class name, or I can build up my CodeDom and then call this at the end to validate all the identifiers in my tree. Just what I needed!\n", "public static bool IsReservedKeyWord(string identifier)\n {\n Microsoft.CSharp.CSharpCodeProvider csharpProvider = new Microsoft.CSharp.CSharpCodeProvider();\n return csharpProvider.IsValidIdentifier(identifier);\n }\n\n" ]
[ 25, 9, 2, 1 ]
[]
[]
[ ".net", "c#", "class", "naming", "validation" ]
stackoverflow_0000092841_.net_c#_class_naming_validation.txt
Q: Asp.net MVC routing ambiguous, two paths for same page I'm trying out ASP.NET MVC routing and have of course stumbled across a problem. I have a section, /Admin/Pages/, and this is also accessible through /Pages/, which it shouldn't. What could I be missing? The routing code in global.asax: public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Pages", // Route name "Admin/Pages/{action}/{id}", // URL with parameters // Parameter defaults new { controller = "Pages", action = "Index", id = "" } ); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters // Parameter defaults new { controller = "Home", action = "Index", id = "" } ); } Thanks! A: I'd suggest adding an explicit route for /Pages/ at the beginning. The problem is that it's being handled by the Default route and deriving: controller = "Pages" action = "Index" id = "" which are exactly the same as the parameters for your Admin route. A: For routing issues like this, you should try out my Route Debugger assembly (use only in testing). It can help figure out these types of issues. P.S. If you're trying to secure the Pages controller, make sure to use the [Authorize] attribute. Don't just rely on URL authorization. A: You could add a constraint to the default rule so that the {Controller} tag cannot be "Pages". A: You have in you first route {action} token/parameter which gets in conflict with setting of default action. Try changing parameter name in your route, or remove default action name.
Asp.net MVC routing ambiguous, two paths for same page
I'm trying out ASP.NET MVC routing and have of course stumbled across a problem. I have a section, /Admin/Pages/, and this is also accessible through /Pages/, which it shouldn't. What could I be missing? The routing code in global.asax: public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Pages", // Route name "Admin/Pages/{action}/{id}", // URL with parameters // Parameter defaults new { controller = "Pages", action = "Index", id = "" } ); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters // Parameter defaults new { controller = "Home", action = "Index", id = "" } ); } Thanks!
[ "I'd suggest adding an explicit route for /Pages/ at the beginning.\nThe problem is that it's being handled by the Default route and deriving:\ncontroller = \"Pages\"\naction = \"Index\"\nid = \"\"\nwhich are exactly the same as the parameters for your Admin route.\n", "For routing issues like this, you should try out my Route Debugger assembly (use only in testing). It can help figure out these types of issues.\nP.S. If you're trying to secure the Pages controller, make sure to use the [Authorize] attribute. Don't just rely on URL authorization.\n", "You could add a constraint to the default rule so that the {Controller} tag cannot be \"Pages\".\n", "You have in you first route {action} token/parameter which gets in conflict with setting of default action. Try changing parameter name in your route, or remove default action name.\n" ]
[ 7, 7, 2, 0 ]
[]
[]
[ "asp.net_mvc", "routing" ]
stackoverflow_0000070371_asp.net_mvc_routing.txt
Q: ASP.NET MVC ViewData (using indices) I had a working solution using ASP.NET MVC Preview 3 (was upgraded from a Preview 2 solution) that uses an untyped ViewMasterPage like so: public partial class Home : ViewMasterPage On Home.Master there is a display statement like this: <%= ((GenericViewData)ViewData["Generic"]).Skin %> However, a developer on the team just changed the assembly references to Preview 4. Following this, the code will no longer populate ViewData with indexed values like the above. Instead, ViewData["Generic"] is null. As per this question, ViewData.Eval("Generic") works, and ViewData.Model is also populated correctly. However, the reason this solution isn't using typed pages etc. is because it is kind of a legacy solution. As such, it is impractical to go through this fairly large solution and update all .aspx pages (especially as the compiler doesn't detect this sort of stuff). I have tried reverting the assemblies by removing the reference and then adding a reference to the Preview 3 assembly in the 'bin' folder of the project. This did not change anything. I have even tried reverting the Project file to an earlier version and that still did not seem to fix the problem. I have other solutions using the same technique that continue to work. Is there anything you can suggest as to why this has suddenly stopped working and how I might go about fixing it (any hint in the right direction would be appreciated)? A: We made that change because we wanted a bit of symmetry with the [] indexer. The Eval() method uses reflection and looks into the model to retrieve values. The indexer only looks at items directly added to the dictionary. A: I've decided to replace all instances of ViewData["blah"] with ViewData.Eval("blah"). However, I'd like to know the cause of this change if possible because: If it happens on my other projects it'd be nice to be able to fix. It would be nice to leave the deployed working code and not overwrite with these changes. It would be nice to know that nothing else has changed that I haven't noticed. A: How are you setting the viewdata? This works for me: Controller: ViewData["CategoryName"] = a.Name; View: <%= ViewData["CategoryName"] %> BTW, I am on Preview 5 now. But this has worked on 3 and 4... A: Re: Ricky I am just passing an object when I call the View() method from the Controller. I've also noticed that on my deployed server where nothing has been updated, ViewData.Eval fails and ViewData["index"] works. On my development server ViewData["index"] fails and ViewData.Eval works... A: Yeah, so whatever you pass into the View is accessible in the View as ViewData.Model. But that will be just a good old object if you don't do the strongly typed Views...
ASP.NET MVC ViewData (using indices)
I had a working solution using ASP.NET MVC Preview 3 (was upgraded from a Preview 2 solution) that uses an untyped ViewMasterPage like so: public partial class Home : ViewMasterPage On Home.Master there is a display statement like this: <%= ((GenericViewData)ViewData["Generic"]).Skin %> However, a developer on the team just changed the assembly references to Preview 4. Following this, the code will no longer populate ViewData with indexed values like the above. Instead, ViewData["Generic"] is null. As per this question, ViewData.Eval("Generic") works, and ViewData.Model is also populated correctly. However, the reason this solution isn't using typed pages etc. is because it is kind of a legacy solution. As such, it is impractical to go through this fairly large solution and update all .aspx pages (especially as the compiler doesn't detect this sort of stuff). I have tried reverting the assemblies by removing the reference and then adding a reference to the Preview 3 assembly in the 'bin' folder of the project. This did not change anything. I have even tried reverting the Project file to an earlier version and that still did not seem to fix the problem. I have other solutions using the same technique that continue to work. Is there anything you can suggest as to why this has suddenly stopped working and how I might go about fixing it (any hint in the right direction would be appreciated)?
[ "We made that change because we wanted a bit of symmetry with the [] indexer. The Eval() method uses reflection and looks into the model to retrieve values. The indexer only looks at items directly added to the dictionary.\n", "I've decided to replace all instances of ViewData[\"blah\"] with ViewData.Eval(\"blah\").\nHowever, I'd like to know the cause of this change if possible because:\n\nIf it happens on my other projects it'd be nice to be able to fix.\nIt would be nice to leave the deployed working code and not overwrite with these changes.\nIt would be nice to know that nothing else has changed that I haven't noticed.\n\n", "How are you setting the viewdata? This works for me:\nController:\nViewData[\"CategoryName\"] = a.Name;\n\nView:\n<%= ViewData[\"CategoryName\"] %>\n\nBTW, I am on Preview 5 now. But this has worked on 3 and 4...\n", "Re: Ricky\nI am just passing an object when I call the View() method from the Controller.\nI've also noticed that on my deployed server where nothing has been updated, ViewData.Eval fails and ViewData[\"index\"] works.\nOn my development server ViewData[\"index\"] fails and ViewData.Eval works...\n", "Yeah, so whatever you pass into the View is accessible in the View as ViewData.Model. But that will be just a good old object if you don't do the strongly typed Views...\n" ]
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "asp.net_mvc" ]
stackoverflow_0000061805_asp.net_mvc.txt
Q: How can I allow others to create Java, .NET, Ruby, PHP, Perl web user interface components that interact with each other? How can I allow others to create Java, .NET, Ruby, PHP, Perl web user interface components that interact with each other? For example, one web ui component written in .NET selects a customer, and the other web user interface components are written in Java, Ruby or PHP are able to refresh showing information about the selected customer from different systems. A: Look up something called WebServices, SOAP and XML-RPC. Should get you well on your way. A: Use web services to wrap common code / libraries that you want to share across the interfaces. All the listed platforms have decent support for webservices. A: Actualy, .Net can natively run all these languages because it ransforms all of them in MSIL, provided you have installed the proper compiler. To do so, you can use visual studio and create a project, using various languages. Import you code and adapt it to fit the .net library. A think it´s a lot of work, but if you have no choices, there are not a lot of other alternatives :-( Anyway, it´s still better to limit yourself to 1 or 2 languages or maintenance will become a nightmare.
How can I allow others to create Java, .NET, Ruby, PHP, Perl web user interface components that interact with each other?
How can I allow others to create Java, .NET, Ruby, PHP, Perl web user interface components that interact with each other? For example, one web ui component written in .NET selects a customer, and the other web user interface components are written in Java, Ruby or PHP are able to refresh showing information about the selected customer from different systems.
[ "Look up something called WebServices, SOAP and XML-RPC. Should get you well on your way.\n", "Use web services to wrap common code / libraries that you want to share across the interfaces. All the listed platforms have decent support for webservices.\n", "Actualy, .Net can natively run all these languages because it ransforms all of them in MSIL, provided you have installed the proper compiler.\nTo do so, you can use visual studio and create a project, using various languages. Import you code and adapt it to fit the .net library. A think it´s a lot of work, but if you have no choices, there are not a lot of other alternatives :-(\nAnyway, it´s still better to limit yourself to 1 or 2 languages or maintenance will become a nightmare.\n" ]
[ 2, 1, 1 ]
[]
[]
[ "components", "integration", "user_interface" ]
stackoverflow_0000093846_components_integration_user_interface.txt
Q: How do I determine the page number for the tab I just clicked on in gtk#? I have a GTK notebook with multiple tabs. Each tab label is a composite container containing, among other things, a button I want to use to close the tab. The button has a handler for the "clicked" signal. When the signal is called, I get the button widget and "EventArgs" as a parameter. I need to determine the page number based on the button widget, but myNotebook.PageNum(buttonWidget) always returns -1. I've even tried buttonWidget.Parent which is the HBox which contains the widget. Any ideas on what I can do or what I am doing wrong? A: One easy work around is to pass the page number to your button's Clicked event as you construct the buttons. for (int page = 0; page < n; page++){ int the_page = page; NotebookPage p = new NotebookPage (); ... Button b = new Button ("Close page {0}", the_page); b.Clicked += delegate { Console.WriteLine ("Page={0}", the_page); }; } The "the_page" is important, as it is a new variable that will be captured by the delegate.
How do I determine the page number for the tab I just clicked on in gtk#?
I have a GTK notebook with multiple tabs. Each tab label is a composite container containing, among other things, a button I want to use to close the tab. The button has a handler for the "clicked" signal. When the signal is called, I get the button widget and "EventArgs" as a parameter. I need to determine the page number based on the button widget, but myNotebook.PageNum(buttonWidget) always returns -1. I've even tried buttonWidget.Parent which is the HBox which contains the widget. Any ideas on what I can do or what I am doing wrong?
[ "One easy work around is to pass the page number to your button's Clicked event as you construct the buttons.\nfor (int page = 0; page < n; page++){ \n int the_page = page;\n NotebookPage p = new NotebookPage ();\n ...\n Button b = new Button (\"Close page {0}\", the_page);\n b.Clicked += delegate { \n Console.WriteLine (\"Page={0}\", the_page); \n };\n}\n\nThe \"the_page\" is important, as it is a new variable that will be captured by the delegate.\n" ]
[ 4 ]
[]
[]
[ "gtk", "gtk#", "mono" ]
stackoverflow_0000093044_gtk_gtk#_mono.txt
Q: How to determine whether a character is a letter in Java? How do you check if a one-character String is a letter - including any letters with accents? I had to work this out recently, so I'll answer it myself, after the recent VB6 question reminded me. A: Character.isLetter() is much faster than string.matches(), because string.matches() compiles a new Pattern every time. Even caching the pattern, I think isLetter() would still beat it. EDIT: Just ran across this again and thought I'd try to come up with some actual numbers. Here's my attempt at a benchmark, checking all three methods (matches() with and without caching the Pattern, and Character.isLetter()). I also made sure that there were both valid and invalid characters checked, so as not to skew things. import java.util.regex.*; class TestLetter { private static final Pattern ONE_CHAR_PATTERN = Pattern.compile("\\p{L}"); private static final int NUM_TESTS = 10000000; public static void main(String[] args) { long start = System.nanoTime(); int counter = 0; for (int i = 0; i < NUM_TESTS; i++) { if (testMatches(Character.toString((char) (i % 128)))) counter++; } System.out.println(NUM_TESTS + " tests of Pattern.matches() took " + (System.nanoTime()-start) + " ns."); System.out.println("There were " + counter + "/" + NUM_TESTS + " valid characters"); /*********************************/ start = System.nanoTime(); counter = 0; for (int i = 0; i < NUM_TESTS; i++) { if (testCharacter(Character.toString((char) (i % 128)))) counter++; } System.out.println(NUM_TESTS + " tests of isLetter() took " + (System.nanoTime()-start) + " ns."); System.out.println("There were " + counter + "/" + NUM_TESTS + " valid characters"); /*********************************/ start = System.nanoTime(); counter = 0; for (int i = 0; i < NUM_TESTS; i++) { if (testMatchesNoCache(Character.toString((char) (i % 128)))) counter++; } System.out.println(NUM_TESTS + " tests of String.matches() took " + (System.nanoTime()-start) + " ns."); System.out.println("There were " + counter + "/" + NUM_TESTS + " valid characters"); } private static boolean testMatches(final String c) { return ONE_CHAR_PATTERN.matcher(c).matches(); } private static boolean testMatchesNoCache(final String c) { return c.matches("\\p{L}"); } private static boolean testCharacter(final String c) { return Character.isLetter(c.charAt(0)); } } And my output: 10000000 tests of Pattern.matches() took 4325146672 ns. There were 4062500/10000000 valid characters 10000000 tests of isLetter() took 546031201 ns. There were 4062500/10000000 valid characters 10000000 tests of String.matches() took 11900205444 ns. There were 4062500/10000000 valid characters So that's almost 8x better, even with a cached Pattern. (And uncached is nearly 3x worse than cached.) A: Just checking if a letter is in A-Z because that doesn't include letters with accents or letters in other alphabets. I found out that you can use the regular expression class for 'Unicode letter', or one of its case-sensitive variations: string.matches("\\p{L}"); // Unicode letter string.matches("\\p{Lu}"); // Unicode upper-case letter You can also do this with Character class: Character.isLetter(character); but that is less convenient if you need to check more than one letter.
How to determine whether a character is a letter in Java?
How do you check if a one-character String is a letter - including any letters with accents? I had to work this out recently, so I'll answer it myself, after the recent VB6 question reminded me.
[ "Character.isLetter() is much faster than string.matches(), because string.matches() compiles a new Pattern every time. Even caching the pattern, I think isLetter() would still beat it.\n\nEDIT: Just ran across this again and thought I'd try to come up with some actual numbers. Here's my attempt at a benchmark, checking all three methods (matches() with and without caching the Pattern, and Character.isLetter()). I also made sure that there were both valid and invalid characters checked, so as not to skew things.\nimport java.util.regex.*;\n\nclass TestLetter {\n private static final Pattern ONE_CHAR_PATTERN = Pattern.compile(\"\\\\p{L}\");\n private static final int NUM_TESTS = 10000000;\n\n public static void main(String[] args) {\n long start = System.nanoTime();\n int counter = 0;\n for (int i = 0; i < NUM_TESTS; i++) {\n if (testMatches(Character.toString((char) (i % 128))))\n counter++;\n }\n System.out.println(NUM_TESTS + \" tests of Pattern.matches() took \" +\n (System.nanoTime()-start) + \" ns.\");\n System.out.println(\"There were \" + counter + \"/\" + NUM_TESTS +\n \" valid characters\");\n /*********************************/\n start = System.nanoTime();\n counter = 0;\n for (int i = 0; i < NUM_TESTS; i++) {\n if (testCharacter(Character.toString((char) (i % 128))))\n counter++;\n }\n System.out.println(NUM_TESTS + \" tests of isLetter() took \" +\n (System.nanoTime()-start) + \" ns.\");\n System.out.println(\"There were \" + counter + \"/\" + NUM_TESTS +\n \" valid characters\");\n /*********************************/\n start = System.nanoTime();\n counter = 0;\n for (int i = 0; i < NUM_TESTS; i++) {\n if (testMatchesNoCache(Character.toString((char) (i % 128))))\n counter++;\n }\n System.out.println(NUM_TESTS + \" tests of String.matches() took \" +\n (System.nanoTime()-start) + \" ns.\");\n System.out.println(\"There were \" + counter + \"/\" + NUM_TESTS +\n \" valid characters\");\n }\n\n private static boolean testMatches(final String c) {\n return ONE_CHAR_PATTERN.matcher(c).matches();\n }\n private static boolean testMatchesNoCache(final String c) {\n return c.matches(\"\\\\p{L}\");\n }\n private static boolean testCharacter(final String c) {\n return Character.isLetter(c.charAt(0));\n }\n}\n\nAnd my output:\n10000000 tests of Pattern.matches() took 4325146672 ns.\nThere were 4062500/10000000 valid characters\n10000000 tests of isLetter() took 546031201 ns.\nThere were 4062500/10000000 valid characters\n10000000 tests of String.matches() took 11900205444 ns.\nThere were 4062500/10000000 valid characters\nSo that's almost 8x better, even with a cached Pattern. (And uncached is nearly 3x worse than cached.)\n", "Just checking if a letter is in A-Z because that doesn't include letters with accents or letters in other alphabets.\nI found out that you can use the regular expression class for 'Unicode letter', or one of its case-sensitive variations:\nstring.matches(\"\\\\p{L}\"); // Unicode letter\nstring.matches(\"\\\\p{Lu}\"); // Unicode upper-case letter\n\nYou can also do this with Character class:\nCharacter.isLetter(character);\n\nbut that is less convenient if you need to check more than one letter.\n" ]
[ 33, 22 ]
[]
[]
[ "java", "unicode" ]
stackoverflow_0000093976_java_unicode.txt
Q: Specifying model in controller? I came across a controller in an older set of code (Rails 1.2.3) that had the following in a controller: class GenericController > ApplicationController # filters and such model :some_model Although the name of the model does not match the name of the model, is there any reason to specify this? Or is this something that has disappeared from later versions of Rails? A: This had to do with dependency injection. I don't recall the details. By now it's just a glorified require, which you don't need because rails auto-requires files for missing constants. A: Yes, that is something that has disappeared in later versions of Rails. There is no need to specify it.
Specifying model in controller?
I came across a controller in an older set of code (Rails 1.2.3) that had the following in a controller: class GenericController > ApplicationController # filters and such model :some_model Although the name of the model does not match the name of the model, is there any reason to specify this? Or is this something that has disappeared from later versions of Rails?
[ "This had to do with dependency injection. I don't recall the details.\nBy now it's just a glorified require, which you don't need because rails auto-requires files for missing constants.\n", "Yes, that is something that has disappeared in later versions of Rails. There is no need to specify it.\n" ]
[ 4, 1 ]
[]
[]
[ "ruby", "ruby_on_rails" ]
stackoverflow_0000094023_ruby_ruby_on_rails.txt
Q: Inheriting a base class I am trying to use forms authentication with Active Directory but I need roles (memberOf) from AD. I am trying to override members of RoleProvider to make this possible (unless someone knows of a better way). I am stuck on an error in the new class that is inheriting from RoleProvider. The error is: ADAuth.ActiveDirectoryRoleProvider' does not implement inherited abstract member 'System.Web.Security.RoleProvider.ApplicationName.get' How do I set up all the other members that I am not overriding? Do I have to create them all in my inherited class or is there a way to tell it to just use the ones from the base class? A: You have to override any abstract elements of your base class. If they are marked abstract, it means the base class does not provide a default implementation, so you cannot call it.
Inheriting a base class
I am trying to use forms authentication with Active Directory but I need roles (memberOf) from AD. I am trying to override members of RoleProvider to make this possible (unless someone knows of a better way). I am stuck on an error in the new class that is inheriting from RoleProvider. The error is: ADAuth.ActiveDirectoryRoleProvider' does not implement inherited abstract member 'System.Web.Security.RoleProvider.ApplicationName.get' How do I set up all the other members that I am not overriding? Do I have to create them all in my inherited class or is there a way to tell it to just use the ones from the base class?
[ "You have to override any abstract elements of your base class. If they are marked abstract, it means the base class does not provide a default implementation, so you cannot call it.\n" ]
[ 2 ]
[]
[]
[ "active_directory", "forms_authentication", "inheritance" ]
stackoverflow_0000094024_active_directory_forms_authentication_inheritance.txt
Q: Web in a desktop application: Good web browser controls? I've been utlising a "web browser control" in desktop based applications (in my case Windows Forms .NET) for a number of years. I mostly use it to create a familiar flow-based user interface that also allows a seamless transition to the internet where required. I'm really tired of the IE browser control because of the poor quality html it generates on output. Also, I guess that it is really just IE7 behind the scenes and so has many of that browser "issues". Despite this, it is quite a powerful control and provides rich interaction with your desktop app. So, what other alternatives to the IE browser control are there? I looked at a Mosaic equivalent a year ago but was disappointed with the number of unimplemented features, maybe this has improved recently? A: hmm..Interestingly Mozilla seems to provide ActiveX control K-Melon is another Gecko based browser control A: Popular layout engines: Mozilla Gecko KHTML WebKit (based on KHTML) Though I'm not sure how easy it is to embed those in a .Net app.
Web in a desktop application: Good web browser controls?
I've been utlising a "web browser control" in desktop based applications (in my case Windows Forms .NET) for a number of years. I mostly use it to create a familiar flow-based user interface that also allows a seamless transition to the internet where required. I'm really tired of the IE browser control because of the poor quality html it generates on output. Also, I guess that it is really just IE7 behind the scenes and so has many of that browser "issues". Despite this, it is quite a powerful control and provides rich interaction with your desktop app. So, what other alternatives to the IE browser control are there? I looked at a Mosaic equivalent a year ago but was disappointed with the number of unimplemented features, maybe this has improved recently?
[ "hmm..Interestingly \n\nMozilla seems to provide ActiveX control\nK-Melon is another Gecko based browser control\n\n", "Popular layout engines:\n\nMozilla Gecko\nKHTML\nWebKit (based on KHTML)\n\nThough I'm not sure how easy it is to embed those in a .Net app.\n" ]
[ 1, 0 ]
[]
[]
[ "browser", "controls", "desktop_application" ]
stackoverflow_0000061180_browser_controls_desktop_application.txt
Q: Applying Aspect Oriented Programming I've been using some basic AOP style solutions for cross-cutting concerns like security, logging, validation, etc. My solution has revolved around Castle Windsor and DynamicProxy because I can apply everything using a Boo based DSL and keep my code clean of Attributes. I was told at the weekend to have a look at PostSharp as it's supposed to be a "better" solution. I've had a quick look at PostSharp, but I've been put off by the Attribute usage. Has anyone tried both solutions and would care to share their experiences? A: Couple of minor issues with PostSharp... One issue I've had with PostSharp is that whilst using asp.net, line numbers for exception messages are 'out' by the number of IL instructions injected into asssemblies by PostSharp as the PDBs aren't injected as well :-). Also, without the PostSharp assemblies available at runtime, runtime errors occur. Using Windsor, the cross-cuts can be turned off at a later date without a recompile of code. (hope this makes sense) A: I only looked at castle-windsor for a short time (yet) so I can't comment on that but I did use postsharp. Postsharp works by weaving at compile time. It ads a post-compile step to your build where it modifies your code. The code is compiled as if you just programmed the cross cutting concerns into you code. This is a bit more performant than runtime weaving and because of the use of attributes Postsharp is very easy to use. I think using attributes for AOP isn't as problematic as using it for DI. But that's just my personal taste. But... If you already use castle for dependency injection I don't see a good reason why you shouldn't also use it for AOP stuff. I think though the AOP at runtime is a bit slower than at compile time it's also more powerful. AOP and DI are in my opinion related concepts so I think it's a good idea to use one framework for both. So I'll probably look at the castle stuff again next project I need AOP.
Applying Aspect Oriented Programming
I've been using some basic AOP style solutions for cross-cutting concerns like security, logging, validation, etc. My solution has revolved around Castle Windsor and DynamicProxy because I can apply everything using a Boo based DSL and keep my code clean of Attributes. I was told at the weekend to have a look at PostSharp as it's supposed to be a "better" solution. I've had a quick look at PostSharp, but I've been put off by the Attribute usage. Has anyone tried both solutions and would care to share their experiences?
[ "Couple of minor issues with PostSharp...\nOne issue I've had with PostSharp is that whilst using asp.net, line numbers for exception messages are 'out' by the number of IL instructions injected into asssemblies by PostSharp as the PDBs aren't injected as well :-).\nAlso, without the PostSharp assemblies available at runtime, runtime errors occur. Using Windsor, the cross-cuts can be turned off at a later date without a recompile of code.\n(hope this makes sense)\n", "I only looked at castle-windsor for a short time (yet) so I can't comment on that but I did use postsharp.\nPostsharp works by weaving at compile time. It ads a post-compile step to your build where it modifies your code. The code is compiled as if you just programmed the cross cutting concerns into you code. This is a bit more performant than runtime weaving and because of the use of attributes Postsharp is very easy to use. I think using attributes for AOP isn't as problematic as using it for DI. But that's just my personal taste.\nBut...\nIf you already use castle for dependency injection I don't see a good reason why you shouldn't also use it for AOP stuff. I think though the AOP at runtime is a bit slower than at compile time it's also more powerful. AOP and DI are in my opinion related concepts so I think it's a good idea to use one framework for both. So I'll probably look at the castle stuff again next project I need AOP.\n" ]
[ 14, 10 ]
[]
[]
[ "aop", "c#", "castle_dynamicproxy", "castle_windsor" ]
stackoverflow_0000062798_aop_c#_castle_dynamicproxy_castle_windsor.txt
Q: How does the ActiveRecord pattern differ from the Domain Object or Data Mapper pattern? I was looking at DataMapper, which appeared at first glance to use the ActiveRecord ORM pattern. Other people said that it uses the DataMapper and/or the Domain Object pattern. What is the difference between those patterns? A: The main difference between the two patterns is this: In the ActiveRecord you have one domain object that both knows all the business logic and how to save/update itself in the database, user.getLinkToProfile() and User::find(1), User::save(user) In the DataMapper pattern you have one domain object that holds all the business logic, for exmaple user.getLinkToProfile() (or something similar) but knows nothing about the database in question, in addition to this you have a mapper-object that is responsible for saving, updating, selecting, etc. user objects from the database which would have UserMapper::find(1), UserMapper.save(user) DataMapper is potentially more complex then ActiveRecord but it's a lot easier to develop your domain model and database asynchronous then with ActiveRecord. A: Active record is very heavy, data mapper and domain object are separating those concerns out so you have a more defined set of code doing various aspects for you "domain" or "entity" objects. I personally prefer, not that you asked, going with the separation into domain object, data mapper, probably use an assembly pattern and even a data transfer pattern to assure clear separation of what happens to data between the database an the upper tiers of an application. ...elegant and simple separations always help.
How does the ActiveRecord pattern differ from the Domain Object or Data Mapper pattern?
I was looking at DataMapper, which appeared at first glance to use the ActiveRecord ORM pattern. Other people said that it uses the DataMapper and/or the Domain Object pattern. What is the difference between those patterns?
[ "The main difference between the two patterns is this:\n\nIn the ActiveRecord you have one domain object that both knows all the business logic and how to save/update itself in the database, user.getLinkToProfile() and User::find(1), User::save(user)\nIn the DataMapper pattern you have one domain object that holds all the business logic, for exmaple user.getLinkToProfile() (or something similar) but knows nothing about the database in question, in addition to this you have a mapper-object that is responsible for saving, updating, selecting, etc. user objects from the database which would have UserMapper::find(1), UserMapper.save(user)\n\nDataMapper is potentially more complex then ActiveRecord but it's a lot easier to develop your domain model and database asynchronous then with ActiveRecord.\n", "Active record is very heavy, data mapper and domain object are separating those concerns out so you have a more defined set of code doing various aspects for you \"domain\" or \"entity\" objects.\nI personally prefer, not that you asked, going with the separation into domain object, data mapper, probably use an assembly pattern and even a data transfer pattern to assure clear separation of what happens to data between the database an the upper tiers of an application.\n...elegant and simple separations always help.\n" ]
[ 22, 3 ]
[]
[]
[ "activerecord", "datamapper", "ruby_on_rails" ]
stackoverflow_0000093773_activerecord_datamapper_ruby_on_rails.txt
Q: How do I sort an ASP.NET DataGrid by the length of a field? I have a DataGrid where each column has a SortExpression. I would like the sort expression to be the equivalent of "ORDER BY LEN(myField)". I have tried SortExpression="LEN(myField)" but this throws an exception as it is not valid syntax. Any ideas? A: What about returning the len by the query already, but don't show that column, only use it as your original column's sortexpression? I don't think that your idea is supported by default. A: Depending on your SQL flavor the following could work: SELECT ColumnA as FieldA , ColumnB as FieldB , LEN(ColumnA) as FieldL FROM TableName ORDER BY L And then do SortExpression="FieldL" A: The SortExpression parameter specifies the name of the column to sort, followed by "ASC" or "DESC" to control the order. You could change the DataType property of the column to specifiy a user defined type whose comparer function compares string lengths. It won't be a trivial task. A: Using Linq, you could write your query like: query.OrderBy(column => column.MyField.Length); A: Hmmm. Had some time to test. I was able to get SortExpression="Description.Length" to work. Is this 1.1, 2.0 or 3.5?
How do I sort an ASP.NET DataGrid by the length of a field?
I have a DataGrid where each column has a SortExpression. I would like the sort expression to be the equivalent of "ORDER BY LEN(myField)". I have tried SortExpression="LEN(myField)" but this throws an exception as it is not valid syntax. Any ideas?
[ "What about returning the len by the query already, but don't show that column, only use it as your original column's sortexpression?\nI don't think that your idea is supported by default.\n", "Depending on your SQL flavor the following could work:\nSELECT\n ColumnA as FieldA\n , ColumnB as FieldB\n , LEN(ColumnA) as FieldL\nFROM TableName\nORDER BY L\n\nAnd then do\nSortExpression=\"FieldL\"\n\n", "The SortExpression parameter specifies the name of the column to sort, followed by \"ASC\" or \"DESC\" to control the order.\nYou could change the DataType property of the column to specifiy a user defined type whose comparer function compares string lengths. It won't be a trivial task.\n", "Using Linq, you could write your query like:\nquery.OrderBy(column => column.MyField.Length);\n\n", "Hmmm. Had some time to test. I was able to get SortExpression=\"Description.Length\" to work. Is this 1.1, 2.0 or 3.5?\n" ]
[ 3, 3, 0, 0, 0 ]
[]
[]
[ "asp.net", "datagrid" ]
stackoverflow_0000091766_asp.net_datagrid.txt
Q: How can I initialize Zend_Form_Element_Select with a config array? I tried: $form->addElement( 'select', 'salutation', array( 'required' => true, 'options' => array( 'Mr.' => 'Mr.', 'Mrs.' => 'Mrs.', 'Ms.' => 'Ms.', ), ) ); Then I print_r()ed the form, and options for salutation are empty. Does anybody know the correct spell for that? As far as I see, there's no documentation for Zend element configs' format. A: You should use 'multiOptions' instead of 'options'.
How can I initialize Zend_Form_Element_Select with a config array?
I tried: $form->addElement( 'select', 'salutation', array( 'required' => true, 'options' => array( 'Mr.' => 'Mr.', 'Mrs.' => 'Mrs.', 'Ms.' => 'Ms.', ), ) ); Then I print_r()ed the form, and options for salutation are empty. Does anybody know the correct spell for that? As far as I see, there's no documentation for Zend element configs' format.
[ "You should use 'multiOptions' instead of 'options'.\n" ]
[ 9 ]
[]
[]
[ "html", "php", "zend_framework" ]
stackoverflow_0000093329_html_php_zend_framework.txt
Q: Are POD types always aligned? For example, if I declare a long variable, can I assume it will always be aligned on a "sizeof(long)" boundary? Microsoft Visual C++ online help says so, but is it standard behavior? some more info: a. It is possible to explicitely create a misaligned integer (*bar): char foo[5] int * bar = (int *)(&foo[1]); b. Apparently, #pragma pack() only affects structures, classes, and unions. c. MSVC documentation states that POD types are aligned to their respective sizes (but is it always or by default, and is it standard behavior, I don't know) A: As others have mentioned, this isn't part of the standard and is left up to the compiler to implement as it sees fit for the processor in question. For example, VC could easily implement different alignment requirements for an ARM processor than it does for x86 processors. Microsoft VC implements what is basically called natural alignment up to the size specified by the #pragma pack directive or the /Zp command line option. This means that, for example, any POD type with a size smaller or equal to 8 bytes will be aligned based on its size. Anything larger will be aligned on an 8 byte boundary. If it is important that you control alignment for different processors and different compilers, then you can use a packing size of 1 and pad your structures. #pragma pack(push) #pragma pack(1) struct Example { short data1; // offset 0 short padding1; // offset 2 long data2; // offset 4 }; #pragma pack(pop) In this code, the padding1 variable exists only to make sure that data2 is naturally aligned. Answer to a: Yes, that can easily cause misaligned data. On an x86 processor, this doesn't really hurt much at all. On other processors, this can result in a crash or a very slow execution. For example, the Alpha processor would throw a processor exception which would be caught by the OS. The OS would then inspect the instruction and then do the work needed to handle the misaligned data. Then execution continues. The __unaligned keyword can be used in VC to mark unaligned access for non-x86 programs (i.e. for CE). A: By default, yes. However, it can be changed via the pack() #pragma. I don't believe the C++ Standard make any requirement in this regard, and leaves it up to the implementation. A: C and C++ don't mandate any kind of alignment. But natural alignment is strongly preferred by x86 and is required by most other CPU architectures, and compilers generally do their utmost to keep CPUs happy. So in practice you won't see a compiler generate misaligned data unless you really twist it's arm. A: Yes, all types are always aligned to at least their alignment requirements. How could it be otherwise? But note that the sizeof() a type is not the same as it's alignment. You can use the following macro to determine the alignment requirements of a type: #define ALIGNMENT_OF( t ) offsetof( struct { char x; t test; }, test ) A: Depends on the compiler, the pragmas and the optimisation level. With modern compilers you can also choose time or space optimisation, which could change the alignment of types as well. A: Generally it will be because reading/writing to it is faster that way. But almost every compiler has a switch to turn this off. In gcc its -malign-???. With aggregates they are generally aligned and sized based on the alignment requirements of each element within.
Are POD types always aligned?
For example, if I declare a long variable, can I assume it will always be aligned on a "sizeof(long)" boundary? Microsoft Visual C++ online help says so, but is it standard behavior? some more info: a. It is possible to explicitely create a misaligned integer (*bar): char foo[5] int * bar = (int *)(&foo[1]); b. Apparently, #pragma pack() only affects structures, classes, and unions. c. MSVC documentation states that POD types are aligned to their respective sizes (but is it always or by default, and is it standard behavior, I don't know)
[ "As others have mentioned, this isn't part of the standard and is left up to the compiler to implement as it sees fit for the processor in question. For example, VC could easily implement different alignment requirements for an ARM processor than it does for x86 processors.\nMicrosoft VC implements what is basically called natural alignment up to the size specified by the #pragma pack directive or the /Zp command line option. This means that, for example, any POD type with a size smaller or equal to 8 bytes will be aligned based on its size. Anything larger will be aligned on an 8 byte boundary.\nIf it is important that you control alignment for different processors and different compilers, then you can use a packing size of 1 and pad your structures.\n#pragma pack(push)\n#pragma pack(1) \nstruct Example\n{\n short data1; // offset 0\n short padding1; // offset 2\n long data2; // offset 4\n};\n#pragma pack(pop)\n\nIn this code, the padding1 variable exists only to make sure that data2 is naturally aligned.\nAnswer to a:\nYes, that can easily cause misaligned data. On an x86 processor, this doesn't really hurt much at all. On other processors, this can result in a crash or a very slow execution. For example, the Alpha processor would throw a processor exception which would be caught by the OS. The OS would then inspect the instruction and then do the work needed to handle the misaligned data. Then execution continues. The __unaligned keyword can be used in VC to mark unaligned access for non-x86 programs (i.e. for CE).\n", "By default, yes. However, it can be changed via the pack() #pragma.\nI don't believe the C++ Standard make any requirement in this regard, and leaves it up to the implementation.\n", "C and C++ don't mandate any kind of alignment. But natural alignment is strongly preferred by x86 and is required by most other CPU architectures, and compilers generally do their utmost to keep CPUs happy. So in practice you won't see a compiler generate misaligned data unless you really twist it's arm.\n", "Yes, all types are always aligned to at least their alignment requirements.\nHow could it be otherwise?\nBut note that the sizeof() a type is not the same as it's alignment.\nYou can use the following macro to determine the alignment requirements of a type:\n#define ALIGNMENT_OF( t ) offsetof( struct { char x; t test; }, test )\n\n", "Depends on the compiler, the pragmas and the optimisation level. With modern compilers you can also choose time or space optimisation, which could change the alignment of types as well.\n", "Generally it will be because reading/writing to it is faster that way. But almost every compiler has a switch to turn this off. In gcc its -malign-???. With aggregates they are generally aligned and sized based on the alignment requirements of each element within.\n" ]
[ 10, 3, 1, 0, 0, 0 ]
[]
[]
[ "c", "c++", "visual_c++" ]
stackoverflow_0000093569_c_c++_visual_c++.txt
Q: WinForm - draw resizing frame using a single-pixel border In a Windows Form with a Resizing Frame, the frame border draws with a raised 3-D look. I'd like it to draw with a flat single pixel border in a color of my choosing. Is this possible without having to owner draw the whole form? A: You could try something like this: Point lastPoint = Point.Empty; Panel leftResizer = new Panel(); leftResizer.Cursor = System.Windows.Forms.Cursors.SizeWE; leftResizer.Dock = System.Windows.Forms.DockStyle.Left; leftResizer.Size = new System.Drawing.Size(1, 100); leftResizer.MouseDown += delegate(object sender, MouseEventArgs e) { lastPoint = leftResizer.PointToScreen(e.Location); leftResizer.Capture = true; } leftResizer.MouseMove += delegate(object sender, MouseEventArgs e) { if (lastPoint != Point.Empty) { Point newPoint = leftResizer.PointToScreen(e.Location); Location = new Point(Location.X + (newPoint.X - lastPoint.X), Location.Y); Width = Math.Max(MinimumSize.Width, Width - (newPoint.X - lastPoint.X)); lastPoint = newPoint; } } leftResizer.MouseUp += delegate (object sender, MouseEventArgs e) { lastPoint = Point.Empty; leftResizer.Capture = false; } form.BorderStyle = BorderStyle.None; form.Add(leftResizer);
WinForm - draw resizing frame using a single-pixel border
In a Windows Form with a Resizing Frame, the frame border draws with a raised 3-D look. I'd like it to draw with a flat single pixel border in a color of my choosing. Is this possible without having to owner draw the whole form?
[ "You could try something like this:\nPoint lastPoint = Point.Empty;\nPanel leftResizer = new Panel();\nleftResizer.Cursor = System.Windows.Forms.Cursors.SizeWE;\nleftResizer.Dock = System.Windows.Forms.DockStyle.Left;\nleftResizer.Size = new System.Drawing.Size(1, 100);\nleftResizer.MouseDown += delegate(object sender, MouseEventArgs e) { \n lastPoint = leftResizer.PointToScreen(e.Location); \n leftResizer.Capture = true;\n}\nleftResizer.MouseMove += delegate(object sender, MouseEventArgs e) {\n if (lastPoint != Point.Empty) {\n Point newPoint = leftResizer.PointToScreen(e.Location);\n Location = new Point(Location.X + (newPoint.X - lastPoint.X), Location.Y);\n Width = Math.Max(MinimumSize.Width, Width - (newPoint.X - lastPoint.X));\n lastPoint = newPoint;\n }\n}\nleftResizer.MouseUp += delegate (object sender, MouseEventArgs e) { \n lastPoint = Point.Empty;\n leftResizer.Capture = false;\n}\n\nform.BorderStyle = BorderStyle.None;\nform.Add(leftResizer);\n\n" ]
[ 2 ]
[]
[]
[ "border", "c#", "resize", "winforms" ]
stackoverflow_0000093811_border_c#_resize_winforms.txt
Q: What is the simplest way to stub a complex interface in Java? My code takes an interface as input but only excercises a couple of the interface's methods (often, just getters). When testing the code, I'd love to define an anonymous inner class that returns the test data. But what do I do about all the other methods that the interface requires? I could use my IDE to auto-generate a stub for the interface but that seems fairly code-heavy. What is the easiest way to stub the two methods I care about and none of the methods I don't? A: If you are using JUnit to test, use Mocks instead of stubs. Read Martin Fowler's seminal article "Mocks Aren't Stubs" I recommend the EasyMock framework, it works like a charm automatically Mocking your interface using reflection. It is a bit more advanced than the code samples in Fowler's article, especially when you use the unitils library to wrap EasyMock, so the syntax will be much simpler than that in the article. Also, if you don't have an interface, but you want to mock a concrete class, EasyMock has a class extension. A: Check out JMock. http://www.jmock.org/ A: Write an "Adapter Class" and overwrite only the methods you care. class MyAdapter extends MyClass { public void A() { } ... } A: I believe the classical way is to make an abstract class with empty methods. At least, that's how Sun did for MouseListener, creating MouseAdapter to ease the use of these events. A: EasyMock or JMock are definitely the winners. I haven't used JMock, but I know with EasyMock you can setup the Mock object according to a testing script and it will return certain values in certain situations or points during your test. It's pretty easy to learn and get running, generally in less than an hour.
What is the simplest way to stub a complex interface in Java?
My code takes an interface as input but only excercises a couple of the interface's methods (often, just getters). When testing the code, I'd love to define an anonymous inner class that returns the test data. But what do I do about all the other methods that the interface requires? I could use my IDE to auto-generate a stub for the interface but that seems fairly code-heavy. What is the easiest way to stub the two methods I care about and none of the methods I don't?
[ "If you are using JUnit to test, use Mocks instead of stubs.\nRead Martin Fowler's seminal article \"Mocks Aren't Stubs\"\nI recommend the EasyMock framework, it works like a charm automatically Mocking your interface using reflection. It is a bit more advanced than the code samples in Fowler's article, especially when you use the unitils library to wrap EasyMock, so the syntax will be much simpler than that in the article. Also, if you don't have an interface, but you want to mock a concrete class, EasyMock has a class extension.\n", "Check out JMock.\nhttp://www.jmock.org/\n", "Write an \"Adapter Class\" and overwrite only the methods you care.\nclass MyAdapter extends MyClass {\n public void A() {\n }\n ...\n}\n\n", "I believe the classical way is to make an abstract class with empty methods.\nAt least, that's how Sun did for MouseListener, creating MouseAdapter to ease the use of these events.\n", "EasyMock or JMock are definitely the winners. I haven't used JMock, but I know with EasyMock you can setup the Mock object according to a testing script and it will return certain values in certain situations or points during your test. It's pretty easy to learn and get running, generally in less than an hour.\n" ]
[ 5, 1, 0, 0, 0 ]
[]
[]
[ "java", "testing" ]
stackoverflow_0000094112_java_testing.txt
Q: Get Accordian Selected Index in ASP.Net C# Im working on an ASP.Net app with c#. I am stuck on a problem with an accoridian. My accordian correctly displays data from a datasource which in this case in some text and then a list of images. On each accordians content there are the images to be displayed and then a button to add another image. This button links to another page that contains the add form. From here I am able to add an image and it forwards me back to the page displaying the accoridan with one new image in the correct section. Now The problem is that I want to re-open the section that was previously open. I have tried a couple different ways but all of them have not worked. Any Ideas? A: If you are redirecting to another page, you are going to have to pass the currently opened section to it via a querystring and then when the new page sends you back, it'll send you back the same value so you know which one to open. Another quick way would be to pop it into a session and then read from that session. But I would recommend the query string route, it has less overhead.
Get Accordian Selected Index in ASP.Net C#
Im working on an ASP.Net app with c#. I am stuck on a problem with an accoridian. My accordian correctly displays data from a datasource which in this case in some text and then a list of images. On each accordians content there are the images to be displayed and then a button to add another image. This button links to another page that contains the add form. From here I am able to add an image and it forwards me back to the page displaying the accoridan with one new image in the correct section. Now The problem is that I want to re-open the section that was previously open. I have tried a couple different ways but all of them have not worked. Any Ideas?
[ "If you are redirecting to another page, you are going to have to pass the currently opened section to it via a querystring and then when the new page sends you back, it'll send you back the same value so you know which one to open.\nAnother quick way would be to pop it into a session and then read from that session. But I would recommend the query string route, it has less overhead.\n" ]
[ 0 ]
[]
[]
[ ".net", "asp.net", "c#", "webforms" ]
stackoverflow_0000093743_.net_asp.net_c#_webforms.txt
Q: OO PHP explanation For a braindead n00b I've been writing PHP for about six years now and have got to a point where I feel I should be doing more to write better code. I know that Object Oriented code is the way to go but I can't get my head around the concept. Can anyone explain in terms that any idiot can understand, OO and how it works in PHP or point me to an idiots guide tutorial? A: Think of a thingy. Any thingy, a thingy you want to do stuff to. Say, a breakfast. (All code is pseudocode, any resemblance to any language living, dead, or being clinically abused in the banking industry is entirely coincidental and nothing to do with your post being tagged PHP) So you define a template for how you'd represent a breakfast. This is a class: class Breakfast { } Breakfasts contain attributes. In normal non-object-oriented stuff, you might use an array for this: $breakfast = array( 'toast_slices' => 2, 'eggs' => 2, 'egg_type' => 'fried', 'beans' => 'Hell yeah', 'bacon_rashers' => 3 ); And you'd have various functions for fiddling with it: function does_user_want_beans($breakfast){ if (isset($breakfast['beans']) && $breakfast['beans'] != 'Hell no'){ return true; } return false; } And you've got a mess, and not just because of the beans. You've got a data structure that programmers can screw with at will, an ever-expanding collection of functions to do with the breakfast entirely divorced from the definition of the data. So instead, you might do this: class Breakfast { var $toast_slices = 2; var $eggs = 2; var $egg_type = 'fried'; var $beans = 'Hell yeah'; var $bacon_rashers = 3; function wants_beans(){ if (isset($this->beans) && $this->beans != 'Hell no'){ return true; } return true; } function moar_magic_pig($amount = 1){ $this->bacon += $amount; } function cook(){ breakfast_cook($this); } } And then manipulating the program's idea of Breakfast becomes a lot cleaner: $users = fetch_list_of_users(); foreach ($users as $user){ // So this creates an instance of the Breakfast template we defined above $breakfast = new Breakfast(); if ($user->likesBacon){ $breakfast->moar_magic_pig(4); } // If you find a PECL module that does this, Email me. $breakfast->cook(); } I think this looks cleaner, and a far neater way of representing blobs of data we want to treat as a consistent object. There are better explanations of what OO actually is, and why it's academically better, but this is my practical reason, and it contains bacon. A: A warning is at place: you won't learn OO programming without learning OO design! The key concept is to define the functions operating on your data together with the appropriate data. Then you can tell your objects what to do, without having to query their contents. Surely take a look at the "Tell, don't Ask" philosophy, and the "Need to know" principle (aka the "Law of Demeter") is a very important one, too. A: Some of the key reasons to use OO are to structure code in a similar way to how we humans like to perceive and relate to things, and exploit the benefits of economy, maintainability, reliability, and scalability. i.e: Humankind designed the wheel thousands of years ago. We may refine it all the time, but we certainly don't need to be re-inventing it again.... 1) We like to categorise things: "this one's bigger than this one", "this one costs more than that one", "this one is almost the same as that one". 2) We like to simplify things: "OK, it's a V8 liquid cooled turbo driven tractor, but I still just turn the steering wheel and press my feet on the peddles to drive it, right?". 3) We like to standardise things: "OK, let's call triangles, circles, and squares all SHAPES, and expect them all to have an AREA and a CIRCUMFERENCE". 4) We like to adapt things: "hmmm, I like that, but can I have it in Racing Green instead?". 5) We like to create blueprints: "I haven't got the time or money (or approval) to build that yet, but it WILL have a door and a roof, and some windows, and walls". 6) We like to protect things: "OK, I'll let you see the total price, but I'm hiding the mark-up I added from you!". 7) We like things to communicate with each other: "I want to access my bank balance through: my mobile; my computer; an ATM; a bank employee; etc..". To learn how to exploit OO (and see some of the advantages) then I suggest you set yourself an exercise as homework - maybe a browser based application that deals with SHAPES such as circles, rectangles, and triangles, and keeps track of their area, colour, position, and z-index etc. Then add squares as a special case of rectangle since it is the same in respect to most of it's definition, area, etc. Just has the added condition where the height is the same as the width. To make it harder then you could make a rectangle a type of quadrangle which is a type of polygon. etc. etc. NOTE: I wouldn't start using a PHP Framework until you are comfortable with the basics of OO programming first. They are much more powerful when you can extend classes of your own and if you can't then it's a bit like learning something by rote -> much harder! A: The best advice was from: xtofl.myopenid.com ^^^^ If you don't understand the purposes of patterns, your really not going to use objects to their fullest. You need to know why inheritence, polymorphism, interfaces, factories, decorators, etc. really make design easier by addressing particular issues. A: Instead of learning OO from scratch, I think it'd be easier if you took on a framework that facilitates object-oriented programming. It will "force" you to use the right OOP methods; you will be able to learn from the way the framework is written as to how to do OOP best. I'd recommend the QCodo PHP5 framework http://www.qcodo.com. It has great video tutorials on how to set it up, as well as video trainings (http://www.qcodo.com/demos/). Full disclosure: I've been developing on top of this framework for two years, and I've contributed code to their codebase (so I'm not completely impartial :-)). A: Another pointer for learning OO: Most OO tutorials will focus on inheritance (e.g. class X extends class Y). I think this is a bad idea. Inheritance is useful, but it can also cause problems. More importantly, inheritance isn't the point of OO. The point is abstraction; hiding the implementation details so you can work with a simple interface. Learn how to write good abstractions of your data, and you'll be in good shape. Don't sweat the inheritance stuff right away. A: I have been in your shoes, but I saw the light after I read this book (a few times!) http://www.apress.com/book/view/9781590599099 After I read this, I really "got" it and I haven't looked back. You'll get it on Amazon. I hope you persist, get it, and love it. When it comes together, it will make you smile. Composition beats inheritence.
OO PHP explanation For a braindead n00b
I've been writing PHP for about six years now and have got to a point where I feel I should be doing more to write better code. I know that Object Oriented code is the way to go but I can't get my head around the concept. Can anyone explain in terms that any idiot can understand, OO and how it works in PHP or point me to an idiots guide tutorial?
[ "Think of a thingy. Any thingy, a thingy you want to do stuff to. Say, a breakfast.\n(All code is pseudocode, any resemblance to any language living, dead, or being clinically abused in the banking industry is entirely coincidental and nothing to do with your post being tagged PHP)\nSo you define a template for how you'd represent a breakfast. This is a class:\nclass Breakfast {\n\n}\n\nBreakfasts contain attributes. In normal non-object-oriented stuff, you might use an array for this:\n$breakfast = array(\n'toast_slices' => 2,\n'eggs' => 2,\n'egg_type' => 'fried',\n'beans' => 'Hell yeah',\n'bacon_rashers' => 3 \n);\n\nAnd you'd have various functions for fiddling with it:\nfunction does_user_want_beans($breakfast){\n if (isset($breakfast['beans']) && $breakfast['beans'] != 'Hell no'){\n return true;\n }\n return false;\n}\n\nAnd you've got a mess, and not just because of the beans. You've got a data structure that programmers can screw with at will, an ever-expanding collection of functions to do with the breakfast entirely divorced from the definition of the data. So instead, you might do this:\nclass Breakfast {\n var $toast_slices = 2;\n var $eggs = 2;\n var $egg_type = 'fried';\n var $beans = 'Hell yeah';\n var $bacon_rashers = 3;\n\n function wants_beans(){\n\n if (isset($this->beans) && $this->beans != 'Hell no'){\n return true;\n }\n\n return true;\n\n }\n\n function moar_magic_pig($amount = 1){\n\n $this->bacon += $amount;\n\n }\n\n function cook(){\n breakfast_cook($this);\n }\n\n}\n\nAnd then manipulating the program's idea of Breakfast becomes a lot cleaner:\n$users = fetch_list_of_users();\n\nforeach ($users as $user){\n // So this creates an instance of the Breakfast template we defined above\n\n $breakfast = new Breakfast(); \n\n if ($user->likesBacon){\n $breakfast->moar_magic_pig(4);\n }\n\n // If you find a PECL module that does this, Email me.\n $breakfast->cook();\n}\n\nI think this looks cleaner, and a far neater way of representing blobs of data we want to treat as a consistent object.\nThere are better explanations of what OO actually is, and why it's academically better, but this is my practical reason, and it contains bacon.\n", "A warning is at place: you won't learn OO programming without learning OO design! The key concept is to define the functions operating on your data together with the appropriate data. Then you can tell your objects what to do, without having to query their contents. \nSurely take a look at the \"Tell, don't Ask\" philosophy, and the \"Need to know\" principle (aka the \"Law of Demeter\") is a very important one, too.\n", "Some of the key reasons to use OO are to structure code in a similar way to how we humans like to perceive and relate to things, and exploit the benefits of economy, maintainability, reliability, and scalability.\ni.e: Humankind designed the wheel thousands of years ago. We may refine it all the time, but we certainly don't need to be re-inventing it again....\n1) We like to categorise things: \"this one's bigger than this one\", \"this one costs more than that one\", \"this one is almost the same as that one\".\n2) We like to simplify things: \"OK, it's a V8 liquid cooled turbo driven tractor, but I still just turn the steering wheel and press my feet on the peddles to drive it, right?\".\n3) We like to standardise things: \"OK, let's call triangles, circles, and squares all SHAPES, and expect them all to have an AREA and a CIRCUMFERENCE\".\n4) We like to adapt things: \"hmmm, I like that, but can I have it in Racing Green instead?\".\n5) We like to create blueprints: \"I haven't got the time or money (or approval) to build that yet, but it WILL have a door and a roof, and some windows, and walls\".\n6) We like to protect things: \"OK, I'll let you see the total price, but I'm hiding the mark-up I added from you!\".\n7) We like things to communicate with each other: \"I want to access my bank balance through: my mobile; my computer; an ATM; a bank employee; etc..\".\nTo learn how to exploit OO (and see some of the advantages) then I suggest you set yourself an exercise as homework - maybe a browser based application that deals with SHAPES such as circles, rectangles, and triangles, and keeps track of their area, colour, position, and z-index etc. Then add squares as a special case of rectangle since it is the same in respect to most of it's definition, area, etc. Just has the added condition where the height is the same as the width. To make it harder then you could make a rectangle a type of quadrangle which is a type of polygon. etc. etc.\nNOTE: I wouldn't start using a PHP Framework until you are comfortable with the basics of OO programming first. They are much more powerful when you can extend classes of your own and if you can't then it's a bit like learning something by rote -> much harder!\n", "The best advice was from: xtofl.myopenid.com ^^^^\nIf you don't understand the purposes of patterns, your really not going to use objects to their fullest. You need to know why inheritence, polymorphism, interfaces, factories, decorators, etc. really make design easier by addressing particular issues.\n", "Instead of learning OO from scratch, I think it'd be easier if you took on a framework that facilitates object-oriented programming. It will \"force\" you to use the right OOP methods; you will be able to learn from the way the framework is written as to how to do OOP best. \nI'd recommend the QCodo PHP5 framework http://www.qcodo.com. It has great video tutorials on how to set it up, as well as video trainings (http://www.qcodo.com/demos/). \nFull disclosure: I've been developing on top of this framework for two years, and I've contributed code to their codebase (so I'm not completely impartial :-)). \n", "Another pointer for learning OO:\nMost OO tutorials will focus on inheritance (e.g. class X extends class Y). I think this is a bad idea. Inheritance is useful, but it can also cause problems. More importantly, inheritance isn't the point of OO. The point is abstraction; hiding the implementation details so you can work with a simple interface. Learn how to write good abstractions of your data, and you'll be in good shape. Don't sweat the inheritance stuff right away.\n", "I have been in your shoes, but I saw the light after I read this book (a few times!) http://www.apress.com/book/view/9781590599099 After I read this, I really \"got\" it and I haven't looked back. You'll get it on Amazon.\nI hope you persist, get it, and love it. When it comes together, it will make you smile.\nComposition beats inheritence.\n" ]
[ 34, 7, 6, 0, 0, 0, 0 ]
[]
[]
[ "oop", "php" ]
stackoverflow_0000084125_oop_php.txt
Q: Tutorial on understanding strings in Symbian I have Carbide.c++ Developer from Nokia and I want to create applications for my S60 phone. I've looked at the samples that goes with the different SDK's for S60 but I haven't found any simple explanation on how strings, called descriptors, are used in Symbian. One of the problems are that I'm visually impaired and therefore it takes quite some time to read through large documents that has page up and page down with lots of unuseful info and I've given up. I'm willing to give it another try. Can anyone help me? A: Here are a few sites on blogspot that may help. They have RSS feeds that will hopefully be easier to consume than paging through PDFs. http://descriptor-tips.blogspot.com/ http://descriptors.blogspot.com/ A: Yeah, The strings in Symbian is nightmarish.. atleast when you start with.. Here are few good references to help: Introducing the RBuf Descriptor from Symbian Developer Comparing C strings and descriptors from Forum Nokia discussion Using Symbian OS String Descriptors from NewLC A: I'd second http://descriptors.blogspot.com/ This is invaluable for getting to grips with Descriptors. Also, sites such as newlc.com have forums for Symbian C++ specific code problems.
Tutorial on understanding strings in Symbian
I have Carbide.c++ Developer from Nokia and I want to create applications for my S60 phone. I've looked at the samples that goes with the different SDK's for S60 but I haven't found any simple explanation on how strings, called descriptors, are used in Symbian. One of the problems are that I'm visually impaired and therefore it takes quite some time to read through large documents that has page up and page down with lots of unuseful info and I've given up. I'm willing to give it another try. Can anyone help me?
[ "Here are a few sites on blogspot that may help. They have RSS feeds that will hopefully be easier to consume than paging through PDFs.\n\nhttp://descriptor-tips.blogspot.com/\nhttp://descriptors.blogspot.com/\n\n", "Yeah, The strings in Symbian is nightmarish.. atleast when you start with..\nHere are few good references to help:\n\nIntroducing the RBuf Descriptor from Symbian Developer\nComparing C strings and descriptors from Forum Nokia discussion\nUsing Symbian OS String Descriptors from NewLC\n\n", "I'd second http://descriptors.blogspot.com/ This is invaluable for getting to grips with Descriptors.\nAlso, sites such as newlc.com have forums for Symbian C++ specific code problems.\n" ]
[ 7, 4, 1 ]
[ "The best advice regarding descriptors I give to any new Symbian developer in my company is to try and avoid using the descriptors when not necessary. The Symbian SDK has the libc API which includes stdio, stdlib, string and more. I usually use char* types and when necessary I convert it to a descriptor (when I need to send a string to an SDK method which requires it).\n" ]
[ -5 ]
[ "c++", "carbide", "symbian" ]
stackoverflow_0000038299_c++_carbide_symbian.txt
Q: Help with algorithm for merging vectors I need a very fast algorithm for the following task. I have already implemented several algorithms that complete it, but they're all too slow for the performance I need. It should be fast enough that the algorithm can be run at least 100,000 times a second on a modern CPU. It will be implemented in C++. I am working with spans/ranges, a structure that has a start and an end coordinate on a line. I have two vectors (dynamic arrays) of spans and I need to merge them. One vector is src and the other dst. The vectors are sorted by span start coordinates, and the spans do not overlap within one vector. The spans in the src vector must be merged with the spans in the dst vector, such that the resulting vector is still sorted and has no overlaps. Ie. if overlaps are detected during the merging, the two spans are merged into one. (Merging two spans is just a matter of changing the coordinates in the structure.) Now, there is one more catch, the spans in the src vector must be "widened" during the merge. This means that a constant will be added to the start and another (larger) constant to the end coordinate of every span in src. This means that after the src spans are widened they might overlap. What I have arrived at so far is that it cannot be done fully in-place, some kind of temporary storage is needed. I think it should be doable in linear time over the number of elements of src and dst summed. Any temporary storage can probably be shared between multiple runs of the algorithm. The two primary approaches I have tried, which are too slow, are: Append all elements of src to dst, widening each element before appending it. Then run an in-place sort. Finally iterate over the resulting vector using a "read" and "write" pointer, with the read pointer running ahead of the write pointer, merging spans as they go. When all elements have been merged (the read pointer reaches end) dst is truncated. Create a temporary work-vector. Do a naive merge as described above by repeatedly picking the next element from either src or dst and merging into the work-vector. When done, copy the work-vector to dst, replacing it. The first method has the problem that sorting is O((m+n)*log(m+n)) instead of O(m+n) and has somewhat overhead. It also means the dst vector has to grow much larger than it really needs. The second has the primary problem of a lot of copying around and again allocation/deallocation of memory. The data structures used for storing/managing the spans/vectors can be altered if you think that's needed. Update: Forgot to say how large the datasets are. The most common cases are between 4 and 30 elements in either vector, and either dst is empty or there is a large amount of overlap between the spans in src and dst. A: We know that the absolute best case runtime is O(m+n) this is due to the fact that you at least have to scan over all of the data in order to be able to merge the lists. Given this, your second method should give you that type of behavior. Have you profiled your second method to find out what the bottlenecks are? It is quite possible that, depending on the amount of data you are talking about it is actually impossible to do what you want in the specified amount of time. One way to verify this is to do something simple like sum up all the start and end values of the spans in each vector in a loop, and time that. Basically here you are doing a minimal amount of work for each element in the vectors. This will provide you with a baseline for the best performance you can expect to get. Beyond that you can avoid copying the vectors element by element by using the stl swap method, and you can preallocate the temp vector to a certain size in order to avoid triggering the expansion of the array when you are merging the elements. You might consider using 2 vectors in your system and whenever you need to do a merge you merge into the unused vector, and then swap (this is similar to double buffering used in graphics). This way you don't have to reallocate the vectors every time you do the merge. However, you are best off profiling first and finding out what your bottleneck is. If the allocations are minimal compared to the actual merging process than you need to figure out how to make that faster. Some possible additional speedups could come from accessing the vectors raw data directly which avoids the bounds checks on each access the data. A: How about the second method without repeated allocation--in other words, allocate your temporary vector once, and never allocate it again? Or, if the input vectors are small enough (But not constant size), just use alloca instead of malloc. Also, in terms of speed, you may want to make sure that your code is using CMOV for the sorting, since if the code is actually branching for every single iteration of the mergesort: if(src1[x] < src2[x]) dst[x] = src1[x]; else dst[x] = src2[x]; The branch prediction will fail 50% of the time, which will have an enormous hit on performance. A conditional move will likely do much much better, so make sure the compiler is doing that, and if not, try to coax it into doing so. A: The sort you mention in Approach 1 can be reduced to linear time (from log-linear as you describe it) because the two input lists are already sorted. Just perform the merge step of merge-sort. With an appropriate representation for the input span vectors (for example singly-linked lists) this can be done in-place. http://en.wikipedia.org/wiki/Merge_sort A: i don't think a strictly linear solution is possible, because widening the src vector spans may in the worst-case cause all of them to overlap (depending on the magnitude of the constant that you are adding) the problem may be in the implementation, not in the algorithm; i would suggest profiling the code for your prior solutions to see where the time is spent reasoning: for a truly "modern" CPU like the Intel Core 2 Extreme QX9770 running at 3.2GHz, one can expect about 59,455 MIPS for 100,000 vectors, you would have to process each vector in 594,550 instuctions. That's a LOT of instructions. ref: wikipedia MIPS in addition, note that adding a constant to the src vector spans does not de-sort them, so you can normalize the src vector spans independently, then merge them with the dst vector spans; this should reduce the workload of your original algorithm A: 1 is right out - a full sort is slower than merging two sorted lists. So you're looking at tweaking 2 (or something entirely new). If you change the data structures to doubly linked lists, then you can merge them in constant working space. Use a fixed-size heap allocator for the list nodes, both to reduce memory use per node and to improve the chance that the nodes are close together in memory, reducing page misses. You might be able to find code online or in your favourite algorithm book to optimise a linked list merge. You'll want to customise this in order to do span coalescing at the same time as the list merge. To optimise the merge, first note that for each run of values coming off the same side without one coming from the other side, you can insert the whole run into the dst list in one go, instead of inserting each node in turn. And you can save one write per insertion over a normal list operation, by leaving the end "dangling", knowing that you'll patch it up later. And provided that you don't do deletions anywhere else in your app, the list can be singly-linked, which means one write per node. As for 10 microsecond runtime - kind of depends on n and m... A: If your most recent implementation still isn't fast enough, you might end up having to look at alternative approaches. What are you using the outputs of this function for? A: I wrote a new container class just for this algorithm, tailored to the needs. This also gave me a chance to adjust other code around my program which got a little speed boost at the same time. This is significantly faster than the old implementation using STL vectors, but which was otherwise basically the same thing. But while it's faster it's still not really fast enough... unfortunately. Profiling doesn't reveal what is the real bottleneck any longer. The MSVC profiler seems to sometimes place the "blame" on the wrong calls (supposedly identical runs assign widely different running times) and most calls are getting coalesced into one big chink. Looking at a disassembly of the generated code shows that there's a very large amount of jumps in the generated code, I think that might be the main reason behind the slowness now. class SpanBuffer { private: int *data; size_t allocated_size; size_t count; inline void EnsureSpace() { if (count == allocated_size) Reserve(count*2); } public: struct Span { int start, end; }; public: SpanBuffer() : data(0) , allocated_size(24) , count(0) { data = new int[allocated_size]; } SpanBuffer(const SpanBuffer &src) : data(0) , allocated_size(src.allocated_size) , count(src.count) { data = new int[allocated_size]; memcpy(data, src.data, sizeof(int)*count); } ~SpanBuffer() { delete [] data; } inline void AddIntersection(int x) { EnsureSpace(); data[count++] = x; } inline void AddSpan(int s, int e) { assert((count & 1) == 0); assert(s >= 0); assert(e >= 0); EnsureSpace(); data[count] = s; data[count+1] = e; count += 2; } inline void Clear() { count = 0; } inline size_t GetCount() const { return count; } inline int GetIntersection(size_t i) const { return data[i]; } inline const Span * GetSpanIteratorBegin() const { assert((count & 1) == 0); return reinterpret_cast<const Span *>(data); } inline Span * GetSpanIteratorBegin() { assert((count & 1) == 0); return reinterpret_cast<Span *>(data); } inline const Span * GetSpanIteratorEnd() const { assert((count & 1) == 0); return reinterpret_cast<const Span *>(data+count); } inline Span * GetSpanIteratorEnd() { assert((count & 1) == 0); return reinterpret_cast<Span *>(data+count); } inline void MergeOrAddSpan(int s, int e) { assert((count & 1) == 0); assert(s >= 0); assert(e >= 0); if (count == 0) { AddSpan(s, e); return; } int *lastspan = data + count-2; if (s > lastspan[1]) { AddSpan(s, e); } else { if (s < lastspan[0]) lastspan[0] = s; if (e > lastspan[1]) lastspan[1] = e; } } inline void Reserve(size_t minsize) { if (minsize <= allocated_size) return; int *newdata = new int[minsize]; memcpy(newdata, data, sizeof(int)*count); delete [] data; data = newdata; allocated_size = minsize; } inline void SortIntersections() { assert((count & 1) == 0); std::sort(data, data+count, std::less<int>()); assert((count & 1) == 0); } inline void Swap(SpanBuffer &other) { std::swap(data, other.data); std::swap(allocated_size, other.allocated_size); std::swap(count, other.count); } }; struct ShapeWidener { // How much to widen in the X direction int widen_by; // Half of width difference of src and dst (width of the border being produced) int xofs; // Temporary storage for OverlayScanline, so it doesn't need to reallocate for each call SpanBuffer buffer; inline void OverlayScanline(const SpanBuffer &src, SpanBuffer &dst); ShapeWidener(int _xofs) : xofs(_xofs) { } }; inline void ShapeWidener::OverlayScanline(const SpanBuffer &src, SpanBuffer &dst) { if (src.GetCount() == 0) return; if (src.GetCount() + dst.GetCount() == 0) return; assert((src.GetCount() & 1) == 0); assert((dst.GetCount() & 1) == 0); assert(buffer.GetCount() == 0); dst.Swap(buffer); const int widen_s = xofs - widen_by; const int widen_e = xofs + widen_by; size_t resta = src.GetCount()/2; size_t restb = buffer.GetCount()/2; const SpanBuffer::Span *spa = src.GetSpanIteratorBegin(); const SpanBuffer::Span *spb = buffer.GetSpanIteratorBegin(); while (resta > 0 || restb > 0) { if (restb == 0) { dst.MergeOrAddSpan(spa->start+widen_s, spa->end+widen_e); --resta, ++spa; } else if (resta == 0) { dst.MergeOrAddSpan(spb->start, spb->end); --restb, ++spb; } else if (spa->start < spb->start) { dst.MergeOrAddSpan(spa->start+widen_s, spa->end+widen_e); --resta, ++spa; } else { dst.MergeOrAddSpan(spb->start, spb->end); --restb, ++spb; } } buffer.Clear(); } A: I would always keep my vector of spans sorted. That makes implementing algorithms a LOT easier -- and possible to do in linear time. OK, so I'd sort the spans based on: span minimum in increasing order then span maximum in decreasing order You need to create a function to do that. Then I'd use std::set_union to merge the vectors (you can merge more than one before continuing). Then for each consecutive sets of spans with identical minimums, you keep the first and remove the rest (they're sub-spans of the first span). Then you need to merge your spans. That should be pretty doable now and feasible in linear time. OK, here's the trick now. Don't try to do this in-place. Use one or more temporary vectors (and reserve enough space ahead of time). Then at the end, call std::vector::swap to put the results in the input vector of your choice. I hope that's enough to get you going. A: What is your target system? Is it multi-core? If so you could consider multithreading this algorithm
Help with algorithm for merging vectors
I need a very fast algorithm for the following task. I have already implemented several algorithms that complete it, but they're all too slow for the performance I need. It should be fast enough that the algorithm can be run at least 100,000 times a second on a modern CPU. It will be implemented in C++. I am working with spans/ranges, a structure that has a start and an end coordinate on a line. I have two vectors (dynamic arrays) of spans and I need to merge them. One vector is src and the other dst. The vectors are sorted by span start coordinates, and the spans do not overlap within one vector. The spans in the src vector must be merged with the spans in the dst vector, such that the resulting vector is still sorted and has no overlaps. Ie. if overlaps are detected during the merging, the two spans are merged into one. (Merging two spans is just a matter of changing the coordinates in the structure.) Now, there is one more catch, the spans in the src vector must be "widened" during the merge. This means that a constant will be added to the start and another (larger) constant to the end coordinate of every span in src. This means that after the src spans are widened they might overlap. What I have arrived at so far is that it cannot be done fully in-place, some kind of temporary storage is needed. I think it should be doable in linear time over the number of elements of src and dst summed. Any temporary storage can probably be shared between multiple runs of the algorithm. The two primary approaches I have tried, which are too slow, are: Append all elements of src to dst, widening each element before appending it. Then run an in-place sort. Finally iterate over the resulting vector using a "read" and "write" pointer, with the read pointer running ahead of the write pointer, merging spans as they go. When all elements have been merged (the read pointer reaches end) dst is truncated. Create a temporary work-vector. Do a naive merge as described above by repeatedly picking the next element from either src or dst and merging into the work-vector. When done, copy the work-vector to dst, replacing it. The first method has the problem that sorting is O((m+n)*log(m+n)) instead of O(m+n) and has somewhat overhead. It also means the dst vector has to grow much larger than it really needs. The second has the primary problem of a lot of copying around and again allocation/deallocation of memory. The data structures used for storing/managing the spans/vectors can be altered if you think that's needed. Update: Forgot to say how large the datasets are. The most common cases are between 4 and 30 elements in either vector, and either dst is empty or there is a large amount of overlap between the spans in src and dst.
[ "We know that the absolute best case runtime is O(m+n) this is due to the fact that you at least have to scan over all of the data in order to be able to merge the lists. Given this, your second method should give you that type of behavior. \nHave you profiled your second method to find out what the bottlenecks are? It is quite possible that, depending on the amount of data you are talking about it is actually impossible to do what you want in the specified amount of time. One way to verify this is to do something simple like sum up all the start and end values of the spans in each vector in a loop, and time that. Basically here you are doing a minimal amount of work for each element in the vectors. This will provide you with a baseline for the best performance you can expect to get.\nBeyond that you can avoid copying the vectors element by element by using the stl swap method, and you can preallocate the temp vector to a certain size in order to avoid triggering the expansion of the array when you are merging the elements.\nYou might consider using 2 vectors in your system and whenever you need to do a merge you merge into the unused vector, and then swap (this is similar to double buffering used in graphics). This way you don't have to reallocate the vectors every time you do the merge.\nHowever, you are best off profiling first and finding out what your bottleneck is. If the allocations are minimal compared to the actual merging process than you need to figure out how to make that faster. \nSome possible additional speedups could come from accessing the vectors raw data directly which avoids the bounds checks on each access the data.\n", "How about the second method without repeated allocation--in other words, allocate your temporary vector once, and never allocate it again? Or, if the input vectors are small enough (But not constant size), just use alloca instead of malloc.\nAlso, in terms of speed, you may want to make sure that your code is using CMOV for the sorting, since if the code is actually branching for every single iteration of the mergesort:\nif(src1[x] < src2[x])\n dst[x] = src1[x];\nelse\n dst[x] = src2[x];\n\nThe branch prediction will fail 50% of the time, which will have an enormous hit on performance. A conditional move will likely do much much better, so make sure the compiler is doing that, and if not, try to coax it into doing so.\n", "The sort you mention in Approach 1 can be reduced to linear time (from log-linear as you describe it) because the two input lists are already sorted. Just perform the merge step of merge-sort. With an appropriate representation for the input span vectors (for example singly-linked lists) this can be done in-place.\nhttp://en.wikipedia.org/wiki/Merge_sort\n", "i don't think a strictly linear solution is possible, because widening the src vector spans may in the worst-case cause all of them to overlap (depending on the magnitude of the constant that you are adding)\nthe problem may be in the implementation, not in the algorithm; i would suggest profiling the code for your prior solutions to see where the time is spent\nreasoning:\nfor a truly \"modern\" CPU like the Intel Core 2 Extreme QX9770 running at 3.2GHz, one can expect about 59,455 MIPS\nfor 100,000 vectors, you would have to process each vector in 594,550 instuctions. That's a LOT of instructions.\nref: wikipedia MIPS\nin addition, note that adding a constant to the src vector spans does not de-sort them, so you can normalize the src vector spans independently, then merge them with the dst vector spans; this should reduce the workload of your original algorithm\n", "1 is right out - a full sort is slower than merging two sorted lists.\nSo you're looking at tweaking 2 (or something entirely new).\nIf you change the data structures to doubly linked lists, then you can merge them in constant working space. \nUse a fixed-size heap allocator for the list nodes, both to reduce memory use per node and to improve the chance that the nodes are close together in memory, reducing page misses.\nYou might be able to find code online or in your favourite algorithm book to optimise a linked list merge. You'll want to customise this in order to do span coalescing at the same time as the list merge.\nTo optimise the merge, first note that for each run of values coming off the same side without one coming from the other side, you can insert the whole run into the dst list in one go, instead of inserting each node in turn. And you can save one write per insertion over a normal list operation, by leaving the end \"dangling\", knowing that you'll patch it up later. And provided that you don't do deletions anywhere else in your app, the list can be singly-linked, which means one write per node.\nAs for 10 microsecond runtime - kind of depends on n and m...\n", "If your most recent implementation still isn't fast enough, you might end up having to look at alternative approaches.\nWhat are you using the outputs of this function for?\n", "I wrote a new container class just for this algorithm, tailored to the needs. This also gave me a chance to adjust other code around my program which got a little speed boost at the same time.\nThis is significantly faster than the old implementation using STL vectors, but which was otherwise basically the same thing. But while it's faster it's still not really fast enough... unfortunately.\nProfiling doesn't reveal what is the real bottleneck any longer. The MSVC profiler seems to sometimes place the \"blame\" on the wrong calls (supposedly identical runs assign widely different running times) and most calls are getting coalesced into one big chink.\nLooking at a disassembly of the generated code shows that there's a very large amount of jumps in the generated code, I think that might be the main reason behind the slowness now.\nclass SpanBuffer {\nprivate:\n int *data;\n size_t allocated_size;\n size_t count;\n\n inline void EnsureSpace()\n {\n if (count == allocated_size)\n Reserve(count*2);\n }\n\npublic:\n struct Span {\n int start, end;\n };\n\npublic:\n SpanBuffer()\n : data(0)\n , allocated_size(24)\n , count(0)\n {\n data = new int[allocated_size];\n }\n\n SpanBuffer(const SpanBuffer &src)\n : data(0)\n , allocated_size(src.allocated_size)\n , count(src.count)\n {\n data = new int[allocated_size];\n memcpy(data, src.data, sizeof(int)*count);\n }\n\n ~SpanBuffer()\n {\n delete [] data;\n }\n\n inline void AddIntersection(int x)\n {\n EnsureSpace();\n data[count++] = x;\n }\n\n inline void AddSpan(int s, int e)\n {\n assert((count & 1) == 0);\n assert(s >= 0);\n assert(e >= 0);\n EnsureSpace();\n data[count] = s;\n data[count+1] = e;\n count += 2;\n }\n\n inline void Clear()\n {\n count = 0;\n }\n\n inline size_t GetCount() const\n {\n return count;\n }\n\n inline int GetIntersection(size_t i) const\n {\n return data[i];\n }\n\n inline const Span * GetSpanIteratorBegin() const\n {\n assert((count & 1) == 0);\n return reinterpret_cast<const Span *>(data);\n }\n\n inline Span * GetSpanIteratorBegin()\n {\n assert((count & 1) == 0);\n return reinterpret_cast<Span *>(data);\n }\n\n inline const Span * GetSpanIteratorEnd() const\n {\n assert((count & 1) == 0);\n return reinterpret_cast<const Span *>(data+count);\n }\n\n inline Span * GetSpanIteratorEnd()\n {\n assert((count & 1) == 0);\n return reinterpret_cast<Span *>(data+count);\n }\n\n inline void MergeOrAddSpan(int s, int e)\n {\n assert((count & 1) == 0);\n assert(s >= 0);\n assert(e >= 0);\n\n if (count == 0)\n {\n AddSpan(s, e);\n return;\n }\n\n int *lastspan = data + count-2;\n\n if (s > lastspan[1])\n {\n AddSpan(s, e);\n }\n else\n {\n if (s < lastspan[0])\n lastspan[0] = s;\n if (e > lastspan[1])\n lastspan[1] = e;\n }\n }\n\n inline void Reserve(size_t minsize)\n {\n if (minsize <= allocated_size)\n return;\n\n int *newdata = new int[minsize];\n\n memcpy(newdata, data, sizeof(int)*count);\n\n delete [] data;\n data = newdata;\n\n allocated_size = minsize;\n }\n\n inline void SortIntersections()\n {\n assert((count & 1) == 0);\n std::sort(data, data+count, std::less<int>());\n assert((count & 1) == 0);\n }\n\n inline void Swap(SpanBuffer &other)\n {\n std::swap(data, other.data);\n std::swap(allocated_size, other.allocated_size);\n std::swap(count, other.count);\n }\n};\n\n\nstruct ShapeWidener {\n // How much to widen in the X direction\n int widen_by;\n // Half of width difference of src and dst (width of the border being produced)\n int xofs;\n\n // Temporary storage for OverlayScanline, so it doesn't need to reallocate for each call\n SpanBuffer buffer;\n\n inline void OverlayScanline(const SpanBuffer &src, SpanBuffer &dst);\n\n ShapeWidener(int _xofs) : xofs(_xofs) { }\n};\n\n\ninline void ShapeWidener::OverlayScanline(const SpanBuffer &src, SpanBuffer &dst)\n{\n if (src.GetCount() == 0) return;\n if (src.GetCount() + dst.GetCount() == 0) return;\n\n assert((src.GetCount() & 1) == 0);\n assert((dst.GetCount() & 1) == 0);\n\n assert(buffer.GetCount() == 0);\n\n dst.Swap(buffer);\n\n const int widen_s = xofs - widen_by;\n const int widen_e = xofs + widen_by;\n\n size_t resta = src.GetCount()/2;\n size_t restb = buffer.GetCount()/2;\n const SpanBuffer::Span *spa = src.GetSpanIteratorBegin();\n const SpanBuffer::Span *spb = buffer.GetSpanIteratorBegin();\n\n while (resta > 0 || restb > 0)\n {\n if (restb == 0)\n {\n dst.MergeOrAddSpan(spa->start+widen_s, spa->end+widen_e);\n --resta, ++spa;\n }\n else if (resta == 0)\n {\n dst.MergeOrAddSpan(spb->start, spb->end);\n --restb, ++spb;\n }\n else if (spa->start < spb->start)\n {\n dst.MergeOrAddSpan(spa->start+widen_s, spa->end+widen_e);\n --resta, ++spa;\n }\n else\n {\n dst.MergeOrAddSpan(spb->start, spb->end);\n --restb, ++spb;\n }\n }\n\n buffer.Clear();\n}\n\n", "I would always keep my vector of spans sorted. That makes implementing algorithms a LOT easier -- and possible to do in linear time.\nOK, so I'd sort the spans based on:\n\nspan minimum in increasing order\nthen span maximum in decreasing order\n\nYou need to create a function to do that.\nThen I'd use std::set_union to merge the vectors (you can merge more than one before continuing). \nThen for each consecutive sets of spans with identical minimums, you keep the first and remove the rest (they're sub-spans of the first span).\nThen you need to merge your spans. That should be pretty doable now and feasible in linear time.\nOK, here's the trick now. Don't try to do this in-place. Use one or more temporary vectors (and reserve enough space ahead of time). Then at the end, call std::vector::swap to put the results in the input vector of your choice.\nI hope that's enough to get you going.\n", "What is your target system? Is it multi-core? If so you could consider multithreading this algorithm\n" ]
[ 8, 0, 0, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "algorithm", "c++", "graphics", "optimization", "vector" ]
stackoverflow_0000089402_algorithm_c++_graphics_optimization_vector.txt
Q: Performance when checking for duplicates I've been working on a project where I need to iterate through a collection of data and remove entries where the "primary key" is duplicated. I have tried using a List<int> and Dictionary<int, bool> With the dictionary I found slightly better performance, even though I never need the Boolean tagged with each entry. My expectation is that this is because a List allows for indexed access and a Dictionary does not. What I was wondering is, is there a better solution to this problem. I do not need to access the entries again, I only need to track what "primary keys" I have seen and make sure I only perform addition work on entries that have a new primary key. I'm using C# and .NET 2.0. And I have no control over fixing the input data to remove the duplicates from the source (unfortunately!). And so you can have a feel for scaling, overall I'm checking for duplicates about 1,000,000 times in the application, but in subsets of no more than about 64,000 that need to be unique. A: They have added the HashSet class in .NET 3.5. But I guess it will be on par with the Dictionary. If you have less than say a 100 elements a List will probably perform better. A: Edit: Nevermind my comment. I thought you're talking about C++. I have no idea if my post is relevant in the C# world.. A hash-table could be a tad faster. Binary trees (that's what used in the dictionary) tend to be relative slow because of the way the memory gets accessed. This is especially true if your tree becomes very large. However, before you change your data-structure, have you tried to use a custom pool allocator for your dictionary? I bet the time is not spent traversing the tree itself but in the millions of allocations and deallocations the dictionary will do for you. You may see a factor 10 speed-boost just plugging a simple pool allocator into the dictionary template. Afaik boost has a component that can be directly used. Another option: If you know only 64.000 entries in your integers exist you can write those to a file and create a perfect hash function for it. That way you can just use the hash function to map your integers into the 0 to 64.000 range and index a bit-array. Probably the fastest way, but less flexible. You have to redo your perfect hash function (can be done automatically) each time your set of integers changes. A: I don't really get what you are asking. Firstly is just the opposite of what you say. The dictionary has indexed access (is a hash table) while de List hasn't. If you already have the data in a dictionary then all keys are unique, there can be no duplicates. I susspect you have the data stored in another data type and you're storing it into the dictionary. If that's the case the inserting the data will work with two dictionarys. foreach (int key in keys) { if (!MyDataDict.ContainsKey(key)) { if (!MyDuplicatesDict.ContainsKey(key)) MyDuplicatesDict.Add(key); } else MyDataDict.Add(key); } A: If you are checking for uniqueness of integers, and the range of integers is constrained enough then you could just use an array. For better packing you could implement a bitmap data structure (basically an array, but each int in the array represents 32 ints in the key space by using 1 bit per key). That way if you maximum number is 1,000,000 you only need ~30.5KB of memory for the data structure. Performs of a bitmap would be O(1) (per check) which is hard to beat. A: There was a question awhile back on removing duplicates from an array. For the purpose of the question performance wasn't much of a consideration, but you might want to take a look at the answers as they might give you some ideas. Also, I might be off base here, but if you are trying to remove duplicates from the array then a LINQ command like Enumerable.Distinct might give you better performance than something that you write yourself. As it turns out there is a way to get LINQ working on .NET 2.0 so this might be a route worth investigating. A: If you're going to use a List, use the BinarySearch: // initailize to a size if you know your set size List<int> FoundKeys = new List<int>( 64000 ); Dictionary<int,int> FoundDuplicates = new Dictionary<int,int>(); foreach ( int Key in MyKeys ) { // this is an O(log N) operation int index = FoundKeys.BinarySearch( Key ); if ( index < 0 ) { // if the Key is not in our list, // index is the two's compliment of the next value that is in the list // i.e. the position it should occupy, and we maintain sorted-ness! FoundKeys.Insert( ~index, Key ); } else { if ( DuplicateKeys.ContainsKey( Key ) ) { DuplicateKeys[Key]++; } else { DuplicateKeys.Add( Key, 1 ); } } } You can also use this for any type for which you can define an IComparer by using an overload: BinarySearch( T item, IComparer< T > );
Performance when checking for duplicates
I've been working on a project where I need to iterate through a collection of data and remove entries where the "primary key" is duplicated. I have tried using a List<int> and Dictionary<int, bool> With the dictionary I found slightly better performance, even though I never need the Boolean tagged with each entry. My expectation is that this is because a List allows for indexed access and a Dictionary does not. What I was wondering is, is there a better solution to this problem. I do not need to access the entries again, I only need to track what "primary keys" I have seen and make sure I only perform addition work on entries that have a new primary key. I'm using C# and .NET 2.0. And I have no control over fixing the input data to remove the duplicates from the source (unfortunately!). And so you can have a feel for scaling, overall I'm checking for duplicates about 1,000,000 times in the application, but in subsets of no more than about 64,000 that need to be unique.
[ "They have added the HashSet class in .NET 3.5. But I guess it will be on par with the Dictionary. If you have less than say a 100 elements a List will probably perform better.\n", "Edit: Nevermind my comment. I thought you're talking about C++. I have no idea if my post is relevant in the C# world..\nA hash-table could be a tad faster. Binary trees (that's what used in the dictionary) tend to be relative slow because of the way the memory gets accessed. This is especially true if your tree becomes very large.\nHowever, before you change your data-structure, have you tried to use a custom pool allocator for your dictionary? I bet the time is not spent traversing the tree itself but in the millions of allocations and deallocations the dictionary will do for you.\nYou may see a factor 10 speed-boost just plugging a simple pool allocator into the dictionary template. Afaik boost has a component that can be directly used.\nAnother option: If you know only 64.000 entries in your integers exist you can write those to a file and create a perfect hash function for it. That way you can just use the hash function to map your integers into the 0 to 64.000 range and index a bit-array.\nProbably the fastest way, but less flexible. You have to redo your perfect hash function (can be done automatically) each time your set of integers changes.\n", "I don't really get what you are asking.\nFirstly is just the opposite of what you say. The dictionary has indexed access (is a hash table) while de List hasn't.\nIf you already have the data in a dictionary then all keys are unique, there can be no duplicates.\nI susspect you have the data stored in another data type and you're storing it into the dictionary. If that's the case the inserting the data will work with two dictionarys.\nforeach (int key in keys)\n{\n if (!MyDataDict.ContainsKey(key))\n {\n if (!MyDuplicatesDict.ContainsKey(key))\n MyDuplicatesDict.Add(key);\n }\n else\n MyDataDict.Add(key); \n}\n\n", "If you are checking for uniqueness of integers, and the range of integers is constrained enough then you could just use an array. \nFor better packing you could implement a bitmap data structure (basically an array, but each int in the array represents 32 ints in the key space by using 1 bit per key). That way if you maximum number is 1,000,000 you only need ~30.5KB of memory for the data structure.\nPerforms of a bitmap would be O(1) (per check) which is hard to beat.\n", "There was a question awhile back on removing duplicates from an array. For the purpose of the question performance wasn't much of a consideration, but you might want to take a look at the answers as they might give you some ideas. Also, I might be off base here, but if you are trying to remove duplicates from the array then a LINQ command like Enumerable.Distinct might give you better performance than something that you write yourself. As it turns out there is a way to get LINQ working on .NET 2.0 so this might be a route worth investigating.\n", "If you're going to use a List, use the BinarySearch:\n // initailize to a size if you know your set size\nList<int> FoundKeys = new List<int>( 64000 );\nDictionary<int,int> FoundDuplicates = new Dictionary<int,int>();\n\nforeach ( int Key in MyKeys )\n{\n // this is an O(log N) operation\n int index = FoundKeys.BinarySearch( Key );\n if ( index < 0 ) \n {\n // if the Key is not in our list, \n // index is the two's compliment of the next value that is in the list\n // i.e. the position it should occupy, and we maintain sorted-ness!\n FoundKeys.Insert( ~index, Key );\n }\n else \n {\n if ( DuplicateKeys.ContainsKey( Key ) )\n {\n DuplicateKeys[Key]++;\n }\n else\n {\n DuplicateKeys.Add( Key, 1 );\n }\n } \n} \n\nYou can also use this for any type for which you can define an IComparer by using an overload: BinarySearch( T item, IComparer< T > );\n" ]
[ 3, 1, 0, 0, 0, 0 ]
[]
[]
[ ".net_2.0", "c#", "collections", "performance" ]
stackoverflow_0000091933_.net_2.0_c#_collections_performance.txt
Q: Is there a macro to conditionally copy rows to another worksheet? Is there a macro or a way to conditionally copy rows from one worksheet to another in Excel 2003? I'm pulling a list of data from SharePoint via a web query into a blank worksheet in Excel, and then I want to copy the rows for a particular month to a particular worksheet (for example, all July data from a SharePoint worksheet to the Jul worksheet, all June data from a SharePoint worksheet to Jun worksheet, etc.). Sample data Date - Project - ID - Engineer 8/2/08 - XYZ - T0908-5555 - JS 9/4/08 - ABC - T0908-6666 - DF 9/5/08 - ZZZ - T0908-7777 - TS It's not a one-off exercise. I'm trying to put together a dashboard that my boss can pull the latest data from SharePoint and see the monthly results, so it needs to be able to do it all the time and organize it cleanly. A: This works: The way it's set up I called it from the immediate pane, but you can easily create a sub() that will call MoveData once for each month, then just invoke the sub. You may want to add logic to sort your monthly data after it's all been copied Public Sub MoveData(MonthNumber As Integer, SheetName As String) Dim sharePoint As Worksheet Dim Month As Worksheet Dim spRange As Range Dim cell As Range Set sharePoint = Sheets("Sharepoint") Set Month = Sheets(SheetName) Set spRange = sharePoint.Range("A2") Set spRange = sharePoint.Range("A2:" & spRange.End(xlDown).Address) For Each cell In spRange If Format(cell.Value, "MM") = MonthNumber Then copyRowTo sharePoint.Range(cell.Row & ":" & cell.Row), Month End If Next cell End Sub Sub copyRowTo(rng As Range, ws As Worksheet) Dim newRange As Range Set newRange = ws.Range("A1") If newRange.Offset(1).Value <> "" Then Set newRange = newRange.End(xlDown).Offset(1) Else Set newRange = newRange.Offset(1) End If rng.Copy newRange.PasteSpecial (xlPasteAll) End Sub A: Here's another solution that uses some of VBA's built in date functions and stores all the date data in an array for comparison, which may give better performance if you get a lot of data: Public Sub MoveData(MonthNum As Integer, FromSheet As Worksheet, ToSheet As Worksheet) Const DateCol = "A" 'column where dates are store Const DestCol = "A" 'destination column where dates are stored. We use this column to find the last populated row in ToSheet Const FirstRow = 2 'first row where date data is stored 'Copy range of values to Dates array Dates = FromSheet.Range(DateCol & CStr(FirstRow) & ":" & DateCol & CStr(FromSheet.Range(DateCol & CStr(FromSheet.Rows.Count)).End(xlUp).Row)).Value Dim i As Integer For i = LBound(Dates) To UBound(Dates) If IsDate(Dates(i, 1)) Then If Month(CDate(Dates(i, 1))) = MonthNum Then Dim CurrRow As Long 'get the current row number in the worksheet CurrRow = FirstRow + i - 1 Dim DestRow As Long 'get the destination row DestRow = ToSheet.Range(DestCol & CStr(ToSheet.Rows.Count)).End(xlUp).Row + 1 'copy row CurrRow in FromSheet to row DestRow in ToSheet FromSheet.Range(CStr(CurrRow) & ":" & CStr(CurrRow)).Copy ToSheet.Range(DestCol & CStr(DestRow)) End If End If Next i End Sub A: This is partially pseudocode, but you will want something like: rows = ActiveSheet.UsedRange.Rows n = 0 while n <= rows if ActiveSheet.Rows(n).Cells(DateColumnOrdinal).Value > '8/1/08' AND < '8/30/08' then ActiveSheet.Rows(n).CopyTo(DestinationSheet) endif n = n + 1 wend A: The way I would do this manually is: Use Data - AutoFilter Apply a custom filter based on a date range Copy the filtered data to the relevant month sheet Repeat for every month Listed below is code to do this process via VBA. It has the advantage of handling monthly sections of data rather than individual rows. Which can result in quicker processing for larger sets of data. Sub SeperateData() Dim vMonthText As Variant Dim ExcelLastCell As Range Dim intMonth As Integer vMonthText = Array("January", "February", "March", "April", "May", _ "June", "July", "August", "September", "October", "November", "December") ThisWorkbook.Worksheets("Sharepoint").Select Range("A1").Select RowCount = ThisWorkbook.Worksheets("Sharepoint").UsedRange.Rows.Count 'Forces excel to determine the last cell, Usually only done on save Set ExcelLastCell = ThisWorkbook.Worksheets("Sharepoint"). _ Cells.SpecialCells(xlLastCell) 'Determines the last cell with data in it Selection.EntireColumn.Insert Range("A1").FormulaR1C1 = "Month No." Range("A2").FormulaR1C1 = "=MONTH(RC[1])" Range("A2").Select Selection.Copy Range("A3:A" & ExcelLastCell.Row).Select ActiveSheet.Paste Application.CutCopyMode = False Calculate 'Insert a helper column to determine the month number for the date For intMonth = 1 To 12 Range("A1").CurrentRegion.Select Selection.AutoFilter Field:=1, Criteria1:="" & intMonth Selection.Copy ThisWorkbook.Worksheets("" & vMonthText(intMonth - 1)).Select Range("A1").Select ActiveSheet.Paste Columns("A:A").Delete Shift:=xlToLeft Cells.Select Cells.EntireColumn.AutoFit Range("A1").Select ThisWorkbook.Worksheets("Sharepoint").Select Range("A1").Select Application.CutCopyMode = False Next intMonth 'Filter the data to a particular month 'Convert the month number to text 'Copy the filtered data to the month sheet 'Delete the helper column 'Repeat for each month Selection.AutoFilter Columns("A:A").Delete Shift:=xlToLeft 'Get rid of the auto-filter and delete the helper column End Sub
Is there a macro to conditionally copy rows to another worksheet?
Is there a macro or a way to conditionally copy rows from one worksheet to another in Excel 2003? I'm pulling a list of data from SharePoint via a web query into a blank worksheet in Excel, and then I want to copy the rows for a particular month to a particular worksheet (for example, all July data from a SharePoint worksheet to the Jul worksheet, all June data from a SharePoint worksheet to Jun worksheet, etc.). Sample data Date - Project - ID - Engineer 8/2/08 - XYZ - T0908-5555 - JS 9/4/08 - ABC - T0908-6666 - DF 9/5/08 - ZZZ - T0908-7777 - TS It's not a one-off exercise. I'm trying to put together a dashboard that my boss can pull the latest data from SharePoint and see the monthly results, so it needs to be able to do it all the time and organize it cleanly.
[ "This works: The way it's set up I called it from the immediate pane, but you can easily create a sub() that will call MoveData once for each month, then just invoke the sub.\nYou may want to add logic to sort your monthly data after it's all been copied\nPublic Sub MoveData(MonthNumber As Integer, SheetName As String)\n\nDim sharePoint As Worksheet\nDim Month As Worksheet\nDim spRange As Range\nDim cell As Range\n\nSet sharePoint = Sheets(\"Sharepoint\")\nSet Month = Sheets(SheetName)\nSet spRange = sharePoint.Range(\"A2\")\nSet spRange = sharePoint.Range(\"A2:\" & spRange.End(xlDown).Address)\nFor Each cell In spRange\n If Format(cell.Value, \"MM\") = MonthNumber Then\n copyRowTo sharePoint.Range(cell.Row & \":\" & cell.Row), Month\n End If\nNext cell\n\nEnd Sub\n\nSub copyRowTo(rng As Range, ws As Worksheet)\n Dim newRange As Range\n Set newRange = ws.Range(\"A1\")\n If newRange.Offset(1).Value <> \"\" Then\n Set newRange = newRange.End(xlDown).Offset(1)\n Else\n Set newRange = newRange.Offset(1)\n End If\n rng.Copy\n newRange.PasteSpecial (xlPasteAll)\nEnd Sub\n\n", "Here's another solution that uses some of VBA's built in date functions and stores all the date data in an array for comparison, which may give better performance if you get a lot of data:\nPublic Sub MoveData(MonthNum As Integer, FromSheet As Worksheet, ToSheet As Worksheet)\n Const DateCol = \"A\" 'column where dates are store\n Const DestCol = \"A\" 'destination column where dates are stored. We use this column to find the last populated row in ToSheet\n Const FirstRow = 2 'first row where date data is stored\n 'Copy range of values to Dates array\n Dates = FromSheet.Range(DateCol & CStr(FirstRow) & \":\" & DateCol & CStr(FromSheet.Range(DateCol & CStr(FromSheet.Rows.Count)).End(xlUp).Row)).Value\n Dim i As Integer\n For i = LBound(Dates) To UBound(Dates)\n If IsDate(Dates(i, 1)) Then\n If Month(CDate(Dates(i, 1))) = MonthNum Then\n Dim CurrRow As Long\n 'get the current row number in the worksheet\n CurrRow = FirstRow + i - 1\n Dim DestRow As Long\n 'get the destination row\n DestRow = ToSheet.Range(DestCol & CStr(ToSheet.Rows.Count)).End(xlUp).Row + 1\n 'copy row CurrRow in FromSheet to row DestRow in ToSheet\n FromSheet.Range(CStr(CurrRow) & \":\" & CStr(CurrRow)).Copy ToSheet.Range(DestCol & CStr(DestRow))\n End If\n End If\n Next i\nEnd Sub\n\n", "This is partially pseudocode, but you will want something like:\n\nrows = ActiveSheet.UsedRange.Rows\nn = 0\n\nwhile n <= rows\n if ActiveSheet.Rows(n).Cells(DateColumnOrdinal).Value > '8/1/08' AND < '8/30/08' then\n ActiveSheet.Rows(n).CopyTo(DestinationSheet)\n endif\n n = n + 1\nwend\n\n", "The way I would do this manually is:\n\nUse Data - AutoFilter \nApply a custom filter based on a date range\nCopy the filtered data to the relevant month sheet\nRepeat for every month\n\nListed below is code to do this process via VBA. \nIt has the advantage of handling monthly sections of data rather than individual rows. Which can result in quicker processing for larger sets of data.\n Sub SeperateData()\n\n Dim vMonthText As Variant\n Dim ExcelLastCell As Range\n Dim intMonth As Integer\n\n vMonthText = Array(\"January\", \"February\", \"March\", \"April\", \"May\", _\n \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\")\n\n ThisWorkbook.Worksheets(\"Sharepoint\").Select\n Range(\"A1\").Select\n\n RowCount = ThisWorkbook.Worksheets(\"Sharepoint\").UsedRange.Rows.Count\n'Forces excel to determine the last cell, Usually only done on save\n Set ExcelLastCell = ThisWorkbook.Worksheets(\"Sharepoint\"). _\n Cells.SpecialCells(xlLastCell)\n'Determines the last cell with data in it\n\n\n Selection.EntireColumn.Insert\n Range(\"A1\").FormulaR1C1 = \"Month No.\"\n Range(\"A2\").FormulaR1C1 = \"=MONTH(RC[1])\"\n Range(\"A2\").Select\n Selection.Copy\n Range(\"A3:A\" & ExcelLastCell.Row).Select\n ActiveSheet.Paste\n Application.CutCopyMode = False\n Calculate\n 'Insert a helper column to determine the month number for the date\n\n For intMonth = 1 To 12\n Range(\"A1\").CurrentRegion.Select\n Selection.AutoFilter Field:=1, Criteria1:=\"\" & intMonth\n Selection.Copy\n ThisWorkbook.Worksheets(\"\" & vMonthText(intMonth - 1)).Select\n Range(\"A1\").Select\n ActiveSheet.Paste\n Columns(\"A:A\").Delete Shift:=xlToLeft\n Cells.Select\n Cells.EntireColumn.AutoFit\n Range(\"A1\").Select\n ThisWorkbook.Worksheets(\"Sharepoint\").Select\n Range(\"A1\").Select\n Application.CutCopyMode = False\n Next intMonth\n 'Filter the data to a particular month\n 'Convert the month number to text\n 'Copy the filtered data to the month sheet\n 'Delete the helper column\n 'Repeat for each month\n\n Selection.AutoFilter\n Columns(\"A:A\").Delete Shift:=xlToLeft\n 'Get rid of the auto-filter and delete the helper column\n\n End Sub\n\n" ]
[ 5, 1, 0, 0 ]
[ "If this is just a one-off exercise, as an easier alternative, you could apply filters to your source data, and then copy and paste the filtered rows into your new worksheet?\n" ]
[ -1 ]
[ "copy", "excel", "excel_2003", "vba", "worksheet" ]
stackoverflow_0000084331_copy_excel_excel_2003_vba_worksheet.txt
Q: How to do manual form authentication for ASP.NET mobile page I am developing an ASP.NET mobile website using .NET 3.5 and mobile controls that come with the framework. I have a login form where the system will authenticate the user so he/she can access certain restricted pages. In a standard ASP.NET website, I can use a session to store some flag after a user had logined, but I wonder can I do the same for the mobile version? Is session variable (or cookies) being support by those mobile device's browser? Is there any standard pratice also on doing authentication for mobile pages? A: Session variables are stored in the server so you can forget the device browser capabilities. I've not practice developing for mobile device, but 4 years ago I was using a service that used cookie authentication and the phone was not top-notch so... I think you can take for granted the cookie availability. Full futured browsers for mobile are taking on so... invest in the future, don't spend energy with old techologies soon to be deprecated... In my opinion, prefer cookie authentication, it's more standard, and you can save the cookie on the phone preventing further authentications.... A: You can indeed support cookie authentication but the only guaranteed way for it to work is to attach the cookie ID as part of the URL i.e. cookieless sessions. Yes, this is bad practice as it's ugly and very insecure and all modern phones support cookies. But some devices have cookie limitations and, what's more, some networks strip all cookie information from the HTTP headers that pass through their gateways even though the phone has no problems (NTT DoCoMo do this in Japan). It may not apply in your situation but it's something to keep in mind. Lucky for you ASP.NET does support cookieless sessions easily. In the app.config file: <sessionState cookieless="true" /> does the trick.
How to do manual form authentication for ASP.NET mobile page
I am developing an ASP.NET mobile website using .NET 3.5 and mobile controls that come with the framework. I have a login form where the system will authenticate the user so he/she can access certain restricted pages. In a standard ASP.NET website, I can use a session to store some flag after a user had logined, but I wonder can I do the same for the mobile version? Is session variable (or cookies) being support by those mobile device's browser? Is there any standard pratice also on doing authentication for mobile pages?
[ "Session variables are stored in the server so you can forget the device browser capabilities.\nI've not practice developing for mobile device, but 4 years ago I was using a service that used cookie authentication and the phone was not top-notch so... I think you can take for granted the cookie availability. Full futured browsers for mobile are taking on so... invest in the future, don't spend energy with old techologies soon to be deprecated...\nIn my opinion, prefer cookie authentication, it's more standard, and you can save the cookie on the phone preventing further authentications....\n", "You can indeed support cookie authentication but the only guaranteed way for it to work is to attach the cookie ID as part of the URL i.e. cookieless sessions. Yes, this is bad practice as it's ugly and very insecure and all modern phones support cookies. But some devices have cookie limitations and, what's more, some networks strip all cookie information from the HTTP headers that pass through their gateways even though the phone has no problems (NTT DoCoMo do this in Japan). It may not apply in your situation but it's something to keep in mind.\nLucky for you ASP.NET does support cookieless sessions easily. In the app.config file:\n<sessionState cookieless=\"true\" />\n\ndoes the trick.\n" ]
[ 1, 0 ]
[]
[]
[ "asp.net", "mobile" ]
stackoverflow_0000081472_asp.net_mobile.txt
Q: How do I get PHP and MySQL working on IIS 7.0? Okay, I've looked all over the internet for a good solution to get PHP and MySQL working on IIS7.0. It's nearly impossible, I've tried it so many times and given up in vain. Please please help by linking some great step-by-step tutorial to adding PHP and MySQL on IIS7.0 from scratch. PHP and MySQL are essential for installing any CMS. A: Have you taken a look at this: http://learn.iis.net/page.aspx/246/using-fastcgi-to-host-php-applications-on-iis7/ MySQL should be pretty straight forward. Let us know what problems you're encountering... A: I've been given a PHP / MySQL web site that I'm to host with IIS 7.0 on 64-bit Windows Server 2008. I'm a .NET / MSSQL developer, and am unfamiliar with either PHP or MySQL. Kev wrote: Have you taken a look at this… I don't know if any one implementation of Win64 PHP is more authoratative or popular than another. I'm going to try following the steps in Kev's Enable FastCGI support in IIS7.0 article with file php-5.2.5-x64-2007-11-12.zip from fusion-x lan. It's "PHP Version 5.2.5 (x64)", but according to php.net, the latest version is PHP 5.2.6. Oh, well. Make sure "ISAPI Extensions" are installed in IIS (mine were). Download and then unzip php-5.2.5-x64-2007-11-12.zip Copy contents of folder php-5.2.5 (x64) into *C:\php* Copy file C:\php\php.ini-dist into folder *C:\Windows* Rename file C:\Windows\php.ini-dist as php.ini Edit php.ini in Notepad. Remove leading semi-colon (;) from line: ;extension=php_mysql.dll Save and close Copy file C:\php\ext\php_mysql.dll into folder *C:\Windows\System32* Within IIS Manager's "Handler Mappings", choose "Add Script Map…" Request path: *.php Executable: C:\php\php5isapi.dll Name: PHP Install MySQL (someone had already installed MySQL 5.0 for me). Create file C:\inetpub\wwwroot\test.php as <html> <head> <title>PHP Information</title> </head> <body> <?php phpInfo(); ?> </body> </html> Navigate to http://localhost/test.php in your web browser. You will see a page of information about PHP. Roadblock: How do I get PHP to work with ADOdb and MySQL? A: It's supposed to work via FastCGI. But I haven't had great success (using Vista). I can get PHP to run, but it crashes after a page loads (FastCGI does). So I'm modding you up. I'd like to see a reliable answer myself. A: From my experience with windows/apache it's just a matter of install MySQL, I can't Imagine that IIS/Apache has anything to do with this. A: Apache is a major pain to get running in Vista. And II7 (and 6) are suppose to run PHP fine. So why bother with Apache? A: I would suggest if you are going for a PHP and MySQL install to instead use WAMP. It works great and is easy to add extensions and modify everything. I use it for work and love it. A: One of the IIS developers has an excellent walkthrough here: http://blogs.iis.net/bills/archive/2006/10/31/PHP-on-IIS.aspx However, for the love of god why?
How do I get PHP and MySQL working on IIS 7.0?
Okay, I've looked all over the internet for a good solution to get PHP and MySQL working on IIS7.0. It's nearly impossible, I've tried it so many times and given up in vain. Please please help by linking some great step-by-step tutorial to adding PHP and MySQL on IIS7.0 from scratch. PHP and MySQL are essential for installing any CMS.
[ "Have you taken a look at this:\nhttp://learn.iis.net/page.aspx/246/using-fastcgi-to-host-php-applications-on-iis7/\nMySQL should be pretty straight forward.\nLet us know what problems you're encountering...\n", "I've been given a PHP / MySQL web site that I'm to host with IIS 7.0 on 64-bit Windows Server 2008.\nI'm a .NET / MSSQL developer, and am unfamiliar with either PHP or MySQL.\n\nKev wrote:\nHave you taken a look at this…\n\nI don't know if any one implementation of Win64 PHP is more authoratative or popular than another.\nI'm going to try following the steps in Kev's Enable FastCGI support in IIS7.0 article with file php-5.2.5-x64-2007-11-12.zip from fusion-x lan.\nIt's \"PHP Version 5.2.5 (x64)\", but according to php.net, the latest version is PHP 5.2.6. Oh, well.\n\n\nMake sure \"ISAPI Extensions\" are installed in IIS (mine were).\nDownload and then unzip php-5.2.5-x64-2007-11-12.zip\nCopy contents of folder php-5.2.5 (x64) into *C:\\php*\nCopy file C:\\php\\php.ini-dist into folder *C:\\Windows*\nRename file C:\\Windows\\php.ini-dist as php.ini\nEdit php.ini in Notepad. Remove leading semi-colon (;) from line:\n;extension=php_mysql.dll\n\nSave and close\nCopy file C:\\php\\ext\\php_mysql.dll into folder *C:\\Windows\\System32*\nWithin IIS Manager's \"Handler Mappings\", choose \"Add Script Map…\"\nRequest path: *.php\nExecutable: C:\\php\\php5isapi.dll\nName: PHP\n\nInstall MySQL (someone had already installed MySQL 5.0 for me).\nCreate file C:\\inetpub\\wwwroot\\test.php as\n<html>\n<head>\n<title>PHP Information</title>\n</head>\n<body>\n<?php phpInfo(); ?>\n</body>\n</html>\n\nNavigate to http://localhost/test.php in your web browser. You will see a page of information about PHP.\n\n\nRoadblock: How do I get PHP to work with ADOdb and MySQL?\n", "It's supposed to work via FastCGI. But I haven't had great success (using Vista). I can get PHP to run, but it crashes after a page loads (FastCGI does). So I'm modding you up. I'd like to see a reliable answer myself.\n", "From my experience with windows/apache it's just a matter of install MySQL, I can't Imagine that IIS/Apache has anything to do with this.\n", "Apache is a major pain to get running in Vista. And II7 (and 6) are suppose to run PHP fine. So why bother with Apache?\n", "I would suggest if you are going for a PHP and MySQL install to instead use WAMP. It works great and is easy to add extensions and modify everything. I use it for work and love it.\n", "One of the IIS developers has an excellent walkthrough here:\nhttp://blogs.iis.net/bills/archive/2006/10/31/PHP-on-IIS.aspx\nHowever, for the love of god why?\n" ]
[ 6, 2, 0, 0, 0, 0, 0 ]
[]
[]
[ "iis_7", "mysql", "php" ]
stackoverflow_0000011919_iis_7_mysql_php.txt
Q: How can you get database specific performance metrics for things like CPU/Memory/etc. in SQL Server 2005? I have a couple databases on a shared SQL Server 2005 cluster instance, that I would like performance metrics on. I have some processes that run for a very long time and suspect that code inefficiencies, rather than insufficient hardware are to blame. I would like some way to get these performance metrics so that I can rule out the database hardware as the culprit. A: That's tricky... you can use performance monitor to track hardware and OS factors - like CPU usage, memory; and also various SQL Server counters like queries per second. Obviously memory usage would tell you if you need more RAM, but it's not so easy to tell if (say) high CPU usage is due to the inefficient code, or just intensive code. Some of the counters are more helpful to drilling down into performance issues - things like locks in the DB can be counted, the problem is you cannot tell how many is too many because all code works differently. You can tell if you're experiencing far too many, or if periods of slowness equate to large counts. This applies to various of the other counters too - go and have a look what there is to view. The other thing to do is run a trace (sql server tools) to get a list of the queries that are run. Take a few of the slowest/biggest and see what execution plans come out when you run them - this would suggest you might optimise the queries, though it's down to you to decide if the code is inefficient or just as intensive as before. Lastly, get a tool like Spotlight that rolls a lot of database stats up and displays them to you in detail. A: I just read a great article on using windows built in typeperf.exe for just this issue. http://www.mssqltips.com/tip.asp?tip=1575 A: Ah, sounds like a job for SQL Profiler. http://msdn.microsoft.com/en-us/library/ms181091(SQL.90).aspx
How can you get database specific performance metrics for things like CPU/Memory/etc. in SQL Server 2005?
I have a couple databases on a shared SQL Server 2005 cluster instance, that I would like performance metrics on. I have some processes that run for a very long time and suspect that code inefficiencies, rather than insufficient hardware are to blame. I would like some way to get these performance metrics so that I can rule out the database hardware as the culprit.
[ "That's tricky... you can use performance monitor to track hardware and OS factors - like CPU usage, memory; and also various SQL Server counters like queries per second. Obviously memory usage would tell you if you need more RAM, but it's not so easy to tell if (say) high CPU usage is due to the inefficient code, or just intensive code.\nSome of the counters are more helpful to drilling down into performance issues - things like locks in the DB can be counted, the problem is you cannot tell how many is too many because all code works differently. You can tell if you're experiencing far too many, or if periods of slowness equate to large counts. This applies to various of the other counters too - go and have a look what there is to view.\nThe other thing to do is run a trace (sql server tools) to get a list of the queries that are run. Take a few of the slowest/biggest and see what execution plans come out when you run them - this would suggest you might optimise the queries, though it's down to you to decide if the code is inefficient or just as intensive as before.\nLastly, get a tool like Spotlight that rolls a lot of database stats up and displays them to you in detail.\n", "I just read a great article on using windows built in typeperf.exe for just this issue. http://www.mssqltips.com/tip.asp?tip=1575\n", "Ah, sounds like a job for SQL Profiler. \nhttp://msdn.microsoft.com/en-us/library/ms181091(SQL.90).aspx\n" ]
[ 1, 1, 1 ]
[]
[]
[ "optimization", "performance", "sql_server", "sql_server_2005" ]
stackoverflow_0000092696_optimization_performance_sql_server_sql_server_2005.txt
Q: C# string manipulation search and replace I have a string which contain tags in the form < tag >. Is there an easy way for me to programmatically replace instances of these tags with special ascii characters? e.g. replace a tag like "< tab >" with the ascii equivelent of '/t'? A: string s = "...<tab>..."; s = s.Replace("<tab>", "\t"); A: using System.Text.RegularExpressions; Regex.Replace(s, "TAB", "\t");//s is your string and TAB is a tab. A: public static Regex regex = new Regex("< tab >", RegexOptions.CultureInvariant | RegexOptions.Compiled); public static string regexReplace = "\t"; string result = regex.Replace(InputText,regexReplace); A: Regex patterns should do the trick.
C# string manipulation search and replace
I have a string which contain tags in the form < tag >. Is there an easy way for me to programmatically replace instances of these tags with special ascii characters? e.g. replace a tag like "< tab >" with the ascii equivelent of '/t'?
[ "string s = \"...<tab>...\";\ns = s.Replace(\"<tab>\", \"\\t\");\n\n", "using System.Text.RegularExpressions;\n\nRegex.Replace(s, \"TAB\", \"\\t\");//s is your string and TAB is a tab.\n\n", "public static Regex regex = new Regex(\"< tab >\", RegexOptions.CultureInvariant | RegexOptions.Compiled);\npublic static string regexReplace = \"\\t\";\nstring result = regex.Replace(InputText,regexReplace);\n\n", "Regex patterns should do the trick.\n" ]
[ 13, 2, 2, 1 ]
[]
[]
[ "c#", "regex", "string" ]
stackoverflow_0000094342_c#_regex_string.txt
Q: C++ Derived Class problems I am making a game in C++ and am having problems with my derived class. I have a base class called GameScreen which has a vitrual void draw() function with no statements. I also have a derived class called MenuScreen which also has a virtual void draw() function and a derived class from MenuScreen called TestMenu which also has a void draw() function. In my program I have a list of GameScreens that I have a GameScreen iterator pass through calling each GameScreens draw() function. The issue is that I have placed a TestMenu object on the GameScreen list. Instead of the iterator calling the draw() function of TestMenu it is calling the draw() function of the GameScreen class. Does anyone know how I could call the draw() function of TestMenu instead of the one in GameScreen. Here is the function: // Tell each screen to draw itself. //gsElement is a GameScreen iterator //gsScreens is a list of type GameScreen void Draw() { for (gsElement = gsScreens.begin(); gsElement != gsScreens.end(); gsElement++) { /*if (gsElement->ssState == Hidden) continue;*/ gsElement->Draw(); } } Here are a copy of my classes: class GameScreen { public: string strName; bool bIsPopup; bool bOtherScreenHasFocus; ScreenState ssState; //ScreenManager smScreenManager; GameScreen(string strName){ this->strName = strName; } //Determine if the screen should be drawn or not bool IsActive(){ return !bOtherScreenHasFocus && (ssState == Active); } //------------------------------------ //Load graphics content for the screen //------------------------------------ virtual void LoadContent(){ } //------------------------------------ //Unload content for the screen //------------------------------------ virtual void UnloadContent(){ } //------------------------------------------------------------------------- //Update changes whether the screen should be updated or not and sets //whether the screen should be drawn or not. // //Input: // bOtherScreenHasFocus - is used set whether the screen should update // bCoveredByOtherScreen - is used to set whether the screen is drawn or not //------------------------------------------------------------------------- virtual void Update(bool bOtherScreenHasFocus, bool bCoveredByOtherScreen){ this->bOtherScreenHasFocus = bOtherScreenHasFocus; //if the screen is covered by another than change the screen state to hidden //else set the screen state to active if(bCoveredByOtherScreen){ ssState = Hidden; } else{ ssState = Active; } } //----------------------------------------------------------- //Takes input from the mouse and calls appropriate actions //----------------------------------------------------------- virtual void HandleInput(){ } //---------------------- //Draw content on screen //---------------------- virtual void Draw(){ } //-------------------------------------- //Deletes screen from the screen manager //-------------------------------------- void ExitScreen(){ //smScreenManager.RemoveScreen(*this); } }; class MenuScreen: public GameScreen{ public: vector <BUTTON> vbtnMenuEntries; MenuScreen(string strName):GameScreen(strName){ } virtual void Update(bool bOtherScreenHasFocus, bool bCoveredByOtherScreen){ GameScreen::Update(bOtherScreenHasFocus, bCoveredByOtherScreen); for(unsigned int i = 0; i < vbtnMenuEntries.size(); i++){ vbtnMenuEntries[i].IsPressed(); } } virtual void Draw(){ GameScreen::Draw(); for(unsigned int i = 0; i < vbtnMenuEntries.size(); i++) vbtnMenuEntries[i].Draw(); } }; class testMenu : public MenuScreen{ public: vector<OBJECT> test; //OBJECT background3(); // OBJECT testPic(512, 384, buttonHover.png, 100, 40, 100, 40); // BUTTON x(256, 384, buttonNormal.png, buttonHover.png, buttonPressed.png, 100, 40, test()); bool draw; testMenu():MenuScreen("testMenu"){ OBJECT background3(1, 1, 0, TEXT("background.png"), 1, 1, 1024, 768); OBJECT testPic(512, 384,0, TEXT("buttonHover.png"), 1, 1, 100, 40); test.push_back(background3); test.push_back(testPic); //background3.Init(int xLoc, int yLoc, int zLoc, LPCTSTR filePath, int Rows, int Cols, int Width, int Height) //test.push_back(background3); // vbtnMenuEntries.push_back(x); draw = false; } void Update(bool bOtherScreenHasFocus, bool bCoveredByOtherScreen){ MenuScreen::Update(bOtherScreenHasFocus, bCoveredByOtherScreen); //cout << "X" << endl; /*if(MouseLButton == true){ testMenu2 t; smManager.AddScreen(t); }*/ } void Draw(){ //background3.Draw(); test[0].Draw(); test[1].Draw(); MenuScreen::Draw(); ///*if(draw){*/ // testPic.Draw(); //} } /*void test(){ draw = true; }*/ }; A: If gsScreens is a list of objects instead of a list of pointers (as your code suggests), then you're not storing what you think you're storing in it. What's happening is that -- instead of putting a TestMenu into the list, you're actually constructing a new MenuScreen using the compiler-generated copy constructor and putting this MenuScreen into the list. C++ is polymorphic through pointers, so if you don't have a pointer you won't get polymorphic behavior. A: To get the polymorphic behavior you're after and at the same time use a std::vector<>, you must store pointers to the base class type in the vector, instead of storing values. Also, you must remember to free their memory before the vector goes out of scope. For instance: #include <vector> #include <algorithm> struct Base { virtual void Foo() = 0; virtual ~Base() { } }; struct Derived1 : public Base { void Foo() { } }; struct Derived2 : public Base { void Foo() { } }; struct delete_ptr { template <typename T> void operator()(T& p) { delete p; p = 0; } }; int wmain(int, wchar_t*[]) { std::vector<Base*> items; items.push_back(new Derived1); items.push_back(new Derived2); Base& first = items.front(); first.Foo(); // Will boil down to Derived1::Foo(). Base& last = items.back(); last.Foo(); // Will boil down to Derived2::Foo(). std::for_each(items.begin(), items.end(), delete_ptr()) }; A: Curt is absolutely correct, but I'd just like to throw a little more information at it. This problem (storing base-class objects, rather than pointers) is sometimes called "slicing". Also, I tend to make use of the following macro: #define DISALLOW_COPYING(X) \ private: \ X(const X &); \ const X& operator= (const X& x) Then you put this somewhere in your class definition: class Foo { // ... DISALLOW_COPYING(Foo); }; If another class attempts to copy the object, you'll get a compiler error (because the methods are declared private). If the class itself attempts to copy the object, you'll get a linker error (because the methods have no implementation). A: Boost (www.boost.org, a library I would recommend anyone coding in C++ use) provides a noncopyable base class that does exactly that; you don't need an ugly macro that way.
C++ Derived Class problems
I am making a game in C++ and am having problems with my derived class. I have a base class called GameScreen which has a vitrual void draw() function with no statements. I also have a derived class called MenuScreen which also has a virtual void draw() function and a derived class from MenuScreen called TestMenu which also has a void draw() function. In my program I have a list of GameScreens that I have a GameScreen iterator pass through calling each GameScreens draw() function. The issue is that I have placed a TestMenu object on the GameScreen list. Instead of the iterator calling the draw() function of TestMenu it is calling the draw() function of the GameScreen class. Does anyone know how I could call the draw() function of TestMenu instead of the one in GameScreen. Here is the function: // Tell each screen to draw itself. //gsElement is a GameScreen iterator //gsScreens is a list of type GameScreen void Draw() { for (gsElement = gsScreens.begin(); gsElement != gsScreens.end(); gsElement++) { /*if (gsElement->ssState == Hidden) continue;*/ gsElement->Draw(); } } Here are a copy of my classes: class GameScreen { public: string strName; bool bIsPopup; bool bOtherScreenHasFocus; ScreenState ssState; //ScreenManager smScreenManager; GameScreen(string strName){ this->strName = strName; } //Determine if the screen should be drawn or not bool IsActive(){ return !bOtherScreenHasFocus && (ssState == Active); } //------------------------------------ //Load graphics content for the screen //------------------------------------ virtual void LoadContent(){ } //------------------------------------ //Unload content for the screen //------------------------------------ virtual void UnloadContent(){ } //------------------------------------------------------------------------- //Update changes whether the screen should be updated or not and sets //whether the screen should be drawn or not. // //Input: // bOtherScreenHasFocus - is used set whether the screen should update // bCoveredByOtherScreen - is used to set whether the screen is drawn or not //------------------------------------------------------------------------- virtual void Update(bool bOtherScreenHasFocus, bool bCoveredByOtherScreen){ this->bOtherScreenHasFocus = bOtherScreenHasFocus; //if the screen is covered by another than change the screen state to hidden //else set the screen state to active if(bCoveredByOtherScreen){ ssState = Hidden; } else{ ssState = Active; } } //----------------------------------------------------------- //Takes input from the mouse and calls appropriate actions //----------------------------------------------------------- virtual void HandleInput(){ } //---------------------- //Draw content on screen //---------------------- virtual void Draw(){ } //-------------------------------------- //Deletes screen from the screen manager //-------------------------------------- void ExitScreen(){ //smScreenManager.RemoveScreen(*this); } }; class MenuScreen: public GameScreen{ public: vector <BUTTON> vbtnMenuEntries; MenuScreen(string strName):GameScreen(strName){ } virtual void Update(bool bOtherScreenHasFocus, bool bCoveredByOtherScreen){ GameScreen::Update(bOtherScreenHasFocus, bCoveredByOtherScreen); for(unsigned int i = 0; i < vbtnMenuEntries.size(); i++){ vbtnMenuEntries[i].IsPressed(); } } virtual void Draw(){ GameScreen::Draw(); for(unsigned int i = 0; i < vbtnMenuEntries.size(); i++) vbtnMenuEntries[i].Draw(); } }; class testMenu : public MenuScreen{ public: vector<OBJECT> test; //OBJECT background3(); // OBJECT testPic(512, 384, buttonHover.png, 100, 40, 100, 40); // BUTTON x(256, 384, buttonNormal.png, buttonHover.png, buttonPressed.png, 100, 40, test()); bool draw; testMenu():MenuScreen("testMenu"){ OBJECT background3(1, 1, 0, TEXT("background.png"), 1, 1, 1024, 768); OBJECT testPic(512, 384,0, TEXT("buttonHover.png"), 1, 1, 100, 40); test.push_back(background3); test.push_back(testPic); //background3.Init(int xLoc, int yLoc, int zLoc, LPCTSTR filePath, int Rows, int Cols, int Width, int Height) //test.push_back(background3); // vbtnMenuEntries.push_back(x); draw = false; } void Update(bool bOtherScreenHasFocus, bool bCoveredByOtherScreen){ MenuScreen::Update(bOtherScreenHasFocus, bCoveredByOtherScreen); //cout << "X" << endl; /*if(MouseLButton == true){ testMenu2 t; smManager.AddScreen(t); }*/ } void Draw(){ //background3.Draw(); test[0].Draw(); test[1].Draw(); MenuScreen::Draw(); ///*if(draw){*/ // testPic.Draw(); //} } /*void test(){ draw = true; }*/ };
[ "If gsScreens is a list of objects instead of a list of pointers (as your code suggests), then you're not storing what you think you're storing in it.\nWhat's happening is that -- instead of putting a TestMenu into the list, you're actually constructing a new MenuScreen using the compiler-generated copy constructor and putting this MenuScreen into the list.\nC++ is polymorphic through pointers, so if you don't have a pointer you won't get polymorphic behavior.\n", "To get the polymorphic behavior you're after and at the same time use a std::vector<>, you must store pointers to the base class type in the vector, instead of storing values. Also, you must remember to free their memory before the vector goes out of scope.\nFor instance:\n#include <vector>\n#include <algorithm>\n\nstruct Base\n{\n virtual void Foo() = 0;\n virtual ~Base() { }\n};\n\nstruct Derived1 : public Base\n{\n void Foo() { }\n};\n\nstruct Derived2 : public Base\n{\n void Foo() { }\n};\n\nstruct delete_ptr\n{\n template <typename T>\n void operator()(T& p)\n {\n delete p;\n p = 0;\n }\n};\n\nint wmain(int, wchar_t*[])\n{\n std::vector<Base*> items;\n items.push_back(new Derived1);\n items.push_back(new Derived2);\n\n Base& first = items.front();\n first.Foo(); // Will boil down to Derived1::Foo().\n\n Base& last = items.back();\n last.Foo(); // Will boil down to Derived2::Foo().\n\n std::for_each(items.begin(), items.end(), delete_ptr())\n};\n\n", "Curt is absolutely correct, but I'd just like to throw a little more information at it.\nThis problem (storing base-class objects, rather than pointers) is sometimes called \"slicing\".\nAlso, I tend to make use of the following macro:\n#define DISALLOW_COPYING(X) \\\n private: \\\n X(const X &); \\\n const X& operator= (const X& x)\n\nThen you put this somewhere in your class definition:\nclass Foo {\n // ...\n DISALLOW_COPYING(Foo);\n};\n\nIf another class attempts to copy the object, you'll get a compiler error (because the methods are declared private). If the class itself attempts to copy the object, you'll get a linker error (because the methods have no implementation).\n", "Boost (www.boost.org, a library I would recommend anyone coding in C++ use) provides a noncopyable base class that does exactly that; you don't need an ugly macro that way.\n" ]
[ 9, 1, 0, 0 ]
[]
[]
[ "c++", "inheritance" ]
stackoverflow_0000088558_c++_inheritance.txt
Q: Bit manipulation and output in Java If you have binary strings (literally String objects that contain only 1's and 0's), how would you output them as bits into a file? This is for a text compressor I was working on; it's still bugging me, and it'd be nice to finally get it working. Thanks! A: Easiest is to simply take 8 consecutive characters, turn them into a byte and output that byte. Pad with zeros at the end if you can recognize the end-of-stream, or add a header with length (in bits) at the beginning of the file. The inner loop would look something like: byte[] buffer = new byte[ ( string.length + 7 ) / 8 ]; for ( int i = 0; i < buffer.length; ++i ) { byte current = 0; for ( int j = 7; j >= 0; --j ) if ( string[ i * 8 + j ] == '1' ) current |= 1 << j; output( current ); } You'll need to make some adjustments, but that's the general idea. A: If you're lucky, java.math.BigInteger may do everything for you. String s = "11001010001010101110101001001110"; byte[] bytes = (new java.math.BigInteger(s, 2)).toByteArray(); This does depend on the byte order (big-endian) and right-aligning (if the number of bits is not a multiple of 8) being what you want but it may be simpler to modify the array afterwards than to do the character conversion yourself. A: public class BitOutputStream extends FilterOutputStream { private int buffer = 0; private int bitCount = 0; public BitOutputStream(OutputStream out) { super(out); } public void writeBits(int value, int numBits) throws IOException { while(numBits>0) { numBits--; int mix = ((value&1)<<bitCount++); buffer|=mix; value>>=1; if(bitCount==8) align8(); } } @Override public void close() throws IOException { align8(); /* Flush any remaining partial bytes */ super.close(); } public void align8() throws IOException { if(bitCount > 0) { bitCount=0; write(buffer); buffer=0; } } } And then... if (nextChar == '0') { bos.writeBits(0, 1); } else { bos.writeBits(1, 1); } A: Assuming the String has a multiple of eight bits, (you can pad it otherwise), take advantage of Java's built in parsing in the Integer.valueOf method to do something like this: String s = "11001010001010101110101001001110"; byte[] data = new byte[s.length() / 8]; for (int i = 0; i < data.length; i++) { data[i] = (byte) Integer.parseInt(s.substring(i * 8, (i + 1) * 8), 2); } Then you should be able to write the bytes to a FileOutputStream pretty simply. On the other hand, if you looking for effeciency, you should consider not using a String to store the bits to begin with, but build up the bytes directly in your compressor.
Bit manipulation and output in Java
If you have binary strings (literally String objects that contain only 1's and 0's), how would you output them as bits into a file? This is for a text compressor I was working on; it's still bugging me, and it'd be nice to finally get it working. Thanks!
[ "Easiest is to simply take 8 consecutive characters, turn them into a byte and output that byte. Pad with zeros at the end if you can recognize the end-of-stream, or add a header with length (in bits) at the beginning of the file.\nThe inner loop would look something like:\n\nbyte[] buffer = new byte[ ( string.length + 7 ) / 8 ];\nfor ( int i = 0; i < buffer.length; ++i ) {\n byte current = 0;\n for ( int j = 7; j >= 0; --j )\n if ( string[ i * 8 + j ] == '1' )\n current |= 1 << j;\n output( current );\n}\n\nYou'll need to make some adjustments, but that's the general idea.\n", "If you're lucky, java.math.BigInteger may do everything for you.\nString s = \"11001010001010101110101001001110\";\nbyte[] bytes = (new java.math.BigInteger(s, 2)).toByteArray();\n\nThis does depend on the byte order (big-endian) and right-aligning (if the number of bits is not a multiple of 8) being what you want but it may be simpler to modify the array afterwards than to do the character conversion yourself.\n", "public class BitOutputStream extends FilterOutputStream\n{\n private int buffer = 0;\n private int bitCount = 0;\n\n public BitOutputStream(OutputStream out)\n {\n super(out);\n }\n\n public void writeBits(int value, int numBits) throws IOException\n {\n while(numBits>0)\n {\n numBits--;\n int mix = ((value&1)<<bitCount++);\n buffer|=mix;\n value>>=1;\n if(bitCount==8)\n align8();\n }\n }\n\n @Override\n public void close() throws IOException\n {\n align8(); /* Flush any remaining partial bytes */\n super.close();\n }\n\n public void align8() throws IOException\n {\n if(bitCount > 0)\n {\n bitCount=0;\n write(buffer);\n buffer=0;\n }\n }\n}\n\nAnd then...\nif (nextChar == '0')\n{\n bos.writeBits(0, 1);\n}\nelse\n{\n bos.writeBits(1, 1);\n}\n\n", "Assuming the String has a multiple of eight bits, (you can pad it otherwise), take advantage of Java's built in parsing in the Integer.valueOf method to do something like this:\nString s = \"11001010001010101110101001001110\";\nbyte[] data = new byte[s.length() / 8];\nfor (int i = 0; i < data.length; i++) {\n data[i] = (byte) Integer.parseInt(s.substring(i * 8, (i + 1) * 8), 2);\n}\n\nThen you should be able to write the bytes to a FileOutputStream pretty simply.\nOn the other hand, if you looking for effeciency, you should consider not using a String to store the bits to begin with, but build up the bytes directly in your compressor.\n" ]
[ 6, 6, 2, 1 ]
[]
[]
[ "bit_manipulation", "java" ]
stackoverflow_0000093839_bit_manipulation_java.txt
Q: How to switch back to a previous version of a file without deleting its subsequent revisions? I have 4 versions of file A.txt in my subversion repository, say: A.txt.r1, A.txt.r2, A.txt.r3 and A.txt.r4. My working copy of the file is r4 and I want to switch back to r2. I don't want to use "svn update -r 2 A.txt" because this will delete all the revisions after r2, namely r3 and r4. So is there any way that I update my working copy to r2 and still having the option to switch to r3 and r4 later? Put it another way, I want to still be able to see all 4 revisions by using "svn log A.txt" after doing the update. A: To make a new revision of A.txt that is equal to revision 2: svn up -r HEAD svn merge -r HEAD:2 A.txt svn commit Also see the description in Undoing changes. A: The command svn up -r 4 only updates your local copy to revision 4. The server still has all versions 1 through to whatever. What you want to do, is create a new revision, revision number 5, which is identical to revision number 2. cd /repo svn up -r 2 cp /repo/file /tmp/file_2 svn up -r 4 cp /tmp/file_2 /repo/file svn commit -m "Making 5 from 2" If you ever change your mind and want 4 back, you can do so by creating revision 6 from revision 4. cd /repo svn up -r 4 cp /repo/file /tmp/file_4 svn up -r 5 cp /tmp/file_4 /repo/file svn commit -m "Making 6 from 4" Happy hacking. ( there is of course a way to do the above in only 2 commands i believe, but its been a while since I did it and it can be a little confusing ) A: I don't have a lot of experience with Subversion so please excuse me if this method doesn't work in this environment. In this situation I follow these steps: Check out the file in question ready for editing as r4 Overwrite your local copy of the file with the revision you require, in this case r2 Check in / commit this "new" revision of the file as r5 with an appropriate comment This way when you go through your file history you will see something like: r1 r2 r3 r4 r5 (comment: "reverted to r2 content") A: svn update -r 2 A.txt This command will not delete any versions in the repository. It will set your working copy of A.txt to be revision 2. You can see this by doing > svn status -u A.txt * 2 A.txt The output of this command show that you are viewing version 2, and that there are updates (that's the *). After doing this update, you will still be able to do "svn log" and see all the revisions. Performing "svn update A.txt" will return you to the latest version (in your case, r4). A: updating to an older rev will not delete your newer revs. so you could do svn up -r2 file, then svn up -r4 file. also, you wouldn't be able to commit the r2 file this way, because you'd have to update before committing, and you'd end up with r4 again. A: "I don't want to use "svn update -r 2 A.txt" because this will delete all the revisions after r2, namely r3 and r4." Uh... it won't, actually. Try it: do a regular svn update after the -r 2 one and you'll see the working copy updated back to r4. A: Update won't delete any revisions on the server. The only changes it makes are to your local working copy: SVN Update Command "brings changes from the repository into your working copy" "synchronizes the working copy to the revision given by the --revision switch"
How to switch back to a previous version of a file without deleting its subsequent revisions?
I have 4 versions of file A.txt in my subversion repository, say: A.txt.r1, A.txt.r2, A.txt.r3 and A.txt.r4. My working copy of the file is r4 and I want to switch back to r2. I don't want to use "svn update -r 2 A.txt" because this will delete all the revisions after r2, namely r3 and r4. So is there any way that I update my working copy to r2 and still having the option to switch to r3 and r4 later? Put it another way, I want to still be able to see all 4 revisions by using "svn log A.txt" after doing the update.
[ "To make a new revision of A.txt that is equal to revision 2:\nsvn up -r HEAD\nsvn merge -r HEAD:2 A.txt\nsvn commit\n\nAlso see the description in Undoing changes.\n", "The command svn up -r 4 only updates your local copy to revision 4. \nThe server still has all versions 1 through to whatever. \nWhat you want to do, is create a new revision, revision number 5, which is identical to revision number 2. \ncd /repo \nsvn up -r 2 \ncp /repo/file /tmp/file_2 \nsvn up -r 4 \ncp /tmp/file_2 /repo/file \nsvn commit -m \"Making 5 from 2\" \n\nIf you ever change your mind and want 4 back, you can do so by creating revision 6 from revision 4. \ncd /repo \nsvn up -r 4\ncp /repo/file /tmp/file_4\nsvn up -r 5 \ncp /tmp/file_4 /repo/file \nsvn commit -m \"Making 6 from 4\" \n\nHappy hacking.\n( there is of course a way to do the above in only 2 commands i believe, but its been a while since I did it and it can be a little confusing )\n", "I don't have a lot of experience with Subversion so please excuse me if this method doesn't work in this environment.\nIn this situation I follow these steps:\n\nCheck out the file in question ready for editing as r4\nOverwrite your local copy of the file with the revision you require, in this case r2\nCheck in / commit this \"new\" revision of the file as r5 with an appropriate comment\n\nThis way when you go through your file history you will see something like:\n\nr1\nr2\nr3\nr4\nr5 (comment: \"reverted to r2 content\")\n\n", "svn update -r 2 A.txt\n\nThis command will not delete any versions in the repository. It will set your working copy of A.txt to be revision 2. You can see this by doing\n> svn status -u A.txt\n * 2 A.txt\n\nThe output of this command show that you are viewing version 2, and that there are updates (that's the *).\nAfter doing this update, you will still be able to do \"svn log\" and see all the revisions.\nPerforming \"svn update A.txt\" will return you to the latest version (in your case, r4). \n", "updating to an older rev will not delete your newer revs.\nso you could do svn up -r2 file, then svn up -r4 file.\nalso, you wouldn't be able to commit the r2 file this way, because you'd have to update before committing, and you'd end up with r4 again.\n", "\n\"I don't want to use \"svn update -r 2 A.txt\" because this will delete all the revisions after r2, namely r3 and r4.\"\n\nUh... it won't, actually. Try it: do a regular svn update after the -r 2 one and you'll see the working copy updated back to r4.\n", "Update won't delete any revisions on the server. The only changes it makes are to your local working copy:\nSVN Update Command\n\"brings changes from the repository into your working copy\"\n\"synchronizes the working copy to the revision given by the --revision switch\"\n" ]
[ 26, 10, 3, 3, 2, 2, 1 ]
[]
[]
[ "svn" ]
stackoverflow_0000094226_svn.txt
Q: Why does StatSVN fail, claiming the directory is not a working copy? I have a working copy of my project, checked out using Subversion 1.5.1. When I attempt to run StatSVN against it, I get the following error: Sep 18, 2008 12:25:22 PM net.sf.statsvn.util.JavaUtilTaskLogger info INFO: StatSVN - SVN statistics generation Sep 18, 2008 12:25:22 PM net.sf.statsvn.util.JavaUtilTaskLogger info INFO: svn: '.' is not a working copy Sep 18, 2008 12:25:22 PM net.sf.statsvn.util.JavaUtilTaskLogger error SEVERE: Repository root not available - verify that the project was checked out with svn version 1.3.0 or above. Has anyone experienced this? I've seen suggestions it might be related to using a locale other than en_US, but I am using en_US. A: Just guessing here, but are you sure that statSVN is compatible with working copies created with version 1.5 of the client? The format changed with svn 1.5... A: @agnul You were right. Here's the relevant feature request from their bugzilla.
Why does StatSVN fail, claiming the directory is not a working copy?
I have a working copy of my project, checked out using Subversion 1.5.1. When I attempt to run StatSVN against it, I get the following error: Sep 18, 2008 12:25:22 PM net.sf.statsvn.util.JavaUtilTaskLogger info INFO: StatSVN - SVN statistics generation Sep 18, 2008 12:25:22 PM net.sf.statsvn.util.JavaUtilTaskLogger info INFO: svn: '.' is not a working copy Sep 18, 2008 12:25:22 PM net.sf.statsvn.util.JavaUtilTaskLogger error SEVERE: Repository root not available - verify that the project was checked out with svn version 1.3.0 or above. Has anyone experienced this? I've seen suggestions it might be related to using a locale other than en_US, but I am using en_US.
[ "Just guessing here, but are you sure that statSVN is compatible with working copies created with version 1.5 of the client? The format changed with svn 1.5...\n", "@agnul\nYou were right. Here's the relevant feature request from their bugzilla.\n" ]
[ 2, 0 ]
[]
[]
[ "statsvn", "svn" ]
stackoverflow_0000094178_statsvn_svn.txt
Q: Windows Form with Resizing Frame and no Title Bar? How can I hide the title bar from a Windows Form but still have a Resizing Frame? A: Setting FormBorderStyle = None will remove the title bar (at both design and run time) - and also remove your ability to resize the form. If you need a border you can set: ControlBox = false Text = "" A: Set the ControlBox property of the form to False, and the Text property to empty string. The form will open with no perceivable (to the user) title bar, but they will be able to resize the form.
Windows Form with Resizing Frame and no Title Bar?
How can I hide the title bar from a Windows Form but still have a Resizing Frame?
[ "Setting FormBorderStyle = None will remove the title bar (at both design and\nrun time) - and also remove your ability to resize the form.\nIf you need a border you can set:\nControlBox = false\nText = \"\"\n\n", "Set the ControlBox property of the form to False, and the Text property to empty string. The form will open with no perceivable (to the user) title bar, but they will be able to resize the form.\n" ]
[ 12, 2 ]
[]
[]
[ "c#", "resize", "titlebar", "visual_studio", "winforms" ]
stackoverflow_0000093716_c#_resize_titlebar_visual_studio_winforms.txt