question_id
int64
4
6.31M
answer_id
int64
7
6.31M
title
stringlengths
9
150
question_body
stringlengths
0
28.8k
answer_body
stringlengths
60
27.2k
question_text
stringlengths
40
28.9k
combined_text
stringlengths
124
39.6k
tags
listlengths
1
6
question_score
int64
0
26.3k
answer_score
int64
0
28.8k
view_count
int64
15
14M
answer_count
int64
0
182
favorite_count
int64
0
32
question_creation_date
stringdate
2008-07-31 21:42:52
2011-06-10 18:12:18
answer_creation_date
stringdate
2008-07-31 22:17:57
2011-06-10 18:14:17
49,724
49,773
Programmatically extract macro (VBA) code from Word 2007 docs
Is it possible to extract all of the VBA code from a Word 2007 "docm" document using the API? I have found how to insert VBA code at runtime, and how to delete all VBA code, but not pull the actual code out into a stream or string that I can store (and insert into other documents in the future). Any tips or resources would be appreciated. Edit: thanks to everyone, Aardvark 's answer was exactly what I was looking for. I have converted his code to C#, and was able to call it from a class library using Visual Studio 2008. using Microsoft.Office.Interop.Word; using Microsoft.Vbe.Interop;... public List GetMacrosFromDoc() { Document doc = GetWordDoc(@"C:\Temp\test.docm"); List macros = new List (); VBProject prj; CodeModule code; string composedFile; prj = doc.VBProject; foreach (VBComponent comp in prj.VBComponents) { code = comp.CodeModule; // Put the name of the code module at the top composedFile = comp.Name + Environment.NewLine; // Loop through the (1-indexed) lines for (int i = 0; i < code.CountOfLines; i++) { composedFile += code.get_Lines(i + 1, 1) + Environment.NewLine; } // Add the macro to the list macros.Add(composedFile); } CloseDoc(doc); return macros; }
You'll have to add a reference to Microsoft Visual Basic for Applications Extensibility 5.3 (or whatever version you have). I have the VBA SDK and such on my box - so this may not be exactly what office ships with. Also you have to enable access to the VBA Object Model specifically - see the "Trust Center" in Word options. This is in addition to all the other Macro security settings Office provides. This example will extract code from the current document it lives in - it itself is a VBA macro (and will display itself and any other code as well). There is also a Application.vbe.VBProjects collection to access other documents. While I've never done it, I assume an external application could get to open files using this VBProjects collection as well. Security is funny with this stuff so it may be tricky. I also wonder what the docm file format is now - XML like the docx? Would that be a better approach? Sub GetCode() Dim prj As VBProject Dim comp As VBComponent Dim code As CodeModule Dim composedFile As String Dim i As Integer Set prj = ThisDocument.VBProject For Each comp In prj.VBComponents Set code = comp.CodeModule composedFile = comp.Name & vbNewLine For i = 1 To code.CountOfLines composedFile = composedFile & code.Lines(i, 1) & vbNewLine Next MsgBox composedFile Next End Sub
Programmatically extract macro (VBA) code from Word 2007 docs Is it possible to extract all of the VBA code from a Word 2007 "docm" document using the API? I have found how to insert VBA code at runtime, and how to delete all VBA code, but not pull the actual code out into a stream or string that I can store (and insert into other documents in the future). Any tips or resources would be appreciated. Edit: thanks to everyone, Aardvark 's answer was exactly what I was looking for. I have converted his code to C#, and was able to call it from a class library using Visual Studio 2008. using Microsoft.Office.Interop.Word; using Microsoft.Vbe.Interop;... public List GetMacrosFromDoc() { Document doc = GetWordDoc(@"C:\Temp\test.docm"); List macros = new List (); VBProject prj; CodeModule code; string composedFile; prj = doc.VBProject; foreach (VBComponent comp in prj.VBComponents) { code = comp.CodeModule; // Put the name of the code module at the top composedFile = comp.Name + Environment.NewLine; // Loop through the (1-indexed) lines for (int i = 0; i < code.CountOfLines; i++) { composedFile += code.get_Lines(i + 1, 1) + Environment.NewLine; } // Add the macro to the list macros.Add(composedFile); } CloseDoc(doc); return macros; }
TITLE: Programmatically extract macro (VBA) code from Word 2007 docs QUESTION: Is it possible to extract all of the VBA code from a Word 2007 "docm" document using the API? I have found how to insert VBA code at runtime, and how to delete all VBA code, but not pull the actual code out into a stream or string that I can store (and insert into other documents in the future). Any tips or resources would be appreciated. Edit: thanks to everyone, Aardvark 's answer was exactly what I was looking for. I have converted his code to C#, and was able to call it from a class library using Visual Studio 2008. using Microsoft.Office.Interop.Word; using Microsoft.Vbe.Interop;... public List GetMacrosFromDoc() { Document doc = GetWordDoc(@"C:\Temp\test.docm"); List macros = new List (); VBProject prj; CodeModule code; string composedFile; prj = doc.VBProject; foreach (VBComponent comp in prj.VBComponents) { code = comp.CodeModule; // Put the name of the code module at the top composedFile = comp.Name + Environment.NewLine; // Loop through the (1-indexed) lines for (int i = 0; i < code.CountOfLines; i++) { composedFile += code.get_Lines(i + 1, 1) + Environment.NewLine; } // Add the macro to the list macros.Add(composedFile); } CloseDoc(doc); return macros; } ANSWER: You'll have to add a reference to Microsoft Visual Basic for Applications Extensibility 5.3 (or whatever version you have). I have the VBA SDK and such on my box - so this may not be exactly what office ships with. Also you have to enable access to the VBA Object Model specifically - see the "Trust Center" in Word options. This is in addition to all the other Macro security settings Office provides. This example will extract code from the current document it lives in - it itself is a VBA macro (and will display itself and any other code as well). There is also a Application.vbe.VBProjects collection to access other documents. While I've never done it, I assume an external application could get to open files using this VBProjects collection as well. Security is funny with this stuff so it may be tricky. I also wonder what the docm file format is now - XML like the docx? Would that be a better approach? Sub GetCode() Dim prj As VBProject Dim comp As VBComponent Dim code As CodeModule Dim composedFile As String Dim i As Integer Set prj = ThisDocument.VBProject For Each comp In prj.VBComponents Set code = comp.CodeModule composedFile = comp.Name & vbNewLine For i = 1 To code.CountOfLines composedFile = composedFile & code.Lines(i, 1) & vbNewLine Next MsgBox composedFile Next End Sub
[ ".net", "automation", "ms-office" ]
16
11
17,123
2
0
2008-09-08T13:39:24.033000
2008-09-08T14:08:09.270000
49,732
49,746
Is automatic upgrades a realistic feature to expect from enterprise Web applications?
Most of the work I do is with what could be considered enterprise Web applications. These projects have large budgets, longer timelines (from 3-12 months), and heavy customizations. Because as developers we have been touting the idea of the Web as the next desktop OS, customers are coming to expect the software running on this "new OS" to react the same as on the desktop. That includes easy to manage automatic upgrades. In other words, "An update is available. Do you want to upgrade?" Is this even a realistic expectation? Can anyone speak from experience on trying to implement this feature?
At my company we have enterprise installations ranging into the thousands of seats. If we implemented an auto-upgrade, our customers would mutiny! Large installations have peculiar issues that don't apply to small ones. For example, with 2000 users (not all of whom are, let us say, the most sophisticated of tool users), tool-training is a big deal: training time, internal demos, internal process documents, etc.. They cannot unleash a new feature or UI change without a chance to understand how it fits in their process and therefore what their internal best practices are and how to communicate that to their users. Also when applications fail, it's the internal IT team who are responsible. Therefore, they want time to install a new version in a test area, beat it up, and deploy on a Saturday only when they're good and ready. I can see the value in making minor patches more easy to install, particularly when the patch is just for a bug-fix and not for anything that would require retraining, and if the admins still get final say over when it's installed. But even then, I don't believe anyone has ever asked for this! Whether because they don't want it or they are trained to not expect it, it doesn't seem worth it.
Is automatic upgrades a realistic feature to expect from enterprise Web applications? Most of the work I do is with what could be considered enterprise Web applications. These projects have large budgets, longer timelines (from 3-12 months), and heavy customizations. Because as developers we have been touting the idea of the Web as the next desktop OS, customers are coming to expect the software running on this "new OS" to react the same as on the desktop. That includes easy to manage automatic upgrades. In other words, "An update is available. Do you want to upgrade?" Is this even a realistic expectation? Can anyone speak from experience on trying to implement this feature?
TITLE: Is automatic upgrades a realistic feature to expect from enterprise Web applications? QUESTION: Most of the work I do is with what could be considered enterprise Web applications. These projects have large budgets, longer timelines (from 3-12 months), and heavy customizations. Because as developers we have been touting the idea of the Web as the next desktop OS, customers are coming to expect the software running on this "new OS" to react the same as on the desktop. That includes easy to manage automatic upgrades. In other words, "An update is available. Do you want to upgrade?" Is this even a realistic expectation? Can anyone speak from experience on trying to implement this feature? ANSWER: At my company we have enterprise installations ranging into the thousands of seats. If we implemented an auto-upgrade, our customers would mutiny! Large installations have peculiar issues that don't apply to small ones. For example, with 2000 users (not all of whom are, let us say, the most sophisticated of tool users), tool-training is a big deal: training time, internal demos, internal process documents, etc.. They cannot unleash a new feature or UI change without a chance to understand how it fits in their process and therefore what their internal best practices are and how to communicate that to their users. Also when applications fail, it's the internal IT team who are responsible. Therefore, they want time to install a new version in a test area, beat it up, and deploy on a Saturday only when they're good and ready. I can see the value in making minor patches more easy to install, particularly when the patch is just for a bug-fix and not for anything that would require retraining, and if the admins still get final say over when it's installed. But even then, I don't believe anyone has ever asked for this! Whether because they don't want it or they are trained to not expect it, it doesn't seem worth it.
[ "upgrade", "enterprise" ]
4
2
174
4
0
2008-09-08T13:42:48.770000
2008-09-08T13:51:28.827000
49,737
49,771
Use-cases for reflection
Recently I was talking to a co-worker about C++ and lamented that there was no way to take a string with the name of a class field and extract the field with that name; in other words, it lacks reflection. He gave me a baffled look and asked when anyone would ever need to do such a thing. Off the top of my head I didn't have a good answer for him, other than "hey, I need to do it right now". So I sat down and came up with a list of some of the things I've actually done with reflection in various languages. Unfortunately, most of my examples come from my web programming in Python, and I was hoping that the people here would have more examples. Here's the list I came up with: Given a config file with lines like x = "Hello World!" y = 5.0 dynamically set the fields of some config object equal to the values in that file. (This was what I wished I could do in C++, but actually couldn't do.) When sorting a list of objects, sort based on an arbitrary attribute given that attribute's name from a config file or web request. When writing software that uses a network protocol, reflection lets you call methods based on string values from that protocol. For example, I wrote an IRC bot that would translate!some_command arg1 arg2 into a method call actions.some_command(arg1, arg2) and print whatever that function returned back to the IRC channel. When using Python's __getattr__ function (which is sort of like method_missing in Ruby/Smalltalk) I was working with a class with a whole lot of statistics, such as late_total. For every statistic, I wanted to be able to add _percent to get that statistic as a percentage of the total things I was counting (for example, stats.late_total_percent). Reflection made this very easy. So can anyone here give any examples from their own programming experiences of times when reflection has been helpful? The next time a co-worker asks me why I'd "ever want to do something like that" I'd like to be more prepared.
I can list following usage for reflection: Late binding Security (introspect code for security reasons) Code analysis Dynamic typing (duck typing is not possible without reflection) Metaprogramming Some real-world usages of reflection from my personal experience: Developed plugin system based on reflection Used aspect-oriented programming model Performed static code analysis Used various Dependency Injection frameworks... Reflection is good thing:)
Use-cases for reflection Recently I was talking to a co-worker about C++ and lamented that there was no way to take a string with the name of a class field and extract the field with that name; in other words, it lacks reflection. He gave me a baffled look and asked when anyone would ever need to do such a thing. Off the top of my head I didn't have a good answer for him, other than "hey, I need to do it right now". So I sat down and came up with a list of some of the things I've actually done with reflection in various languages. Unfortunately, most of my examples come from my web programming in Python, and I was hoping that the people here would have more examples. Here's the list I came up with: Given a config file with lines like x = "Hello World!" y = 5.0 dynamically set the fields of some config object equal to the values in that file. (This was what I wished I could do in C++, but actually couldn't do.) When sorting a list of objects, sort based on an arbitrary attribute given that attribute's name from a config file or web request. When writing software that uses a network protocol, reflection lets you call methods based on string values from that protocol. For example, I wrote an IRC bot that would translate!some_command arg1 arg2 into a method call actions.some_command(arg1, arg2) and print whatever that function returned back to the IRC channel. When using Python's __getattr__ function (which is sort of like method_missing in Ruby/Smalltalk) I was working with a class with a whole lot of statistics, such as late_total. For every statistic, I wanted to be able to add _percent to get that statistic as a percentage of the total things I was counting (for example, stats.late_total_percent). Reflection made this very easy. So can anyone here give any examples from their own programming experiences of times when reflection has been helpful? The next time a co-worker asks me why I'd "ever want to do something like that" I'd like to be more prepared.
TITLE: Use-cases for reflection QUESTION: Recently I was talking to a co-worker about C++ and lamented that there was no way to take a string with the name of a class field and extract the field with that name; in other words, it lacks reflection. He gave me a baffled look and asked when anyone would ever need to do such a thing. Off the top of my head I didn't have a good answer for him, other than "hey, I need to do it right now". So I sat down and came up with a list of some of the things I've actually done with reflection in various languages. Unfortunately, most of my examples come from my web programming in Python, and I was hoping that the people here would have more examples. Here's the list I came up with: Given a config file with lines like x = "Hello World!" y = 5.0 dynamically set the fields of some config object equal to the values in that file. (This was what I wished I could do in C++, but actually couldn't do.) When sorting a list of objects, sort based on an arbitrary attribute given that attribute's name from a config file or web request. When writing software that uses a network protocol, reflection lets you call methods based on string values from that protocol. For example, I wrote an IRC bot that would translate!some_command arg1 arg2 into a method call actions.some_command(arg1, arg2) and print whatever that function returned back to the IRC channel. When using Python's __getattr__ function (which is sort of like method_missing in Ruby/Smalltalk) I was working with a class with a whole lot of statistics, such as late_total. For every statistic, I wanted to be able to add _percent to get that statistic as a percentage of the total things I was counting (for example, stats.late_total_percent). Reflection made this very easy. So can anyone here give any examples from their own programming experiences of times when reflection has been helpful? The next time a co-worker asks me why I'd "ever want to do something like that" I'd like to be more prepared. ANSWER: I can list following usage for reflection: Late binding Security (introspect code for security reasons) Code analysis Dynamic typing (duck typing is not possible without reflection) Metaprogramming Some real-world usages of reflection from my personal experience: Developed plugin system based on reflection Used aspect-oriented programming model Performed static code analysis Used various Dependency Injection frameworks... Reflection is good thing:)
[ "reflection" ]
26
23
11,305
9
0
2008-09-08T13:46:43.330000
2008-09-08T14:08:02.733000
49,747
49,817
Autoupdating .net applications
I've written 2 reasonably large scale apps in.net so far, and both of them have needed an updating facility to automatically update the application when I roll out new code. I've found the 'Enterprise application block updater' a bit too complex for my needs, and I've found 'click once' frustrating when it comes to publishing. The most adequate updating code I've found is the.net Application Updater Component, which I've used for both projects. I've had to modify it recently because it uses web dav, which isn't always installed on our web servers (it still needs directory browsing, however). I'm surprised that there isn't more on the web about automatically updating applications, and was wondering whether people have had success with any other methods than the ones mentioned above?
See the answers to this similar question: a few auto-update frameworks were recommended there which are designed for (or work with).net apps: Application Updater Block (which you mention) ClickOnce, ClickThrough
Autoupdating .net applications I've written 2 reasonably large scale apps in.net so far, and both of them have needed an updating facility to automatically update the application when I roll out new code. I've found the 'Enterprise application block updater' a bit too complex for my needs, and I've found 'click once' frustrating when it comes to publishing. The most adequate updating code I've found is the.net Application Updater Component, which I've used for both projects. I've had to modify it recently because it uses web dav, which isn't always installed on our web servers (it still needs directory browsing, however). I'm surprised that there isn't more on the web about automatically updating applications, and was wondering whether people have had success with any other methods than the ones mentioned above?
TITLE: Autoupdating .net applications QUESTION: I've written 2 reasonably large scale apps in.net so far, and both of them have needed an updating facility to automatically update the application when I roll out new code. I've found the 'Enterprise application block updater' a bit too complex for my needs, and I've found 'click once' frustrating when it comes to publishing. The most adequate updating code I've found is the.net Application Updater Component, which I've used for both projects. I've had to modify it recently because it uses web dav, which isn't always installed on our web servers (it still needs directory browsing, however). I'm surprised that there isn't more on the web about automatically updating applications, and was wondering whether people have had success with any other methods than the ones mentioned above? ANSWER: See the answers to this similar question: a few auto-update frameworks were recommended there which are designed for (or work with).net apps: Application Updater Block (which you mention) ClickOnce, ClickThrough
[ ".net", "winforms", "updating" ]
4
3
732
4
0
2008-09-08T13:51:44.427000
2008-09-08T14:34:04.370000
49,755
49,758
Design Pattern for Undo Engine
I'm writing a structural modeling tool for a civil enginering application. I have one huge model class representing the entire building, which include collections of nodes, line elements, loads, etc. which are also custom classes. I have already coded an undo engine which saves a deep-copy after each modification to the model. Now I started thinking if I could have coded differently. Instead of saving the deep-copies, I could perhaps save a list of each modifier action with a corresponding reverse modifier. So that I could apply the reverse modifiers to the current model to undo, or the modifiers to redo. I can imagine how you would carry out simple commands that change object properties, etc. But how about complex commands? Like inserting new node objects to the model and adding some line objects which keep references to the new nodes. How would one go about implementing that?
Most examples I've seen use a variant of the Command-Pattern for this. Every user-action that's undoable gets its own command instance with all the information to execute the action and roll it back. You can then maintain a list of all the commands that have been executed and you can roll them back one by one.
Design Pattern for Undo Engine I'm writing a structural modeling tool for a civil enginering application. I have one huge model class representing the entire building, which include collections of nodes, line elements, loads, etc. which are also custom classes. I have already coded an undo engine which saves a deep-copy after each modification to the model. Now I started thinking if I could have coded differently. Instead of saving the deep-copies, I could perhaps save a list of each modifier action with a corresponding reverse modifier. So that I could apply the reverse modifiers to the current model to undo, or the modifiers to redo. I can imagine how you would carry out simple commands that change object properties, etc. But how about complex commands? Like inserting new node objects to the model and adding some line objects which keep references to the new nodes. How would one go about implementing that?
TITLE: Design Pattern for Undo Engine QUESTION: I'm writing a structural modeling tool for a civil enginering application. I have one huge model class representing the entire building, which include collections of nodes, line elements, loads, etc. which are also custom classes. I have already coded an undo engine which saves a deep-copy after each modification to the model. Now I started thinking if I could have coded differently. Instead of saving the deep-copies, I could perhaps save a list of each modifier action with a corresponding reverse modifier. So that I could apply the reverse modifiers to the current model to undo, or the modifiers to redo. I can imagine how you would carry out simple commands that change object properties, etc. But how about complex commands? Like inserting new node objects to the model and adding some line objects which keep references to the new nodes. How would one go about implementing that? ANSWER: Most examples I've seen use a variant of the Command-Pattern for this. Every user-action that's undoable gets its own command instance with all the information to execute the action and roll it back. You can then maintain a list of all the commands that have been executed and you can roll them back one by one.
[ "design-patterns", "undo" ]
127
95
39,399
22
0
2008-09-08T13:58:06.687000
2008-09-08T14:00:58.273000
49,790
49,862
In HTML, what should happen to a selected, disabled option element?
In my specific example, I'm dealing with a drop-down, e.g.: Select an item: an item another item Of course, that's pretty nonsensical, but I'm wondering whether any strict behaviour is defined. Opera effectively rejects the 'selected' attribute and selects the next item in the list. All other browsers appear to allow it, and it remains selected. Update: To clarify, I'm specifically interested in the initial selection. I'm dealing with one of those 'Select an item:'-type drop-downs, in which case the first option is really a label, and an action occurs onchange(). This is fairly well 'progressively enhanced', in that a submit button is present, and only removed via JavaScript. If the "select..." option were removed, whatever then were to become the first item would not be selectable. Are we just ruling out onchange drop downs altogether, or should the "select..." option be selectable, just with no effect?
In reply to the update in the question, I would say that the 'label' option should be selectable but either make it do nothing on submission or via JavaScript, don't allow the form to be submitted without a value being selected (assuming it's a required field). From a usablilty point of view I'd suggest doing both, that way all bases are covered.
In HTML, what should happen to a selected, disabled option element? In my specific example, I'm dealing with a drop-down, e.g.: Select an item: an item another item Of course, that's pretty nonsensical, but I'm wondering whether any strict behaviour is defined. Opera effectively rejects the 'selected' attribute and selects the next item in the list. All other browsers appear to allow it, and it remains selected. Update: To clarify, I'm specifically interested in the initial selection. I'm dealing with one of those 'Select an item:'-type drop-downs, in which case the first option is really a label, and an action occurs onchange(). This is fairly well 'progressively enhanced', in that a submit button is present, and only removed via JavaScript. If the "select..." option were removed, whatever then were to become the first item would not be selectable. Are we just ruling out onchange drop downs altogether, or should the "select..." option be selectable, just with no effect?
TITLE: In HTML, what should happen to a selected, disabled option element? QUESTION: In my specific example, I'm dealing with a drop-down, e.g.: Select an item: an item another item Of course, that's pretty nonsensical, but I'm wondering whether any strict behaviour is defined. Opera effectively rejects the 'selected' attribute and selects the next item in the list. All other browsers appear to allow it, and it remains selected. Update: To clarify, I'm specifically interested in the initial selection. I'm dealing with one of those 'Select an item:'-type drop-downs, in which case the first option is really a label, and an action occurs onchange(). This is fairly well 'progressively enhanced', in that a submit button is present, and only removed via JavaScript. If the "select..." option were removed, whatever then were to become the first item would not be selectable. Are we just ruling out onchange drop downs altogether, or should the "select..." option be selectable, just with no effect? ANSWER: In reply to the update in the question, I would say that the 'label' option should be selectable but either make it do nothing on submission or via JavaScript, don't allow the form to be submitted without a value being selected (assuming it's a required field). From a usablilty point of view I'd suggest doing both, that way all bases are covered.
[ "html", "forms", "cross-browser", "specifications" ]
10
2
15,672
6
0
2008-09-08T14:18:29.277000
2008-09-08T14:54:17.927000
49,799
49,836
How often do you use System.Component.BackgroundWorker in your UIs ? (if ever)
I am sure a responsive UI is something that everyone strives for and the reccomended way to do stuff is to use the BackgroundWorker for this. Do you find it easy to work with? Do you use it often? Or do you have your own frameworks for lengthy tasks and reporting process. I have found that I am using it quite a lot and even using its delegates wherever I need some sort of progress reporting.
Multithreaded programming is hard to grasp in the beginning (and veterans still fail sometimes) and BackgroundWorker makes it a bit easier to use. I like the fact that BackgroundWorker has functionality which is easy to implement but even easier to wrongly implement in a subtle way, like cancellation. I use it if I have and need a progress update, so I can display a meaningful progress bar. If not, I use a Thread (or borrow from the ThreadPool), because I don't need all the functionality of BackgroundWorker and am proficient enough with threads to start a Thread and wait for it to stop. As for delegates for non-related tasks, I use those of the Thread classes, like plain void ThreadStart(), or I create my own.
How often do you use System.Component.BackgroundWorker in your UIs ? (if ever) I am sure a responsive UI is something that everyone strives for and the reccomended way to do stuff is to use the BackgroundWorker for this. Do you find it easy to work with? Do you use it often? Or do you have your own frameworks for lengthy tasks and reporting process. I have found that I am using it quite a lot and even using its delegates wherever I need some sort of progress reporting.
TITLE: How often do you use System.Component.BackgroundWorker in your UIs ? (if ever) QUESTION: I am sure a responsive UI is something that everyone strives for and the reccomended way to do stuff is to use the BackgroundWorker for this. Do you find it easy to work with? Do you use it often? Or do you have your own frameworks for lengthy tasks and reporting process. I have found that I am using it quite a lot and even using its delegates wherever I need some sort of progress reporting. ANSWER: Multithreaded programming is hard to grasp in the beginning (and veterans still fail sometimes) and BackgroundWorker makes it a bit easier to use. I like the fact that BackgroundWorker has functionality which is easy to implement but even easier to wrongly implement in a subtle way, like cancellation. I use it if I have and need a progress update, so I can display a meaningful progress bar. If not, I use a Thread (or borrow from the ThreadPool), because I don't need all the functionality of BackgroundWorker and am proficient enough with threads to start a Thread and wait for it to stop. As for delegates for non-related tasks, I use those of the Thread classes, like plain void ThreadStart(), or I create my own.
[ ".net", "winforms", "multithreading", "user-interface" ]
5
3
798
6
0
2008-09-08T14:25:29.417000
2008-09-08T14:42:21.513000
49,806
49,843
How to create a non-interactive window in MFC
In my application I have a window which I popup with small messages on it (think similar to tooltip). This window uses the layered attributes to draw alpha backgrounds etc. If I have several of these windows open at once, and I click one with my mouse, when they disappear they cause my application to lose focus (it switches focus to the app behind the current one). How do I stop any interaction in my window?
After playing with the WM_NCACTIVATE message with no luck, I overrode the WM_SETFOCUS message: void CMyWindow::OnSetFocus(CWnd* pOldWnd) { if (pOldWnd!= NULL) { pOldWnd->SetFocus(); } } That seems to do the trick. No idea why it works though! Comments welcome on that issue.
How to create a non-interactive window in MFC In my application I have a window which I popup with small messages on it (think similar to tooltip). This window uses the layered attributes to draw alpha backgrounds etc. If I have several of these windows open at once, and I click one with my mouse, when they disappear they cause my application to lose focus (it switches focus to the app behind the current one). How do I stop any interaction in my window?
TITLE: How to create a non-interactive window in MFC QUESTION: In my application I have a window which I popup with small messages on it (think similar to tooltip). This window uses the layered attributes to draw alpha backgrounds etc. If I have several of these windows open at once, and I click one with my mouse, when they disappear they cause my application to lose focus (it switches focus to the app behind the current one). How do I stop any interaction in my window? ANSWER: After playing with the WM_NCACTIVATE message with no luck, I overrode the WM_SETFOCUS message: void CMyWindow::OnSetFocus(CWnd* pOldWnd) { if (pOldWnd!= NULL) { pOldWnd->SetFocus(); } } That seems to do the trick. No idea why it works though! Comments welcome on that issue.
[ "mfc", "focus", "activation" ]
2
1
750
2
0
2008-09-08T14:28:36.037000
2008-09-08T14:45:24
49,824
49,953
Java -> Python?
Besides the dynamic nature of Python (and the syntax), what are some of the major features of the Python language that Java doesn't have, and vice versa?
List comprehensions. I often find myself filtering/mapping lists, and being able to say [line.replace("spam","eggs") for line in open("somefile.txt") if line.startswith("nee")] is really nice. Functions are first class objects. They can be passed as parameters to other functions, defined inside other function, and have lexical scope. This makes it really easy to say things like people.sort(key=lambda p: p.age) and thus sort a bunch of people on their age without having to define a custom comparator class or something equally verbose. Everything is an object. Java has basic types which aren't objects, which is why many classes in the standard library define 9 different versions of functions (for boolean, byte, char, double, float, int, long, Object, short). Array.sort is a good example. Autoboxing helps, although it makes things awkward when something turns out to be null. Properties. Python lets you create classes with read-only fields, lazily-generated fields, as well as fields which are checked upon assignment to make sure they're never 0 or null or whatever you want to guard against, etc.' Default and keyword arguments. In Java if you want a constructor that can take up to 5 optional arguments, you must define 6 different versions of that constructor. And there's no way at all to say Student(name="Eli", age=25) Functions can only return 1 thing. In Python you have tuple assignment, so you can say spam, eggs = nee() but in Java you'd need to either resort to mutable out parameters or have a custom class with 2 fields and then have two additional lines of code to extract those fields. Built-in syntax for lists and dictionaries. Operator Overloading. Generally better designed libraries. For example, to parse an XML document in Java, you say Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("test.xml"); and in Python you say doc = parse("test.xml") Anyway, I could go on and on with further examples, but Python is just overall a much more flexible and expressive language. It's also dynamically typed, which I really like, but which comes with some disadvantages. Java has much better performance than Python and has way better tool support. Sometimes those things matter a lot and Java is the better language than Python for a task; I continue to use Java for some new projects despite liking Python a lot more. But as a language I think Python is superior for most things I find myself needing to accomplish.
Java -> Python? Besides the dynamic nature of Python (and the syntax), what are some of the major features of the Python language that Java doesn't have, and vice versa?
TITLE: Java -> Python? QUESTION: Besides the dynamic nature of Python (and the syntax), what are some of the major features of the Python language that Java doesn't have, and vice versa? ANSWER: List comprehensions. I often find myself filtering/mapping lists, and being able to say [line.replace("spam","eggs") for line in open("somefile.txt") if line.startswith("nee")] is really nice. Functions are first class objects. They can be passed as parameters to other functions, defined inside other function, and have lexical scope. This makes it really easy to say things like people.sort(key=lambda p: p.age) and thus sort a bunch of people on their age without having to define a custom comparator class or something equally verbose. Everything is an object. Java has basic types which aren't objects, which is why many classes in the standard library define 9 different versions of functions (for boolean, byte, char, double, float, int, long, Object, short). Array.sort is a good example. Autoboxing helps, although it makes things awkward when something turns out to be null. Properties. Python lets you create classes with read-only fields, lazily-generated fields, as well as fields which are checked upon assignment to make sure they're never 0 or null or whatever you want to guard against, etc.' Default and keyword arguments. In Java if you want a constructor that can take up to 5 optional arguments, you must define 6 different versions of that constructor. And there's no way at all to say Student(name="Eli", age=25) Functions can only return 1 thing. In Python you have tuple assignment, so you can say spam, eggs = nee() but in Java you'd need to either resort to mutable out parameters or have a custom class with 2 fields and then have two additional lines of code to extract those fields. Built-in syntax for lists and dictionaries. Operator Overloading. Generally better designed libraries. For example, to parse an XML document in Java, you say Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("test.xml"); and in Python you say doc = parse("test.xml") Anyway, I could go on and on with further examples, but Python is just overall a much more flexible and expressive language. It's also dynamically typed, which I really like, but which comes with some disadvantages. Java has much better performance than Python and has way better tool support. Sometimes those things matter a lot and Java is the better language than Python for a task; I continue to use Java for some new projects despite liking Python a lot more. But as a language I think Python is superior for most things I find myself needing to accomplish.
[ "java", "python" ]
30
47
11,809
5
0
2008-09-08T14:36:24.083000
2008-09-08T15:35:32.867000
49,847
51,382
Open source or low cost "log shipping" program
I have written a log shipping program a number of times. It is a simple program that is used to maintain a warm fail over box for SQL Server. It has two pieces. On the live dB server it: Does full and transaction backups and removes old files On the backup server it: Copies the backups from the live box Restores the backups or trans into databases that are set to recovery zips the backups deletes them based on retention If there is a failure, the program can go through each database on the backup server and set them to active. I am looking for an open source or low cost program that does this.
MS SQL server 2005 and 2008 already support this. http://technet.microsoft.com/en-us/library/ms188698.aspx http://technet.microsoft.com/en-us/library/ms188698(SQL.90).aspx
Open source or low cost "log shipping" program I have written a log shipping program a number of times. It is a simple program that is used to maintain a warm fail over box for SQL Server. It has two pieces. On the live dB server it: Does full and transaction backups and removes old files On the backup server it: Copies the backups from the live box Restores the backups or trans into databases that are set to recovery zips the backups deletes them based on retention If there is a failure, the program can go through each database on the backup server and set them to active. I am looking for an open source or low cost program that does this.
TITLE: Open source or low cost "log shipping" program QUESTION: I have written a log shipping program a number of times. It is a simple program that is used to maintain a warm fail over box for SQL Server. It has two pieces. On the live dB server it: Does full and transaction backups and removes old files On the backup server it: Copies the backups from the live box Restores the backups or trans into databases that are set to recovery zips the backups deletes them based on retention If there is a failure, the program can go through each database on the backup server and set them to active. I am looking for an open source or low cost program that does this. ANSWER: MS SQL server 2005 and 2008 already support this. http://technet.microsoft.com/en-us/library/ms188698.aspx http://technet.microsoft.com/en-us/library/ms188698(SQL.90).aspx
[ "sql-server", "backup" ]
9
3
518
1
0
2008-09-08T14:46:03.360000
2008-09-09T08:21:44.850000
49,870
49,872
I understand threading in theory but not in practice in .net
I have a basic cs-major understanding of multi-threading but have never had to do anything beyond simple timers in an application. Does anyone know of a good resource that will give me a tour how to work with multi-threaded applications, explaining the basics and maybe posing some of the more difficult stuff?
This is a great free resource by Joseph Albahari. Threading in C#
I understand threading in theory but not in practice in .net I have a basic cs-major understanding of multi-threading but have never had to do anything beyond simple timers in an application. Does anyone know of a good resource that will give me a tour how to work with multi-threaded applications, explaining the basics and maybe posing some of the more difficult stuff?
TITLE: I understand threading in theory but not in practice in .net QUESTION: I have a basic cs-major understanding of multi-threading but have never had to do anything beyond simple timers in an application. Does anyone know of a good resource that will give me a tour how to work with multi-threaded applications, explaining the basics and maybe posing some of the more difficult stuff? ANSWER: This is a great free resource by Joseph Albahari. Threading in C#
[ ".net", "multithreading", "reference" ]
7
23
1,260
5
0
2008-09-08T14:58:06.170000
2008-09-08T14:59:30.037000
49,876
70,515
Simpler interface for SQL Server analysis services cubes for end users
Is there a simpler interface for end users to run "queries" on pre-existing SqlServer Analysis Service cubes? I'm looking for a way to deploy the cubes and allow the users to work with the data through a simpler interface than BIDS. Is this even possible?
I would recommend Excel too. It is an environment that your users are familiar with anyway, and they will be able to perform additional analysis (totals etc) without learning any new interfaces. However, I would advise against pivot tables as a method of getting the data into Excel. I once worked on a project using pivot tables, and it was a filthy nightmare. The more recent versions of Office have a slightly different tool called "Microsoft Office Excel Add-in for SQL Server Analysis Services" which can get OLAP data into Excel. I downloaded XLAddinSetup.msi for Excel 2002/3 or you can use this method for Excel 2007.
Simpler interface for SQL Server analysis services cubes for end users Is there a simpler interface for end users to run "queries" on pre-existing SqlServer Analysis Service cubes? I'm looking for a way to deploy the cubes and allow the users to work with the data through a simpler interface than BIDS. Is this even possible?
TITLE: Simpler interface for SQL Server analysis services cubes for end users QUESTION: Is there a simpler interface for end users to run "queries" on pre-existing SqlServer Analysis Service cubes? I'm looking for a way to deploy the cubes and allow the users to work with the data through a simpler interface than BIDS. Is this even possible? ANSWER: I would recommend Excel too. It is an environment that your users are familiar with anyway, and they will be able to perform additional analysis (totals etc) without learning any new interfaces. However, I would advise against pivot tables as a method of getting the data into Excel. I once worked on a project using pivot tables, and it was a filthy nightmare. The more recent versions of Office have a slightly different tool called "Microsoft Office Excel Add-in for SQL Server Analysis Services" which can get OLAP data into Excel. I downloaded XLAddinSetup.msi for Excel 2002/3 or you can use this method for Excel 2007.
[ "sql-server", "olap", "cubes" ]
2
7
7,077
7
0
2008-09-08T15:00:25.213000
2008-09-16T08:57:04.253000
49,890
50,460
Mediawiki custom tag Stops page parsing
I created a few mediawiki custom tags, using the guide found here http://www.mediawiki.org/wiki/Manual:Tag_extensions I will post my code below, but the problem is after it hits the first custom tag in the page, it calls it, and prints the response, but does not get anything that comes after it in the wikitext. It seems it just stops parsing the page. Any Ideas? if ( defined( 'MW_SUPPORTS_PARSERFIRSTCALLINIT' ) ) { $wgHooks['ParserFirstCallInit'][] = 'tagregister'; } else { // Otherwise do things the old fashioned way $wgExtensionFunctions[] = 'tagregister'; } function tagregister(){ global $wgParser; $wgParser->setHook('tag1','tag1func'); $wgParser->setHook('tag2','tag2func'); return true; } function tag1func($input,$params) { return "It called me"; } function tag2func($input,$params) { return "It called me -- 2"; } Update: @George Mauer -- I have seen that as well, but this does not stop the page from rendering, just the Mediawiki engine from parsing the rest of the wikitext. Its as if hitting the custom function is signaling mediawiki that processing is done. I am in the process of diving into the rabbit hole but was hoping someone else has seen this behavior.
Never used Mediawiki but that sort of problem in my experience is indicative of a PHP error that occurred but was suppressed either with the @ operator or because PHP error output to screen is turned off. I hate to resort to this debugging method but when absolutely and utterly frustrated in PHP I will just start putting echo statements every few lines (always with a marker so I remember to remove them later), to figure out exactly where the error is coming from. Eventually, you'll get to the bottom of the rabbit hole and figure out exactly what the problematic line of code is.
Mediawiki custom tag Stops page parsing I created a few mediawiki custom tags, using the guide found here http://www.mediawiki.org/wiki/Manual:Tag_extensions I will post my code below, but the problem is after it hits the first custom tag in the page, it calls it, and prints the response, but does not get anything that comes after it in the wikitext. It seems it just stops parsing the page. Any Ideas? if ( defined( 'MW_SUPPORTS_PARSERFIRSTCALLINIT' ) ) { $wgHooks['ParserFirstCallInit'][] = 'tagregister'; } else { // Otherwise do things the old fashioned way $wgExtensionFunctions[] = 'tagregister'; } function tagregister(){ global $wgParser; $wgParser->setHook('tag1','tag1func'); $wgParser->setHook('tag2','tag2func'); return true; } function tag1func($input,$params) { return "It called me"; } function tag2func($input,$params) { return "It called me -- 2"; } Update: @George Mauer -- I have seen that as well, but this does not stop the page from rendering, just the Mediawiki engine from parsing the rest of the wikitext. Its as if hitting the custom function is signaling mediawiki that processing is done. I am in the process of diving into the rabbit hole but was hoping someone else has seen this behavior.
TITLE: Mediawiki custom tag Stops page parsing QUESTION: I created a few mediawiki custom tags, using the guide found here http://www.mediawiki.org/wiki/Manual:Tag_extensions I will post my code below, but the problem is after it hits the first custom tag in the page, it calls it, and prints the response, but does not get anything that comes after it in the wikitext. It seems it just stops parsing the page. Any Ideas? if ( defined( 'MW_SUPPORTS_PARSERFIRSTCALLINIT' ) ) { $wgHooks['ParserFirstCallInit'][] = 'tagregister'; } else { // Otherwise do things the old fashioned way $wgExtensionFunctions[] = 'tagregister'; } function tagregister(){ global $wgParser; $wgParser->setHook('tag1','tag1func'); $wgParser->setHook('tag2','tag2func'); return true; } function tag1func($input,$params) { return "It called me"; } function tag2func($input,$params) { return "It called me -- 2"; } Update: @George Mauer -- I have seen that as well, but this does not stop the page from rendering, just the Mediawiki engine from parsing the rest of the wikitext. Its as if hitting the custom function is signaling mediawiki that processing is done. I am in the process of diving into the rabbit hole but was hoping someone else has seen this behavior. ANSWER: Never used Mediawiki but that sort of problem in my experience is indicative of a PHP error that occurred but was suppressed either with the @ operator or because PHP error output to screen is turned off. I hate to resort to this debugging method but when absolutely and utterly frustrated in PHP I will just start putting echo statements every few lines (always with a marker so I remember to remove them later), to figure out exactly where the error is coming from. Eventually, you'll get to the bottom of the rabbit hole and figure out exactly what the problematic line of code is.
[ "php", "mediawiki" ]
1
0
588
2
0
2008-09-08T15:06:23.827000
2008-09-08T19:16:21.447000
49,896
74,866
Which is the best way to bring a file from a remote host to local host over an SSH session?
When connecting to remote hosts via ssh, I frequently want to bring a file on that system to the local system for viewing or processing. Is there a way to copy the file over without (a) opening a new terminal/pausing the ssh session (b) authenticating again to either the local or remote hosts which works (c) even when one or both of the hosts is behind a NAT router? The goal is to take advantage of as much of the current state as possible: that there is a connection between the two machines, that I'm authenticated on both, that I'm in the working directory of the file---so I don't have to open another terminal and copy and paste the remote host and path in, which is what I do now. The best solution also wouldn't require any setup before the session began, but if the setup was a one-time or able to be automated, than that's perfectly acceptable.
Here is my preferred solution to this problem. Set up a reverse ssh tunnel upon creating the ssh session. This is made easy by two bash function: grabfrom() needs to be defined on the local host, while grab() should be defined on the remote host. You can add any other ssh variables you use (e.g. -X or -Y) as you see fit. function grabfrom() { ssh -R 2202:127.0.0.1:22 ${@}; }; function grab() { scp -P 2202 $@ localuser@127.0.0.1:~; }; Usage: localhost% grabfrom remoteuser@remotehost password: remotehost% grab somefile1 somefile2 *.txt password: Positives: It works without special software on either host beyond OpenSSH It works when local host is behind a NAT router It can be implemented as a pair of two one-line bash function Negatives: It uses a fixed port number so: won't work with multiple connections to remote host might conflict with a process using that port on the remote host It requires localhost accept ssh connections It requires a special command on initiation the session It doesn't implicitly handle authentication to the localhost It doesn't allow one to specify the destination directory on localhost If you grab from multiple localhosts to the same remote host, ssh won't like the keys changing Future work: This is still pretty kludgy. Obviously, it would be possible to handle the authentication issue by setting up ssh keys appropriately and it's even easier to allow the specification of a remote directory by adding a parameter to grab() More difficult is addressing the other negatives. It would be nice to pick a dynamic port but as far as I can tell there is no elegant way to pass that port to the shell on the remote host; As best as I can tell, OpenSSH doesn't allow you to set arbitrary environment variables on the remote host and bash can't take environment variables from a command line argument. Even if you could pick a dynamic port, there is no way to ensure it isn't used on the remote host without connecting first.
Which is the best way to bring a file from a remote host to local host over an SSH session? When connecting to remote hosts via ssh, I frequently want to bring a file on that system to the local system for viewing or processing. Is there a way to copy the file over without (a) opening a new terminal/pausing the ssh session (b) authenticating again to either the local or remote hosts which works (c) even when one or both of the hosts is behind a NAT router? The goal is to take advantage of as much of the current state as possible: that there is a connection between the two machines, that I'm authenticated on both, that I'm in the working directory of the file---so I don't have to open another terminal and copy and paste the remote host and path in, which is what I do now. The best solution also wouldn't require any setup before the session began, but if the setup was a one-time or able to be automated, than that's perfectly acceptable.
TITLE: Which is the best way to bring a file from a remote host to local host over an SSH session? QUESTION: When connecting to remote hosts via ssh, I frequently want to bring a file on that system to the local system for viewing or processing. Is there a way to copy the file over without (a) opening a new terminal/pausing the ssh session (b) authenticating again to either the local or remote hosts which works (c) even when one or both of the hosts is behind a NAT router? The goal is to take advantage of as much of the current state as possible: that there is a connection between the two machines, that I'm authenticated on both, that I'm in the working directory of the file---so I don't have to open another terminal and copy and paste the remote host and path in, which is what I do now. The best solution also wouldn't require any setup before the session began, but if the setup was a one-time or able to be automated, than that's perfectly acceptable. ANSWER: Here is my preferred solution to this problem. Set up a reverse ssh tunnel upon creating the ssh session. This is made easy by two bash function: grabfrom() needs to be defined on the local host, while grab() should be defined on the remote host. You can add any other ssh variables you use (e.g. -X or -Y) as you see fit. function grabfrom() { ssh -R 2202:127.0.0.1:22 ${@}; }; function grab() { scp -P 2202 $@ localuser@127.0.0.1:~; }; Usage: localhost% grabfrom remoteuser@remotehost password: remotehost% grab somefile1 somefile2 *.txt password: Positives: It works without special software on either host beyond OpenSSH It works when local host is behind a NAT router It can be implemented as a pair of two one-line bash function Negatives: It uses a fixed port number so: won't work with multiple connections to remote host might conflict with a process using that port on the remote host It requires localhost accept ssh connections It requires a special command on initiation the session It doesn't implicitly handle authentication to the localhost It doesn't allow one to specify the destination directory on localhost If you grab from multiple localhosts to the same remote host, ssh won't like the keys changing Future work: This is still pretty kludgy. Obviously, it would be possible to handle the authentication issue by setting up ssh keys appropriately and it's even easier to allow the specification of a remote directory by adding a parameter to grab() More difficult is addressing the other negatives. It would be nice to pick a dynamic port but as far as I can tell there is no elegant way to pass that port to the shell on the remote host; As best as I can tell, OpenSSH doesn't allow you to set arbitrary environment variables on the remote host and bash can't take environment variables from a command line argument. Even if you could pick a dynamic port, there is no way to ensure it isn't used on the remote host without connecting first.
[ "ssh" ]
15
0
4,521
11
0
2008-09-08T15:07:30.017000
2008-09-16T17:34:50.330000
49,900
65,947
Is there a way to generalize an Apache ANT target?
We have an Apache ANT script to build our application, then check in the resulting JAR file into version control (VSS in this case). However, now we have a change that requires us to build 2 JAR files for this project, then check both into VSS. The current target that checks the original JAR file into VSS discovers the name of the JAR file through some property. Is there an easy way to "generalize" this target so that I can reuse it to check in a JAR file with any name? In a normal language this would obviously call for a function parameter but, to my knowledge, there really isn't an equivalent concept in ANT.
I would suggest to work with macros over subant/antcall because the main advantage I found with macros is that you're in complete control over the properties that are passed to the macro (especially if you want to add new properties). You simply refactor your Ant script starting with your target: creating a macro (notice the copy/paste and replacement with the @{file}): and invoke the macros with your files: Refactoring, "the Ant way"
Is there a way to generalize an Apache ANT target? We have an Apache ANT script to build our application, then check in the resulting JAR file into version control (VSS in this case). However, now we have a change that requires us to build 2 JAR files for this project, then check both into VSS. The current target that checks the original JAR file into VSS discovers the name of the JAR file through some property. Is there an easy way to "generalize" this target so that I can reuse it to check in a JAR file with any name? In a normal language this would obviously call for a function parameter but, to my knowledge, there really isn't an equivalent concept in ANT.
TITLE: Is there a way to generalize an Apache ANT target? QUESTION: We have an Apache ANT script to build our application, then check in the resulting JAR file into version control (VSS in this case). However, now we have a change that requires us to build 2 JAR files for this project, then check both into VSS. The current target that checks the original JAR file into VSS discovers the name of the JAR file through some property. Is there an easy way to "generalize" this target so that I can reuse it to check in a JAR file with any name? In a normal language this would obviously call for a function parameter but, to my knowledge, there really isn't an equivalent concept in ANT. ANSWER: I would suggest to work with macros over subant/antcall because the main advantage I found with macros is that you're in complete control over the properties that are passed to the macro (especially if you want to add new properties). You simply refactor your Ant script starting with your target: creating a macro (notice the copy/paste and replacement with the @{file}): and invoke the macros with your files: Refactoring, "the Ant way"
[ "java", "build-process", "build-automation", "ant" ]
21
47
13,761
5
0
2008-09-08T15:08:57.533000
2008-09-15T19:26:30.460000
49,908
172,280
How to create custom pages in dasBlog?
I know I've seen this in the past, but I can't seem to find it now. Basically I want to create a page that I can host on a dasBlog instance that contains the layout from my theme, but the content of the page I control. Ideally the content is a user control or ASPX that I write. Anybody know how I can accomplish this?
The easist way to do this is to "hijack" the FormatPage functionality. First add the following to your web.config in the newtelligence.DasBlog.UrlMapper section: Now you can create a directory in your content directory called static. From there, you can create html files and the file name will map to the url like this: http://BASEURL/Static.aspx?=FILENAME will map to a file called: /content/static/FILENAME.format.html You can place anything in that file that you would normally place in itemTemplate.blogtemplate, except it obviously won't have any post data. But you can essentially use this to put other macros, and still have it use the hometemplate.blogtemplate to keep the rest of your theme wrapped around the page.
How to create custom pages in dasBlog? I know I've seen this in the past, but I can't seem to find it now. Basically I want to create a page that I can host on a dasBlog instance that contains the layout from my theme, but the content of the page I control. Ideally the content is a user control or ASPX that I write. Anybody know how I can accomplish this?
TITLE: How to create custom pages in dasBlog? QUESTION: I know I've seen this in the past, but I can't seem to find it now. Basically I want to create a page that I can host on a dasBlog instance that contains the layout from my theme, but the content of the page I control. Ideally the content is a user control or ASPX that I write. Anybody know how I can accomplish this? ANSWER: The easist way to do this is to "hijack" the FormatPage functionality. First add the following to your web.config in the newtelligence.DasBlog.UrlMapper section: Now you can create a directory in your content directory called static. From there, you can create html files and the file name will map to the url like this: http://BASEURL/Static.aspx?=FILENAME will map to a file called: /content/static/FILENAME.format.html You can place anything in that file that you would normally place in itemTemplate.blogtemplate, except it obviously won't have any post data. But you can essentially use this to put other macros, and still have it use the hometemplate.blogtemplate to keep the rest of your theme wrapped around the page.
[ "dasblog" ]
3
4
260
2
0
2008-09-08T15:12:45.760000
2008-10-05T16:59:19.453000
49,912
49,943
Best .NET memory and performance profiler?
We are using JetBrains ' dotTrace. What other profiling tools can be recommended that are better for profiling C# Windows Forms applications?
No. I have tried pretty much every.NET profiler on the market (ANTS, vTune, OptimizeIt, DevPartner, YourKit), and in my opinion dotTrace is the best of the lot. It is one of only two profilers I have used (the other being YourKit) that has low enough overhead to handle a highly CPU-intensive application. If and only if your application is relatively light, I could recommend ANTS Profiler. Its line-by-line stats are sometimes quite useful, but they come at a price in profiling efficiency.
Best .NET memory and performance profiler? We are using JetBrains ' dotTrace. What other profiling tools can be recommended that are better for profiling C# Windows Forms applications?
TITLE: Best .NET memory and performance profiler? QUESTION: We are using JetBrains ' dotTrace. What other profiling tools can be recommended that are better for profiling C# Windows Forms applications? ANSWER: No. I have tried pretty much every.NET profiler on the market (ANTS, vTune, OptimizeIt, DevPartner, YourKit), and in my opinion dotTrace is the best of the lot. It is one of only two profilers I have used (the other being YourKit) that has low enough overhead to handle a highly CPU-intensive application. If and only if your application is relatively light, I could recommend ANTS Profiler. Its line-by-line stats are sometimes quite useful, but they come at a price in profiling efficiency.
[ "c#", ".net", "profiling", "profiler" ]
56
37
42,807
11
0
2008-09-08T15:14:00.280000
2008-09-08T15:28:22.790000
49,919
49,938
Regex to Match first 28 days of the month
I am looking for a Regular expression to match only if a date is in the first 28 days of the month. This is for my validator control in ASP.NET
Don't do this with Regex. Dates are formatted differently in different countries. Use the DateTime.TryParse routine instead: DateTime parsedDate; if ( DateTime.TryParse( dateString, out parsedDate) && parsedDate.Day <= 28 ) { // logic goes here. } Regex is nearly the golden hammer of input validation, but in this instance, it's the wrong choice.
Regex to Match first 28 days of the month I am looking for a Regular expression to match only if a date is in the first 28 days of the month. This is for my validator control in ASP.NET
TITLE: Regex to Match first 28 days of the month QUESTION: I am looking for a Regular expression to match only if a date is in the first 28 days of the month. This is for my validator control in ASP.NET ANSWER: Don't do this with Regex. Dates are formatted differently in different countries. Use the DateTime.TryParse routine instead: DateTime parsedDate; if ( DateTime.TryParse( dateString, out parsedDate) && parsedDate.Day <= 28 ) { // logic goes here. } Regex is nearly the golden hammer of input validation, but in this instance, it's the wrong choice.
[ "asp.net", "regex" ]
5
18
1,250
5
0
2008-09-08T15:17:22.020000
2008-09-08T15:26:56.147000
49,925
49,928
What is the difference between UNION and UNION ALL?
What is the difference between UNION and UNION ALL?
UNION removes duplicate rows (where all columns in the results are the same), UNION ALL does not. There is a performance hit when using UNION instead of UNION ALL, since the database server must do additional work to remove the duplicate rows, but usually you do not want the duplicates (especially when developing reports). To identify duplicates, rows must be comparable types as well as compatible types. This will depend on the SQL system. For example the system may truncate all long text columns to make short text columns for comparison (MS Jet), or may refuse to compare binary columns (ORACLE) UNION Example: SELECT 'foo' AS bar UNION SELECT 'foo' AS bar Result: +-----+ | bar | +-----+ | foo | +-----+ 1 row in set (0.00 sec) UNION ALL example: SELECT 'foo' AS bar UNION ALL SELECT 'foo' AS bar Result: +-----+ | bar | +-----+ | foo | | foo | +-----+ 2 rows in set (0.00 sec)
What is the difference between UNION and UNION ALL? What is the difference between UNION and UNION ALL?
TITLE: What is the difference between UNION and UNION ALL? QUESTION: What is the difference between UNION and UNION ALL? ANSWER: UNION removes duplicate rows (where all columns in the results are the same), UNION ALL does not. There is a performance hit when using UNION instead of UNION ALL, since the database server must do additional work to remove the duplicate rows, but usually you do not want the duplicates (especially when developing reports). To identify duplicates, rows must be comparable types as well as compatible types. This will depend on the SQL system. For example the system may truncate all long text columns to make short text columns for comparison (MS Jet), or may refuse to compare binary columns (ORACLE) UNION Example: SELECT 'foo' AS bar UNION SELECT 'foo' AS bar Result: +-----+ | bar | +-----+ | foo | +-----+ 1 row in set (0.00 sec) UNION ALL example: SELECT 'foo' AS bar UNION ALL SELECT 'foo' AS bar Result: +-----+ | bar | +-----+ | foo | | foo | +-----+ 2 rows in set (0.00 sec)
[ "sql", "union", "union-all" ]
1,702
2,034
1,581,198
19
0
2008-09-08T15:19:33.263000
2008-09-08T15:21:15.193000
49,926
196,806
Open source alternative to MATLAB's fmincon function?
Is there an open-source alternative to MATLAB's fmincon function for constrained linear optimization? I'm rewriting a MATLAB program to use Python / NumPy / SciPy and this is the only function I haven't found an equivalent to. A NumPy-based solution would be ideal, but any language will do.
Is your problem convex? Linear? Non-linear? I agree that SciPy.optimize will probably do the job, but fmincon is a sort of bazooka for solving optimization problems, and you'll be better off if you can confine it to one of the categories below (in increasing level of difficulty to solve efficiently) Linear Program (LP) Quadratic Program (QP) Convex Quadratically-Constrained Quadratic Program (QCQP) Second Order Cone Program (SOCP) Semidefinite Program (SDP) Non-Linear Convex Problem Non-Convex Problem There are also combinatoric problems such as Mixed-Integer Linear Programs (MILP), but you didn't mention any sort of integrality constraints, suffice to say that they fall into a different class of problems. The CVXOpt package will be of great use to you if your problem is convex. If your problem is not convex, you need to choose between finding a local solution or the global solution. Many convex solvers 'sort of' work in a non-convex domain. Finding a good approximation to the global solution would require some form Simulated Annealing or Genetic Algorithm. Finding the global solution will require an enumeration of all local solutions or a combinatorial strategy such as Branch and Bound.
Open source alternative to MATLAB's fmincon function? Is there an open-source alternative to MATLAB's fmincon function for constrained linear optimization? I'm rewriting a MATLAB program to use Python / NumPy / SciPy and this is the only function I haven't found an equivalent to. A NumPy-based solution would be ideal, but any language will do.
TITLE: Open source alternative to MATLAB's fmincon function? QUESTION: Is there an open-source alternative to MATLAB's fmincon function for constrained linear optimization? I'm rewriting a MATLAB program to use Python / NumPy / SciPy and this is the only function I haven't found an equivalent to. A NumPy-based solution would be ideal, but any language will do. ANSWER: Is your problem convex? Linear? Non-linear? I agree that SciPy.optimize will probably do the job, but fmincon is a sort of bazooka for solving optimization problems, and you'll be better off if you can confine it to one of the categories below (in increasing level of difficulty to solve efficiently) Linear Program (LP) Quadratic Program (QP) Convex Quadratically-Constrained Quadratic Program (QCQP) Second Order Cone Program (SOCP) Semidefinite Program (SDP) Non-Linear Convex Problem Non-Convex Problem There are also combinatoric problems such as Mixed-Integer Linear Programs (MILP), but you didn't mention any sort of integrality constraints, suffice to say that they fall into a different class of problems. The CVXOpt package will be of great use to you if your problem is convex. If your problem is not convex, you need to choose between finding a local solution or the global solution. Many convex solvers 'sort of' work in a non-convex domain. Finding a good approximation to the global solution would require some form Simulated Annealing or Genetic Algorithm. Finding the global solution will require an enumeration of all local solutions or a combinatorial strategy such as Branch and Bound.
[ "python", "numpy", "matlab", "numeric", "scientific-computing" ]
37
33
44,991
10
0
2008-09-08T15:19:59.533000
2008-10-13T05:51:51.143000
49,934
49,951
How come a 32 bit kernel can run a 64 bit binary?
On my OS X box, the kernel is a 32-bit binary and yet it can run a 64-bit binary. How does this work? cristi:~ diciu$ file./a.out./a.out: Mach-O 64-bit executable x86_64 cristi:~ diciu$ file /mach_kernel /mach_kernel: Mach-O universal binary with 2 architectures /mach_kernel (for architecture i386): Mach-O executable i386 /mach_kernel (for architecture ppc): Mach-O executable ppc cristi:~ diciu$./a.out cristi:~ diciu$ echo $? 1
The CPU can be switched from 64 bit execution mode to 32 bit when it traps into kernel context, and a 32 bit kernel can still be constructed to understand the structures passed in from 64 bit user-space apps. The MacOS X kernel does not directly dereference pointers from the user app anyway, as it resides its own separate address space. A user-space pointer in an ioctl call, for example, must first be resolved to its physical address and then a new virtual address created in the kernel address space. It doesn't really matter whether that pointer in the ioctl was 64 bits or 32 bits, the kernel does not dereference it directly in either case. So mixing a 32 bit kernel and 64 bit binaries can work, and vice-versa. The thing you cannot do is mix 32 bit libraries with a 64 bit application, as pointers passed between them would be truncated. MacOS X supplies more of its frameworks in both 32 and 64 bit versions in each release.
How come a 32 bit kernel can run a 64 bit binary? On my OS X box, the kernel is a 32-bit binary and yet it can run a 64-bit binary. How does this work? cristi:~ diciu$ file./a.out./a.out: Mach-O 64-bit executable x86_64 cristi:~ diciu$ file /mach_kernel /mach_kernel: Mach-O universal binary with 2 architectures /mach_kernel (for architecture i386): Mach-O executable i386 /mach_kernel (for architecture ppc): Mach-O executable ppc cristi:~ diciu$./a.out cristi:~ diciu$ echo $? 1
TITLE: How come a 32 bit kernel can run a 64 bit binary? QUESTION: On my OS X box, the kernel is a 32-bit binary and yet it can run a 64-bit binary. How does this work? cristi:~ diciu$ file./a.out./a.out: Mach-O 64-bit executable x86_64 cristi:~ diciu$ file /mach_kernel /mach_kernel: Mach-O universal binary with 2 architectures /mach_kernel (for architecture i386): Mach-O executable i386 /mach_kernel (for architecture ppc): Mach-O executable ppc cristi:~ diciu$./a.out cristi:~ diciu$ echo $? 1 ANSWER: The CPU can be switched from 64 bit execution mode to 32 bit when it traps into kernel context, and a 32 bit kernel can still be constructed to understand the structures passed in from 64 bit user-space apps. The MacOS X kernel does not directly dereference pointers from the user app anyway, as it resides its own separate address space. A user-space pointer in an ioctl call, for example, must first be resolved to its physical address and then a new virtual address created in the kernel address space. It doesn't really matter whether that pointer in the ioctl was 64 bits or 32 bits, the kernel does not dereference it directly in either case. So mixing a 32 bit kernel and 64 bit binaries can work, and vice-versa. The thing you cannot do is mix 32 bit libraries with a 64 bit application, as pointers passed between them would be truncated. MacOS X supplies more of its frameworks in both 32 and 64 bit versions in each release.
[ "c", "macos", "x86", "x86-64", "32-bit" ]
26
45
8,580
6
0
2008-09-08T15:23:07.250000
2008-09-08T15:34:59.263000
49,937
49,984
What is Dynamic Code Analysis?
What is Dynamic Code Analysis? How is it different from Static Code Analysis (ie, what can it catch that can't be caught in static)? I've heard of bounds checking and memory analysis - what are these? What other things are checked using dynamic analysis? -Adam
Simply put, static analysis collect information based on source code and dynamic analysis is based on the system execution, often using instrumentation. Advantages of dynamic analysis Is able to detect dependencies that are not possible to detect in static analysis. Ex.: dynamic dependencies using reflection, dependency injection, polymorphism. Can collect temporal information. Deals with real input data. During the static analysis it is difficult to impossible to know what files will be passed as input, what WEB requests will come, what user will click, etc. Disadvantages of dynamic analysis May negatively impact the performance of the application. Cannot guarantee the full coverage of the source code, as it's runs are based on user interaction or automatic tests. Resources There's many dynamic analysis tools in the market, being debuggers the most notorious one. On the other hand, it's still an academic research field. There's many researchers studying how to use dynamic analysis for better understanding of software systems. There's an annual workshop dedicated to dependency analysis.
What is Dynamic Code Analysis? What is Dynamic Code Analysis? How is it different from Static Code Analysis (ie, what can it catch that can't be caught in static)? I've heard of bounds checking and memory analysis - what are these? What other things are checked using dynamic analysis? -Adam
TITLE: What is Dynamic Code Analysis? QUESTION: What is Dynamic Code Analysis? How is it different from Static Code Analysis (ie, what can it catch that can't be caught in static)? I've heard of bounds checking and memory analysis - what are these? What other things are checked using dynamic analysis? -Adam ANSWER: Simply put, static analysis collect information based on source code and dynamic analysis is based on the system execution, often using instrumentation. Advantages of dynamic analysis Is able to detect dependencies that are not possible to detect in static analysis. Ex.: dynamic dependencies using reflection, dependency injection, polymorphism. Can collect temporal information. Deals with real input data. During the static analysis it is difficult to impossible to know what files will be passed as input, what WEB requests will come, what user will click, etc. Disadvantages of dynamic analysis May negatively impact the performance of the application. Cannot guarantee the full coverage of the source code, as it's runs are based on user interaction or automatic tests. Resources There's many dynamic analysis tools in the market, being debuggers the most notorious one. On the other hand, it's still an academic research field. There's many researchers studying how to use dynamic analysis for better understanding of software systems. There's an annual workshop dedicated to dependency analysis.
[ "code-analysis", "dynamic-analysis" ]
25
32
38,112
4
0
2008-09-08T15:23:46.280000
2008-09-08T15:47:06.193000
49,950
49,961
Garbage Collection: Is it necessary to set large objects to null in a Dispose method?
Is it necessary to set large objects to null when implementing a Dispose() method?
Not usually. The garbage collector looks for rooted objects, and circular dependencies don't prevent collection if neither object is rooted. There is a caveat: if object A has a reference to object B, and object B is being disposed, you may want to clean up that relationship or else you could end up with a leak. The most common place this surfaces is in event handlers (the reference from A->B is one that B controls, because it subscribed to an event on A). In this case, if A is still rooted, B cannot be collected even though it's been disposed.
Garbage Collection: Is it necessary to set large objects to null in a Dispose method? Is it necessary to set large objects to null when implementing a Dispose() method?
TITLE: Garbage Collection: Is it necessary to set large objects to null in a Dispose method? QUESTION: Is it necessary to set large objects to null when implementing a Dispose() method? ANSWER: Not usually. The garbage collector looks for rooted objects, and circular dependencies don't prevent collection if neither object is rooted. There is a caveat: if object A has a reference to object B, and object B is being disposed, you may want to clean up that relationship or else you could end up with a leak. The most common place this surfaces is in event handlers (the reference from A->B is one that B controls, because it subscribed to an event on A). In this case, if A is still rooted, B cannot be collected even though it's been disposed.
[ ".net", "garbage-collection" ]
7
5
1,764
6
0
2008-09-08T15:34:43.257000
2008-09-08T15:39:41.967000
49,962
50,056
Task Schedulers
Had an interesting discussion with some colleagues about the best scheduling strategies for realtime tasks, but not everyone had a good understanding of the common or useful scheduling strategies. For your answer, please choose one strategy and go over it in some detail, rather than giving a little info on several strategies. If you have something to add to someone else's description and it's short, add a comment rather than a new answer (if it's long or useful, or simply a much better description, then please use an answer) What is the strategy - describe the general case (assume people know what a task queue is, semaphores, locks, and other OS fundamentals outside the scheduler itself) What is this strategy optimized for (task latency, efficiency, realtime, jitter, resource sharing, etc) Is it realtime, or can it be made realtime Current strategies: Priority Based Preemptive Lowest power slowest clock -Adam
As described in a paper titled Real-Time Task Scheduling for Energy-Aware Embedded Systems, Swaminathan and Chakrabarty describe the challenges of real-time task scheduling in low-power (embedded) devices with multiple processor speeds and power consumption profiles available. The scheduling algorithm they outline (and is shown to be only about 1% worse than an optimal solution in tests) has an interesting way of scheduling tasks they call the LEDF Heuristic. From the paper: The low-energy earliest deadline first heuristic, or simply LEDF, is an extension of the well-known earliest deadline first (EDF) algorithm. The operation of LEDF is as follows: LEDF maintains a list of all released tasks, called the “ready list”. When tasks are released, the task with the nearest deadline is chosen to be executed. A check is performed to see if the task deadline can be met by executing it at the lower voltage (speed). If the deadline can be met, LEDF assigns the lower voltage to the task and the task begins execution. During the task’s execution, other tasks may enter the system. These tasks are assumed to be placed automatically on the “ready list”. LEDF again selects the task with the nearest deadline to be executed. As long as there are tasks waiting to be executed, LEDF does not keep the pro- cessor idle. This process is repeated until all the tasks have been scheduled. And in pseudo-code: Repeat forever { if tasks are waiting to be scheduled { Sort deadlines in ascending order Schedule task with earliest deadline Check if deadline can be met at lower speed (voltage) If deadline can be met, schedule task to execute at lower voltage (speed) If deadline cannot be met, check if deadline can be met at higher speed (voltage) If deadline can be met, schedule task to execute at higher voltage (speed) If deadline cannot be met, task cannot be scheduled: run the exception handler! } } It seems that real-time scheduling is an interesting and evolving problem as small, low-power devices become more ubiquitous. I think this is an area in which we'll see plenty of further research and I look forward to keeping abreast!
Task Schedulers Had an interesting discussion with some colleagues about the best scheduling strategies for realtime tasks, but not everyone had a good understanding of the common or useful scheduling strategies. For your answer, please choose one strategy and go over it in some detail, rather than giving a little info on several strategies. If you have something to add to someone else's description and it's short, add a comment rather than a new answer (if it's long or useful, or simply a much better description, then please use an answer) What is the strategy - describe the general case (assume people know what a task queue is, semaphores, locks, and other OS fundamentals outside the scheduler itself) What is this strategy optimized for (task latency, efficiency, realtime, jitter, resource sharing, etc) Is it realtime, or can it be made realtime Current strategies: Priority Based Preemptive Lowest power slowest clock -Adam
TITLE: Task Schedulers QUESTION: Had an interesting discussion with some colleagues about the best scheduling strategies for realtime tasks, but not everyone had a good understanding of the common or useful scheduling strategies. For your answer, please choose one strategy and go over it in some detail, rather than giving a little info on several strategies. If you have something to add to someone else's description and it's short, add a comment rather than a new answer (if it's long or useful, or simply a much better description, then please use an answer) What is the strategy - describe the general case (assume people know what a task queue is, semaphores, locks, and other OS fundamentals outside the scheduler itself) What is this strategy optimized for (task latency, efficiency, realtime, jitter, resource sharing, etc) Is it realtime, or can it be made realtime Current strategies: Priority Based Preemptive Lowest power slowest clock -Adam ANSWER: As described in a paper titled Real-Time Task Scheduling for Energy-Aware Embedded Systems, Swaminathan and Chakrabarty describe the challenges of real-time task scheduling in low-power (embedded) devices with multiple processor speeds and power consumption profiles available. The scheduling algorithm they outline (and is shown to be only about 1% worse than an optimal solution in tests) has an interesting way of scheduling tasks they call the LEDF Heuristic. From the paper: The low-energy earliest deadline first heuristic, or simply LEDF, is an extension of the well-known earliest deadline first (EDF) algorithm. The operation of LEDF is as follows: LEDF maintains a list of all released tasks, called the “ready list”. When tasks are released, the task with the nearest deadline is chosen to be executed. A check is performed to see if the task deadline can be met by executing it at the lower voltage (speed). If the deadline can be met, LEDF assigns the lower voltage to the task and the task begins execution. During the task’s execution, other tasks may enter the system. These tasks are assumed to be placed automatically on the “ready list”. LEDF again selects the task with the nearest deadline to be executed. As long as there are tasks waiting to be executed, LEDF does not keep the pro- cessor idle. This process is repeated until all the tasks have been scheduled. And in pseudo-code: Repeat forever { if tasks are waiting to be scheduled { Sort deadlines in ascending order Schedule task with earliest deadline Check if deadline can be met at lower speed (voltage) If deadline can be met, schedule task to execute at lower voltage (speed) If deadline cannot be met, check if deadline can be met at higher speed (voltage) If deadline can be met, schedule task to execute at higher voltage (speed) If deadline cannot be met, task cannot be scheduled: run the exception handler! } } It seems that real-time scheduling is an interesting and evolving problem as small, low-power devices become more ubiquitous. I think this is an area in which we'll see plenty of further research and I look forward to keeping abreast!
[ "operating-system", "kernel", "scheduling" ]
4
8
882
2
0
2008-09-08T15:40:49.453000
2008-09-08T16:09:55.887000
49,972
50,058
In what order are locations searched to load referenced DLLs?
I know that the.NET framework looks for referenced DLLs in several locations Global assembly cache (GAC) Any private paths added to the AppDomain The current directory of the executing assembly What order are those locations searched? Is the search for a DLL ceased if a match is found or does it continue through all locations (and if so, how are conflicts resolved)? Also, please confirm or deny those locations and provide any other locations I have failed to mention.
Assembly loading is a rather elaborate process which depends on lots of different factors like configuration files, publisher policies, appdomain settings, CLR hosts, partial or full assembly names, etc. The simple version is that the GAC is first, then the private paths. %PATH% is never used. It is best to use Assembly Binding Log Viewer (Fuslogvw.exe) to debug any assembly loading problems. EDIT How the Runtime Locates Assemblies explains the process in more detail.
In what order are locations searched to load referenced DLLs? I know that the.NET framework looks for referenced DLLs in several locations Global assembly cache (GAC) Any private paths added to the AppDomain The current directory of the executing assembly What order are those locations searched? Is the search for a DLL ceased if a match is found or does it continue through all locations (and if so, how are conflicts resolved)? Also, please confirm or deny those locations and provide any other locations I have failed to mention.
TITLE: In what order are locations searched to load referenced DLLs? QUESTION: I know that the.NET framework looks for referenced DLLs in several locations Global assembly cache (GAC) Any private paths added to the AppDomain The current directory of the executing assembly What order are those locations searched? Is the search for a DLL ceased if a match is found or does it continue through all locations (and if so, how are conflicts resolved)? Also, please confirm or deny those locations and provide any other locations I have failed to mention. ANSWER: Assembly loading is a rather elaborate process which depends on lots of different factors like configuration files, publisher policies, appdomain settings, CLR hosts, partial or full assembly names, etc. The simple version is that the GAC is first, then the private paths. %PATH% is never used. It is best to use Assembly Binding Log Viewer (Fuslogvw.exe) to debug any assembly loading problems. EDIT How the Runtime Locates Assemblies explains the process in more detail.
[ ".net", "dll" ]
55
57
41,022
3
0
2008-09-08T15:45:25.853000
2008-09-08T16:10:16.637000
49,988
50,011
Really killing a process in Windows
Occasionally a program on a Windows machine goes crazy and just hangs. So I'll call up the task manager and hit the "End Process" button for it. However, this doesn't always work; if I try it enough times then it'll usually die eventually, but I'd really like to be able to just kill it immediately. On Linux I could just kill -9 to guarantee that a process will die. This also could be used for writing batch scripts and writing batch scripts is programming. Is there some program or command that comes with Windows that will always kill a process? A free third-party app would be fine, although I'd prefer to be able to do this on machines I sit down at for the first time.
"End Process" on the Processes-Tab calls TerminateProcess which is the most ultimate way Windows knows to kill a process. If it doesn't go away, it's currently locked waiting on some kernel resource (probably a buggy driver) and there is nothing (short of a reboot) you could do to make the process go away. Have a look at this blog-entry from wayback when: http://blogs.technet.com/markrussinovich/archive/2005/08/17/unkillable-processes.aspx Unix based systems like Linux also have that problem where processes could survive a kill -9 if they are in what's known as "Uninterruptible sleep" (shown by top and ps as state D ) at which point the processes sleep so well that they can't process incoming signals (which is what kill does - sending signals). Normally, Uninterruptible sleep should not last long, but as under Windows, broken drivers or broken userpace programs ( vfork without exec ) can end up sleeping in D forever.
Really killing a process in Windows Occasionally a program on a Windows machine goes crazy and just hangs. So I'll call up the task manager and hit the "End Process" button for it. However, this doesn't always work; if I try it enough times then it'll usually die eventually, but I'd really like to be able to just kill it immediately. On Linux I could just kill -9 to guarantee that a process will die. This also could be used for writing batch scripts and writing batch scripts is programming. Is there some program or command that comes with Windows that will always kill a process? A free third-party app would be fine, although I'd prefer to be able to do this on machines I sit down at for the first time.
TITLE: Really killing a process in Windows QUESTION: Occasionally a program on a Windows machine goes crazy and just hangs. So I'll call up the task manager and hit the "End Process" button for it. However, this doesn't always work; if I try it enough times then it'll usually die eventually, but I'd really like to be able to just kill it immediately. On Linux I could just kill -9 to guarantee that a process will die. This also could be used for writing batch scripts and writing batch scripts is programming. Is there some program or command that comes with Windows that will always kill a process? A free third-party app would be fine, although I'd prefer to be able to do this on machines I sit down at for the first time. ANSWER: "End Process" on the Processes-Tab calls TerminateProcess which is the most ultimate way Windows knows to kill a process. If it doesn't go away, it's currently locked waiting on some kernel resource (probably a buggy driver) and there is nothing (short of a reboot) you could do to make the process go away. Have a look at this blog-entry from wayback when: http://blogs.technet.com/markrussinovich/archive/2005/08/17/unkillable-processes.aspx Unix based systems like Linux also have that problem where processes could survive a kill -9 if they are in what's known as "Uninterruptible sleep" (shown by top and ps as state D ) at which point the processes sleep so well that they can't process incoming signals (which is what kill does - sending signals). Normally, Uninterruptible sleep should not last long, but as under Windows, broken drivers or broken userpace programs ( vfork without exec ) can end up sleeping in D forever.
[ "windows" ]
406
334
672,058
11
0
2008-09-08T15:48:31.103000
2008-09-08T15:52:09.643000
50,003
50,015
SQL 2000 database copy to SQL 2005 options
We have a production web and database server with SQL Server 2000. (However, a few clients they have their own servers with SQL 2005.) So we have local installs of SQL 2005 Express for development on Windows XP SP3 boxes (which don't allow SQL 2000 Enterprise installations). We often need to copy SQL 2000 databases to SQL 2005 instances. In the past, we have used the SQL Publishing tool (also mentioned here ). However, one of our databases is so big that using that tool fails as it creates SQL scripts that get too large for Management Studio to handle them properly. Besides, it takes too long...:) We would use the Copy Database Wizard included with SQL 2005, but our development machines run SQL 2005 Express which don't included SQL Server Agent, which is required for Copy Database Wizard to work. So, I guess our solution will be to upgrade our development installs with the full version of SQL 2005 (we have an MSDN subscription of course). I was wondering what other solutions, if any, work well for you guys? (Besides complaining to the bosses to upgrade our production servers to 2005 or even 2008--which I've already tried.)
Back it up in SQL Server 2000 and then use the RESTORE WITH MOVE command into 2005 Express.
SQL 2000 database copy to SQL 2005 options We have a production web and database server with SQL Server 2000. (However, a few clients they have their own servers with SQL 2005.) So we have local installs of SQL 2005 Express for development on Windows XP SP3 boxes (which don't allow SQL 2000 Enterprise installations). We often need to copy SQL 2000 databases to SQL 2005 instances. In the past, we have used the SQL Publishing tool (also mentioned here ). However, one of our databases is so big that using that tool fails as it creates SQL scripts that get too large for Management Studio to handle them properly. Besides, it takes too long...:) We would use the Copy Database Wizard included with SQL 2005, but our development machines run SQL 2005 Express which don't included SQL Server Agent, which is required for Copy Database Wizard to work. So, I guess our solution will be to upgrade our development installs with the full version of SQL 2005 (we have an MSDN subscription of course). I was wondering what other solutions, if any, work well for you guys? (Besides complaining to the bosses to upgrade our production servers to 2005 or even 2008--which I've already tried.)
TITLE: SQL 2000 database copy to SQL 2005 options QUESTION: We have a production web and database server with SQL Server 2000. (However, a few clients they have their own servers with SQL 2005.) So we have local installs of SQL 2005 Express for development on Windows XP SP3 boxes (which don't allow SQL 2000 Enterprise installations). We often need to copy SQL 2000 databases to SQL 2005 instances. In the past, we have used the SQL Publishing tool (also mentioned here ). However, one of our databases is so big that using that tool fails as it creates SQL scripts that get too large for Management Studio to handle them properly. Besides, it takes too long...:) We would use the Copy Database Wizard included with SQL 2005, but our development machines run SQL 2005 Express which don't included SQL Server Agent, which is required for Copy Database Wizard to work. So, I guess our solution will be to upgrade our development installs with the full version of SQL 2005 (we have an MSDN subscription of course). I was wondering what other solutions, if any, work well for you guys? (Besides complaining to the bosses to upgrade our production servers to 2005 or even 2008--which I've already tried.) ANSWER: Back it up in SQL Server 2000 and then use the RESTORE WITH MOVE command into 2005 Express.
[ "sql-server" ]
1
1
1,330
1
0
2008-09-08T15:51:00.910000
2008-09-08T15:53:11.637000
50,033
50,063
Asp.Net Form DefaultButton Error in Firefox
The.Net generated code for a form with the "DefaultButton" attribute set contains poor javascript that allows the functionality to work in IE but not in other browsers (Firefox specifcially). Hitting enter key does submit the form with all browsers but Firefox cannot disregard the key press when it happens inside of a control. The result is a multiline text area control that cannot be multiline in Firefox as the enter key submits the form instead of creating a new line. For more information on the bug, read it here. This could be fixed in Asp.Net 3.0+ but a workaround still has to be created for 2.0. Any ideas for the lightest workaround (a hack that doesn't look like a hack =D)? The solution in the above link scares me a little as it could easily have unintended side-effects.
I use this function adapted from codesta. [Edit: the very same one, I see, that scares you! Oops. Can't help you then.] http://blog.codesta.com/codesta_weblog/2007/12/net-gotchas---p.html. You use it by surrounding your code with a div like so. You could subclass the Form to include this automatically. I don't use it that much, so I didn't. (your form goes here) Here's the function. function FireDefaultButton(event, target) { // srcElement is for IE var element = event.target || event.srcElement; if (13 == event.keyCode &&!(element && "textarea" == element.tagName.toLowerCase())) { var defaultButton; defaultButton = document.getElementById(target); if (defaultButton && "undefined"!= typeof defaultButton.click) { defaultButton.click(); event.cancelBubble = true; if (event.stopPropagation) event.stopPropagation(); return false; } } return true; }
Asp.Net Form DefaultButton Error in Firefox The.Net generated code for a form with the "DefaultButton" attribute set contains poor javascript that allows the functionality to work in IE but not in other browsers (Firefox specifcially). Hitting enter key does submit the form with all browsers but Firefox cannot disregard the key press when it happens inside of a control. The result is a multiline text area control that cannot be multiline in Firefox as the enter key submits the form instead of creating a new line. For more information on the bug, read it here. This could be fixed in Asp.Net 3.0+ but a workaround still has to be created for 2.0. Any ideas for the lightest workaround (a hack that doesn't look like a hack =D)? The solution in the above link scares me a little as it could easily have unintended side-effects.
TITLE: Asp.Net Form DefaultButton Error in Firefox QUESTION: The.Net generated code for a form with the "DefaultButton" attribute set contains poor javascript that allows the functionality to work in IE but not in other browsers (Firefox specifcially). Hitting enter key does submit the form with all browsers but Firefox cannot disregard the key press when it happens inside of a control. The result is a multiline text area control that cannot be multiline in Firefox as the enter key submits the form instead of creating a new line. For more information on the bug, read it here. This could be fixed in Asp.Net 3.0+ but a workaround still has to be created for 2.0. Any ideas for the lightest workaround (a hack that doesn't look like a hack =D)? The solution in the above link scares me a little as it could easily have unintended side-effects. ANSWER: I use this function adapted from codesta. [Edit: the very same one, I see, that scares you! Oops. Can't help you then.] http://blog.codesta.com/codesta_weblog/2007/12/net-gotchas---p.html. You use it by surrounding your code with a div like so. You could subclass the Form to include this automatically. I don't use it that much, so I didn't. (your form goes here) Here's the function. function FireDefaultButton(event, target) { // srcElement is for IE var element = event.target || event.srcElement; if (13 == event.keyCode &&!(element && "textarea" == element.tagName.toLowerCase())) { var defaultButton; defaultButton = document.getElementById(target); if (defaultButton && "undefined"!= typeof defaultButton.click) { defaultButton.click(); event.cancelBubble = true; if (event.stopPropagation) event.stopPropagation(); return false; } } return true; }
[ "asp.net", "firefox", "webforms", "textarea" ]
5
4
8,062
3
0
2008-09-08T15:57:36.527000
2008-09-08T16:12:13.543000
50,037
50,081
What are some good SharePoint security resources?
I've got a SharePoint application and I'm sad to say that in my SharePoint-induced excitement, I ignored a lot of the security concerns I should have been paying more attention to. Though we didn't before, now we actually need granular security, so I need to get educated. I'm mostly interested in how to best create groups and add users to those groups. We have a single main site collection and a couple dozen subsites under that collection. How can I best create a granular security world where I can independently assign rights to each of these subsites?
To have permissions vary at the "sub site" level which is the SPWeb object in object model terms you need to enable unique permission for the site. A good article outlining the permission hierarchy in SharePoint 2007 can be found on the office web site About controlling access to sites and site content In my experience if you are able to use permission inheritance over granular security it's much less hassle to manage. Breaking site permission inheritance Click " People and groups " Click " Site permissions " From the actions menu in the list click " Edit Permissions " http://blog.richfinn.net/content/binary/WindowsLiveWriter/InstallandConfiguretheCommunityKitforSha_E660/image_3.png http://blog.richfinn.net/content/binary/WindowsLiveWriter/InstallandConfiguretheCommunityKitforSha_E660/image_3.png Other references SharePoint 2007: Permissions, permissions, permissions. SharePoint 2007 SiteGroups - part 1 - the basics
What are some good SharePoint security resources? I've got a SharePoint application and I'm sad to say that in my SharePoint-induced excitement, I ignored a lot of the security concerns I should have been paying more attention to. Though we didn't before, now we actually need granular security, so I need to get educated. I'm mostly interested in how to best create groups and add users to those groups. We have a single main site collection and a couple dozen subsites under that collection. How can I best create a granular security world where I can independently assign rights to each of these subsites?
TITLE: What are some good SharePoint security resources? QUESTION: I've got a SharePoint application and I'm sad to say that in my SharePoint-induced excitement, I ignored a lot of the security concerns I should have been paying more attention to. Though we didn't before, now we actually need granular security, so I need to get educated. I'm mostly interested in how to best create groups and add users to those groups. We have a single main site collection and a couple dozen subsites under that collection. How can I best create a granular security world where I can independently assign rights to each of these subsites? ANSWER: To have permissions vary at the "sub site" level which is the SPWeb object in object model terms you need to enable unique permission for the site. A good article outlining the permission hierarchy in SharePoint 2007 can be found on the office web site About controlling access to sites and site content In my experience if you are able to use permission inheritance over granular security it's much less hassle to manage. Breaking site permission inheritance Click " People and groups " Click " Site permissions " From the actions menu in the list click " Edit Permissions " http://blog.richfinn.net/content/binary/WindowsLiveWriter/InstallandConfiguretheCommunityKitforSha_E660/image_3.png http://blog.richfinn.net/content/binary/WindowsLiveWriter/InstallandConfiguretheCommunityKitforSha_E660/image_3.png Other references SharePoint 2007: Permissions, permissions, permissions. SharePoint 2007 SiteGroups - part 1 - the basics
[ "security", "sharepoint" ]
5
5
559
1
0
2008-09-08T15:58:48.770000
2008-09-08T16:22:02.117000
50,042
50,111
Graphics card memory usage in linux
What tools are available to monitor graphics card memory usage in linux?
If you just need to know it for 3D graphics development purposes, you may want to look into something like gDEBugger or, if you only care about NVIDIA cards, you can try NVIDIA PerfHUD. I have not used them myself, but I would expect them to track such information.
Graphics card memory usage in linux What tools are available to monitor graphics card memory usage in linux?
TITLE: Graphics card memory usage in linux QUESTION: What tools are available to monitor graphics card memory usage in linux? ANSWER: If you just need to know it for 3D graphics development purposes, you may want to look into something like gDEBugger or, if you only care about NVIDIA cards, you can try NVIDIA PerfHUD. I have not used them myself, but I would expect them to track such information.
[ "linux", "graphics" ]
4
0
7,346
2
0
2008-09-08T16:03:03.737000
2008-09-08T16:41:49.650000
50,046
50,057
Is Visual Studio 2003 still available/supported
Pretty much what the title says really. We have some code that is.NET 1.1 based and no real desire to up-convert it. However, we are looking to add developers to the team and they will need copies of Visual Studio. My understanding is that they will need VS 2003 - as this is the only IDE that supports.NET 1.1 but I am wondering if we are still able to purchase it!
Visual Studio 2003 is still available to download for MSDN subscribers. The EULA for Visual Studio includes a 'downgrade' clause, which appears, IMNAL, to allow you to buy Visual Studio 2008 and then install 2003 under the same license. DOWNGRADE. You may install and use this version and an earlier version of the software at the same time. This agreement applies to your use of the earlier version. If the earlier version includes different components, any terms for those components in the agreement that comes with the earlier version apply to your use of them. Microsoft is not obligated to supply earlier versions to you.
Is Visual Studio 2003 still available/supported Pretty much what the title says really. We have some code that is.NET 1.1 based and no real desire to up-convert it. However, we are looking to add developers to the team and they will need copies of Visual Studio. My understanding is that they will need VS 2003 - as this is the only IDE that supports.NET 1.1 but I am wondering if we are still able to purchase it!
TITLE: Is Visual Studio 2003 still available/supported QUESTION: Pretty much what the title says really. We have some code that is.NET 1.1 based and no real desire to up-convert it. However, we are looking to add developers to the team and they will need copies of Visual Studio. My understanding is that they will need VS 2003 - as this is the only IDE that supports.NET 1.1 but I am wondering if we are still able to purchase it! ANSWER: Visual Studio 2003 is still available to download for MSDN subscribers. The EULA for Visual Studio includes a 'downgrade' clause, which appears, IMNAL, to allow you to buy Visual Studio 2008 and then install 2003 under the same license. DOWNGRADE. You may install and use this version and an earlier version of the software at the same time. This agreement applies to your use of the earlier version. If the earlier version includes different components, any terms for those components in the agreement that comes with the earlier version apply to your use of them. Microsoft is not obligated to supply earlier versions to you.
[ ".net", "visual-studio", "visual-studio-2003" ]
7
8
3,168
7
0
2008-09-08T16:05:17.850000
2008-09-08T16:10:00.130000
50,064
50,128
Setting Colors in SWT
This is pretty simple, I come from a swing/awt background. I'm just wondering what the proper way to set the background color for a SWT widget is? I've been trying: widget.setBackground( ); Except I have no idea how to create the color Object in SWT?
To create a color, try this: Device device = Display.getCurrent (); Color red = new Color (device, 255, 0, 0);
Setting Colors in SWT This is pretty simple, I come from a swing/awt background. I'm just wondering what the proper way to set the background color for a SWT widget is? I've been trying: widget.setBackground( ); Except I have no idea how to create the color Object in SWT?
TITLE: Setting Colors in SWT QUESTION: This is pretty simple, I come from a swing/awt background. I'm just wondering what the proper way to set the background color for a SWT widget is? I've been trying: widget.setBackground( ); Except I have no idea how to create the color Object in SWT? ANSWER: To create a color, try this: Device device = Display.getCurrent (); Color red = new Color (device, 255, 0, 0);
[ "java", "swt", "colors" ]
65
60
81,938
3
0
2008-09-08T16:12:57.707000
2008-09-08T16:49:54.717000
50,074
50,127
Where do the Linux TCP/IP hackers 'live'?
Over the past year or so my production platform has been plagued by an odd TCP/IP issue. I've spent zillions of hours working with competent & knowledgeable sysadmins, scouring the net, reading source code, been jerked around by RH's pathetic support, and crying tears of blood! To no avail. (Google 'unkn-4' and you'll see many posts with my name all over.) Work-a-rounds are in place, so the issue is not a priority. But the geek in me really would like to understand and solve this problem. So, where can a moderately competent systems programmer go to ask detailed questions and receive detailed answers from The Lords of TCP/IP stacks? I assume that their world so close to the bare metal, their population so small, is different from my own. That, and they don't want to answer emails to "My modem doesn't work" so they hide in the shadows. Any pointers would be greatly appreciated.
Dave Miller (person in charge of networking in the linux kernel) and their fellow henchmen all inhabit the lkml or Linux Kernel Mailing List. If you can provide a reasonably decent bug report they'll get you a reasonable answer. On the other hand if you tell them it's a very old kernel, they'll tell you to try the newest... At the very least you can try searching its archives.
Where do the Linux TCP/IP hackers 'live'? Over the past year or so my production platform has been plagued by an odd TCP/IP issue. I've spent zillions of hours working with competent & knowledgeable sysadmins, scouring the net, reading source code, been jerked around by RH's pathetic support, and crying tears of blood! To no avail. (Google 'unkn-4' and you'll see many posts with my name all over.) Work-a-rounds are in place, so the issue is not a priority. But the geek in me really would like to understand and solve this problem. So, where can a moderately competent systems programmer go to ask detailed questions and receive detailed answers from The Lords of TCP/IP stacks? I assume that their world so close to the bare metal, their population so small, is different from my own. That, and they don't want to answer emails to "My modem doesn't work" so they hide in the shadows. Any pointers would be greatly appreciated.
TITLE: Where do the Linux TCP/IP hackers 'live'? QUESTION: Over the past year or so my production platform has been plagued by an odd TCP/IP issue. I've spent zillions of hours working with competent & knowledgeable sysadmins, scouring the net, reading source code, been jerked around by RH's pathetic support, and crying tears of blood! To no avail. (Google 'unkn-4' and you'll see many posts with my name all over.) Work-a-rounds are in place, so the issue is not a priority. But the geek in me really would like to understand and solve this problem. So, where can a moderately competent systems programmer go to ask detailed questions and receive detailed answers from The Lords of TCP/IP stacks? I assume that their world so close to the bare metal, their population so small, is different from my own. That, and they don't want to answer emails to "My modem doesn't work" so they hide in the shadows. Any pointers would be greatly appreciated. ANSWER: Dave Miller (person in charge of networking in the linux kernel) and their fellow henchmen all inhabit the lkml or Linux Kernel Mailing List. If you can provide a reasonably decent bug report they'll get you a reasonable answer. On the other hand if you tell them it's a very old kernel, they'll tell you to try the newest... At the very least you can try searching its archives.
[ "linux", "networking", "tcp", "kernel" ]
4
5
1,115
2
0
2008-09-08T16:21:25.847000
2008-09-08T16:49:42.330000
50,079
3,392,463
C Image Library
Can anyone recommend a decent C image library? I'm after loaders for bmp, gif, jpg, png and tga. I want to use this for programming my Sony Playstation Portable, so opensource would be very handy. After some googleing I've found FreeImage and CImg, but both feel rather heavy, and CImg is C++ not C.
If you control the images you're loading, the lightest loader I know is Sean Barrett's awesome stb_image.c (direct link to single file source code!). There are also other very worthwhile libraries on Sean's site such as a tiny TrueType rasterizer and Vorbis decompressor, btw. If you need OpenGL image loading that uses stb_image, I'll humbly point you to SOILex...
C Image Library Can anyone recommend a decent C image library? I'm after loaders for bmp, gif, jpg, png and tga. I want to use this for programming my Sony Playstation Portable, so opensource would be very handy. After some googleing I've found FreeImage and CImg, but both feel rather heavy, and CImg is C++ not C.
TITLE: C Image Library QUESTION: Can anyone recommend a decent C image library? I'm after loaders for bmp, gif, jpg, png and tga. I want to use this for programming my Sony Playstation Portable, so opensource would be very handy. After some googleing I've found FreeImage and CImg, but both feel rather heavy, and CImg is C++ not C. ANSWER: If you control the images you're loading, the lightest loader I know is Sean Barrett's awesome stb_image.c (direct link to single file source code!). There are also other very worthwhile libraries on Sean's site such as a tiny TrueType rasterizer and Vorbis decompressor, btw. If you need OpenGL image loading that uses stb_image, I'll humbly point you to SOILex...
[ "c", "image", "playstation-portable" ]
18
21
36,033
7
0
2008-09-08T16:21:54.610000
2010-08-02T23:03:36.257000
50,089
51,365
How do you backup IIS's metabase in C#?
exact code will be helpful. I assume the DirectoryServices namespace does it but I can't find the method that does it. I need actual C# code. All the samples I found so far are VB or VBScript. The C# examples I found are for reading/setting ADSI properties. A command like backup seems to have a certain.NET syntax which I am not clear how to use. In VB there's a straightforward backup command. Need an equivalent in.NET.
I found it: DirectoryEntry de = new DirectoryEntry("IIS://localhost"); de.Invoke("Backup", new object[0] ); new object needs to be set to hold proper arguments like overwriting current backup
How do you backup IIS's metabase in C#? exact code will be helpful. I assume the DirectoryServices namespace does it but I can't find the method that does it. I need actual C# code. All the samples I found so far are VB or VBScript. The C# examples I found are for reading/setting ADSI properties. A command like backup seems to have a certain.NET syntax which I am not clear how to use. In VB there's a straightforward backup command. Need an equivalent in.NET.
TITLE: How do you backup IIS's metabase in C#? QUESTION: exact code will be helpful. I assume the DirectoryServices namespace does it but I can't find the method that does it. I need actual C# code. All the samples I found so far are VB or VBScript. The C# examples I found are for reading/setting ADSI properties. A command like backup seems to have a certain.NET syntax which I am not clear how to use. In VB there's a straightforward backup command. Need an equivalent in.NET. ANSWER: I found it: DirectoryEntry de = new DirectoryEntry("IIS://localhost"); de.Invoke("Backup", new object[0] ); new object needs to be set to hold proper arguments like overwriting current backup
[ "iis", "directoryservices", "metabase" ]
0
0
981
2
0
2008-09-08T16:25:06.397000
2008-09-09T07:52:46.043000
50,096
50,102
How to pass password to scp?
I know it is not recommended, but is it at all possible to pass the user's password to scp? I'd like to copy a file via scp as part of a batch job and the receiving server does, of course, need a password and, no, I cannot easily change that to key-based authentication.
You can script it with a tool like expect (there are handy bindings too, like Pexpect for Python).
How to pass password to scp? I know it is not recommended, but is it at all possible to pass the user's password to scp? I'd like to copy a file via scp as part of a batch job and the receiving server does, of course, need a password and, no, I cannot easily change that to key-based authentication.
TITLE: How to pass password to scp? QUESTION: I know it is not recommended, but is it at all possible to pass the user's password to scp? I'd like to copy a file via scp as part of a batch job and the receiving server does, of course, need a password and, no, I cannot easily change that to key-based authentication. ANSWER: You can script it with a tool like expect (there are handy bindings too, like Pexpect for Python).
[ "linux", "scp", "io-redirection" ]
463
42
1,170,365
22
0
2008-09-08T16:35:09.230000
2008-09-08T16:38:10.297000
50,098
3,790,621
Comparing two collections for equality irrespective of the order of items in them
I would like to compare two collections (in C#), but I'm not sure of the best way to implement this efficiently. I've read the other thread about Enumerable.SequenceEqual, but it's not exactly what I'm looking for. In my case, two collections would be equal if they both contain the same items (no matter the order). Example: collection1 = {1, 2, 3, 4}; collection2 = {2, 4, 1, 3}; collection1 == collection2; // true What I usually do is to loop through each item of one collection and see if it exists in the other collection, then loop through each item of the other collection and see if it exists in the first collection. (I start by comparing the lengths). if (collection1.Count!= collection2.Count) return false; // the collections are not equal foreach (Item item in collection1) { if (!collection2.Contains(item)) return false; // the collections are not equal } foreach (Item item in collection2) { if (!collection1.Contains(item)) return false; // the collections are not equal } return true; // the collections are equal However, this is not entirely correct, and it's probably not the most efficient way to do compare two collections for equality. An example I can think of that would be wrong is: collection1 = {1, 2, 3, 3, 4} collection2 = {1, 2, 2, 3, 4} Which would be equal with my implementation. Should I just count the number of times each item is found and make sure the counts are equal in both collections? The examples are in some sort of C# (let's call it pseudo-C#), but give your answer in whatever language you wish, it does not matter. Note: I used integers in the examples for simplicity, but I want to be able to use reference-type objects too (they do not behave correctly as keys because only the reference of the object is compared, not the content).
It turns out Microsoft already has this covered in its testing framework: CollectionAssert.AreEquivalent Remarks Two collections are equivalent if they have the same elements in the same quantity, but in any order. Elements are equal if their values are equal, not if they refer to the same object. Using reflector, I modified the code behind AreEquivalent() to create a corresponding equality comparer. It is more complete than existing answers, since it takes nulls into account, implements IEqualityComparer and has some efficiency and edge case checks. plus, it's Microsoft:) public class MultiSetComparer: IEqualityComparer > { private readonly IEqualityComparer m_comparer; public MultiSetComparer(IEqualityComparer comparer = null) { m_comparer = comparer?? EqualityComparer.Default; } public bool Equals(IEnumerable first, IEnumerable second) { if (first == null) return second == null; if (second == null) return false; if (ReferenceEquals(first, second)) return true; if (first is ICollection firstCollection && second is ICollection secondCollection) { if (firstCollection.Count!= secondCollection.Count) return false; if (firstCollection.Count == 0) return true; } return!HaveMismatchedElement(first, second); } private bool HaveMismatchedElement(IEnumerable first, IEnumerable second) { int firstNullCount; int secondNullCount; var firstElementCounts = GetElementCounts(first, out firstNullCount); var secondElementCounts = GetElementCounts(second, out secondNullCount); if (firstNullCount!= secondNullCount || firstElementCounts.Count!= secondElementCounts.Count) return true; foreach (var kvp in firstElementCounts) { var firstElementCount = kvp.Value; int secondElementCount; secondElementCounts.TryGetValue(kvp.Key, out secondElementCount); if (firstElementCount!= secondElementCount) return true; } return false; } private Dictionary GetElementCounts(IEnumerable enumerable, out int nullCount) { var dictionary = new Dictionary (m_comparer); nullCount = 0; foreach (T element in enumerable) { if (element == null) { nullCount++; } else { int num; dictionary.TryGetValue(element, out num); num++; dictionary[element] = num; } } return dictionary; } public int GetHashCode(IEnumerable enumerable) { if (enumerable == null) throw new ArgumentNullException(nameof(enumerable)); int hash = 17; foreach (T val in enumerable) hash ^= (val == null? 42: m_comparer.GetHashCode(val)); return hash; } } Sample usage: var set = new HashSet >(new[] {new[]{1,2,3}}, new MultiSetComparer ()); Console.WriteLine(set.Contains(new [] {3,2,1})); //true Console.WriteLine(set.Contains(new [] {1, 2, 3, 3})); //false Or if you just want to compare two collections directly: var comp = new MultiSetComparer (); Console.WriteLine(comp.Equals(new[] {"a","b","c"}, new[] {"a","c","b"})); //true Console.WriteLine(comp.Equals(new[] {"a","b","c"}, new[] {"a","b"})); //false Finally, you can use your an equality comparer of your choice: var strcomp = new MultiSetComparer (StringComparer.OrdinalIgnoreCase); Console.WriteLine(strcomp.Equals(new[] {"a", "b"}, new []{"B", "A"})); //true
Comparing two collections for equality irrespective of the order of items in them I would like to compare two collections (in C#), but I'm not sure of the best way to implement this efficiently. I've read the other thread about Enumerable.SequenceEqual, but it's not exactly what I'm looking for. In my case, two collections would be equal if they both contain the same items (no matter the order). Example: collection1 = {1, 2, 3, 4}; collection2 = {2, 4, 1, 3}; collection1 == collection2; // true What I usually do is to loop through each item of one collection and see if it exists in the other collection, then loop through each item of the other collection and see if it exists in the first collection. (I start by comparing the lengths). if (collection1.Count!= collection2.Count) return false; // the collections are not equal foreach (Item item in collection1) { if (!collection2.Contains(item)) return false; // the collections are not equal } foreach (Item item in collection2) { if (!collection1.Contains(item)) return false; // the collections are not equal } return true; // the collections are equal However, this is not entirely correct, and it's probably not the most efficient way to do compare two collections for equality. An example I can think of that would be wrong is: collection1 = {1, 2, 3, 3, 4} collection2 = {1, 2, 2, 3, 4} Which would be equal with my implementation. Should I just count the number of times each item is found and make sure the counts are equal in both collections? The examples are in some sort of C# (let's call it pseudo-C#), but give your answer in whatever language you wish, it does not matter. Note: I used integers in the examples for simplicity, but I want to be able to use reference-type objects too (they do not behave correctly as keys because only the reference of the object is compared, not the content).
TITLE: Comparing two collections for equality irrespective of the order of items in them QUESTION: I would like to compare two collections (in C#), but I'm not sure of the best way to implement this efficiently. I've read the other thread about Enumerable.SequenceEqual, but it's not exactly what I'm looking for. In my case, two collections would be equal if they both contain the same items (no matter the order). Example: collection1 = {1, 2, 3, 4}; collection2 = {2, 4, 1, 3}; collection1 == collection2; // true What I usually do is to loop through each item of one collection and see if it exists in the other collection, then loop through each item of the other collection and see if it exists in the first collection. (I start by comparing the lengths). if (collection1.Count!= collection2.Count) return false; // the collections are not equal foreach (Item item in collection1) { if (!collection2.Contains(item)) return false; // the collections are not equal } foreach (Item item in collection2) { if (!collection1.Contains(item)) return false; // the collections are not equal } return true; // the collections are equal However, this is not entirely correct, and it's probably not the most efficient way to do compare two collections for equality. An example I can think of that would be wrong is: collection1 = {1, 2, 3, 3, 4} collection2 = {1, 2, 2, 3, 4} Which would be equal with my implementation. Should I just count the number of times each item is found and make sure the counts are equal in both collections? The examples are in some sort of C# (let's call it pseudo-C#), but give your answer in whatever language you wish, it does not matter. Note: I used integers in the examples for simplicity, but I want to be able to use reference-type objects too (they do not behave correctly as keys because only the reference of the object is compared, not the content). ANSWER: It turns out Microsoft already has this covered in its testing framework: CollectionAssert.AreEquivalent Remarks Two collections are equivalent if they have the same elements in the same quantity, but in any order. Elements are equal if their values are equal, not if they refer to the same object. Using reflector, I modified the code behind AreEquivalent() to create a corresponding equality comparer. It is more complete than existing answers, since it takes nulls into account, implements IEqualityComparer and has some efficiency and edge case checks. plus, it's Microsoft:) public class MultiSetComparer: IEqualityComparer > { private readonly IEqualityComparer m_comparer; public MultiSetComparer(IEqualityComparer comparer = null) { m_comparer = comparer?? EqualityComparer.Default; } public bool Equals(IEnumerable first, IEnumerable second) { if (first == null) return second == null; if (second == null) return false; if (ReferenceEquals(first, second)) return true; if (first is ICollection firstCollection && second is ICollection secondCollection) { if (firstCollection.Count!= secondCollection.Count) return false; if (firstCollection.Count == 0) return true; } return!HaveMismatchedElement(first, second); } private bool HaveMismatchedElement(IEnumerable first, IEnumerable second) { int firstNullCount; int secondNullCount; var firstElementCounts = GetElementCounts(first, out firstNullCount); var secondElementCounts = GetElementCounts(second, out secondNullCount); if (firstNullCount!= secondNullCount || firstElementCounts.Count!= secondElementCounts.Count) return true; foreach (var kvp in firstElementCounts) { var firstElementCount = kvp.Value; int secondElementCount; secondElementCounts.TryGetValue(kvp.Key, out secondElementCount); if (firstElementCount!= secondElementCount) return true; } return false; } private Dictionary GetElementCounts(IEnumerable enumerable, out int nullCount) { var dictionary = new Dictionary (m_comparer); nullCount = 0; foreach (T element in enumerable) { if (element == null) { nullCount++; } else { int num; dictionary.TryGetValue(element, out num); num++; dictionary[element] = num; } } return dictionary; } public int GetHashCode(IEnumerable enumerable) { if (enumerable == null) throw new ArgumentNullException(nameof(enumerable)); int hash = 17; foreach (T val in enumerable) hash ^= (val == null? 42: m_comparer.GetHashCode(val)); return hash; } } Sample usage: var set = new HashSet >(new[] {new[]{1,2,3}}, new MultiSetComparer ()); Console.WriteLine(set.Contains(new [] {3,2,1})); //true Console.WriteLine(set.Contains(new [] {1, 2, 3, 3})); //false Or if you just want to compare two collections directly: var comp = new MultiSetComparer (); Console.WriteLine(comp.Equals(new[] {"a","b","c"}, new[] {"a","c","b"})); //true Console.WriteLine(comp.Equals(new[] {"a","b","c"}, new[] {"a","b"})); //false Finally, you can use your an equality comparer of your choice: var strcomp = new MultiSetComparer (StringComparer.OrdinalIgnoreCase); Console.WriteLine(strcomp.Equals(new[] {"a", "b"}, new []{"B", "A"})); //true
[ ".net", "collections", "comparison", "equality" ]
186
129
116,882
21
0
2008-09-08T16:36:15.840000
2010-09-24T20:10:30.170000
50,106
50,116
Looking for a SQL Transaction Log file viewer
If any of you have worked with a cool tool for viewing/querying the SQL Transaction logs, please let me know. This should show all the transactional sql statements which are committed or rolled back. For Database files, if it has some additional graphical capabilities like showing the internal Binary Tree structure of the indexes, that will be awesome but I guess I am asking for too much huh..
This is only relevant if you're talking SQL Server 2000 but RedGate produced a free tool called SQL Log Rescue. Otherwise, for SQL Server 2005 ApexSQLLog from ApexSQL is the only other product I'm aware of
Looking for a SQL Transaction Log file viewer If any of you have worked with a cool tool for viewing/querying the SQL Transaction logs, please let me know. This should show all the transactional sql statements which are committed or rolled back. For Database files, if it has some additional graphical capabilities like showing the internal Binary Tree structure of the indexes, that will be awesome but I guess I am asking for too much huh..
TITLE: Looking for a SQL Transaction Log file viewer QUESTION: If any of you have worked with a cool tool for viewing/querying the SQL Transaction logs, please let me know. This should show all the transactional sql statements which are committed or rolled back. For Database files, if it has some additional graphical capabilities like showing the internal Binary Tree structure of the indexes, that will be awesome but I guess I am asking for too much huh.. ANSWER: This is only relevant if you're talking SQL Server 2000 but RedGate produced a free tool called SQL Log Rescue. Otherwise, for SQL Server 2005 ApexSQLLog from ApexSQL is the only other product I'm aware of
[ "sql", "sql-server", "logging", "transactions" ]
23
14
29,374
5
0
2008-09-08T16:38:36.803000
2008-09-08T16:43:07.277000
50,114
877,642
Does WCF raise the bar or just the complexity level?
I understand the value of the three-part service/host/client model offered by WCF. But is it just me or does it seem like WCF took something pretty direct and straightforward (the ASMX model) and made a mess out of it? Is there an alternative to using SvcUtil's command line step back in time to generate the proxy? With ASMX services a test harness was automatically provided; is there a good alternative today with WCF? I appreciate that the WS* stuff is more tightly integrated with WCF and hope to find some payoff for WCF there, but geeze, otherwise I'm perplexed. Also, the state of books available for WCF is abysmal at best. Juval Lowy, a superb author, has written a good O'Reilly reference book "Programming WCF Services" but it doesn't do that much (for me anyway) for learning now to use WCF. That book's precursor (and a little better organized, but not much, as a tutorial) is Michele Leroux Bustamante's Learning WCF. It has good spots but is outdated in place and its corresponding Web site is gone. Do you have good WCF learning references besides just continuing to Google the bejebus out of things?
Okay, here we go. First, Michele Leroux Bustamante's book has been updated for VS2008. The website for the book is not gone. It's up right now, and it has tons of great WCF info. On that website she provides updated code compatible with VS2008 for all the examples in her book. If you order from Amazon, you will get the reprint which is updated. WCF is not only a replacement for ASMX. Sure it can (and does quite well) replace ASMX, but the real benefit is that it allows your services to be self-hosted. Most of the functionality from WSE has been baked in from the start. The framework is highly configurable, and the ability to serve multiple endpoints over multiple protocols is amazing, IMO. While you can still generate proxy classes from the "Add Service Reference" option, it's not necessary. All you really have to do is copy your ServiceContract interface and tell your code where to find the endpoint for the service, and that's it. You can call methods from the service with very little code. Using this method, you have complete control over the implementation. Regardless of the method you choose to generate a proxy class, Michele shows both and uses both in her excellent series of webcasts on the subject. Michele has tons of great material out there, and I recommend you check out her website(s). Here's some links that were incredibly helpful for me as I was learning WCF. I hope that you'll come to realize how strong WCF really is, and how easy it is to implement. The learning curve is a little bit steep, but the rewards for your time investment are well worth it: Michele's webcasts: http://www.dasblonde.net/2007/06/24/WCFWebcastSeries.aspx Michele's book website (alive and updated for VS2008): http://www.thatindigogirl.com/ I recommend you watch at least 1 of Michele's webcasts. She is a very effective presenter, and she's obviously incredibly knowledgeable when it comes to WCF. She does a great job of demystifying the inner workings of WCF from the ground up.
Does WCF raise the bar or just the complexity level? I understand the value of the three-part service/host/client model offered by WCF. But is it just me or does it seem like WCF took something pretty direct and straightforward (the ASMX model) and made a mess out of it? Is there an alternative to using SvcUtil's command line step back in time to generate the proxy? With ASMX services a test harness was automatically provided; is there a good alternative today with WCF? I appreciate that the WS* stuff is more tightly integrated with WCF and hope to find some payoff for WCF there, but geeze, otherwise I'm perplexed. Also, the state of books available for WCF is abysmal at best. Juval Lowy, a superb author, has written a good O'Reilly reference book "Programming WCF Services" but it doesn't do that much (for me anyway) for learning now to use WCF. That book's precursor (and a little better organized, but not much, as a tutorial) is Michele Leroux Bustamante's Learning WCF. It has good spots but is outdated in place and its corresponding Web site is gone. Do you have good WCF learning references besides just continuing to Google the bejebus out of things?
TITLE: Does WCF raise the bar or just the complexity level? QUESTION: I understand the value of the three-part service/host/client model offered by WCF. But is it just me or does it seem like WCF took something pretty direct and straightforward (the ASMX model) and made a mess out of it? Is there an alternative to using SvcUtil's command line step back in time to generate the proxy? With ASMX services a test harness was automatically provided; is there a good alternative today with WCF? I appreciate that the WS* stuff is more tightly integrated with WCF and hope to find some payoff for WCF there, but geeze, otherwise I'm perplexed. Also, the state of books available for WCF is abysmal at best. Juval Lowy, a superb author, has written a good O'Reilly reference book "Programming WCF Services" but it doesn't do that much (for me anyway) for learning now to use WCF. That book's precursor (and a little better organized, but not much, as a tutorial) is Michele Leroux Bustamante's Learning WCF. It has good spots but is outdated in place and its corresponding Web site is gone. Do you have good WCF learning references besides just continuing to Google the bejebus out of things? ANSWER: Okay, here we go. First, Michele Leroux Bustamante's book has been updated for VS2008. The website for the book is not gone. It's up right now, and it has tons of great WCF info. On that website she provides updated code compatible with VS2008 for all the examples in her book. If you order from Amazon, you will get the reprint which is updated. WCF is not only a replacement for ASMX. Sure it can (and does quite well) replace ASMX, but the real benefit is that it allows your services to be self-hosted. Most of the functionality from WSE has been baked in from the start. The framework is highly configurable, and the ability to serve multiple endpoints over multiple protocols is amazing, IMO. While you can still generate proxy classes from the "Add Service Reference" option, it's not necessary. All you really have to do is copy your ServiceContract interface and tell your code where to find the endpoint for the service, and that's it. You can call methods from the service with very little code. Using this method, you have complete control over the implementation. Regardless of the method you choose to generate a proxy class, Michele shows both and uses both in her excellent series of webcasts on the subject. Michele has tons of great material out there, and I recommend you check out her website(s). Here's some links that were incredibly helpful for me as I was learning WCF. I hope that you'll come to realize how strong WCF really is, and how easy it is to implement. The learning curve is a little bit steep, but the rewards for your time investment are well worth it: Michele's webcasts: http://www.dasblonde.net/2007/06/24/WCFWebcastSeries.aspx Michele's book website (alive and updated for VS2008): http://www.thatindigogirl.com/ I recommend you watch at least 1 of Michele's webcasts. She is a very effective presenter, and she's obviously incredibly knowledgeable when it comes to WCF. She does a great job of demystifying the inner workings of WCF from the ground up.
[ "wcf", "web-services" ]
84
61
13,181
16
0
2008-09-08T16:42:21.130000
2009-05-18T13:04:09.460000
50,115
58,198
Using shadowbox disables keyboard shortcuts?
So my site uses shadowbox to do display some dynamic text. Problem is I need the user to be able to copy and paste that text. Right-clicking and selecting copy works but Ctrl + C doesn't (no keyboard shortcuts do) and most people use Ctrl + C? You can see an example of what I'm talking about here. Just go to the "web" examples and click "inline". Notice keyboard shortcuts do work on the "this page" example. The only difference between the two I see is the player js files they use. "Inline" uses the html.js player and "this page" uses iframe.js. Also, I believe it uses the mootools library. Any ideas?
The best option is to disable keyboard navigation shortcuts in the shadowbox by setting the "enableKeys" option to false (see this page ). Alternatively you could do what Robby suggests and modify the shadowbox.js file, but only do this if you need to have the shadowbox keyboard navigation. I think that you want to search for this block of code and modify it so that it only cancels the default event if one of the shortcuts is used (I've added some line breaks and indention): var handleKey = function(e) { var code = SL.keyCode(e); SL.preventDefault(e); if (code == 81 || code == 88 || code == 27) { SB.close() } else { if (code == 37) { SB.previous() } else { if (code == 39) { SB.next() } else { if (code == 32) { SB[(typeof slide_timer == "number"? "pause": "play")]() } } } } }; I think you could change it to look more like this: var handleKey = function(e) { switch (SL.keyCode(e)) { case 81: case 88: case 27: SB.close() SL.preventDefault(e); break; case 37: SB.previous() SL.preventDefault(e); break; case 39: SB.next() SL.preventDefault(e); break; case 32: SB[(typeof slide_timer == "number"? "pause": "play")]() SL.preventDefault(e); break; } }; This should prevent the shadowbox event handler from swallowing any keystrokes that it doesn't care about.
Using shadowbox disables keyboard shortcuts? So my site uses shadowbox to do display some dynamic text. Problem is I need the user to be able to copy and paste that text. Right-clicking and selecting copy works but Ctrl + C doesn't (no keyboard shortcuts do) and most people use Ctrl + C? You can see an example of what I'm talking about here. Just go to the "web" examples and click "inline". Notice keyboard shortcuts do work on the "this page" example. The only difference between the two I see is the player js files they use. "Inline" uses the html.js player and "this page" uses iframe.js. Also, I believe it uses the mootools library. Any ideas?
TITLE: Using shadowbox disables keyboard shortcuts? QUESTION: So my site uses shadowbox to do display some dynamic text. Problem is I need the user to be able to copy and paste that text. Right-clicking and selecting copy works but Ctrl + C doesn't (no keyboard shortcuts do) and most people use Ctrl + C? You can see an example of what I'm talking about here. Just go to the "web" examples and click "inline". Notice keyboard shortcuts do work on the "this page" example. The only difference between the two I see is the player js files they use. "Inline" uses the html.js player and "this page" uses iframe.js. Also, I believe it uses the mootools library. Any ideas? ANSWER: The best option is to disable keyboard navigation shortcuts in the shadowbox by setting the "enableKeys" option to false (see this page ). Alternatively you could do what Robby suggests and modify the shadowbox.js file, but only do this if you need to have the shadowbox keyboard navigation. I think that you want to search for this block of code and modify it so that it only cancels the default event if one of the shortcuts is used (I've added some line breaks and indention): var handleKey = function(e) { var code = SL.keyCode(e); SL.preventDefault(e); if (code == 81 || code == 88 || code == 27) { SB.close() } else { if (code == 37) { SB.previous() } else { if (code == 39) { SB.next() } else { if (code == 32) { SB[(typeof slide_timer == "number"? "pause": "play")]() } } } } }; I think you could change it to look more like this: var handleKey = function(e) { switch (SL.keyCode(e)) { case 81: case 88: case 27: SB.close() SL.preventDefault(e); break; case 37: SB.previous() SL.preventDefault(e); break; case 39: SB.next() SL.preventDefault(e); break; case 32: SB[(typeof slide_timer == "number"? "pause": "play")]() SL.preventDefault(e); break; } }; This should prevent the shadowbox event handler from swallowing any keystrokes that it doesn't care about.
[ "javascript", "keyboard-shortcuts", "mootools" ]
3
2
1,531
3
0
2008-09-08T16:42:31.787000
2008-09-12T02:32:50.233000
50,120
50,168
Database abstraction layers for (Visual) C++
What options exist for accessing different databases from C++? Put differently, what alternatives are there to ADO? What are the pros and cons?
Microsoft ODBC. The MFC ODBC classes such as CDatabase. OleDB (via COM). And you can always go through the per-RDBMS native libraries (for example, the SQL Server native library ) DAO (don't). 3rd party ORM providers. I would recommend going through ODBC or OleDB by default. Native libraries really restrict you, DAO is no fun, there aren't a lot of great 3rd-party ORM for C++/Windows.
Database abstraction layers for (Visual) C++ What options exist for accessing different databases from C++? Put differently, what alternatives are there to ADO? What are the pros and cons?
TITLE: Database abstraction layers for (Visual) C++ QUESTION: What options exist for accessing different databases from C++? Put differently, what alternatives are there to ADO? What are the pros and cons? ANSWER: Microsoft ODBC. The MFC ODBC classes such as CDatabase. OleDB (via COM). And you can always go through the per-RDBMS native libraries (for example, the SQL Server native library ) DAO (don't). 3rd party ORM providers. I would recommend going through ODBC or OleDB by default. Native libraries really restrict you, DAO is no fun, there aren't a lot of great 3rd-party ORM for C++/Windows.
[ "c++", "database" ]
3
2
790
4
0
2008-09-08T16:45:24.460000
2008-09-08T17:05:03.650000
50,121
50,130
Ever Heard of a License Transfer Fee upon Acquisition?
My employer was recently acquired by a much larger company. In the process of sorting out all the legal details around our licenses for our development software, we have learned that the vendor of our IDE charges a "nominal" fee of 25% of the cost of a new license to transfer our existing licenses to the new corporate name. This struck me as absurd. I have not seen such a customer-unfriendly policy from any other vendor. Has anyone else seen this type of policy? Am I way off base in considering this unfriendly and abnormal?
Unfriendly? Yes. Abnormal? No. Its actually very common for tools with a hefty per-seat license fee to charge for a transfer after acquisition. I believe they do it because they can: the cost of transferring license is either overlooked during the M&A due diligence or is considered inconsequential compared to the rest. The tool vendor justifies the fee because they now have one less potential customer, and the combined company will be paying a lower price per seat due to volume discounts.
Ever Heard of a License Transfer Fee upon Acquisition? My employer was recently acquired by a much larger company. In the process of sorting out all the legal details around our licenses for our development software, we have learned that the vendor of our IDE charges a "nominal" fee of 25% of the cost of a new license to transfer our existing licenses to the new corporate name. This struck me as absurd. I have not seen such a customer-unfriendly policy from any other vendor. Has anyone else seen this type of policy? Am I way off base in considering this unfriendly and abnormal?
TITLE: Ever Heard of a License Transfer Fee upon Acquisition? QUESTION: My employer was recently acquired by a much larger company. In the process of sorting out all the legal details around our licenses for our development software, we have learned that the vendor of our IDE charges a "nominal" fee of 25% of the cost of a new license to transfer our existing licenses to the new corporate name. This struck me as absurd. I have not seen such a customer-unfriendly policy from any other vendor. Has anyone else seen this type of policy? Am I way off base in considering this unfriendly and abnormal? ANSWER: Unfriendly? Yes. Abnormal? No. Its actually very common for tools with a hefty per-seat license fee to charge for a transfer after acquisition. I believe they do it because they can: the cost of transferring license is either overlooked during the M&A due diligence or is considered inconsequential compared to the rest. The tool vendor justifies the fee because they now have one less potential customer, and the combined company will be paying a lower price per seat due to volume discounts.
[ "licensing" ]
3
3
2,842
9
0
2008-09-08T16:45:40.717000
2008-09-08T16:50:07.273000
50,140
50,212
Replace huge Case statement in Classic ASP
I have a 200+ case statement in Classic ASP which is getting out of control. It sets 5 variables, based on which case is selected. Address, Phone, Name etc. Just sets the variables and nothing else in each case. Databases or files are not an option for this application. Coming from the Perl world I would use a hash to store this info.
Brian, the classic ASP equivalent of a Perl hash is the Scripting.Dictionary object.
Replace huge Case statement in Classic ASP I have a 200+ case statement in Classic ASP which is getting out of control. It sets 5 variables, based on which case is selected. Address, Phone, Name etc. Just sets the variables and nothing else in each case. Databases or files are not an option for this application. Coming from the Perl world I would use a hash to store this info.
TITLE: Replace huge Case statement in Classic ASP QUESTION: I have a 200+ case statement in Classic ASP which is getting out of control. It sets 5 variables, based on which case is selected. Address, Phone, Name etc. Just sets the variables and nothing else in each case. Databases or files are not an option for this application. Coming from the Perl world I would use a hash to store this info. ANSWER: Brian, the classic ASP equivalent of a Perl hash is the Scripting.Dictionary object.
[ "asp-classic" ]
2
3
1,757
7
0
2008-09-08T16:53:51.897000
2008-09-08T17:18:34.133000
50,142
70,641
Symmetric key storage
My company is going to be storing sensitive data for our customers, and will be encrypting data using one of the managed.NET encryption algorithm classes. Most of the work is done, but we haven't figured out how/where to store the key. I've done some light searching and reading, and it seems like a hardware solution might be the most secure. Does anyone have any recommendations on a key storage solution or method? Thanks for your replies, everyone. spoulson, the issue is actually both the "scopes" that you mentioned. I suppose I should have been clearer. The data itself, as well as the logic that encrypts it and decrypts it is abstracted away into an ASP.NET profile provider. This profile provider allows both encrypted profile properties as well as plain text ones. The encrypted property values are stored in exactly the same way the plain text ones are - with the obvious exception that they've been encrypted. That said, the key will need to be able to be summoned for one of three reasons: The authorized web application, running on an authorized server, needs to encrypt data. Same as #1, but for decrypting the data. Authorized members of our business team need to view the encrypted data. The way I'm imagining it is that nobody would ever actually know the key - there would be a piece of software controlling the actual encrypting and decrypting of data. That said, the key still needs to come from somewhere. Full disclosure - if you couldn't already tell, I've never done anything like this before, so if I'm completely off base in my perception of how this should work, by all means, let me know.
There only two real solutions for (the technical aspect of) this problem. Assuming it's only the application itself that needs access the key... Hardware Security Module (HSM) - usually pretty expensive, and not simple to implement. Can be dedicated appliance (e.g. nCipher) or specific token (e.g. Alladin eToken). And then you still have to define how to handle that hardware... DPAPI (Windows Data Protection API). There are classes for this in System.Security.Cryptography (ProtectedMemory, ProtectedStorage, etc). This hands off key management to the OS - and it handles it well. Used in "USER_MODE", DPAPI will lock decryption of the key to the single user that encrypted it. (Without getting too detailed, the user's password is part of the encryption/decryption scheme - and no, changing the password does not foul it up.) ADDED: Best to use DPAPI for protecting your master key, and not encrypting your application's data directly. And don't forget to set strong ACLs on your encrypted key...
Symmetric key storage My company is going to be storing sensitive data for our customers, and will be encrypting data using one of the managed.NET encryption algorithm classes. Most of the work is done, but we haven't figured out how/where to store the key. I've done some light searching and reading, and it seems like a hardware solution might be the most secure. Does anyone have any recommendations on a key storage solution or method? Thanks for your replies, everyone. spoulson, the issue is actually both the "scopes" that you mentioned. I suppose I should have been clearer. The data itself, as well as the logic that encrypts it and decrypts it is abstracted away into an ASP.NET profile provider. This profile provider allows both encrypted profile properties as well as plain text ones. The encrypted property values are stored in exactly the same way the plain text ones are - with the obvious exception that they've been encrypted. That said, the key will need to be able to be summoned for one of three reasons: The authorized web application, running on an authorized server, needs to encrypt data. Same as #1, but for decrypting the data. Authorized members of our business team need to view the encrypted data. The way I'm imagining it is that nobody would ever actually know the key - there would be a piece of software controlling the actual encrypting and decrypting of data. That said, the key still needs to come from somewhere. Full disclosure - if you couldn't already tell, I've never done anything like this before, so if I'm completely off base in my perception of how this should work, by all means, let me know.
TITLE: Symmetric key storage QUESTION: My company is going to be storing sensitive data for our customers, and will be encrypting data using one of the managed.NET encryption algorithm classes. Most of the work is done, but we haven't figured out how/where to store the key. I've done some light searching and reading, and it seems like a hardware solution might be the most secure. Does anyone have any recommendations on a key storage solution or method? Thanks for your replies, everyone. spoulson, the issue is actually both the "scopes" that you mentioned. I suppose I should have been clearer. The data itself, as well as the logic that encrypts it and decrypts it is abstracted away into an ASP.NET profile provider. This profile provider allows both encrypted profile properties as well as plain text ones. The encrypted property values are stored in exactly the same way the plain text ones are - with the obvious exception that they've been encrypted. That said, the key will need to be able to be summoned for one of three reasons: The authorized web application, running on an authorized server, needs to encrypt data. Same as #1, but for decrypting the data. Authorized members of our business team need to view the encrypted data. The way I'm imagining it is that nobody would ever actually know the key - there would be a piece of software controlling the actual encrypting and decrypting of data. That said, the key still needs to come from somewhere. Full disclosure - if you couldn't already tell, I've never done anything like this before, so if I'm completely off base in my perception of how this should work, by all means, let me know. ANSWER: There only two real solutions for (the technical aspect of) this problem. Assuming it's only the application itself that needs access the key... Hardware Security Module (HSM) - usually pretty expensive, and not simple to implement. Can be dedicated appliance (e.g. nCipher) or specific token (e.g. Alladin eToken). And then you still have to define how to handle that hardware... DPAPI (Windows Data Protection API). There are classes for this in System.Security.Cryptography (ProtectedMemory, ProtectedStorage, etc). This hands off key management to the OS - and it handles it well. Used in "USER_MODE", DPAPI will lock decryption of the key to the single user that encrypted it. (Without getting too detailed, the user's password is part of the encryption/decryption scheme - and no, changing the password does not foul it up.) ADDED: Best to use DPAPI for protecting your master key, and not encrypting your application's data directly. And don't forget to set strong ACLs on your encrypted key...
[ "security", "symmetric-key", "key-storage" ]
23
9
8,887
9
0
2008-09-08T16:54:39.370000
2008-09-16T09:15:49.717000
50,144
50,198
A good algorithm similar to Levenshtein but weighted for Qwerty keyboards?
I noticed some posts here on string matching, which reminded me of an old problem I'd like to solve. Does anyone have a good Levenshtein -like algorithm that is weighted toward Qwerty keyboards? I want to compare two strings, and and allow for typos. Levenshtein is okay, but I'd prefer to also accept spelling errors based on the physical distance between keys on Qwerty keyboard. In other words, the algorithm should prefer "yelephone" to "zelephone" since the "y" key is located nearer to the "t" key than to the "z" key on most keyboards. Any help would be great... this feature isn't central to my project, so I don't want to veer off into a rat-hole when I should be doing something more productive.
In bioinformatics when you align two sequences of DNA you might have a model that has a different cost based on if the substitution is a transition or a transversion. This is exactly what you want but instead of a 4x4 matrix, you want a 40x40 matrix or some, dare I say distance function? So the cost of a replacement is from the matrix/function, not a constant. CAVEAT: Be sure that deletions and insertions are weighted properly though, so they aren't over accepted as the minimum. You'll end up with a string of insertions/deletions/no-change-substitution characters. The new function you are trying to minimize would be: d[i, j]:= minimum( d[i-1, j] + del_cost, d[i, j-1] + ins_cost, d[i-1, j-1] + keyboard_distance( s[i], t[j] ) )
A good algorithm similar to Levenshtein but weighted for Qwerty keyboards? I noticed some posts here on string matching, which reminded me of an old problem I'd like to solve. Does anyone have a good Levenshtein -like algorithm that is weighted toward Qwerty keyboards? I want to compare two strings, and and allow for typos. Levenshtein is okay, but I'd prefer to also accept spelling errors based on the physical distance between keys on Qwerty keyboard. In other words, the algorithm should prefer "yelephone" to "zelephone" since the "y" key is located nearer to the "t" key than to the "z" key on most keyboards. Any help would be great... this feature isn't central to my project, so I don't want to veer off into a rat-hole when I should be doing something more productive.
TITLE: A good algorithm similar to Levenshtein but weighted for Qwerty keyboards? QUESTION: I noticed some posts here on string matching, which reminded me of an old problem I'd like to solve. Does anyone have a good Levenshtein -like algorithm that is weighted toward Qwerty keyboards? I want to compare two strings, and and allow for typos. Levenshtein is okay, but I'd prefer to also accept spelling errors based on the physical distance between keys on Qwerty keyboard. In other words, the algorithm should prefer "yelephone" to "zelephone" since the "y" key is located nearer to the "t" key than to the "z" key on most keyboards. Any help would be great... this feature isn't central to my project, so I don't want to veer off into a rat-hole when I should be doing something more productive. ANSWER: In bioinformatics when you align two sequences of DNA you might have a model that has a different cost based on if the substitution is a transition or a transversion. This is exactly what you want but instead of a 4x4 matrix, you want a 40x40 matrix or some, dare I say distance function? So the cost of a replacement is from the matrix/function, not a constant. CAVEAT: Be sure that deletions and insertions are weighted properly though, so they aren't over accepted as the minimum. You'll end up with a string of insertions/deletions/no-change-substitution characters. The new function you are trying to minimize would be: d[i, j]:= minimum( d[i-1, j] + del_cost, d[i, j-1] + ins_cost, d[i-1, j-1] + keyboard_distance( s[i], t[j] ) )
[ "algorithm", "string", "text", "comparison" ]
25
20
4,088
1
0
2008-09-08T16:55:41.287000
2008-09-08T17:14:07.967000
50,145
50,637
How to promote WCF to a non-techie?
How would you describe and promote WCF as a technology to a non-technical client/manager/CEO/etc? What are competing solutions or ideas that they might bring up(such as those they read about in their magazines touting new technology)? What is WCF not good for that you've seen people try to shoehorn it into? -Adam
Comparing with.asmx: WCF is the next generation of Microsoft's Web service development platform, which addresses many of the issues with older versions, specifically: better interoperation, so you can interoperate with Web services that aren't from Microsoft or that are published on the Internet much more flexible, so it's easier and faster for developers to get their jobs done easier to configure without changing code, reducing the cost of maintenance significantly It may be that they raise the question of how it relates to SOA, a "service-oriented architecture". WCF is the Microsoft solution for creating applications that participate in these distributed systems.
How to promote WCF to a non-techie? How would you describe and promote WCF as a technology to a non-technical client/manager/CEO/etc? What are competing solutions or ideas that they might bring up(such as those they read about in their magazines touting new technology)? What is WCF not good for that you've seen people try to shoehorn it into? -Adam
TITLE: How to promote WCF to a non-techie? QUESTION: How would you describe and promote WCF as a technology to a non-technical client/manager/CEO/etc? What are competing solutions or ideas that they might bring up(such as those they read about in their magazines touting new technology)? What is WCF not good for that you've seen people try to shoehorn it into? -Adam ANSWER: Comparing with.asmx: WCF is the next generation of Microsoft's Web service development platform, which addresses many of the issues with older versions, specifically: better interoperation, so you can interoperate with Web services that aren't from Microsoft or that are published on the Internet much more flexible, so it's easier and faster for developers to get their jobs done easier to configure without changing code, reducing the cost of maintenance significantly It may be that they raise the question of how it relates to SOA, a "service-oriented architecture". WCF is the Microsoft solution for creating applications that participate in these distributed systems.
[ "c#", ".net", "wcf", "web-services", "soa" ]
5
6
434
4
0
2008-09-08T16:55:41.333000
2008-09-08T20:45:39.250000
50,148
50,152
Why does a "file exists" method in many languages return true for a directory?
I know that it does in PHP, and I'm pretty sure it does in Java. I haven't used the latest versions of.NET, so I won't speak for them. It seems very awkward, but I was wondering if there was an underlying reason for this.
One reason is compatibility - anyone who has done 'check for existence' knows to exclude directories; changing that behaviour may confuse those who rely on that behaviour. Secondly, the underlying code often does a check on the operating system for existence in a catlog of filesystem entries - to the OS, a directory is the same as a file. In other words, it's looking for an entry of 'xyz' in the catalog not a file with name 'xyz' in the catalog. Backwards compatability is the main reason, I suspect.
Why does a "file exists" method in many languages return true for a directory? I know that it does in PHP, and I'm pretty sure it does in Java. I haven't used the latest versions of.NET, so I won't speak for them. It seems very awkward, but I was wondering if there was an underlying reason for this.
TITLE: Why does a "file exists" method in many languages return true for a directory? QUESTION: I know that it does in PHP, and I'm pretty sure it does in Java. I haven't used the latest versions of.NET, so I won't speak for them. It seems very awkward, but I was wondering if there was an underlying reason for this. ANSWER: One reason is compatibility - anyone who has done 'check for existence' knows to exclude directories; changing that behaviour may confuse those who rely on that behaviour. Secondly, the underlying code often does a check on the operating system for existence in a catlog of filesystem entries - to the OS, a directory is the same as a file. In other words, it's looking for an entry of 'xyz' in the catalog not a file with name 'xyz' in the catalog. Backwards compatability is the main reason, I suspect.
[ "file-io", "methods", "language-design" ]
1
3
310
4
0
2008-09-08T16:57:22.560000
2008-09-08T16:59:51.947000
50,149
50,193
Best way to convert DateTime to "n Hours Ago" in SQL
I wrote a SQL function to convert a datetime value in SQL to a friendlier "n Hours Ago" or "n Days Ago" etc type of message. And I was wondering if there was a better way to do it. (Yes I know "don't do it in SQL" but for design reasons I have to do it this way). Here is the function I've written: CREATE FUNCTION dbo.GetFriendlyDateTimeValue ( @CompareDate DateTime ) RETURNS nvarchar(48) AS BEGIN DECLARE @Now DateTime DECLARE @Hours int DECLARE @Suff nvarchar(256) DECLARE @Found bit SET @Found = 0 SET @Now = getDate() SET @Hours = DATEDIFF(MI, @CompareDate, @Now)/60 IF @Hours <= 1 BEGIN SET @Suff = 'Just Now' SET @Found = 1 RETURN @Suff END IF @Hours < 24 BEGIN SET @Suff = ' Hours Ago' SET @Found = 1 END IF @Hours >= 8760 AND @Found = 0 BEGIN SET @Hours = @Hours / 8760 SET @Suff = ' Years Ago' SET @Found = 1 END IF @Hours >= 720 AND @Found = 0 BEGIN SET @Hours = @Hours / 720 SET @Suff = ' Months Ago' SET @Found = 1 END IF @Hours >= 168 AND @Found = 0 BEGIN SET @Hours = @Hours / 168 SET @Suff = ' Weeks Ago' SET @Found = 1 END IF @Hours >= 24 AND @Found = 0 BEGIN SET @Hours = @Hours / 24 SET @Suff = ' Days Ago' SET @Found = 1 END RETURN Convert(nvarchar, @Hours) + @Suff END
As you say, I probably wouldn't do it in SQL, but as a thought exercise have a MySQL implementation: CASE WHEN compare_date between date_sub(now(), INTERVAL 60 minute) and now() THEN concat(minute(TIMEDIFF(now(), compare_date)), ' minutes ago') WHEN datediff(now(), compare_date) = 1 THEN 'Yesterday' WHEN compare_date between date_sub(now(), INTERVAL 24 hour) and now() THEN concat(hour(TIMEDIFF(NOW(), compare_date)), ' hours ago') ELSE concat(datediff(now(), compare_date),' days ago') END Based on a similar sample seen on the MySQL Date and Time manual pages
Best way to convert DateTime to "n Hours Ago" in SQL I wrote a SQL function to convert a datetime value in SQL to a friendlier "n Hours Ago" or "n Days Ago" etc type of message. And I was wondering if there was a better way to do it. (Yes I know "don't do it in SQL" but for design reasons I have to do it this way). Here is the function I've written: CREATE FUNCTION dbo.GetFriendlyDateTimeValue ( @CompareDate DateTime ) RETURNS nvarchar(48) AS BEGIN DECLARE @Now DateTime DECLARE @Hours int DECLARE @Suff nvarchar(256) DECLARE @Found bit SET @Found = 0 SET @Now = getDate() SET @Hours = DATEDIFF(MI, @CompareDate, @Now)/60 IF @Hours <= 1 BEGIN SET @Suff = 'Just Now' SET @Found = 1 RETURN @Suff END IF @Hours < 24 BEGIN SET @Suff = ' Hours Ago' SET @Found = 1 END IF @Hours >= 8760 AND @Found = 0 BEGIN SET @Hours = @Hours / 8760 SET @Suff = ' Years Ago' SET @Found = 1 END IF @Hours >= 720 AND @Found = 0 BEGIN SET @Hours = @Hours / 720 SET @Suff = ' Months Ago' SET @Found = 1 END IF @Hours >= 168 AND @Found = 0 BEGIN SET @Hours = @Hours / 168 SET @Suff = ' Weeks Ago' SET @Found = 1 END IF @Hours >= 24 AND @Found = 0 BEGIN SET @Hours = @Hours / 24 SET @Suff = ' Days Ago' SET @Found = 1 END RETURN Convert(nvarchar, @Hours) + @Suff END
TITLE: Best way to convert DateTime to "n Hours Ago" in SQL QUESTION: I wrote a SQL function to convert a datetime value in SQL to a friendlier "n Hours Ago" or "n Days Ago" etc type of message. And I was wondering if there was a better way to do it. (Yes I know "don't do it in SQL" but for design reasons I have to do it this way). Here is the function I've written: CREATE FUNCTION dbo.GetFriendlyDateTimeValue ( @CompareDate DateTime ) RETURNS nvarchar(48) AS BEGIN DECLARE @Now DateTime DECLARE @Hours int DECLARE @Suff nvarchar(256) DECLARE @Found bit SET @Found = 0 SET @Now = getDate() SET @Hours = DATEDIFF(MI, @CompareDate, @Now)/60 IF @Hours <= 1 BEGIN SET @Suff = 'Just Now' SET @Found = 1 RETURN @Suff END IF @Hours < 24 BEGIN SET @Suff = ' Hours Ago' SET @Found = 1 END IF @Hours >= 8760 AND @Found = 0 BEGIN SET @Hours = @Hours / 8760 SET @Suff = ' Years Ago' SET @Found = 1 END IF @Hours >= 720 AND @Found = 0 BEGIN SET @Hours = @Hours / 720 SET @Suff = ' Months Ago' SET @Found = 1 END IF @Hours >= 168 AND @Found = 0 BEGIN SET @Hours = @Hours / 168 SET @Suff = ' Weeks Ago' SET @Found = 1 END IF @Hours >= 24 AND @Found = 0 BEGIN SET @Hours = @Hours / 24 SET @Suff = ' Days Ago' SET @Found = 1 END RETURN Convert(nvarchar, @Hours) + @Suff END ANSWER: As you say, I probably wouldn't do it in SQL, but as a thought exercise have a MySQL implementation: CASE WHEN compare_date between date_sub(now(), INTERVAL 60 minute) and now() THEN concat(minute(TIMEDIFF(now(), compare_date)), ' minutes ago') WHEN datediff(now(), compare_date) = 1 THEN 'Yesterday' WHEN compare_date between date_sub(now(), INTERVAL 24 hour) and now() THEN concat(hour(TIMEDIFF(NOW(), compare_date)), ' hours ago') ELSE concat(datediff(now(), compare_date),' days ago') END Based on a similar sample seen on the MySQL Date and Time manual pages
[ "sql", "datetime", "function" ]
8
7
13,696
8
0
2008-09-08T16:58:26.053000
2008-09-08T17:12:53.070000
50,151
50,199
What is the best way to display a status message in WPF?
I have several wpf pages with update/delete/add buttons. I want to display to the user messages like "successful delete", etc. How can I best implement this so the message is defined in a single place (similar to an asp.net master page) and I can update this message from anywhere?
You may want to consider doing a publish/subscribe ("Observer" pattern) -- define a "status changed" event on a base page, and create a custom control that sets up a delegate and event handler to listen for status updates. Then you could drop the custom control on any page that inherits from the base, and it would automatically listen for and display status messages whenever the event is fired. Edit: I put together a sample implementation of this pattern and published a blog post walking through the code.
What is the best way to display a status message in WPF? I have several wpf pages with update/delete/add buttons. I want to display to the user messages like "successful delete", etc. How can I best implement this so the message is defined in a single place (similar to an asp.net master page) and I can update this message from anywhere?
TITLE: What is the best way to display a status message in WPF? QUESTION: I have several wpf pages with update/delete/add buttons. I want to display to the user messages like "successful delete", etc. How can I best implement this so the message is defined in a single place (similar to an asp.net master page) and I can update this message from anywhere? ANSWER: You may want to consider doing a publish/subscribe ("Observer" pattern) -- define a "status changed" event on a base page, and create a custom control that sets up a delegate and event handler to listen for status updates. Then you could drop the custom control on any page that inherits from the base, and it would automatically listen for and display status messages whenever the event is fired. Edit: I put together a sample implementation of this pattern and published a blog post walking through the code.
[ "wpf" ]
4
4
2,690
2
0
2008-09-08T16:59:31.853000
2008-09-08T17:14:33.563000
50,153
50,180
Interprocess communication for Windows in C# (.NET 2.0)
I've never had to do IPC on Windows before. I'm developing a pair of programs, a standard GUI/CLI app, and a windows service. The app has to tell the service what to do. So, assuming the communication is local only, what would be the best communication method for these two processes? By best I mean more robust and less error prone, not the best performance nor the easiest to code. Note I'm asking about what to use, a standard TCP socket, named pipes, or some other means of communication only.
IPC in.Net can be achieved using: WCF using named pipes requires.Net 3.0 and above. Code example The WCF class NetNamedPipeBinding can be used for interprocess communication on the same machine. The MSDN documentaion for this class includes a code sample covering this scenario http://msdn.microsoft.com/en-us/library/system.servicemodel.netnamedpipebinding.aspx Remoting The original IPC framework released with.Net 1.0. I believe remoting is no longer being actively developed, and you are encouraged to use WCF instead Code example Inter-process communication via Remoting - uses a tcp channel Resources GenuineChannels, sell a remoting toolkit that includes a Shared Memory Channel. http://www.genuinechannels.com/Index.aspx Ingo Rammer, wrote the definitive.Net remoting book, Advanced.NET Remoting, Second Edition Win32 RPC using csharptest-net RpcLibrary I came across a project recently that has wrapped the Win32 RPC library and created a.net class library that can be used for local and remote RPC Project home page: http://csharptest.net/projects/rpclibrary/ MSDN references: How rpc works: http://technet.microsoft.com/en-us/library/cc738291(v=ws.10).aspx RPC functions: http://msdn.microsoft.com/en-us/library/aa378623(v=VS.85).aspx Also has a google protocol buffers rpc client that runs on top of the library: https://code.google.com/p/protobuf-csharp-rpc/ WM_COPYDATA For completeness it's also possible to use the WIN32 method with the WM_COPYDATA message. I've used this method before in.Net 1.1 to create a single instance application opening multiple files from windows explorer. Resources MSDN - WM_COPYDATA Code example PInvoke.net declaration Sockets Using a custom protocol (harder)
Interprocess communication for Windows in C# (.NET 2.0) I've never had to do IPC on Windows before. I'm developing a pair of programs, a standard GUI/CLI app, and a windows service. The app has to tell the service what to do. So, assuming the communication is local only, what would be the best communication method for these two processes? By best I mean more robust and less error prone, not the best performance nor the easiest to code. Note I'm asking about what to use, a standard TCP socket, named pipes, or some other means of communication only.
TITLE: Interprocess communication for Windows in C# (.NET 2.0) QUESTION: I've never had to do IPC on Windows before. I'm developing a pair of programs, a standard GUI/CLI app, and a windows service. The app has to tell the service what to do. So, assuming the communication is local only, what would be the best communication method for these two processes? By best I mean more robust and less error prone, not the best performance nor the easiest to code. Note I'm asking about what to use, a standard TCP socket, named pipes, or some other means of communication only. ANSWER: IPC in.Net can be achieved using: WCF using named pipes requires.Net 3.0 and above. Code example The WCF class NetNamedPipeBinding can be used for interprocess communication on the same machine. The MSDN documentaion for this class includes a code sample covering this scenario http://msdn.microsoft.com/en-us/library/system.servicemodel.netnamedpipebinding.aspx Remoting The original IPC framework released with.Net 1.0. I believe remoting is no longer being actively developed, and you are encouraged to use WCF instead Code example Inter-process communication via Remoting - uses a tcp channel Resources GenuineChannels, sell a remoting toolkit that includes a Shared Memory Channel. http://www.genuinechannels.com/Index.aspx Ingo Rammer, wrote the definitive.Net remoting book, Advanced.NET Remoting, Second Edition Win32 RPC using csharptest-net RpcLibrary I came across a project recently that has wrapped the Win32 RPC library and created a.net class library that can be used for local and remote RPC Project home page: http://csharptest.net/projects/rpclibrary/ MSDN references: How rpc works: http://technet.microsoft.com/en-us/library/cc738291(v=ws.10).aspx RPC functions: http://msdn.microsoft.com/en-us/library/aa378623(v=VS.85).aspx Also has a google protocol buffers rpc client that runs on top of the library: https://code.google.com/p/protobuf-csharp-rpc/ WM_COPYDATA For completeness it's also possible to use the WIN32 method with the WM_COPYDATA message. I've used this method before in.Net 1.1 to create a single instance application opening multiple files from windows explorer. Resources MSDN - WM_COPYDATA Code example PInvoke.net declaration Sockets Using a custom protocol (harder)
[ "c#", ".net", "ipc" ]
53
73
54,349
6
0
2008-09-08T17:00:00.400000
2008-09-08T17:08:16.387000
50,159
50,218
How to show all shared libraries used by executables in Linux?
I'd like to know which libraries are used by executables on my system. More specifically, I'd like to rank which libraries are used the most, along with the binaries that use them. How can I do this?
Use ldd to list shared libraries for each executable. Cleanup the output Sort, compute counts, sort by count To find the answer for all executables in the "/bin" directory: find /bin -type f -perm /a+x -exec ldd {} \; \ | grep so \ | sed -e '/^[^\t]/ d' \ | sed -e 's/\t//' \ | sed -e 's/.*=..//' \ | sed -e 's/ (0.*)//' \ | sort \ | uniq -c \ | sort -n Change "/bin" above to "/" to search all directories. Output (for just the /bin directory) will look something like this: 1 /lib64/libexpat.so.0 1 /lib64/libgcc_s.so.1 1 /lib64/libnsl.so.1 1 /lib64/libpcre.so.0 1 /lib64/libproc-3.2.7.so 1 /usr/lib64/libbeecrypt.so.6 1 /usr/lib64/libbz2.so.1 1 /usr/lib64/libelf.so.1 1 /usr/lib64/libpopt.so.0 1 /usr/lib64/librpm-4.4.so 1 /usr/lib64/librpmdb-4.4.so 1 /usr/lib64/librpmio-4.4.so 1 /usr/lib64/libsqlite3.so.0 1 /usr/lib64/libstdc++.so.6 1 /usr/lib64/libz.so.1 2 /lib64/libasound.so.2 2 /lib64/libblkid.so.1 2 /lib64/libdevmapper.so.1.02 2 /lib64/libpam_misc.so.0 2 /lib64/libpam.so.0 2 /lib64/libuuid.so.1 3 /lib64/libaudit.so.0 3 /lib64/libcrypt.so.1 3 /lib64/libdbus-1.so.3 4 /lib64/libresolv.so.2 4 /lib64/libtermcap.so.2 5 /lib64/libacl.so.1 5 /lib64/libattr.so.1 5 /lib64/libcap.so.1 6 /lib64/librt.so.1 7 /lib64/libm.so.6 9 /lib64/libpthread.so.0 13 /lib64/libselinux.so.1 13 /lib64/libsepol.so.1 22 /lib64/libdl.so.2 83 /lib64/ld-linux-x86-64.so.2 83 /lib64/libc.so.6 Edit - Removed "grep -P"
How to show all shared libraries used by executables in Linux? I'd like to know which libraries are used by executables on my system. More specifically, I'd like to rank which libraries are used the most, along with the binaries that use them. How can I do this?
TITLE: How to show all shared libraries used by executables in Linux? QUESTION: I'd like to know which libraries are used by executables on my system. More specifically, I'd like to rank which libraries are used the most, along with the binaries that use them. How can I do this? ANSWER: Use ldd to list shared libraries for each executable. Cleanup the output Sort, compute counts, sort by count To find the answer for all executables in the "/bin" directory: find /bin -type f -perm /a+x -exec ldd {} \; \ | grep so \ | sed -e '/^[^\t]/ d' \ | sed -e 's/\t//' \ | sed -e 's/.*=..//' \ | sed -e 's/ (0.*)//' \ | sort \ | uniq -c \ | sort -n Change "/bin" above to "/" to search all directories. Output (for just the /bin directory) will look something like this: 1 /lib64/libexpat.so.0 1 /lib64/libgcc_s.so.1 1 /lib64/libnsl.so.1 1 /lib64/libpcre.so.0 1 /lib64/libproc-3.2.7.so 1 /usr/lib64/libbeecrypt.so.6 1 /usr/lib64/libbz2.so.1 1 /usr/lib64/libelf.so.1 1 /usr/lib64/libpopt.so.0 1 /usr/lib64/librpm-4.4.so 1 /usr/lib64/librpmdb-4.4.so 1 /usr/lib64/librpmio-4.4.so 1 /usr/lib64/libsqlite3.so.0 1 /usr/lib64/libstdc++.so.6 1 /usr/lib64/libz.so.1 2 /lib64/libasound.so.2 2 /lib64/libblkid.so.1 2 /lib64/libdevmapper.so.1.02 2 /lib64/libpam_misc.so.0 2 /lib64/libpam.so.0 2 /lib64/libuuid.so.1 3 /lib64/libaudit.so.0 3 /lib64/libcrypt.so.1 3 /lib64/libdbus-1.so.3 4 /lib64/libresolv.so.2 4 /lib64/libtermcap.so.2 5 /lib64/libacl.so.1 5 /lib64/libattr.so.1 5 /lib64/libcap.so.1 6 /lib64/librt.so.1 7 /lib64/libm.so.6 9 /lib64/libpthread.so.0 13 /lib64/libselinux.so.1 13 /lib64/libsepol.so.1 22 /lib64/libdl.so.2 83 /lib64/ld-linux-x86-64.so.2 83 /lib64/libc.so.6 Edit - Removed "grep -P"
[ "linux", "shared-libraries" ]
291
327
457,595
14
0
2008-09-08T17:02:25.623000
2008-09-08T17:21:54.407000
50,164
50,215
How can I lock down my MS-SQL DB from my users and yet still access it through ODBC?
I've got an ms-access application that's accessing and ms-sql db through an ODBC connection. I'm trying to force my users to update the data only through the application portion, but I don't care if they read the data directly or through their own custom ms-access db (they use it for creating ad hoc reports). What I'm looking for is a way to make the data only editable if they are using the compiled.mde file I distribute to them. I know I can make the data read only for the general population, and editable for select users. Is there a way I can get ms-sql to make the data editable only if they are accessing it through the my canned mde? Thought, is there a way to get ms-access to log into the database as a different user (or change the login once connected)? @Jake, Yes, it's using forms. What I'm looking to do is just have it switch users once when I have my launchpad/mainmenu form pop up. @Peter, That is indeed the direction I'm headed. What I haven't determined was how to go about switching to that second ID. I'm not so worried about the password being sniffed, the users are all internal, and on an internal LAN. If they can sniff that password, they can certainly sniff the one for my privileged ID. @no one in general, Right now its security by obscurity. I've given the uses a special.mdb for doing reporting that will let them read data, but not update it. They don't know about relinking to the tables through the ODBC connection. A slightly more ms-access/DB literate user could by pass what I've done in seconds - and there a few who imagine themselves to be DBA, so they will figure it out eventually.
There is a way to do this that is effective with internal users, but can be hacked. You create two IDs for each user. One is a reporting ID that has read-only access. This is they ID that the user knows about: Fred / mypassword The second is an ID that can do updates. That id is Fred_app / mypassword_mangled. They log on to your app with Fred. When your application accesses data, it uses the application id. This can be sniffed, but for many applications it is sufficient.
How can I lock down my MS-SQL DB from my users and yet still access it through ODBC? I've got an ms-access application that's accessing and ms-sql db through an ODBC connection. I'm trying to force my users to update the data only through the application portion, but I don't care if they read the data directly or through their own custom ms-access db (they use it for creating ad hoc reports). What I'm looking for is a way to make the data only editable if they are using the compiled.mde file I distribute to them. I know I can make the data read only for the general population, and editable for select users. Is there a way I can get ms-sql to make the data editable only if they are accessing it through the my canned mde? Thought, is there a way to get ms-access to log into the database as a different user (or change the login once connected)? @Jake, Yes, it's using forms. What I'm looking to do is just have it switch users once when I have my launchpad/mainmenu form pop up. @Peter, That is indeed the direction I'm headed. What I haven't determined was how to go about switching to that second ID. I'm not so worried about the password being sniffed, the users are all internal, and on an internal LAN. If they can sniff that password, they can certainly sniff the one for my privileged ID. @no one in general, Right now its security by obscurity. I've given the uses a special.mdb for doing reporting that will let them read data, but not update it. They don't know about relinking to the tables through the ODBC connection. A slightly more ms-access/DB literate user could by pass what I've done in seconds - and there a few who imagine themselves to be DBA, so they will figure it out eventually.
TITLE: How can I lock down my MS-SQL DB from my users and yet still access it through ODBC? QUESTION: I've got an ms-access application that's accessing and ms-sql db through an ODBC connection. I'm trying to force my users to update the data only through the application portion, but I don't care if they read the data directly or through their own custom ms-access db (they use it for creating ad hoc reports). What I'm looking for is a way to make the data only editable if they are using the compiled.mde file I distribute to them. I know I can make the data read only for the general population, and editable for select users. Is there a way I can get ms-sql to make the data editable only if they are accessing it through the my canned mde? Thought, is there a way to get ms-access to log into the database as a different user (or change the login once connected)? @Jake, Yes, it's using forms. What I'm looking to do is just have it switch users once when I have my launchpad/mainmenu form pop up. @Peter, That is indeed the direction I'm headed. What I haven't determined was how to go about switching to that second ID. I'm not so worried about the password being sniffed, the users are all internal, and on an internal LAN. If they can sniff that password, they can certainly sniff the one for my privileged ID. @no one in general, Right now its security by obscurity. I've given the uses a special.mdb for doing reporting that will let them read data, but not update it. They don't know about relinking to the tables through the ODBC connection. A slightly more ms-access/DB literate user could by pass what I've done in seconds - and there a few who imagine themselves to be DBA, so they will figure it out eventually. ANSWER: There is a way to do this that is effective with internal users, but can be hacked. You create two IDs for each user. One is a reporting ID that has read-only access. This is they ID that the user knows about: Fred / mypassword The second is an ID that can do updates. That id is Fred_app / mypassword_mangled. They log on to your app with Fred. When your application accesses data, it uses the application id. This can be sniffed, but for many applications it is sufficient.
[ "sql-server", "ms-access", "odbc" ]
2
2
2,921
2
0
2008-09-08T17:04:17.910000
2008-09-08T17:21:04.610000
50,169
50,240
Optimizing a LINQ to SQL query
I have a query that looks like this: public IList FetchLatestOrders(int pageIndex, int recordCount) { DatabaseDataContext db = new DatabaseDataContext(); return (from o in db.Orders orderby o.CreatedDate descending select o).Skip(pageIndex * recordCount).Take(recordCount).ToList(); } I need to print the information of the order and the user who created it: foreach (var o in FetchLatestOrders(0, 10)) { Console.WriteLine("{0} {1}", o.Code, o.Customer.Name); } This produces a SQL query to bring the orders and one query for each order to bring the customer. Is it possible to optimize the query so that it brings the orders and it's customer in one SQL query? Thanks UDPATE: By suggestion of sirrocco I changed the query like this and it works. Only one select query is generated: public IList FetchLatestOrders(int pageIndex, int recordCount) { var options = new DataLoadOptions(); options.LoadWith (o => o.Customer); using (var db = new DatabaseDataContext()) { db.LoadOptions = options; return (from o in db.Orders orderby o.CreatedDate descending select o).Skip(pageIndex * recordCount).Take(recordCount).ToList(); } } Thanks sirrocco.
Something else you can do is EagerLoading. In Linq2SQL you can use LoadOptions: More on LoadOptions One VERY weird thing about L2S is that you can set LoadOptions only before the first query is sent to the Database.
Optimizing a LINQ to SQL query I have a query that looks like this: public IList FetchLatestOrders(int pageIndex, int recordCount) { DatabaseDataContext db = new DatabaseDataContext(); return (from o in db.Orders orderby o.CreatedDate descending select o).Skip(pageIndex * recordCount).Take(recordCount).ToList(); } I need to print the information of the order and the user who created it: foreach (var o in FetchLatestOrders(0, 10)) { Console.WriteLine("{0} {1}", o.Code, o.Customer.Name); } This produces a SQL query to bring the orders and one query for each order to bring the customer. Is it possible to optimize the query so that it brings the orders and it's customer in one SQL query? Thanks UDPATE: By suggestion of sirrocco I changed the query like this and it works. Only one select query is generated: public IList FetchLatestOrders(int pageIndex, int recordCount) { var options = new DataLoadOptions(); options.LoadWith (o => o.Customer); using (var db = new DatabaseDataContext()) { db.LoadOptions = options; return (from o in db.Orders orderby o.CreatedDate descending select o).Skip(pageIndex * recordCount).Take(recordCount).ToList(); } } Thanks sirrocco.
TITLE: Optimizing a LINQ to SQL query QUESTION: I have a query that looks like this: public IList FetchLatestOrders(int pageIndex, int recordCount) { DatabaseDataContext db = new DatabaseDataContext(); return (from o in db.Orders orderby o.CreatedDate descending select o).Skip(pageIndex * recordCount).Take(recordCount).ToList(); } I need to print the information of the order and the user who created it: foreach (var o in FetchLatestOrders(0, 10)) { Console.WriteLine("{0} {1}", o.Code, o.Customer.Name); } This produces a SQL query to bring the orders and one query for each order to bring the customer. Is it possible to optimize the query so that it brings the orders and it's customer in one SQL query? Thanks UDPATE: By suggestion of sirrocco I changed the query like this and it works. Only one select query is generated: public IList FetchLatestOrders(int pageIndex, int recordCount) { var options = new DataLoadOptions(); options.LoadWith (o => o.Customer); using (var db = new DatabaseDataContext()) { db.LoadOptions = options; return (from o in db.Orders orderby o.CreatedDate descending select o).Skip(pageIndex * recordCount).Take(recordCount).ToList(); } } Thanks sirrocco. ANSWER: Something else you can do is EagerLoading. In Linq2SQL you can use LoadOptions: More on LoadOptions One VERY weird thing about L2S is that you can set LoadOptions only before the first query is sent to the Database.
[ "linq", "linq-to-sql", "optimization" ]
7
4
2,038
3
0
2008-09-08T17:05:22.480000
2008-09-08T17:33:54.407000
50,170
50,201
Does "display: marker" work in any current browsers, and if so, how?
I can't be sure if my code is sucking, or if it's just that the browsers haven't caught up with the spec yet. My goal is to simulate list markers using generated content, so as to get e.g. continuation of the counters from list to list in pure CSS. So the code below, which I think is correct according to the spec, is like this: html { counter-reset: myCounter; } li { counter-increment: myCounter; } li:before { content: counter(myCounter)". "; display: marker; width: 5em; text-align: right; marker-offset: 1em; } The quick brown fox jumped over But this doesn't seem to generate markers, in either FF3, Chrome, or IE8 beta 2, and if I recall correctly not Opera either (although I've since uninstalled Opera). So, does anyone know if markers are supposed to work? Quirksmode.org isn't being its usual helpful self in this regard:(.
Apparently marker was introduced as a value in CSS 2 but did not make it to CSS 2.1 because of lacking browser support. I suppose that didn’t help its popularity … Source: http://de.selfhtml.org/css/eigenschaften/positionierung.htm#display (German)
Does "display: marker" work in any current browsers, and if so, how? I can't be sure if my code is sucking, or if it's just that the browsers haven't caught up with the spec yet. My goal is to simulate list markers using generated content, so as to get e.g. continuation of the counters from list to list in pure CSS. So the code below, which I think is correct according to the spec, is like this: html { counter-reset: myCounter; } li { counter-increment: myCounter; } li:before { content: counter(myCounter)". "; display: marker; width: 5em; text-align: right; marker-offset: 1em; } The quick brown fox jumped over But this doesn't seem to generate markers, in either FF3, Chrome, or IE8 beta 2, and if I recall correctly not Opera either (although I've since uninstalled Opera). So, does anyone know if markers are supposed to work? Quirksmode.org isn't being its usual helpful self in this regard:(.
TITLE: Does "display: marker" work in any current browsers, and if so, how? QUESTION: I can't be sure if my code is sucking, or if it's just that the browsers haven't caught up with the spec yet. My goal is to simulate list markers using generated content, so as to get e.g. continuation of the counters from list to list in pure CSS. So the code below, which I think is correct according to the spec, is like this: html { counter-reset: myCounter; } li { counter-increment: myCounter; } li:before { content: counter(myCounter)". "; display: marker; width: 5em; text-align: right; marker-offset: 1em; } The quick brown fox jumped over But this doesn't seem to generate markers, in either FF3, Chrome, or IE8 beta 2, and if I recall correctly not Opera either (although I've since uninstalled Opera). So, does anyone know if markers are supposed to work? Quirksmode.org isn't being its usual helpful self in this regard:(. ANSWER: Apparently marker was introduced as a value in CSS 2 but did not make it to CSS 2.1 because of lacking browser support. I suppose that didn’t help its popularity … Source: http://de.selfhtml.org/css/eigenschaften/positionierung.htm#display (German)
[ "css", "cross-browser" ]
2
3
3,621
2
0
2008-09-08T17:05:30.950000
2008-09-08T17:15:04.373000
50,182
52,266
Linux/X11 input library without creating a window
Is there a good library to use for gathering user input in Linux from the mouse/keyboard/joystick that doesn't force you to create a visible window to do so? SDL lets you get user input in a reasonable way, but seems to force you to create a window, which is troublesome if you have abstracted control so the control machine doesn't have to be the same as the render machine. However, if the control and render machines are the same, this results in an ugly little SDL window on top of your display. Edit To Clarify: The renderer has an output window, in its normal use case, that window is full screen, except when they are both running on the same computer, just so it is possible to give the controller focus. There can actually be multiple renderers displaying a different view of the same data on different computers all controlled by the same controller, hence the total decoupling of the input from the output (Making taking advantage of the built in X11 client/server stuff for display less useable) Also, multiple controller applications for one renderer is also possible. Communication between the controllers and renderers is via sockets.
OK, if you're under X11 and you want to get the kbd, you need to do a grab. If you're not, my only good answer is ncurses from a terminal. Here's how you grab everything from the keyboard and release again: /* Demo code, needs more error checking, compile * with "gcc nameofthisfile.c -lX11". /* weird formatting for markdown follows. argh! */ #include int main(int argc, char **argv) { Display *dpy; XEvent ev; char *s; unsigned int kc; int quit = 0; if (NULL==(dpy=XOpenDisplay(NULL))) { perror(argv[0]); exit(1); } /* * You might want to warp the pointer to somewhere that you know * is not associated with anything that will drain events. * (void)XWarpPointer(dpy, None, DefaultRootWindow(dpy), 0, 0, 0, 0, x, y); */ XGrabKeyboard(dpy, DefaultRootWindow(dpy), True, GrabModeAsync, GrabModeAsync, CurrentTime); printf("KEYBOARD GRABBED! Hit 'q' to quit!\n" "If this job is killed or you get stuck, use Ctrl-Alt-F1\n" "to switch to a console (if possible) and run something that\n" "ungrabs the keyboard.\n"); /* A very simple event loop: start at "man XEvent" for more info. */ /* Also see "apropos XGrab" for various ways to lock down access to * certain types of info. coming out of or going into the server */ for (;!quit;) { XNextEvent(dpy, &ev); switch (ev.type) { case KeyPress: kc = ((XKeyPressedEvent*)&ev)->keycode; s = XKeysymToString(XKeycodeToKeysym(dpy, kc, 0)); /* s is NULL or a static no-touchy return string. */ if (s) printf("KEY:%s\n", s); if (!strcmp(s, "q")) quit=~0; break; case Expose: /* Often, it's a good idea to drain residual exposes to * avoid visiting Blinky's Fun Club. */ while (XCheckTypedEvent(dpy, Expose, &ev)) /* empty body */; break; case ButtonPress: case ButtonRelease: case KeyRelease: case MotionNotify: case ConfigureNotify: default: break; } } XUngrabKeyboard(dpy, CurrentTime); if (XCloseDisplay(dpy)) { perror(argv[0]); exit(1); } return 0; } Run this from a terminal and all kbd events should hit it. I'm testing it under Xorg but it uses venerable, stable Xlib mechanisms. Hope this helps. BE CAREFUL with grabs under X. When you're new to them, sometimes it's a good idea to start a time delay process that will ungrab the server when you're testing code and let it sit and run and ungrab every couple of minutes. It saves having to kill or switch away from the server to externally reset state. From here, I'll leave it to you to decide how to multiplex renderes. Read the XGrabKeyboard docs and XEvent docs to get started. If you have small windows exposed at the screen corners, you could jam the pointer into one corner to select a controller. XWarpPointer can shove the pointer to one of them as well from code. One more point: you can grab the pointer as well, and other resources. If you had one controller running on the box in front of which you sit, you could use keyboard and mouse input to switch it between open sockets with different renderers. You shouldn't need to resize the output window to less than full screen anymore with this approach, ever. With more work, you could actually drop alpha-blended overlays on top using the SHAPE and COMPOSITE extensions to get a nice overlay feature in response to user input (which might count as gilding the lily).
Linux/X11 input library without creating a window Is there a good library to use for gathering user input in Linux from the mouse/keyboard/joystick that doesn't force you to create a visible window to do so? SDL lets you get user input in a reasonable way, but seems to force you to create a window, which is troublesome if you have abstracted control so the control machine doesn't have to be the same as the render machine. However, if the control and render machines are the same, this results in an ugly little SDL window on top of your display. Edit To Clarify: The renderer has an output window, in its normal use case, that window is full screen, except when they are both running on the same computer, just so it is possible to give the controller focus. There can actually be multiple renderers displaying a different view of the same data on different computers all controlled by the same controller, hence the total decoupling of the input from the output (Making taking advantage of the built in X11 client/server stuff for display less useable) Also, multiple controller applications for one renderer is also possible. Communication between the controllers and renderers is via sockets.
TITLE: Linux/X11 input library without creating a window QUESTION: Is there a good library to use for gathering user input in Linux from the mouse/keyboard/joystick that doesn't force you to create a visible window to do so? SDL lets you get user input in a reasonable way, but seems to force you to create a window, which is troublesome if you have abstracted control so the control machine doesn't have to be the same as the render machine. However, if the control and render machines are the same, this results in an ugly little SDL window on top of your display. Edit To Clarify: The renderer has an output window, in its normal use case, that window is full screen, except when they are both running on the same computer, just so it is possible to give the controller focus. There can actually be multiple renderers displaying a different view of the same data on different computers all controlled by the same controller, hence the total decoupling of the input from the output (Making taking advantage of the built in X11 client/server stuff for display less useable) Also, multiple controller applications for one renderer is also possible. Communication between the controllers and renderers is via sockets. ANSWER: OK, if you're under X11 and you want to get the kbd, you need to do a grab. If you're not, my only good answer is ncurses from a terminal. Here's how you grab everything from the keyboard and release again: /* Demo code, needs more error checking, compile * with "gcc nameofthisfile.c -lX11". /* weird formatting for markdown follows. argh! */ #include int main(int argc, char **argv) { Display *dpy; XEvent ev; char *s; unsigned int kc; int quit = 0; if (NULL==(dpy=XOpenDisplay(NULL))) { perror(argv[0]); exit(1); } /* * You might want to warp the pointer to somewhere that you know * is not associated with anything that will drain events. * (void)XWarpPointer(dpy, None, DefaultRootWindow(dpy), 0, 0, 0, 0, x, y); */ XGrabKeyboard(dpy, DefaultRootWindow(dpy), True, GrabModeAsync, GrabModeAsync, CurrentTime); printf("KEYBOARD GRABBED! Hit 'q' to quit!\n" "If this job is killed or you get stuck, use Ctrl-Alt-F1\n" "to switch to a console (if possible) and run something that\n" "ungrabs the keyboard.\n"); /* A very simple event loop: start at "man XEvent" for more info. */ /* Also see "apropos XGrab" for various ways to lock down access to * certain types of info. coming out of or going into the server */ for (;!quit;) { XNextEvent(dpy, &ev); switch (ev.type) { case KeyPress: kc = ((XKeyPressedEvent*)&ev)->keycode; s = XKeysymToString(XKeycodeToKeysym(dpy, kc, 0)); /* s is NULL or a static no-touchy return string. */ if (s) printf("KEY:%s\n", s); if (!strcmp(s, "q")) quit=~0; break; case Expose: /* Often, it's a good idea to drain residual exposes to * avoid visiting Blinky's Fun Club. */ while (XCheckTypedEvent(dpy, Expose, &ev)) /* empty body */; break; case ButtonPress: case ButtonRelease: case KeyRelease: case MotionNotify: case ConfigureNotify: default: break; } } XUngrabKeyboard(dpy, CurrentTime); if (XCloseDisplay(dpy)) { perror(argv[0]); exit(1); } return 0; } Run this from a terminal and all kbd events should hit it. I'm testing it under Xorg but it uses venerable, stable Xlib mechanisms. Hope this helps. BE CAREFUL with grabs under X. When you're new to them, sometimes it's a good idea to start a time delay process that will ungrab the server when you're testing code and let it sit and run and ungrab every couple of minutes. It saves having to kill or switch away from the server to externally reset state. From here, I'll leave it to you to decide how to multiplex renderes. Read the XGrabKeyboard docs and XEvent docs to get started. If you have small windows exposed at the screen corners, you could jam the pointer into one corner to select a controller. XWarpPointer can shove the pointer to one of them as well from code. One more point: you can grab the pointer as well, and other resources. If you had one controller running on the box in front of which you sit, you could use keyboard and mouse input to switch it between open sockets with different renderers. You shouldn't need to resize the output window to less than full screen anymore with this approach, ever. With more work, you could actually drop alpha-blended overlays on top using the SHAPE and COMPOSITE extensions to get a nice overlay feature in response to user input (which might count as gilding the lily).
[ "linux", "user-input", "sdl" ]
7
7
5,878
2
0
2008-09-08T17:09:40.143000
2008-09-09T16:14:01.033000
50,194
50,225
Source Control for Everyone?
I've got a number of non-technical users that all share a set of project files. It would be ideal to have them using version control, but I think that both subversion and git are too technical for non-technical office staff. Is there any distributed source control software that would work well for normal people?
If source control is too technical they can use Subversion with WebDav. The less technical people will just save files normally from whatever application they use, without worrying/thinking about source control. They get the benefit of auto-versioning without doing anything. When ever they need more functionality they can learn to use TortoiseSVN to view diffs, revert to old version that were made automatically for them etc... From the subversion book: Because so many operating systems already have integrated WebDAV clients, the use case for this feature borders on fantastical: imagine an office of ordinary users running Microsoft Windows or Mac OS. Each user “mounts” the Subversion repository, which appears to be an ordinary network folder. They use the shared folder as they always do: open files, edit them, save them. Meanwhile, the server is automatically versioning everything. Any administrator (or knowledgeable user) can still use a Subversion client to search history and retrieve older versions of data.
Source Control for Everyone? I've got a number of non-technical users that all share a set of project files. It would be ideal to have them using version control, but I think that both subversion and git are too technical for non-technical office staff. Is there any distributed source control software that would work well for normal people?
TITLE: Source Control for Everyone? QUESTION: I've got a number of non-technical users that all share a set of project files. It would be ideal to have them using version control, but I think that both subversion and git are too technical for non-technical office staff. Is there any distributed source control software that would work well for normal people? ANSWER: If source control is too technical they can use Subversion with WebDav. The less technical people will just save files normally from whatever application they use, without worrying/thinking about source control. They get the benefit of auto-versioning without doing anything. When ever they need more functionality they can learn to use TortoiseSVN to view diffs, revert to old version that were made automatically for them etc... From the subversion book: Because so many operating systems already have integrated WebDAV clients, the use case for this feature borders on fantastical: imagine an office of ordinary users running Microsoft Windows or Mac OS. Each user “mounts” the Subversion repository, which appears to be an ordinary network folder. They use the shared folder as they always do: open files, edit them, save them. Meanwhile, the server is automatically versioning everything. Any administrator (or knowledgeable user) can still use a Subversion client to search history and retrieve older versions of data.
[ "svn", "git", "version-control" ]
18
17
1,086
11
0
2008-09-08T17:13:16.533000
2008-09-08T17:28:08.930000
50,213
50,326
Are there any issues with using log4net in a multi-threaded environment?
I'm wondering if anyone has any experience using log4net in a multi-threaded environment like asp.net. We are currently using log4net and I want to make sure we won't run into any issues.
We run log4net (and log4cxx) in highly multi-threaded environments without issue. You will want to be careful how you configure them though. The issue with log4net that Jeff describes pertains to the use of a certain appender. We stick with simple log file appenders on the whole to reduce the impact of logging on the operation of the code. Writing a line to a file is pretty minimal, kicking off another database transaction is very heavy.
Are there any issues with using log4net in a multi-threaded environment? I'm wondering if anyone has any experience using log4net in a multi-threaded environment like asp.net. We are currently using log4net and I want to make sure we won't run into any issues.
TITLE: Are there any issues with using log4net in a multi-threaded environment? QUESTION: I'm wondering if anyone has any experience using log4net in a multi-threaded environment like asp.net. We are currently using log4net and I want to make sure we won't run into any issues. ANSWER: We run log4net (and log4cxx) in highly multi-threaded environments without issue. You will want to be careful how you configure them though. The issue with log4net that Jeff describes pertains to the use of a certain appender. We stick with simple log file appenders on the whole to reduce the impact of logging on the operation of the code. Writing a line to a file is pretty minimal, kicking off another database transaction is very heavy.
[ "log4net" ]
3
1
5,180
1
0
2008-09-08T17:20:03.473000
2008-09-08T18:15:08.677000
50,217
50,229
Does a language-specific IDE have any advantages over a plugin for a multi-language IDE?
I do mostly Java and C/C++ development, but I'm starting to do more web development (PHP, Rails) and Eiffel (learning a new language is always good). Currently, I use Eclipse for Java, C/C++, and Ruby (not Rails). Since I know the environment, I'm thinking that it would be easier for me to find a plugin and use Eclipse for all of my development languages. But are there cases where a language-specific IDE (EiffelStudio for Eiffel, as an example) would be better than Eclipse?
I have used many many IDE's and in most cases to me it breaks down to personal preferences. Sometimes the language specific ones have some addins/addons/features that are nice but unless they are things you can not live without you should go with what is most comfortable for you. I would think that if you are comfortable with the multi-language IDE it would be better to stick with that one. This way you dont have to memorize multiple IDE layouts, keyboard shortcuts etc.
Does a language-specific IDE have any advantages over a plugin for a multi-language IDE? I do mostly Java and C/C++ development, but I'm starting to do more web development (PHP, Rails) and Eiffel (learning a new language is always good). Currently, I use Eclipse for Java, C/C++, and Ruby (not Rails). Since I know the environment, I'm thinking that it would be easier for me to find a plugin and use Eclipse for all of my development languages. But are there cases where a language-specific IDE (EiffelStudio for Eiffel, as an example) would be better than Eclipse?
TITLE: Does a language-specific IDE have any advantages over a plugin for a multi-language IDE? QUESTION: I do mostly Java and C/C++ development, but I'm starting to do more web development (PHP, Rails) and Eiffel (learning a new language is always good). Currently, I use Eclipse for Java, C/C++, and Ruby (not Rails). Since I know the environment, I'm thinking that it would be easier for me to find a plugin and use Eclipse for all of my development languages. But are there cases where a language-specific IDE (EiffelStudio for Eiffel, as an example) would be better than Eclipse? ANSWER: I have used many many IDE's and in most cases to me it breaks down to personal preferences. Sometimes the language specific ones have some addins/addons/features that are nice but unless they are things you can not live without you should go with what is most comfortable for you. I would think that if you are comfortable with the multi-language IDE it would be better to stick with that one. This way you dont have to memorize multiple IDE layouts, keyboard shortcuts etc.
[ "ide" ]
5
7
472
3
0
2008-09-08T17:21:38.010000
2008-09-08T17:29:15.870000
50,223
50,475
How to repeatedly merge branches in Mercurial
We're using Mercurial where I work and I want to have a setup similar to how I used SVN: Trunk Tags Production Branches Since Mercurial supports branches natively, I know how to create a named branch, but I can't find any documentation on how to repeatedly merge 'Trunk' with 'Production'. Quite simply, I want to have a development branch for normal work and a production branch that I routinely pull changes from the development branch into. How do I do this with Mercurial?
As the previous poster mentioned, the transplant extension can be used for cherry-picking individual changes from one branch to another. If, however, you always want to pull all the latest changes, the hg merge command will get you there. The simplest case is when you're using clones to implement branching (since that's the use case Mercurial is designed around). Assuming you've turned on the built-in fetch extension in your.hgrc / Mercurial.ini: cd ~/src/development # hack hack hack hg commit -m "Made some changes" cd../production hg fetch../development If you're using local branches: hg update -C development # hack hack hack hg commit -m "Made some changes" hg update -C production hg merge development hg commit -m "Merged from development"
How to repeatedly merge branches in Mercurial We're using Mercurial where I work and I want to have a setup similar to how I used SVN: Trunk Tags Production Branches Since Mercurial supports branches natively, I know how to create a named branch, but I can't find any documentation on how to repeatedly merge 'Trunk' with 'Production'. Quite simply, I want to have a development branch for normal work and a production branch that I routinely pull changes from the development branch into. How do I do this with Mercurial?
TITLE: How to repeatedly merge branches in Mercurial QUESTION: We're using Mercurial where I work and I want to have a setup similar to how I used SVN: Trunk Tags Production Branches Since Mercurial supports branches natively, I know how to create a named branch, but I can't find any documentation on how to repeatedly merge 'Trunk' with 'Production'. Quite simply, I want to have a development branch for normal work and a production branch that I routinely pull changes from the development branch into. How do I do this with Mercurial? ANSWER: As the previous poster mentioned, the transplant extension can be used for cherry-picking individual changes from one branch to another. If, however, you always want to pull all the latest changes, the hg merge command will get you there. The simplest case is when you're using clones to implement branching (since that's the use case Mercurial is designed around). Assuming you've turned on the built-in fetch extension in your.hgrc / Mercurial.ini: cd ~/src/development # hack hack hack hg commit -m "Made some changes" cd../production hg fetch../development If you're using local branches: hg update -C development # hack hack hack hg commit -m "Made some changes" hg update -C production hg merge development hg commit -m "Merged from development"
[ "mercurial", "version-control" ]
14
20
5,450
2
0
2008-09-08T17:27:16.140000
2008-09-08T19:26:01.690000
50,236
50,241
How do you programmatically change the tab order in a Win32 dialog?
Often time I need to add a control to a dialog after the dialog has been generated via dialog template and CreateDialogIndirect. In these cases the tab order is set by the dialog template and there is no obvious way to change the tab order by including a newly created control.
I recently discovered that you can use SetWindowPos to accomplish this. Determine which control after which you want to insert the new control in the tab order then use SetWindowPos like this: SetWindowPos(hNewControl, hOldControl, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE); This changes the z-order of controls which, in turn, establishes the tab order.
How do you programmatically change the tab order in a Win32 dialog? Often time I need to add a control to a dialog after the dialog has been generated via dialog template and CreateDialogIndirect. In these cases the tab order is set by the dialog template and there is no obvious way to change the tab order by including a newly created control.
TITLE: How do you programmatically change the tab order in a Win32 dialog? QUESTION: Often time I need to add a control to a dialog after the dialog has been generated via dialog template and CreateDialogIndirect. In these cases the tab order is set by the dialog template and there is no obvious way to change the tab order by including a newly created control. ANSWER: I recently discovered that you can use SetWindowPos to accomplish this. Determine which control after which you want to insert the new control in the tab order then use SetWindowPos like this: SetWindowPos(hNewControl, hOldControl, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE); This changes the z-order of controls which, in turn, establishes the tab order.
[ "winapi", "dialog" ]
14
20
9,286
2
0
2008-09-08T17:31:55.753000
2008-09-08T17:34:11.130000
50,237
50,314
View of allocated memory
I'm looking for a tool ($, free, open source; I don't care) that will allow me to view not just the memory statistics for a.NET program, but also the object hierarchy. I'd really like to be able to drill down each thourgh each object and view it's foot print, as well as all the object's it references. I've looked at things like Ants Profiler from RedGate, but it's not quite what I want: I can't view specific instances. EDIT: I've used the.NET Memory Profiler (the one that ships with visual studio, and the one that used to be part of the SDK (?))before, and while it's really good (and shows views most other don't), what I'm really after is being able to drill down through my object hierarchy, viewing each object instance.
I have used JetBrains DotTrace and Redgate Ants, both of which I would recommend. A lesser known profiler I have also used is.Net Memory Profiler ( http://memprofiler.com/ ), which at the time I used it provided a different perspective on memory usage than the former two profilers mentioned. I find DotTrace and Ants to be very similar, though each one is slightly different.
View of allocated memory I'm looking for a tool ($, free, open source; I don't care) that will allow me to view not just the memory statistics for a.NET program, but also the object hierarchy. I'd really like to be able to drill down each thourgh each object and view it's foot print, as well as all the object's it references. I've looked at things like Ants Profiler from RedGate, but it's not quite what I want: I can't view specific instances. EDIT: I've used the.NET Memory Profiler (the one that ships with visual studio, and the one that used to be part of the SDK (?))before, and while it's really good (and shows views most other don't), what I'm really after is being able to drill down through my object hierarchy, viewing each object instance.
TITLE: View of allocated memory QUESTION: I'm looking for a tool ($, free, open source; I don't care) that will allow me to view not just the memory statistics for a.NET program, but also the object hierarchy. I'd really like to be able to drill down each thourgh each object and view it's foot print, as well as all the object's it references. I've looked at things like Ants Profiler from RedGate, but it's not quite what I want: I can't view specific instances. EDIT: I've used the.NET Memory Profiler (the one that ships with visual studio, and the one that used to be part of the SDK (?))before, and while it's really good (and shows views most other don't), what I'm really after is being able to drill down through my object hierarchy, viewing each object instance. ANSWER: I have used JetBrains DotTrace and Redgate Ants, both of which I would recommend. A lesser known profiler I have also used is.Net Memory Profiler ( http://memprofiler.com/ ), which at the time I used it provided a different perspective on memory usage than the former two profilers mentioned. I find DotTrace and Ants to be very similar, though each one is slightly different.
[ ".net", "memory" ]
6
5
778
3
0
2008-09-08T17:32:55.237000
2008-09-08T18:06:27.933000
50,251
55,511
Dynamic linq:Creating an extension method that produces JSON result
I'm stuck trying to create a dynamic linq extension method that returns a string in JSON format - I'm using System.Linq.Dynamic and Newtonsoft.Json and I can't get the Linq.Dynamic to parse the "cell=new object[]" part. Perhaps too complex? Any ideas?: My Main method: static void Main(string[] args) { NorthwindDataContext db = new NorthwindDataContext(); var query = db.Customers; string json = JSonify.GetJsonTable( query, 2, 10, "CustomerID", new string[] { "CustomerID", "CompanyName", "City", "Country", "Orders.Count" }); Console.WriteLine(json); } JSonify class public static class JSonify { public static string GetJsonTable( this IQueryable query, int pageNumber, int pageSize, string IDColumnName, string[] columnNames) { string selectItems = String.Format(@" new { {{0}} as ID, cell = new object[]{{{1}}} }", IDColumnName, String.Join(",", columnNames)); var items = new { page = pageNumber, total = query.Count(), rows = query.Select(selectItems).Skip(pageNumber * pageSize).Take(pageSize) }; return JavaScriptConvert.SerializeObject(items); // Should produce this result: // { // "page":2, // "total":91, // "rows": // [ // {"ID":"FAMIA","cell":["FAMIA","Familia Arquibaldo","Sao Paulo","Brazil",7]}, // {"ID":"FISSA","cell":["FISSA","FISSA Fabrica Inter. Salchichas S.A.","Madrid","Spain",0]}, // {"ID":"FOLIG","cell":["FOLIG","Folies gourmandes","Lille","France",5]}, // {"ID":"FOLKO","cell":["FOLKO","Folk och fä HB","Bräcke","Sweden",19]}, // {"ID":"FRANK","cell":["FRANK","Frankenversand","München","Germany",15]}, // {"ID":"FRANR","cell":["FRANR","France restauration","Nantes","France",3]}, // {"ID":"FRANS","cell":["FRANS","Franchi S.p.A.","Torino","Italy",6]}, // {"ID":"FURIB","cell":["FURIB","Furia Bacalhau e Frutos do Mar","Lisboa","Portugal",8]}, // {"ID":"GALED","cell":["GALED","Galería del gastrónomo","Barcelona","Spain",5]}, // {"ID":"GODOS","cell":["GODOS","Godos Cocina Típica","Sevilla","Spain",10]} // ] // } } }
This is really ugly and there may be some issues with the string replacement, but it produces the expected results: public static class JSonify { public static string GetJsonTable ( this IQueryable query, int pageNumber, int pageSize, string IDColumnName, string[] columnNames) { string select = string.Format("new ({0} as ID, \"CELLSTART\" as CELLSTART, {1}, \"CELLEND\" as CELLEND)", IDColumnName, string.Join(",", columnNames)); var items = new { page = pageNumber, total = query.Count(), rows = query.Select(select).Skip((pageNumber - 1) * pageSize).Take(pageSize) }; string json = JavaScriptConvert.SerializeObject(items); json = json.Replace("\"CELLSTART\":\"CELLSTART\",", "\"cell\":["); json = json.Replace(",\"CELLEND\":\"CELLEND\"", "]"); foreach (string column in columnNames) { json = json.Replace("\"" + column + "\":", ""); } return json; } }
Dynamic linq:Creating an extension method that produces JSON result I'm stuck trying to create a dynamic linq extension method that returns a string in JSON format - I'm using System.Linq.Dynamic and Newtonsoft.Json and I can't get the Linq.Dynamic to parse the "cell=new object[]" part. Perhaps too complex? Any ideas?: My Main method: static void Main(string[] args) { NorthwindDataContext db = new NorthwindDataContext(); var query = db.Customers; string json = JSonify.GetJsonTable( query, 2, 10, "CustomerID", new string[] { "CustomerID", "CompanyName", "City", "Country", "Orders.Count" }); Console.WriteLine(json); } JSonify class public static class JSonify { public static string GetJsonTable( this IQueryable query, int pageNumber, int pageSize, string IDColumnName, string[] columnNames) { string selectItems = String.Format(@" new { {{0}} as ID, cell = new object[]{{{1}}} }", IDColumnName, String.Join(",", columnNames)); var items = new { page = pageNumber, total = query.Count(), rows = query.Select(selectItems).Skip(pageNumber * pageSize).Take(pageSize) }; return JavaScriptConvert.SerializeObject(items); // Should produce this result: // { // "page":2, // "total":91, // "rows": // [ // {"ID":"FAMIA","cell":["FAMIA","Familia Arquibaldo","Sao Paulo","Brazil",7]}, // {"ID":"FISSA","cell":["FISSA","FISSA Fabrica Inter. Salchichas S.A.","Madrid","Spain",0]}, // {"ID":"FOLIG","cell":["FOLIG","Folies gourmandes","Lille","France",5]}, // {"ID":"FOLKO","cell":["FOLKO","Folk och fä HB","Bräcke","Sweden",19]}, // {"ID":"FRANK","cell":["FRANK","Frankenversand","München","Germany",15]}, // {"ID":"FRANR","cell":["FRANR","France restauration","Nantes","France",3]}, // {"ID":"FRANS","cell":["FRANS","Franchi S.p.A.","Torino","Italy",6]}, // {"ID":"FURIB","cell":["FURIB","Furia Bacalhau e Frutos do Mar","Lisboa","Portugal",8]}, // {"ID":"GALED","cell":["GALED","Galería del gastrónomo","Barcelona","Spain",5]}, // {"ID":"GODOS","cell":["GODOS","Godos Cocina Típica","Sevilla","Spain",10]} // ] // } } }
TITLE: Dynamic linq:Creating an extension method that produces JSON result QUESTION: I'm stuck trying to create a dynamic linq extension method that returns a string in JSON format - I'm using System.Linq.Dynamic and Newtonsoft.Json and I can't get the Linq.Dynamic to parse the "cell=new object[]" part. Perhaps too complex? Any ideas?: My Main method: static void Main(string[] args) { NorthwindDataContext db = new NorthwindDataContext(); var query = db.Customers; string json = JSonify.GetJsonTable( query, 2, 10, "CustomerID", new string[] { "CustomerID", "CompanyName", "City", "Country", "Orders.Count" }); Console.WriteLine(json); } JSonify class public static class JSonify { public static string GetJsonTable( this IQueryable query, int pageNumber, int pageSize, string IDColumnName, string[] columnNames) { string selectItems = String.Format(@" new { {{0}} as ID, cell = new object[]{{{1}}} }", IDColumnName, String.Join(",", columnNames)); var items = new { page = pageNumber, total = query.Count(), rows = query.Select(selectItems).Skip(pageNumber * pageSize).Take(pageSize) }; return JavaScriptConvert.SerializeObject(items); // Should produce this result: // { // "page":2, // "total":91, // "rows": // [ // {"ID":"FAMIA","cell":["FAMIA","Familia Arquibaldo","Sao Paulo","Brazil",7]}, // {"ID":"FISSA","cell":["FISSA","FISSA Fabrica Inter. Salchichas S.A.","Madrid","Spain",0]}, // {"ID":"FOLIG","cell":["FOLIG","Folies gourmandes","Lille","France",5]}, // {"ID":"FOLKO","cell":["FOLKO","Folk och fä HB","Bräcke","Sweden",19]}, // {"ID":"FRANK","cell":["FRANK","Frankenversand","München","Germany",15]}, // {"ID":"FRANR","cell":["FRANR","France restauration","Nantes","France",3]}, // {"ID":"FRANS","cell":["FRANS","Franchi S.p.A.","Torino","Italy",6]}, // {"ID":"FURIB","cell":["FURIB","Furia Bacalhau e Frutos do Mar","Lisboa","Portugal",8]}, // {"ID":"GALED","cell":["GALED","Galería del gastrónomo","Barcelona","Spain",5]}, // {"ID":"GODOS","cell":["GODOS","Godos Cocina Típica","Sevilla","Spain",10]} // ] // } } } ANSWER: This is really ugly and there may be some issues with the string replacement, but it produces the expected results: public static class JSonify { public static string GetJsonTable ( this IQueryable query, int pageNumber, int pageSize, string IDColumnName, string[] columnNames) { string select = string.Format("new ({0} as ID, \"CELLSTART\" as CELLSTART, {1}, \"CELLEND\" as CELLEND)", IDColumnName, string.Join(",", columnNames)); var items = new { page = pageNumber, total = query.Count(), rows = query.Select(select).Skip((pageNumber - 1) * pageSize).Take(pageSize) }; string json = JavaScriptConvert.SerializeObject(items); json = json.Replace("\"CELLSTART\":\"CELLSTART\",", "\"cell\":["); json = json.Replace(",\"CELLEND\":\"CELLEND\"", "]"); foreach (string column in columnNames) { json = json.Replace("\"" + column + "\":", ""); } return json; } }
[ "c#", "linq", "json" ]
3
2
2,031
3
0
2008-09-08T17:36:16.040000
2008-09-10T23:50:24.377000
50,252
50,269
Modeling Geographic Locations in an Relational Database
I am designing a contact management system and have come across an interesting issue regarding modeling geographic locations in a consistent way. I would like to be able to record locations associated with a particular person (mailing address(es) for work, school, home, etc.) My thought is to create a table of locales such as the following: Locales (ID, LocationName, ParentID) where autonomous locations (such as countries, e.g. USA) are parents of themselves. This way I can have an arbitrarily deep nesting of 'political units' (COUNTRY > STATE > CITY or COUNTRY > STATE > CITY > UNIVERSITY). Some queries will necessarily involve recursion. I would appreciate any other recommendations or perhaps advice regarding predictable issues that I am likely to encounter with such a scheme.
You might want to have a look at Freebase.com as a site that's had some open discussion about what a "location" means and what it means when a location is included in another. These sorts of questions can generate a lot of discussion. For example, there is the obvious "geographic nesting", but there are less obvious logical nestings. For example, in a strictly geographic sense, Vatican City is nested within Italy. But it's not nested politically. Similarly, if your user is located in a research center that belongs to a university, but isn't located on the University's property, do you model that relationship or not?
Modeling Geographic Locations in an Relational Database I am designing a contact management system and have come across an interesting issue regarding modeling geographic locations in a consistent way. I would like to be able to record locations associated with a particular person (mailing address(es) for work, school, home, etc.) My thought is to create a table of locales such as the following: Locales (ID, LocationName, ParentID) where autonomous locations (such as countries, e.g. USA) are parents of themselves. This way I can have an arbitrarily deep nesting of 'political units' (COUNTRY > STATE > CITY or COUNTRY > STATE > CITY > UNIVERSITY). Some queries will necessarily involve recursion. I would appreciate any other recommendations or perhaps advice regarding predictable issues that I am likely to encounter with such a scheme.
TITLE: Modeling Geographic Locations in an Relational Database QUESTION: I am designing a contact management system and have come across an interesting issue regarding modeling geographic locations in a consistent way. I would like to be able to record locations associated with a particular person (mailing address(es) for work, school, home, etc.) My thought is to create a table of locales such as the following: Locales (ID, LocationName, ParentID) where autonomous locations (such as countries, e.g. USA) are parents of themselves. This way I can have an arbitrarily deep nesting of 'political units' (COUNTRY > STATE > CITY or COUNTRY > STATE > CITY > UNIVERSITY). Some queries will necessarily involve recursion. I would appreciate any other recommendations or perhaps advice regarding predictable issues that I am likely to encounter with such a scheme. ANSWER: You might want to have a look at Freebase.com as a site that's had some open discussion about what a "location" means and what it means when a location is included in another. These sorts of questions can generate a lot of discussion. For example, there is the obvious "geographic nesting", but there are less obvious logical nestings. For example, in a strictly geographic sense, Vatican City is nested within Italy. But it's not nested politically. Similarly, if your user is located in a research center that belongs to a university, but isn't located on the University's property, do you model that relationship or not?
[ "sql", "database-design" ]
6
5
3,363
8
0
2008-09-08T17:36:36.210000
2008-09-08T17:47:05.063000
50,268
50,333
.MSI Not Always Uninstalling Previous Versions
In a number of applications we create an MSI Installer with the Visual Studio Setup Project. In most cases, the install works fine, but every now and then the previous version was not uninstalled correctly. The user ends up with two icons on the desktop, and in the Add/Remove program list, the application appears twice. We have yet to find any pattern and in most cases the installer works without any problems.
What happens when the uninstall of the previous version fails depends on the sequencing of the RemoveExistingProducts action. I have written a summary about the various options in the past: http://jpassing.wordpress.com/2007/06/16/where-to-place-removeexistingproducts-in-a-major-msi-upgrade/. Unfortunately, you do not have control over RemoveExistingProducts sequencing when using VS setup projects (Unless you edit the MSI with Orca after it has been built, which usually is not practical). But if your setup project is not completely trivial, I would strongly suggest you to use a different MSI authoring tool like WiX or one of the commercial tools anyway.
.MSI Not Always Uninstalling Previous Versions In a number of applications we create an MSI Installer with the Visual Studio Setup Project. In most cases, the install works fine, but every now and then the previous version was not uninstalled correctly. The user ends up with two icons on the desktop, and in the Add/Remove program list, the application appears twice. We have yet to find any pattern and in most cases the installer works without any problems.
TITLE: .MSI Not Always Uninstalling Previous Versions QUESTION: In a number of applications we create an MSI Installer with the Visual Studio Setup Project. In most cases, the install works fine, but every now and then the previous version was not uninstalled correctly. The user ends up with two icons on the desktop, and in the Add/Remove program list, the application appears twice. We have yet to find any pattern and in most cases the installer works without any problems. ANSWER: What happens when the uninstall of the previous version fails depends on the sequencing of the RemoveExistingProducts action. I have written a summary about the various options in the past: http://jpassing.wordpress.com/2007/06/16/where-to-place-removeexistingproducts-in-a-major-msi-upgrade/. Unfortunately, you do not have control over RemoveExistingProducts sequencing when using VS setup projects (Unless you edit the MSI with Orca after it has been built, which usually is not practical). But if your setup project is not completely trivial, I would strongly suggest you to use a different MSI authoring tool like WiX or one of the commercial tools anyway.
[ ".net", "windows-installer" ]
4
1
1,736
1
0
2008-09-08T17:44:56.800000
2008-09-08T18:18:55.297000
50,280
50,336
Floats messing up in Safari browsers
I have a site I made really fast that uses floats to display different sections of content. The floated content and the content that has an additional margin both appear fine in FF/IE, but on safari one of the divs is completely hidden. I've tried switching to padding and position:relative, but nothing has worked for me. If I take out the code to display it to the right it shows up again but under the floated content. The main section of css that seems to be causing the problem is: #settings{ float:left; } #right_content{ margin-top:20px; margin-left:440px; width:400px; } This gives me the same result whether I specify a size to the #settings div or not. Any ideas would be appreciated. The site is available at: http://frickinsweet.com/tools/Theme.mvc.aspx to see the source code.
I believe the error lies in the mark up that the color picker is generating. I saved the page and removed that code for the color picker and it renders fine in IE/FF/SF.
Floats messing up in Safari browsers I have a site I made really fast that uses floats to display different sections of content. The floated content and the content that has an additional margin both appear fine in FF/IE, but on safari one of the divs is completely hidden. I've tried switching to padding and position:relative, but nothing has worked for me. If I take out the code to display it to the right it shows up again but under the floated content. The main section of css that seems to be causing the problem is: #settings{ float:left; } #right_content{ margin-top:20px; margin-left:440px; width:400px; } This gives me the same result whether I specify a size to the #settings div or not. Any ideas would be appreciated. The site is available at: http://frickinsweet.com/tools/Theme.mvc.aspx to see the source code.
TITLE: Floats messing up in Safari browsers QUESTION: I have a site I made really fast that uses floats to display different sections of content. The floated content and the content that has an additional margin both appear fine in FF/IE, but on safari one of the divs is completely hidden. I've tried switching to padding and position:relative, but nothing has worked for me. If I take out the code to display it to the right it shows up again but under the floated content. The main section of css that seems to be causing the problem is: #settings{ float:left; } #right_content{ margin-top:20px; margin-left:440px; width:400px; } This gives me the same result whether I specify a size to the #settings div or not. Any ideas would be appreciated. The site is available at: http://frickinsweet.com/tools/Theme.mvc.aspx to see the source code. ANSWER: I believe the error lies in the mark up that the color picker is generating. I saved the page and removed that code for the color picker and it renders fine in IE/FF/SF.
[ "css", "safari", "css-float" ]
3
1
4,811
4
0
2008-09-08T17:50:07.130000
2008-09-08T18:21:39.473000
50,303
51,583
Persistent DB Connections - Yea or Nay?
I'm using PHP's PDO layer for data access in a project, and I've been reading up on it and seeing that it has good innate support for persistent DB connections. I'm wondering when/if I should use them. Would I see performance benefits in a CRUD-heavy app? Are there downsides to consider, perhaps related to security? If it matters to you, I'm using MySQL 5.x.
You could use this as a rough "ruleset": YES, use persistent connections, if: There are only few applications/users accessing the database, i.e. you will not result in 200 open (but probably idle) connections, because there are 200 different users shared on the same host. The database is running on another server that you are accessing over the network An (one) application accesses the database very often NO, don't use persistent connections, if: Your application only needs to access the database 100 times an hour. You have many webservers accessing one database server You're using Apache in prefork mode. It uses one connection for each child process, which can ramp up fairly quickly. (via @Powerlord in the comments) Using persistent connections is considerable faster, especially if you are accessing the database over a network. It doesn't make so much difference if the database is running on the same machine, but it is still a little bit faster. However - as the name says - the connection is persistent, i.e. it stays open, even if it is not used. The problem with that is, that in "default configuration", MySQL only allows 1000 parallel "open channels". After that, new connections are refused (You can tweak this setting). So if you have - say - 20 Webservers with each 100 Clients on them, and every one of them has just one page access per hour, simple math will show you that you'll need 2000 parallel connections to the database. That won't work. Ergo: Only use it for applications with lots of requests.
Persistent DB Connections - Yea or Nay? I'm using PHP's PDO layer for data access in a project, and I've been reading up on it and seeing that it has good innate support for persistent DB connections. I'm wondering when/if I should use them. Would I see performance benefits in a CRUD-heavy app? Are there downsides to consider, perhaps related to security? If it matters to you, I'm using MySQL 5.x.
TITLE: Persistent DB Connections - Yea or Nay? QUESTION: I'm using PHP's PDO layer for data access in a project, and I've been reading up on it and seeing that it has good innate support for persistent DB connections. I'm wondering when/if I should use them. Would I see performance benefits in a CRUD-heavy app? Are there downsides to consider, perhaps related to security? If it matters to you, I'm using MySQL 5.x. ANSWER: You could use this as a rough "ruleset": YES, use persistent connections, if: There are only few applications/users accessing the database, i.e. you will not result in 200 open (but probably idle) connections, because there are 200 different users shared on the same host. The database is running on another server that you are accessing over the network An (one) application accesses the database very often NO, don't use persistent connections, if: Your application only needs to access the database 100 times an hour. You have many webservers accessing one database server You're using Apache in prefork mode. It uses one connection for each child process, which can ramp up fairly quickly. (via @Powerlord in the comments) Using persistent connections is considerable faster, especially if you are accessing the database over a network. It doesn't make so much difference if the database is running on the same machine, but it is still a little bit faster. However - as the name says - the connection is persistent, i.e. it stays open, even if it is not used. The problem with that is, that in "default configuration", MySQL only allows 1000 parallel "open channels". After that, new connections are refused (You can tweak this setting). So if you have - say - 20 Webservers with each 100 Clients on them, and every one of them has just one page access per hour, simple math will show you that you'll need 2000 parallel connections to the database. That won't work. Ergo: Only use it for applications with lots of requests.
[ "pdo", "persistence", "database-connection" ]
58
76
42,930
7
0
2008-09-08T18:01:11.423000
2008-09-09T10:54:49.413000
50,306
1,686,356
Is it possible to do the Navision 5.0 export to Word/Excel to OpenOffice.org?
Navision 5.0 includes a feature to export to Word or Excel. Is it possible to make this work with OpenOffice.org Writer or Calc instead? If so, what has to be done to set it up? I have been told by my Navision reseller that the feature works best with Office 2007, and export to Excel 2003 works. No mention of Office 2000 (which is what we mostly have installed currently) or OpenOffice.org. I'm hoping to be able to standardise on OpenOffice.org across the company when 3.0 is released, to avoid the expense of upgrading everyone to Microsoft Office 2007.
I know this is an old question, but I'll add the answer just in case anyone comes here: You can export directly to OpenOffice without customizations. The only thing you need is to go into Tools > Manage Style Sheets... and modify the existing StyleSheets so that they open OpenCalc and OpenWrite instead of Excel and Word. Note: it's been a while since I last configured it, but I seem to remember that you might need to export and reimport the stylesheets to change the associated program. It's quite easy, and you can actually keep both options (Export to Excel/Export to OpenCalc) so that users who need MS Office can use Excel, while the rest use OpenCalc. This answer applies to the functionality to export to Word and Excel in Dynamics Nav 5.0 and Nav 5.0SP1. I haven't tried it in Dynamics Nav 2009 (Role Tailored Client).
Is it possible to do the Navision 5.0 export to Word/Excel to OpenOffice.org? Navision 5.0 includes a feature to export to Word or Excel. Is it possible to make this work with OpenOffice.org Writer or Calc instead? If so, what has to be done to set it up? I have been told by my Navision reseller that the feature works best with Office 2007, and export to Excel 2003 works. No mention of Office 2000 (which is what we mostly have installed currently) or OpenOffice.org. I'm hoping to be able to standardise on OpenOffice.org across the company when 3.0 is released, to avoid the expense of upgrading everyone to Microsoft Office 2007.
TITLE: Is it possible to do the Navision 5.0 export to Word/Excel to OpenOffice.org? QUESTION: Navision 5.0 includes a feature to export to Word or Excel. Is it possible to make this work with OpenOffice.org Writer or Calc instead? If so, what has to be done to set it up? I have been told by my Navision reseller that the feature works best with Office 2007, and export to Excel 2003 works. No mention of Office 2000 (which is what we mostly have installed currently) or OpenOffice.org. I'm hoping to be able to standardise on OpenOffice.org across the company when 3.0 is released, to avoid the expense of upgrading everyone to Microsoft Office 2007. ANSWER: I know this is an old question, but I'll add the answer just in case anyone comes here: You can export directly to OpenOffice without customizations. The only thing you need is to go into Tools > Manage Style Sheets... and modify the existing StyleSheets so that they open OpenCalc and OpenWrite instead of Excel and Word. Note: it's been a while since I last configured it, but I seem to remember that you might need to export and reimport the stylesheets to change the associated program. It's quite easy, and you can actually keep both options (Export to Excel/Export to OpenCalc) so that users who need MS Office can use Excel, while the rest use OpenCalc. This answer applies to the functionality to export to Word and Excel in Dynamics Nav 5.0 and Nav 5.0SP1. I haven't tried it in Dynamics Nav 2009 (Role Tailored Client).
[ "export", "openoffice.org", "navision" ]
2
3
5,036
3
0
2008-09-08T18:03:18.080000
2009-11-06T09:07:00.257000
50,310
51,034
Why the option to use attributes in new ATL projects was removed from Visual Studio 2008?
This is the text from MSDN comment: "According to the book ATL Internals (2ed) the use of attributes is deprecated and should not be used in new ATL projects." But WHY?!!
In ATL these attributes were a compiler trick. They were not a core part of the platform like attributes in C#. They were also more confusing to debug than macros's and the method of dumping generated attribute code was a hassle. I suspect another issue is likely to have been C++ compiler compatibility and standards-adherence. Attributes didn't make for more beautiful C++ code, and perhaps this syntax may be used in a future version of a real C++ standard.
Why the option to use attributes in new ATL projects was removed from Visual Studio 2008? This is the text from MSDN comment: "According to the book ATL Internals (2ed) the use of attributes is deprecated and should not be used in new ATL projects." But WHY?!!
TITLE: Why the option to use attributes in new ATL projects was removed from Visual Studio 2008? QUESTION: This is the text from MSDN comment: "According to the book ATL Internals (2ed) the use of attributes is deprecated and should not be used in new ATL projects." But WHY?!! ANSWER: In ATL these attributes were a compiler trick. They were not a core part of the platform like attributes in C#. They were also more confusing to debug than macros's and the method of dumping generated attribute code was a hassle. I suspect another issue is likely to have been C++ compiler compatibility and standards-adherence. Attributes didn't make for more beautiful C++ code, and perhaps this syntax may be used in a future version of a real C++ standard.
[ "visual-studio", "visual-studio-2008", "visual-c++", "atl" ]
3
4
1,768
2
0
2008-09-08T18:04:11.650000
2008-09-09T00:49:19.900000
50,311
56,899
create and stream large XML document in C++
I have some code that creates a fairly large xml DOM and writes it off to a file (up to 50-100MB). It basically creates the DOM and then calls a toString on it and writes it out with ofstream. Is there a way to get streaming output of the generated dom so that it doesn't create the whole structure in memory all at once and then copy it, etc? I will not modify any node after i create it so it can write it out and free up the memory right away. I could write my own xml class that does the xml construction but... i don't think that's a good idea since i'll probably miss something when it comes down to escaping etc.
Ok, turns out libxml2 has a streaming API: http://xmlsoft.org/examples/testWriter.c It's a little old style (very C-ish) but you can write your wrapper around it.
create and stream large XML document in C++ I have some code that creates a fairly large xml DOM and writes it off to a file (up to 50-100MB). It basically creates the DOM and then calls a toString on it and writes it out with ofstream. Is there a way to get streaming output of the generated dom so that it doesn't create the whole structure in memory all at once and then copy it, etc? I will not modify any node after i create it so it can write it out and free up the memory right away. I could write my own xml class that does the xml construction but... i don't think that's a good idea since i'll probably miss something when it comes down to escaping etc.
TITLE: create and stream large XML document in C++ QUESTION: I have some code that creates a fairly large xml DOM and writes it off to a file (up to 50-100MB). It basically creates the DOM and then calls a toString on it and writes it out with ofstream. Is there a way to get streaming output of the generated dom so that it doesn't create the whole structure in memory all at once and then copy it, etc? I will not modify any node after i create it so it can write it out and free up the memory right away. I could write my own xml class that does the xml construction but... i don't think that's a good idea since i'll probably miss something when it comes down to escaping etc. ANSWER: Ok, turns out libxml2 has a streaming API: http://xmlsoft.org/examples/testWriter.c It's a little old style (very C-ish) but you can write your wrapper around it.
[ "c++", "xml" ]
1
3
2,981
4
0
2008-09-08T18:05:14.193000
2008-09-11T15:33:23.813000
50,312
50,334
Get CPU usage in shell script?
I'm running some JMeter tests against a Java process to determine how responsive a web application is under load (500+ users). JMeter will give the response time for each web request, and I've written a script to ping the Tomcat Manager every X seconds which will get me the current size of the JVM heap. I'd like to collect stats on the server of the % of CPU being used by Tomcat. I tried to do it in a shell script using ps like this: PS_RESULTS=`ps -o pcpu,pmem,nlwp -p $PID`...running the command every X seconds and appending the results to a text file. (for anyone wondering, pmem = % mem usage and nlwp is number of threads) However I've found that this gives a different definition of "% of CPU Utilization" than I'd like - according to the manpages for ps, pcpu is defined as: cpu utilization of the process in "##.#" format. It is the CPU time used divided by the time the process has been running (cputime/realtime ratio), expressed as a percentage. In other words, pcpu gives me the % CPU utilization for the process for the lifetime of the process. Since I want to take a sample every X seconds, I'd like to be collecting the CPU utilization of the process at the current time only - similar to what top would give me (CPU utilization of the process since the last update). How can I collect this from within a shell script?
Use top -b (and other switches if you want different outputs). It will just dump to stdout instead of jumping into a curses window.
Get CPU usage in shell script? I'm running some JMeter tests against a Java process to determine how responsive a web application is under load (500+ users). JMeter will give the response time for each web request, and I've written a script to ping the Tomcat Manager every X seconds which will get me the current size of the JVM heap. I'd like to collect stats on the server of the % of CPU being used by Tomcat. I tried to do it in a shell script using ps like this: PS_RESULTS=`ps -o pcpu,pmem,nlwp -p $PID`...running the command every X seconds and appending the results to a text file. (for anyone wondering, pmem = % mem usage and nlwp is number of threads) However I've found that this gives a different definition of "% of CPU Utilization" than I'd like - according to the manpages for ps, pcpu is defined as: cpu utilization of the process in "##.#" format. It is the CPU time used divided by the time the process has been running (cputime/realtime ratio), expressed as a percentage. In other words, pcpu gives me the % CPU utilization for the process for the lifetime of the process. Since I want to take a sample every X seconds, I'd like to be collecting the CPU utilization of the process at the current time only - similar to what top would give me (CPU utilization of the process since the last update). How can I collect this from within a shell script?
TITLE: Get CPU usage in shell script? QUESTION: I'm running some JMeter tests against a Java process to determine how responsive a web application is under load (500+ users). JMeter will give the response time for each web request, and I've written a script to ping the Tomcat Manager every X seconds which will get me the current size of the JVM heap. I'd like to collect stats on the server of the % of CPU being used by Tomcat. I tried to do it in a shell script using ps like this: PS_RESULTS=`ps -o pcpu,pmem,nlwp -p $PID`...running the command every X seconds and appending the results to a text file. (for anyone wondering, pmem = % mem usage and nlwp is number of threads) However I've found that this gives a different definition of "% of CPU Utilization" than I'd like - according to the manpages for ps, pcpu is defined as: cpu utilization of the process in "##.#" format. It is the CPU time used divided by the time the process has been running (cputime/realtime ratio), expressed as a percentage. In other words, pcpu gives me the % CPU utilization for the process for the lifetime of the process. Since I want to take a sample every X seconds, I'd like to be collecting the CPU utilization of the process at the current time only - similar to what top would give me (CPU utilization of the process since the last update). How can I collect this from within a shell script? ANSWER: Use top -b (and other switches if you want different outputs). It will just dump to stdout instead of jumping into a curses window.
[ "linux", "shell", "scripting" ]
8
13
29,548
6
0
2008-09-08T18:05:34.300000
2008-09-08T18:21:06.027000
50,315
240,321
How do you allow multiple file uploads on an internal windows-authentication intranet?
I have a couple of solutions, but none of them work perfectly. Platform ASP.NET / VB.NET /.NET 2.0 IIS 6 IE6 (primarily), with some IE7; Firefox not necessary, but useful Allowed 3rd Party Options Flash ActiveX (would like to avoid) Java (would like to avoid) Current Attempts Gmail Style: You can use javascript to add new Upload elements (input type='file'), then upload them all at once with the click of a button. This works, but still requires a lot of clicks. (I was able to use an invisible ActiveX control to detect things like File Size, which would be useful.) Flash Uploader: I discovered a couple of Flash Upload controls that use a 1x1 flash file to act as the uploader, callable by javascript. (One such control is FancyUpload, another is Dojo's Multiple File Uploader, yet another is one by darick_c at CodeProject.) These excited me, but I quickly ran into two issues: Flash 10 will break the functionality that is used to call the multiple file upload dialogue box. The workaround is to use a transparent flash frame, or just use a flash button to call the dialogue box. That's not a huge deal. The integrated windows authentication used on our intranet is not used when the Flash file attempts to upload the files, prompting the user for credentials. The workaround for this is to use cookieless sessions, which would be a nightmare for our project due to several other reasons. Java Uploader: I noticed several Java-based multiple-file uploaders, but most of the appear to cost money. If I found one that worked really well, I could arrange to purchase it. I'd just rather not. I also don't like the look of most of them. I liked FancyUpload because it interacted with html/javascript so that I could easily style and manage it any way I want. ActiveX Uploader: I found an ActiveX solution as well. It appears that ActiveX will work. I would just write my own instead of buying that one. This will be my last resort, I think. Resolution I would love to be able to use something like FancyUpload. If I can just get by the credentials prompt some way, it would be perfect. But, from my research, it appears that the only real workaround is cookieless sessions, which I just can't do. So, the question is: Is there a way to resolve the issues presented above OR is there a different solution that I have not listed which accomplishes the same goal?
@davidinbcn.myopenid.co: That's basically how I solved this issue. But, in an effort to provide a more detailed answer, I'm posting my solution here. The Solution! Create two web applications, or websites, or whatever. Application A is a simple web application. The purpose of this application is to receive file uploads and save them to the proper place. Set this up as an anonymous access allowed. Then make a single ASPX page that accepts posted files and saves them to a given location. (I'm doing this on an intranet. Internet sites may be exposing themselves to security issues by doing this. Take extra precautions if that is the case.) The code behind for this page would look something like this: Dim uploads As HttpFileCollection = HttpContext.Current.Request.Files If uploads.Count > 0 Then UploadFiles(uploads) Else result = "error" err = "File Not Uploaded" End If Application B is your primary site that will allow file uploads. Set this up as an authenticated web application that does not allow anonymous access. Then, place the FancyUpload (or similar solution) on a page on this site. Configure it to post its files to Application A's upload ASPX page.
How do you allow multiple file uploads on an internal windows-authentication intranet? I have a couple of solutions, but none of them work perfectly. Platform ASP.NET / VB.NET /.NET 2.0 IIS 6 IE6 (primarily), with some IE7; Firefox not necessary, but useful Allowed 3rd Party Options Flash ActiveX (would like to avoid) Java (would like to avoid) Current Attempts Gmail Style: You can use javascript to add new Upload elements (input type='file'), then upload them all at once with the click of a button. This works, but still requires a lot of clicks. (I was able to use an invisible ActiveX control to detect things like File Size, which would be useful.) Flash Uploader: I discovered a couple of Flash Upload controls that use a 1x1 flash file to act as the uploader, callable by javascript. (One such control is FancyUpload, another is Dojo's Multiple File Uploader, yet another is one by darick_c at CodeProject.) These excited me, but I quickly ran into two issues: Flash 10 will break the functionality that is used to call the multiple file upload dialogue box. The workaround is to use a transparent flash frame, or just use a flash button to call the dialogue box. That's not a huge deal. The integrated windows authentication used on our intranet is not used when the Flash file attempts to upload the files, prompting the user for credentials. The workaround for this is to use cookieless sessions, which would be a nightmare for our project due to several other reasons. Java Uploader: I noticed several Java-based multiple-file uploaders, but most of the appear to cost money. If I found one that worked really well, I could arrange to purchase it. I'd just rather not. I also don't like the look of most of them. I liked FancyUpload because it interacted with html/javascript so that I could easily style and manage it any way I want. ActiveX Uploader: I found an ActiveX solution as well. It appears that ActiveX will work. I would just write my own instead of buying that one. This will be my last resort, I think. Resolution I would love to be able to use something like FancyUpload. If I can just get by the credentials prompt some way, it would be perfect. But, from my research, it appears that the only real workaround is cookieless sessions, which I just can't do. So, the question is: Is there a way to resolve the issues presented above OR is there a different solution that I have not listed which accomplishes the same goal?
TITLE: How do you allow multiple file uploads on an internal windows-authentication intranet? QUESTION: I have a couple of solutions, but none of them work perfectly. Platform ASP.NET / VB.NET /.NET 2.0 IIS 6 IE6 (primarily), with some IE7; Firefox not necessary, but useful Allowed 3rd Party Options Flash ActiveX (would like to avoid) Java (would like to avoid) Current Attempts Gmail Style: You can use javascript to add new Upload elements (input type='file'), then upload them all at once with the click of a button. This works, but still requires a lot of clicks. (I was able to use an invisible ActiveX control to detect things like File Size, which would be useful.) Flash Uploader: I discovered a couple of Flash Upload controls that use a 1x1 flash file to act as the uploader, callable by javascript. (One such control is FancyUpload, another is Dojo's Multiple File Uploader, yet another is one by darick_c at CodeProject.) These excited me, but I quickly ran into two issues: Flash 10 will break the functionality that is used to call the multiple file upload dialogue box. The workaround is to use a transparent flash frame, or just use a flash button to call the dialogue box. That's not a huge deal. The integrated windows authentication used on our intranet is not used when the Flash file attempts to upload the files, prompting the user for credentials. The workaround for this is to use cookieless sessions, which would be a nightmare for our project due to several other reasons. Java Uploader: I noticed several Java-based multiple-file uploaders, but most of the appear to cost money. If I found one that worked really well, I could arrange to purchase it. I'd just rather not. I also don't like the look of most of them. I liked FancyUpload because it interacted with html/javascript so that I could easily style and manage it any way I want. ActiveX Uploader: I found an ActiveX solution as well. It appears that ActiveX will work. I would just write my own instead of buying that one. This will be my last resort, I think. Resolution I would love to be able to use something like FancyUpload. If I can just get by the credentials prompt some way, it would be perfect. But, from my research, it appears that the only real workaround is cookieless sessions, which I just can't do. So, the question is: Is there a way to resolve the issues presented above OR is there a different solution that I have not listed which accomplishes the same goal? ANSWER: @davidinbcn.myopenid.co: That's basically how I solved this issue. But, in an effort to provide a more detailed answer, I'm posting my solution here. The Solution! Create two web applications, or websites, or whatever. Application A is a simple web application. The purpose of this application is to receive file uploads and save them to the proper place. Set this up as an anonymous access allowed. Then make a single ASPX page that accepts posted files and saves them to a given location. (I'm doing this on an intranet. Internet sites may be exposing themselves to security issues by doing this. Take extra precautions if that is the case.) The code behind for this page would look something like this: Dim uploads As HttpFileCollection = HttpContext.Current.Request.Files If uploads.Count > 0 Then UploadFiles(uploads) Else result = "error" err = "File Not Uploaded" End If Application B is your primary site that will allow file uploads. Set this up as an authenticated web application that does not allow anonymous access. Then, place the FancyUpload (or similar solution) on a page on this site. Configure it to post its files to Application A's upload ASPX page.
[ "javascript", "flash", "authentication", "activex", "file-upload" ]
3
0
1,961
5
0
2008-09-08T18:06:45.717000
2008-10-27T15:35:07.910000
50,316
50,320
How do I suppress firefox password field completion?
I'm developing a website. I'm using a single-page web-app style, so all of the different parts of the site are AJAX'd into index.php. When a user logs in and tells Firefox to remember his username and password, all input boxes on the site get auto-filled with that username and password. This is a problem on the form to change a password. How can i prevent Firefox from automatically filling out these fields? I already tried giving them different names and ids. Edit: Someone has already asked this. Thanks Joel Coohorn.
From Mozilla's documentation [...] http://developer.mozilla.org/en/How_to_Turn_Off_Form_Autocompletion
How do I suppress firefox password field completion? I'm developing a website. I'm using a single-page web-app style, so all of the different parts of the site are AJAX'd into index.php. When a user logs in and tells Firefox to remember his username and password, all input boxes on the site get auto-filled with that username and password. This is a problem on the form to change a password. How can i prevent Firefox from automatically filling out these fields? I already tried giving them different names and ids. Edit: Someone has already asked this. Thanks Joel Coohorn.
TITLE: How do I suppress firefox password field completion? QUESTION: I'm developing a website. I'm using a single-page web-app style, so all of the different parts of the site are AJAX'd into index.php. When a user logs in and tells Firefox to remember his username and password, all input boxes on the site get auto-filled with that username and password. This is a problem on the form to change a password. How can i prevent Firefox from automatically filling out these fields? I already tried giving them different names and ids. Edit: Someone has already asked this. Thanks Joel Coohorn. ANSWER: From Mozilla's documentation [...] http://developer.mozilla.org/en/How_to_Turn_Off_Form_Autocompletion
[ "html", "firefox" ]
16
27
11,290
5
0
2008-09-08T18:07:50.193000
2008-09-08T18:10:28.533000
50,318
50,329
How do I stop Visual Studio's 'Publish Web Site' from publishing my _ReSharper folder?
It's really quite annoying as they are not part of the project.
The Visual Studio Web Deployment addin lets you exclude folders and more. VS2005 VS2008 Also a decent writeup on the Web Deployment addin
How do I stop Visual Studio's 'Publish Web Site' from publishing my _ReSharper folder? It's really quite annoying as they are not part of the project.
TITLE: How do I stop Visual Studio's 'Publish Web Site' from publishing my _ReSharper folder? QUESTION: It's really quite annoying as they are not part of the project. ANSWER: The Visual Studio Web Deployment addin lets you exclude folders and more. VS2005 VS2008 Also a decent writeup on the Web Deployment addin
[ "asp.net", "visual-studio", "deployment" ]
2
1
7,013
2
0
2008-09-08T18:09:32.123000
2008-09-08T18:16:52.947000
50,327
387,588
WPF DatePicker: What is the best?
I need a Datepicker for a WPF application. What is considered to be the best one?
There is also the WPF Tool Kit which has a DatePicker/Calendar control (i added emphasis because this is the answer)
WPF DatePicker: What is the best? I need a Datepicker for a WPF application. What is considered to be the best one?
TITLE: WPF DatePicker: What is the best? QUESTION: I need a Datepicker for a WPF application. What is considered to be the best one? ANSWER: There is also the WPF Tool Kit which has a DatePicker/Calendar control (i added emphasis because this is the answer)
[ "wpf" ]
5
20
14,133
5
0
2008-09-08T18:16:38.890000
2008-12-22T22:31:35.583000
50,330
50,517
Override ScriptControl or BaseValidator for an async ASP.NET validator control?
I'm planning to develop an ASP.NET server control to provide asynchronous username availability validation for new user registrations. The control will allow a developer to point it at a "username" TextBox and it will provide an indication of whether or not the username is available. Like this example, but without the clunky UpdatePanel. One design decision that's giving me headaches is whether to inherit from ScriptControl or BaseValidator. By implementing it as a ScriptControl, I can make the client side portion easier to deal with and easily localize it with a resx. However, I want to make sure that the validator functions properly with respect to Page.IsValid. The only way I know to do this is to override BaseValidator and implement EvaluateIsValid(). So, my question is, how would you suggest structuring this control? Is inheriting from BaseValidator the best (only) way to get the validator part right, or can I do that in some other way?
You should be able to do both if you implement the IScriptControl interface while also deriving from BaseValidator: public class YourControl: IScriptControl, BaseValidator To implement the IScriptControl interface means your control will also have to have the GetScriptReferences and GetScriptDescriptors methods.
Override ScriptControl or BaseValidator for an async ASP.NET validator control? I'm planning to develop an ASP.NET server control to provide asynchronous username availability validation for new user registrations. The control will allow a developer to point it at a "username" TextBox and it will provide an indication of whether or not the username is available. Like this example, but without the clunky UpdatePanel. One design decision that's giving me headaches is whether to inherit from ScriptControl or BaseValidator. By implementing it as a ScriptControl, I can make the client side portion easier to deal with and easily localize it with a resx. However, I want to make sure that the validator functions properly with respect to Page.IsValid. The only way I know to do this is to override BaseValidator and implement EvaluateIsValid(). So, my question is, how would you suggest structuring this control? Is inheriting from BaseValidator the best (only) way to get the validator part right, or can I do that in some other way?
TITLE: Override ScriptControl or BaseValidator for an async ASP.NET validator control? QUESTION: I'm planning to develop an ASP.NET server control to provide asynchronous username availability validation for new user registrations. The control will allow a developer to point it at a "username" TextBox and it will provide an indication of whether or not the username is available. Like this example, but without the clunky UpdatePanel. One design decision that's giving me headaches is whether to inherit from ScriptControl or BaseValidator. By implementing it as a ScriptControl, I can make the client side portion easier to deal with and easily localize it with a resx. However, I want to make sure that the validator functions properly with respect to Page.IsValid. The only way I know to do this is to override BaseValidator and implement EvaluateIsValid(). So, my question is, how would you suggest structuring this control? Is inheriting from BaseValidator the best (only) way to get the validator part right, or can I do that in some other way? ANSWER: You should be able to do both if you implement the IScriptControl interface while also deriving from BaseValidator: public class YourControl: IScriptControl, BaseValidator To implement the IScriptControl interface means your control will also have to have the GetScriptReferences and GetScriptDescriptors methods.
[ "asp.net", "validation", "asp.net-ajax" ]
5
4
880
1
0
2008-09-08T18:17:11.823000
2008-09-08T19:52:08.053000
50,345
50,461
Why is AppDomain.CurrentDomain.BaseDirectory different between Windows Forms and Library
In my winforms application, AppDomain.CurrentDomain.BaseDirectory is set to "C:\Projects\TestProject\bin\Debug\" In my unit tests it is "C:\Projects\TestProject\bin\Debug" (no final slash). Why is this? [Edit] @Will: I am asking why the test project's directory doesn't have a trailing slash?
You may be asking one of two possible questions: Why are they different, or why the test project's directory doesn't have a trailing slash. Assuming its the first: That's where the code is executing from. When you debug the program, its compiled and the binaries are placed under the project's \bin\debug directory. When you're testing, you're running the test's binaries, which are compiled and placed under the test project's bin\debug directory. Assuming its the last: Possibly some obscure reason, possibly a bug, or possibly to catch people who are concatenating paths rather than using Path.Combine (naughty naughty!). Well, I don't know why it's different. Test applications may be run within a custom CLR host; I think this may be the case as test apps do some weird stuff with private accessors that normally aren't allowed within the standard CLR host. I'm only grasping at straws here as I don't have any actual knowledge about how this stuff is actually being coded. Anyhow, the workaround stands (Path.Combine). Nobody should be concatenating paths, as path delimeters can change.
Why is AppDomain.CurrentDomain.BaseDirectory different between Windows Forms and Library In my winforms application, AppDomain.CurrentDomain.BaseDirectory is set to "C:\Projects\TestProject\bin\Debug\" In my unit tests it is "C:\Projects\TestProject\bin\Debug" (no final slash). Why is this? [Edit] @Will: I am asking why the test project's directory doesn't have a trailing slash?
TITLE: Why is AppDomain.CurrentDomain.BaseDirectory different between Windows Forms and Library QUESTION: In my winforms application, AppDomain.CurrentDomain.BaseDirectory is set to "C:\Projects\TestProject\bin\Debug\" In my unit tests it is "C:\Projects\TestProject\bin\Debug" (no final slash). Why is this? [Edit] @Will: I am asking why the test project's directory doesn't have a trailing slash? ANSWER: You may be asking one of two possible questions: Why are they different, or why the test project's directory doesn't have a trailing slash. Assuming its the first: That's where the code is executing from. When you debug the program, its compiled and the binaries are placed under the project's \bin\debug directory. When you're testing, you're running the test's binaries, which are compiled and placed under the test project's bin\debug directory. Assuming its the last: Possibly some obscure reason, possibly a bug, or possibly to catch people who are concatenating paths rather than using Path.Combine (naughty naughty!). Well, I don't know why it's different. Test applications may be run within a custom CLR host; I think this may be the case as test apps do some weird stuff with private accessors that normally aren't allowed within the standard CLR host. I'm only grasping at straws here as I don't have any actual knowledge about how this stuff is actually being coded. Anyhow, the workaround stands (Path.Combine). Nobody should be concatenating paths, as path delimeters can change.
[ ".net" ]
5
9
4,131
1
0
2008-09-08T18:24:48.450000
2008-09-08T19:16:51.460000
50,346
50,352
Why is parameterized SQL generated by NHibernate just as fast as a stored procedure?
One of my co-workers claims that even though the execution path is cached, there is no way parameterized SQL generated from an ORM is as quick as a stored procedure. Any help with this stubborn developer?
I would start by reading this article: http://decipherinfosys.wordpress.com/2007/03/27/using-stored-procedures-vs-dynamic-sql-generated-by-orm/ Here is a speed test between the two: http://www.blackwasp.co.uk/SpeedTestSqlSproc.aspx
Why is parameterized SQL generated by NHibernate just as fast as a stored procedure? One of my co-workers claims that even though the execution path is cached, there is no way parameterized SQL generated from an ORM is as quick as a stored procedure. Any help with this stubborn developer?
TITLE: Why is parameterized SQL generated by NHibernate just as fast as a stored procedure? QUESTION: One of my co-workers claims that even though the execution path is cached, there is no way parameterized SQL generated from an ORM is as quick as a stored procedure. Any help with this stubborn developer? ANSWER: I would start by reading this article: http://decipherinfosys.wordpress.com/2007/03/27/using-stored-procedures-vs-dynamic-sql-generated-by-orm/ Here is a speed test between the two: http://www.blackwasp.co.uk/SpeedTestSqlSproc.aspx
[ "sql", "stored-procedures", "orm" ]
16
13
3,711
13
0
2008-09-08T18:25:01.197000
2008-09-08T18:26:36.777000
50,364
97,547
Image library that will auto-crop
I'm looking for a.Net library that will accept an image or filename and an aspect ratio, and crop the image to that aspect ratio. That's the easy part: I could do it myself. But I also want it to show a little intelligence in choosing exactly what content gets cropped, even if it's just picking which edge to slice. This is for a personal project, and the pain isn't high enough to justify spending any money on it, but if you can recommend a for-pay tool go ahead. Maybe someone else will find the suggestion useful.
Disclaimer: I work for a.NET Imaging vendor ( Atalasoft ) It depends on what kind of image you are talking about. If you are talking about 1-bit document images (like faxes or scans) we can do this. If you are talking about photographs, our product doesn't do this, but you might be looking for Seam carving. I wrote this application http://www.atalasoft.com/cs/blogs/31appsin31days/archive/2008/05/26/simple-seam-carver.aspx with our library that could be ported to just using the built-in.NET images with some work. The idea of seam carving is to find connected paths in the image with the least interesting variation from the surrounding pixels. In the normal implementation, you would pick a continuous (but not necessarily vertical) path and remove it. If you wanted a crop, you could find the area with the least energy and remove it. My code shows how to calculate the energy of a pixel and path (how different it is from it's surrounding pixels) If you look up seam carving, you will find some free implementations out there.
Image library that will auto-crop I'm looking for a.Net library that will accept an image or filename and an aspect ratio, and crop the image to that aspect ratio. That's the easy part: I could do it myself. But I also want it to show a little intelligence in choosing exactly what content gets cropped, even if it's just picking which edge to slice. This is for a personal project, and the pain isn't high enough to justify spending any money on it, but if you can recommend a for-pay tool go ahead. Maybe someone else will find the suggestion useful.
TITLE: Image library that will auto-crop QUESTION: I'm looking for a.Net library that will accept an image or filename and an aspect ratio, and crop the image to that aspect ratio. That's the easy part: I could do it myself. But I also want it to show a little intelligence in choosing exactly what content gets cropped, even if it's just picking which edge to slice. This is for a personal project, and the pain isn't high enough to justify spending any money on it, but if you can recommend a for-pay tool go ahead. Maybe someone else will find the suggestion useful. ANSWER: Disclaimer: I work for a.NET Imaging vendor ( Atalasoft ) It depends on what kind of image you are talking about. If you are talking about 1-bit document images (like faxes or scans) we can do this. If you are talking about photographs, our product doesn't do this, but you might be looking for Seam carving. I wrote this application http://www.atalasoft.com/cs/blogs/31appsin31days/archive/2008/05/26/simple-seam-carver.aspx with our library that could be ported to just using the built-in.NET images with some work. The idea of seam carving is to find connected paths in the image with the least interesting variation from the surrounding pixels. In the normal implementation, you would pick a continuous (but not necessarily vertical) path and remove it. If you wanted a crop, you could find the area with the least energy and remove it. My code shows how to calculate the energy of a pixel and path (how different it is from it's surrounding pixels) If you look up seam carving, you will find some free implementations out there.
[ ".net", "image-manipulation" ]
3
2
2,353
1
0
2008-09-08T18:29:38.330000
2008-09-18T22:13:16.150000
50,371
50,407
Better Merge Tool for Subversion
Is there a good external merge tool for tortoisesvn (I don't particularly like the built in Merge tool). I use WinMerge for diffs, but it doesn't work with the three way merge (maybe a better question would be is there a way to force tortoisesvn to merge like tortoisecvs?) [Edit] After trying all of them, for me, the SourceGear is the one I prefer. The way to specify the DiffMerge from sourcegear is: C:\Program Files\SourceGear\DiffMerge\DiffMerge.exe /t1="My Working Version" /t2="Repository Version" /t3="Base" /r=%merged %mine %theirs %base
Take a look at Sourcegear DiffMerge. DiffMerge is the compare and merge tool from their Vault and Fortress products, but they make it available for free as a standalone tool. One noteworthy feature is that it allows diffing of entire directory trees. Edit: While DiffMerge remains a free tool, it nags for registration with a popup at least once a day (since at least version 4.2). It also states in the popup: Select new features in future releases will also require registration, but core features and fixes will be available to everyone.
Better Merge Tool for Subversion Is there a good external merge tool for tortoisesvn (I don't particularly like the built in Merge tool). I use WinMerge for diffs, but it doesn't work with the three way merge (maybe a better question would be is there a way to force tortoisesvn to merge like tortoisecvs?) [Edit] After trying all of them, for me, the SourceGear is the one I prefer. The way to specify the DiffMerge from sourcegear is: C:\Program Files\SourceGear\DiffMerge\DiffMerge.exe /t1="My Working Version" /t2="Repository Version" /t3="Base" /r=%merged %mine %theirs %base
TITLE: Better Merge Tool for Subversion QUESTION: Is there a good external merge tool for tortoisesvn (I don't particularly like the built in Merge tool). I use WinMerge for diffs, but it doesn't work with the three way merge (maybe a better question would be is there a way to force tortoisesvn to merge like tortoisecvs?) [Edit] After trying all of them, for me, the SourceGear is the one I prefer. The way to specify the DiffMerge from sourcegear is: C:\Program Files\SourceGear\DiffMerge\DiffMerge.exe /t1="My Working Version" /t2="Repository Version" /t3="Base" /r=%merged %mine %theirs %base ANSWER: Take a look at Sourcegear DiffMerge. DiffMerge is the compare and merge tool from their Vault and Fortress products, but they make it available for free as a standalone tool. One noteworthy feature is that it allows diffing of entire directory trees. Edit: While DiffMerge remains a free tool, it nags for registration with a popup at least once a day (since at least version 4.2). It also states in the popup: Select new features in future releases will also require registration, but core features and fixes will be available to everyone.
[ "svn", "tortoisesvn" ]
58
32
35,613
7
0
2008-09-08T18:32:13.503000
2008-09-08T18:50:25.550000
50,373
50,420
MultiMap in Scala
I'm trying to mixin the MultiMap trait with a HashMap like so: val children:MultiMap[Integer, TreeNode] = new HashMap[Integer, Set[TreeNode]] with MultiMap[Integer, TreeNode] The definition for the MultiMap trait is: trait MultiMap[A, B] extends Map[A, Set[B]] Meaning that a MultiMap of types A & B is a Map of types A & Set[B], or so it seems to me. However, the compiler complains: C:\...\TestTreeDataModel.scala:87: error: illegal inheritance; template $anon inherits different type instances of trait Map: scala.collection.mutable.Map[Integer,scala.collection.mutable.Set[package.TreeNode]] and scala.collection.mutable.Map[Integer,Set[package.TreeNode]] new HashMap[Integer, Set[TreeNode]] with MultiMap[Integer, TreeNode] ^ one error found It seems that generics are tripping me up again.
I had to import scala.collection.mutable.Set. It seems the compiler thought the Set in HashMap[Integer, Set[TreeNode]] was scala.collection.Set. The Set in the MultiMap def is scala.collection. mutable.Set.
MultiMap in Scala I'm trying to mixin the MultiMap trait with a HashMap like so: val children:MultiMap[Integer, TreeNode] = new HashMap[Integer, Set[TreeNode]] with MultiMap[Integer, TreeNode] The definition for the MultiMap trait is: trait MultiMap[A, B] extends Map[A, Set[B]] Meaning that a MultiMap of types A & B is a Map of types A & Set[B], or so it seems to me. However, the compiler complains: C:\...\TestTreeDataModel.scala:87: error: illegal inheritance; template $anon inherits different type instances of trait Map: scala.collection.mutable.Map[Integer,scala.collection.mutable.Set[package.TreeNode]] and scala.collection.mutable.Map[Integer,Set[package.TreeNode]] new HashMap[Integer, Set[TreeNode]] with MultiMap[Integer, TreeNode] ^ one error found It seems that generics are tripping me up again.
TITLE: MultiMap in Scala QUESTION: I'm trying to mixin the MultiMap trait with a HashMap like so: val children:MultiMap[Integer, TreeNode] = new HashMap[Integer, Set[TreeNode]] with MultiMap[Integer, TreeNode] The definition for the MultiMap trait is: trait MultiMap[A, B] extends Map[A, Set[B]] Meaning that a MultiMap of types A & B is a Map of types A & Set[B], or so it seems to me. However, the compiler complains: C:\...\TestTreeDataModel.scala:87: error: illegal inheritance; template $anon inherits different type instances of trait Map: scala.collection.mutable.Map[Integer,scala.collection.mutable.Set[package.TreeNode]] and scala.collection.mutable.Map[Integer,Set[package.TreeNode]] new HashMap[Integer, Set[TreeNode]] with MultiMap[Integer, TreeNode] ^ one error found It seems that generics are tripping me up again. ANSWER: I had to import scala.collection.mutable.Set. It seems the compiler thought the Set in HashMap[Integer, Set[TreeNode]] was scala.collection.Set. The Set in the MultiMap def is scala.collection. mutable.Set.
[ "generics", "scala" ]
18
26
4,864
2
0
2008-09-08T18:32:58.790000
2008-09-08T18:59:25.310000
50,389
50,396
Does having a registry full of old stuff slow down Windows?
I know this isn't strictly speaking a programming question but something I always hear from pseudo-techies is that having a lot of entries in your registry slows down your Windows-based PC. I think this notion comes from people who are trying to troubleshoot their PC and why it's running so slow and they open up the registry at some point and see leftover entries from programs they uninstalled ages ago. But is there any truth to this idea? I would not think so since the registry is essentially just a database and drilling down to an entry wouldn't take significantly longer on a larger registry. But does it? EDIT: To be clear, I'm not looking for advice on how to make a PC run faster, or asking why my PC in particular is slow (it's not), I'm just curious if people who say "bigger registry means slower PC" are accurate or not.
In short, not really. In the old days when machines were slower the answer was yes; but having a modern processor rip through even a 60MB registry is not a problem. Typically, the real reason a modern machine starts running slow is due to everything from malware to virus scanners: Mcafee, Norton's, etc are prime targets in my mind. Also, the WinSXS folder tends to grow as service packs and applications are installed. This seems to have a negative impact on system performance. There are only two possible solutions in this scenario. First, if possible, reinstall the OS with the latest service pack already slipstreamed into the install. Second, if that isn't possible AND you are running Vista with SP1, you can run the vsp1cln.exe tool (see technet ) which will clean up a lot of the older versions of components. Note that this tool can only be executed once and it does not allow you to roll back.
Does having a registry full of old stuff slow down Windows? I know this isn't strictly speaking a programming question but something I always hear from pseudo-techies is that having a lot of entries in your registry slows down your Windows-based PC. I think this notion comes from people who are trying to troubleshoot their PC and why it's running so slow and they open up the registry at some point and see leftover entries from programs they uninstalled ages ago. But is there any truth to this idea? I would not think so since the registry is essentially just a database and drilling down to an entry wouldn't take significantly longer on a larger registry. But does it? EDIT: To be clear, I'm not looking for advice on how to make a PC run faster, or asking why my PC in particular is slow (it's not), I'm just curious if people who say "bigger registry means slower PC" are accurate or not.
TITLE: Does having a registry full of old stuff slow down Windows? QUESTION: I know this isn't strictly speaking a programming question but something I always hear from pseudo-techies is that having a lot of entries in your registry slows down your Windows-based PC. I think this notion comes from people who are trying to troubleshoot their PC and why it's running so slow and they open up the registry at some point and see leftover entries from programs they uninstalled ages ago. But is there any truth to this idea? I would not think so since the registry is essentially just a database and drilling down to an entry wouldn't take significantly longer on a larger registry. But does it? EDIT: To be clear, I'm not looking for advice on how to make a PC run faster, or asking why my PC in particular is slow (it's not), I'm just curious if people who say "bigger registry means slower PC" are accurate or not. ANSWER: In short, not really. In the old days when machines were slower the answer was yes; but having a modern processor rip through even a 60MB registry is not a problem. Typically, the real reason a modern machine starts running slow is due to everything from malware to virus scanners: Mcafee, Norton's, etc are prime targets in my mind. Also, the WinSXS folder tends to grow as service packs and applications are installed. This seems to have a negative impact on system performance. There are only two possible solutions in this scenario. First, if possible, reinstall the OS with the latest service pack already slipstreamed into the install. Second, if that isn't possible AND you are running Vista with SP1, you can run the vsp1cln.exe tool (see technet ) which will clean up a lot of the older versions of components. Note that this tool can only be executed once and it does not allow you to roll back.
[ "windows", "registry" ]
7
4
4,631
4
0
2008-09-08T18:39:35.280000
2008-09-08T18:44:36.110000
50,391
50,419
Is it possible to track allocation/deallocation?
As far as I can tell, this is isn't possible, so I'm really just hoping for a left field undocumented allocation hook function. I want a way to track allocations like in _CrtSetAllocHook, but for C#/.NET. The only visibility to the garbage collector/allocation appears to be GC.CollectionCount. Anyone have any other.NET memory mojo?
The CLR has a 'profiling API' that hooks into pretty much everything - it is what the commercial.NET memory profiling products use, I believe. Here is an MSDN link to the top level of the documentation:.NET Framework General Reference: About the Profiling API See this MSDN magazine article for an introduction to the memory piece: Inspect and Optimize Your Program's Memory Usage with the.NET Profiler API
Is it possible to track allocation/deallocation? As far as I can tell, this is isn't possible, so I'm really just hoping for a left field undocumented allocation hook function. I want a way to track allocations like in _CrtSetAllocHook, but for C#/.NET. The only visibility to the garbage collector/allocation appears to be GC.CollectionCount. Anyone have any other.NET memory mojo?
TITLE: Is it possible to track allocation/deallocation? QUESTION: As far as I can tell, this is isn't possible, so I'm really just hoping for a left field undocumented allocation hook function. I want a way to track allocations like in _CrtSetAllocHook, but for C#/.NET. The only visibility to the garbage collector/allocation appears to be GC.CollectionCount. Anyone have any other.NET memory mojo? ANSWER: The CLR has a 'profiling API' that hooks into pretty much everything - it is what the commercial.NET memory profiling products use, I believe. Here is an MSDN link to the top level of the documentation:.NET Framework General Reference: About the Profiling API See this MSDN magazine article for an introduction to the memory piece: Inspect and Optimize Your Program's Memory Usage with the.NET Profiler API
[ "c#", "memory", "hook", "allocation" ]
5
8
2,523
2
0
2008-09-08T18:41:16.897000
2008-09-08T18:57:13.380000
50,394
55,385
What Python way would you suggest to check whois database records?
I'm trying to get a webservice up and running that actually requires to check whois databases. What I'm doing right now is ugly and I'd like to avoid it as much as I can: I call gwhois command and parse its output. Ugly. I did some search to try to find a pythonic way to do this task. Generally I got quite much nothing - this old discussion list link has a way to check if domain exist. Quite not what I was looking for... But still, it was best anwser Google gave me - everything else is just a bunch of unanwsered questions. Any of you have succeeded to get some method up and running? I'd very much appreciate some tips, or should I just do it the opensource-way, sit down and code something by myself?:)
There's nothing wrong with using a command line utility to do what you want. If you put a nice wrapper around the service, you can implement the internals however you want! For example: class Whois(object): _whois_by_query_cache = {} def __init__(self, query): """Initializes the instance variables to defaults. See:meth:`lookup` for details on how to submit the query.""" self.query = query self.domain = None #... other fields. def lookup(self): """Submits the `whois` query and stores results internally.""" #... implementation Now, whether or not you roll your own using urllib, wrap around a command line utility (like you're doing), or import a third party library and use that (like you're saying ), this interface stays the same. This approach is generally not considered ugly at all -- sometimes command utilities do what you want and you should be able to leverage them. If speed ends up being a bottleneck, your abstraction makes the process of switching to a native Python implementation transparent to your client code. Practicality beats purity -- that's what's Pythonic.:)
What Python way would you suggest to check whois database records? I'm trying to get a webservice up and running that actually requires to check whois databases. What I'm doing right now is ugly and I'd like to avoid it as much as I can: I call gwhois command and parse its output. Ugly. I did some search to try to find a pythonic way to do this task. Generally I got quite much nothing - this old discussion list link has a way to check if domain exist. Quite not what I was looking for... But still, it was best anwser Google gave me - everything else is just a bunch of unanwsered questions. Any of you have succeeded to get some method up and running? I'd very much appreciate some tips, or should I just do it the opensource-way, sit down and code something by myself?:)
TITLE: What Python way would you suggest to check whois database records? QUESTION: I'm trying to get a webservice up and running that actually requires to check whois databases. What I'm doing right now is ugly and I'd like to avoid it as much as I can: I call gwhois command and parse its output. Ugly. I did some search to try to find a pythonic way to do this task. Generally I got quite much nothing - this old discussion list link has a way to check if domain exist. Quite not what I was looking for... But still, it was best anwser Google gave me - everything else is just a bunch of unanwsered questions. Any of you have succeeded to get some method up and running? I'd very much appreciate some tips, or should I just do it the opensource-way, sit down and code something by myself?:) ANSWER: There's nothing wrong with using a command line utility to do what you want. If you put a nice wrapper around the service, you can implement the internals however you want! For example: class Whois(object): _whois_by_query_cache = {} def __init__(self, query): """Initializes the instance variables to defaults. See:meth:`lookup` for details on how to submit the query.""" self.query = query self.domain = None #... other fields. def lookup(self): """Submits the `whois` query and stores results internally.""" #... implementation Now, whether or not you roll your own using urllib, wrap around a command line utility (like you're doing), or import a third party library and use that (like you're saying ), this interface stays the same. This approach is generally not considered ugly at all -- sometimes command utilities do what you want and you should be able to leverage them. If speed ends up being a bottleneck, your abstraction makes the process of switching to a native Python implementation transparent to your client code. Practicality beats purity -- that's what's Pythonic.:)
[ "python", "system-administration", "whois" ]
11
7
24,217
9
0
2008-09-08T18:43:52.790000
2008-09-10T21:44:53.197000
50,398
50,440
Calling C# code from Java?
Does anyone have a good solution for integrating some C# code into a java application? The code is small, so I could re-write in java, but I would rather reuse the code if possible. Don't repeat yourself, etc. Also, I know I can expose the C# as a web service or whatever, but it has some security/encryption stuff in there, so I would rather keep it tightly integrated if possible. Edit: It's going to be on a server-based app, so "downloading" another runtime is irrelevant.
There is an IL to Java Bytecode compiler GrassHopper which may be of use to you. I've never tried it though. I'd look at rewriting your code in Java though EDIT: Note that Grasshopper seems to be no longer available.
Calling C# code from Java? Does anyone have a good solution for integrating some C# code into a java application? The code is small, so I could re-write in java, but I would rather reuse the code if possible. Don't repeat yourself, etc. Also, I know I can expose the C# as a web service or whatever, but it has some security/encryption stuff in there, so I would rather keep it tightly integrated if possible. Edit: It's going to be on a server-based app, so "downloading" another runtime is irrelevant.
TITLE: Calling C# code from Java? QUESTION: Does anyone have a good solution for integrating some C# code into a java application? The code is small, so I could re-write in java, but I would rather reuse the code if possible. Don't repeat yourself, etc. Also, I know I can expose the C# as a web service or whatever, but it has some security/encryption stuff in there, so I would rather keep it tightly integrated if possible. Edit: It's going to be on a server-based app, so "downloading" another runtime is irrelevant. ANSWER: There is an IL to Java Bytecode compiler GrassHopper which may be of use to you. I've never tried it though. I'd look at rewriting your code in Java though EDIT: Note that Grasshopper seems to be no longer available.
[ "c#", "java", "java-native-interface" ]
37
5
57,745
10
0
2008-09-08T18:46:09.537000
2008-09-08T19:06:52.267000
50,417
50,422
How do I get list of recent files in GNU Emacs?
When I use Emacs I want to be able to easily display and navigate through a list of files I worked on from not just the current session but from previous sessions. (BTW, running Emacs 22.2 on Windows)
From Joe Grossberg 's blog (no longer available): But if you're using GNU Emacs 21.2 (the latest version, which includes this as part of the standard distro), you can just put the following lines into your.emacs file;; recentf stuff (require 'recentf) (recentf-mode 1) (setq recentf-max-menu-items 25) (global-set-key "\C-x\ \C-r" 'recentf-open-files) Then, when you launch emacs, hit CTRL - X CTRL - R. It will show a list of the recently-opened files in a buffer. Move the cursor to a line and press ENTER. That will open the file in question, and move it to the top of your recent-file list. (Note: Emacs records file names. Therefore, if you move or rename a file outside of Emacs, it won't automatically update the list. You'll have to open the renamed file with the normal CTRL - X CTRL - F method.) Jayakrishnan Varnam has a page including screenshots of how this package works. Note: You don't need the (require 'recentf) line.
How do I get list of recent files in GNU Emacs? When I use Emacs I want to be able to easily display and navigate through a list of files I worked on from not just the current session but from previous sessions. (BTW, running Emacs 22.2 on Windows)
TITLE: How do I get list of recent files in GNU Emacs? QUESTION: When I use Emacs I want to be able to easily display and navigate through a list of files I worked on from not just the current session but from previous sessions. (BTW, running Emacs 22.2 on Windows) ANSWER: From Joe Grossberg 's blog (no longer available): But if you're using GNU Emacs 21.2 (the latest version, which includes this as part of the standard distro), you can just put the following lines into your.emacs file;; recentf stuff (require 'recentf) (recentf-mode 1) (setq recentf-max-menu-items 25) (global-set-key "\C-x\ \C-r" 'recentf-open-files) Then, when you launch emacs, hit CTRL - X CTRL - R. It will show a list of the recently-opened files in a buffer. Move the cursor to a line and press ENTER. That will open the file in question, and move it to the top of your recent-file list. (Note: Emacs records file names. Therefore, if you move or rename a file outside of Emacs, it won't automatically update the list. You'll have to open the renamed file with the normal CTRL - X CTRL - F method.) Jayakrishnan Varnam has a page including screenshots of how this package works. Note: You don't need the (require 'recentf) line.
[ "emacs", "ide" ]
32
30
8,094
2
0
2008-09-08T18:56:14.677000
2008-09-08T19:00:55.960000
50,421
50,427
Does silverlight work on chrome?
Does anyone know if silverlight plugs into chrome, or when they plan to support it?
This guy have had partial success with silverlight in chrome, but it does not seem to be supported: http://wildermuth.com/2008/09/02/Silverlight_2_and_Google_Chrome From The Microsoft Silverlight Team in the silverlight forum: Hello, currently we don't have plans to support Chrome. We will support it in the future if it gains enough market share. Please understand, each browser implements the plug-in model differently, so it'll be a lot of effort to officially support a browser 100%... By the way, IE 8 also runs each tab in its own process. If a tab crashes, other tabs will still work fine. UPDATE: Jon Galloway has just posted instructions on how to get silverlight successfully running on Chrome here: http://weblogs.asp.net/jgalloway/archive/2008/09/17/silverlight-on-chrome.aspx
Does silverlight work on chrome? Does anyone know if silverlight plugs into chrome, or when they plan to support it?
TITLE: Does silverlight work on chrome? QUESTION: Does anyone know if silverlight plugs into chrome, or when they plan to support it? ANSWER: This guy have had partial success with silverlight in chrome, but it does not seem to be supported: http://wildermuth.com/2008/09/02/Silverlight_2_and_Google_Chrome From The Microsoft Silverlight Team in the silverlight forum: Hello, currently we don't have plans to support Chrome. We will support it in the future if it gains enough market share. Please understand, each browser implements the plug-in model differently, so it'll be a lot of effort to officially support a browser 100%... By the way, IE 8 also runs each tab in its own process. If a tab crashes, other tabs will still work fine. UPDATE: Jon Galloway has just posted instructions on how to get silverlight successfully running on Chrome here: http://weblogs.asp.net/jgalloway/archive/2008/09/17/silverlight-on-chrome.aspx
[ "silverlight", "google-chrome" ]
4
3
7,647
4
0
2008-09-08T19:00:01.720000
2008-09-08T19:01:53.697000
50,426
50,439
Preventing accidental double clicking on a button
I have a few controls that inherit from ASP.NET buttons and use onserverclick. If the user clicks twice, the button fires two server side events. How can I prevent this? I tried setting this.disabled='true' after the click (in the onclick attribute) via javascript, but that blocks the first postback as well.
See this example for disabling control on postback. It should help you do what you're trying to achieve. http://encosia.com/2007/04/17/disable-a-button-control-during-postback/
Preventing accidental double clicking on a button I have a few controls that inherit from ASP.NET buttons and use onserverclick. If the user clicks twice, the button fires two server side events. How can I prevent this? I tried setting this.disabled='true' after the click (in the onclick attribute) via javascript, but that blocks the first postback as well.
TITLE: Preventing accidental double clicking on a button QUESTION: I have a few controls that inherit from ASP.NET buttons and use onserverclick. If the user clicks twice, the button fires two server side events. How can I prevent this? I tried setting this.disabled='true' after the click (in the onclick attribute) via javascript, but that blocks the first postback as well. ANSWER: See this example for disabling control on postback. It should help you do what you're trying to achieve. http://encosia.com/2007/04/17/disable-a-button-control-during-postback/
[ "asp.net", "javascript", "button" ]
8
14
11,819
7
0
2008-09-08T19:01:38.767000
2008-09-08T19:06:11.300000
50,430
50,442
CSS - Placement of a div in the lower left-hand corner
I wish I were a CSS smarty.... How can you place a div container in the lower left-hand corner of the web page; taking into account the users scroll-position?
To position an element relative to the "viewport" (the window or frame it's in), and have it ignore how that viewport is scrolled, you can use the position: fixed; property value ( MDN documentation ). This has been supported by every browser since Internet Explorer 7. To position the element at the bottom-left of the window, we need to also specify that it should be positioned at 0 distance from the bottom and left: position: fixed; bottom: 0; left: 0; Full Example.bottom-left { position: fixed; bottom: 0; left: 0; }.alert { border: 2px solid red; background: white; font-weight: bold; padding: 1em; } Look at me! Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam dignissim diam arcu, a gravida justo malesuada et. Fusce iaculis, dui laoreet ultricies congue, arcu lectus rhoncus neque, ut molestie magna augue ut neque. Duis in feugiat ipsum, et imperdiet nunc. Cras convallis lorem eu diam malesuada malesuada. Nunc dapibus suscipit ligula, vel mattis eros blandit id. In placerat justo vitae pretium fermentum. Proin ac erat commodo nibh ullamcorper feugiat. Nulla ultricies maximus massa, non semper dolor malesuada vel. Nullam sem justo, bibendum vel tempus pharetra, gravida vel sapien. Morbi facilisis tristique mauris vel elementum. Ut porttitor egestas metus eget auctor. Phasellus efficitur rutrum massa nec fringilla. Aliquam et imperdiet leo. Sed tincidunt hendrerit tortor eget tempor. Sed vel dolor lectus. Nulla sed blandit lacus. Mauris ac magna nec libero vehicula aliquet id a libero. Vivamus sed lobortis velit. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed at feugiat sapien, ut commodo mi. Quisque scelerisque maximus efficitur. In ultrices, magna eu semper pellentesque, tellus odio hendrerit augue, ut porta sapien lacus quis odio. Duis sodales, dui a condimentum imperdiet, tellus est laoreet velit, a viverra risus libero sed urna. Phasellus sollicitudin tincidunt viverra. Proin vulputate leo at justo auctor feugiat. Nam auctor, mauris at commodo tempus, eros diam varius ligula, vitae efficitur massa lectus et enim. Integer tristique nibh in lacus condimentum, et interdum urna mollis. Aenean id risus tristique, volutpat dolor sed, fermentum ex. Interdum et malesuada fames ac ante ipsum primis in faucibus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nullam velit nibh, elementum at orci quis, tempor fermentum tellus. Nunc facilisis nisi at leo auctor aliquet. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam tempor ipsum vel scelerisque tincidunt. Etiam vulputate auctor ante, in tristique est congue ut. Vestibulum maximus nibh vestibulum tristique ullamcorper. Phasellus eu eleifend ante, nec efficitur nulla. Nunc pulvinar purus id arcu egestas, sed iaculis nisl finibus. Sed cursus bibendum tortor, id cursus lacus euismod in. Nam lacinia, sapien faucibus dapibus varius, neque velit fringilla est, in porta quam sem sit amet ligula. Aliquam ornare est ac pellentesque suscipit. Curabitur eleifend convallis sem, volutpat efficitur erat laoreet id. Maecenas interdum ante in lectus varius, lobortis auctor quam rutrum. Nullam tristique felis quis lectus luctus gravida. Cras porttitor pellentesque nibh. Fusce placerat vehicula commodo. Mauris vel lectus viverra sem consectetur sagittis quis vel lectus. Quisque vel dapibus augue. Sed lacinia massa quis dui sodales faucibus. Donec sagittis, dolor sed fermentum dapibus, justo ipsum porttitor purus, sed fermentum mi nulla non lorem. Praesent aliquet iaculis molestie. Phasellus enim nunc, vestibulum non odio vel, porta imperdiet lorem. Morbi laoreet felis a ipsum elementum sollicitudin. Morbi varius mollis ex, a posuere lorem fringilla ac. Curabitur metus ligula, mollis quis diam eu, pulvinar placerat libero. Aenean vestibulum lacinia diam in facilisis. Praesent egestas sapien a est consequat facilisis. Nulla id mauris a metus venenatis pellentesque. Praesent justo augue, efficitur ac vulputate et, luctus at elit. Proin quis urna quam. Pellentesque iaculis, felis sed hendrerit venenatis, purus augue venenatis tellus, a posuere justo tellus at ex. Donec et arcu non arcu scelerisque efficitur nec sed dolor. Sed eget lacus enim. Donec sodales mollis condimentum.
CSS - Placement of a div in the lower left-hand corner I wish I were a CSS smarty.... How can you place a div container in the lower left-hand corner of the web page; taking into account the users scroll-position?
TITLE: CSS - Placement of a div in the lower left-hand corner QUESTION: I wish I were a CSS smarty.... How can you place a div container in the lower left-hand corner of the web page; taking into account the users scroll-position? ANSWER: To position an element relative to the "viewport" (the window or frame it's in), and have it ignore how that viewport is scrolled, you can use the position: fixed; property value ( MDN documentation ). This has been supported by every browser since Internet Explorer 7. To position the element at the bottom-left of the window, we need to also specify that it should be positioned at 0 distance from the bottom and left: position: fixed; bottom: 0; left: 0; Full Example.bottom-left { position: fixed; bottom: 0; left: 0; }.alert { border: 2px solid red; background: white; font-weight: bold; padding: 1em; } Look at me! Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam dignissim diam arcu, a gravida justo malesuada et. Fusce iaculis, dui laoreet ultricies congue, arcu lectus rhoncus neque, ut molestie magna augue ut neque. Duis in feugiat ipsum, et imperdiet nunc. Cras convallis lorem eu diam malesuada malesuada. Nunc dapibus suscipit ligula, vel mattis eros blandit id. In placerat justo vitae pretium fermentum. Proin ac erat commodo nibh ullamcorper feugiat. Nulla ultricies maximus massa, non semper dolor malesuada vel. Nullam sem justo, bibendum vel tempus pharetra, gravida vel sapien. Morbi facilisis tristique mauris vel elementum. Ut porttitor egestas metus eget auctor. Phasellus efficitur rutrum massa nec fringilla. Aliquam et imperdiet leo. Sed tincidunt hendrerit tortor eget tempor. Sed vel dolor lectus. Nulla sed blandit lacus. Mauris ac magna nec libero vehicula aliquet id a libero. Vivamus sed lobortis velit. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed at feugiat sapien, ut commodo mi. Quisque scelerisque maximus efficitur. In ultrices, magna eu semper pellentesque, tellus odio hendrerit augue, ut porta sapien lacus quis odio. Duis sodales, dui a condimentum imperdiet, tellus est laoreet velit, a viverra risus libero sed urna. Phasellus sollicitudin tincidunt viverra. Proin vulputate leo at justo auctor feugiat. Nam auctor, mauris at commodo tempus, eros diam varius ligula, vitae efficitur massa lectus et enim. Integer tristique nibh in lacus condimentum, et interdum urna mollis. Aenean id risus tristique, volutpat dolor sed, fermentum ex. Interdum et malesuada fames ac ante ipsum primis in faucibus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nullam velit nibh, elementum at orci quis, tempor fermentum tellus. Nunc facilisis nisi at leo auctor aliquet. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam tempor ipsum vel scelerisque tincidunt. Etiam vulputate auctor ante, in tristique est congue ut. Vestibulum maximus nibh vestibulum tristique ullamcorper. Phasellus eu eleifend ante, nec efficitur nulla. Nunc pulvinar purus id arcu egestas, sed iaculis nisl finibus. Sed cursus bibendum tortor, id cursus lacus euismod in. Nam lacinia, sapien faucibus dapibus varius, neque velit fringilla est, in porta quam sem sit amet ligula. Aliquam ornare est ac pellentesque suscipit. Curabitur eleifend convallis sem, volutpat efficitur erat laoreet id. Maecenas interdum ante in lectus varius, lobortis auctor quam rutrum. Nullam tristique felis quis lectus luctus gravida. Cras porttitor pellentesque nibh. Fusce placerat vehicula commodo. Mauris vel lectus viverra sem consectetur sagittis quis vel lectus. Quisque vel dapibus augue. Sed lacinia massa quis dui sodales faucibus. Donec sagittis, dolor sed fermentum dapibus, justo ipsum porttitor purus, sed fermentum mi nulla non lorem. Praesent aliquet iaculis molestie. Phasellus enim nunc, vestibulum non odio vel, porta imperdiet lorem. Morbi laoreet felis a ipsum elementum sollicitudin. Morbi varius mollis ex, a posuere lorem fringilla ac. Curabitur metus ligula, mollis quis diam eu, pulvinar placerat libero. Aenean vestibulum lacinia diam in facilisis. Praesent egestas sapien a est consequat facilisis. Nulla id mauris a metus venenatis pellentesque. Praesent justo augue, efficitur ac vulputate et, luctus at elit. Proin quis urna quam. Pellentesque iaculis, felis sed hendrerit venenatis, purus augue venenatis tellus, a posuere justo tellus at ex. Donec et arcu non arcu scelerisque efficitur nec sed dolor. Sed eget lacus enim. Donec sodales mollis condimentum.
[ "css", "html", "positioning" ]
28
42
40,298
1
0
2008-09-08T19:03:27.093000
2008-09-08T19:07:55.180000
50,450
50,633
How to iterate a jagged array?
This has been driving me crazy for a few days. Why doesn't the following work? Dim arr(3, 3) As Integer For y As Integer = 0 To arr.GetLength(0) - 1 For x As Integer = 0 To arr.GetLength(y) - 1 arr(y, x) = y + x Next Next Also, what if the array looked like this instead? { {1, 2, 3}, {4, 5, 6, 7, 8, 9, 9, 9}, {5, 4, 3, 2} }
Ok, so what you really need is a "jagged array". This will allow you to have an "array that contains other arrays of varying lengths". Dim arr As Integer()() = {New Integer() {1, 2, 3}, New Integer() {4, 5, 6, 7, 8, 9, 9, 9}, New Integer() {5, 4, 3, 2}} For x = 0 To arr.GetUpperBound(0) Console.WriteLine("Row " & x & " has " & arr(x).GetUpperBound(0) & " columns") For y = 0 To arr(x).GetUpperBound(0) Console.WriteLine("(" & x & "," & y & ") = " & arr(x)(y)) Next Next Output: Row 0 has 2 columns (0,0) = 1 (0,1) = 2 (0,2) = 3 Row 1 has 7 columns (1,0) = 4 (1,1) = 5 (1,2) = 6 (1,3) = 7 (1,4) = 8 (1,5) = 9 (1,6) = 9 (1,7) = 9 Row 2 has 3 columns (2,0) = 5 (2,1) = 4 (2,2) = 3 (2,3) = 2
How to iterate a jagged array? This has been driving me crazy for a few days. Why doesn't the following work? Dim arr(3, 3) As Integer For y As Integer = 0 To arr.GetLength(0) - 1 For x As Integer = 0 To arr.GetLength(y) - 1 arr(y, x) = y + x Next Next Also, what if the array looked like this instead? { {1, 2, 3}, {4, 5, 6, 7, 8, 9, 9, 9}, {5, 4, 3, 2} }
TITLE: How to iterate a jagged array? QUESTION: This has been driving me crazy for a few days. Why doesn't the following work? Dim arr(3, 3) As Integer For y As Integer = 0 To arr.GetLength(0) - 1 For x As Integer = 0 To arr.GetLength(y) - 1 arr(y, x) = y + x Next Next Also, what if the array looked like this instead? { {1, 2, 3}, {4, 5, 6, 7, 8, 9, 9, 9}, {5, 4, 3, 2} } ANSWER: Ok, so what you really need is a "jagged array". This will allow you to have an "array that contains other arrays of varying lengths". Dim arr As Integer()() = {New Integer() {1, 2, 3}, New Integer() {4, 5, 6, 7, 8, 9, 9, 9}, New Integer() {5, 4, 3, 2}} For x = 0 To arr.GetUpperBound(0) Console.WriteLine("Row " & x & " has " & arr(x).GetUpperBound(0) & " columns") For y = 0 To arr(x).GetUpperBound(0) Console.WriteLine("(" & x & "," & y & ") = " & arr(x)(y)) Next Next Output: Row 0 has 2 columns (0,0) = 1 (0,1) = 2 (0,2) = 3 Row 1 has 7 columns (1,0) = 4 (1,1) = 5 (1,2) = 6 (1,3) = 7 (1,4) = 8 (1,5) = 9 (1,6) = 9 (1,7) = 9 Row 2 has 3 columns (2,0) = 5 (2,1) = 4 (2,2) = 3 (2,3) = 2
[ "vb.net", "arrays", "jagged-arrays" ]
2
5
8,904
7
0
2008-09-08T19:12:28.587000
2008-09-08T20:45:17.957000
50,470
50,481
Can I prevent user pasting Javascript into Design Mode IFrame?
I'm building a webapp that contains an IFrame in design mode so my user's can "tart" their content up and paste in content to be displayed on their page. Like the WYSIWYG editor on most blog engines or forums. I'm trying to think of all potential security holes I need to plug, one of which is a user pasting in Javascript: Now I know I can strip this out at the server end, before saving it and/or serving it back, but I'm worried about the possibility of someone being able to paste some script in and run it there and then, without even sending it back to the server for processing. Am I worrying over nothing? Any advice would be great, couldn't find much searching Google. Anthony
...I'm worried about the possibility of someone being able to paste some script in and run it there and then, without even sending it back to the server for processing. Am I worrying over nothing? Firefox has a plug-in called Greasemonkey that allows users to arbitrarily run JavaScript against any page that loads into their browser, and there is nothing you can do about it. Firebug allows you to modify web pages as well as run arbitrary JavaScript. AFAIK, you really only need to worry once it gets to your server, and then potentially hits other users.
Can I prevent user pasting Javascript into Design Mode IFrame? I'm building a webapp that contains an IFrame in design mode so my user's can "tart" their content up and paste in content to be displayed on their page. Like the WYSIWYG editor on most blog engines or forums. I'm trying to think of all potential security holes I need to plug, one of which is a user pasting in Javascript: Now I know I can strip this out at the server end, before saving it and/or serving it back, but I'm worried about the possibility of someone being able to paste some script in and run it there and then, without even sending it back to the server for processing. Am I worrying over nothing? Any advice would be great, couldn't find much searching Google. Anthony
TITLE: Can I prevent user pasting Javascript into Design Mode IFrame? QUESTION: I'm building a webapp that contains an IFrame in design mode so my user's can "tart" their content up and paste in content to be displayed on their page. Like the WYSIWYG editor on most blog engines or forums. I'm trying to think of all potential security holes I need to plug, one of which is a user pasting in Javascript: Now I know I can strip this out at the server end, before saving it and/or serving it back, but I'm worried about the possibility of someone being able to paste some script in and run it there and then, without even sending it back to the server for processing. Am I worrying over nothing? Any advice would be great, couldn't find much searching Google. Anthony ANSWER: ...I'm worried about the possibility of someone being able to paste some script in and run it there and then, without even sending it back to the server for processing. Am I worrying over nothing? Firefox has a plug-in called Greasemonkey that allows users to arbitrarily run JavaScript against any page that loads into their browser, and there is nothing you can do about it. Firebug allows you to modify web pages as well as run arbitrary JavaScript. AFAIK, you really only need to worry once it gets to your server, and then potentially hits other users.
[ "javascript", "iframe" ]
0
3
835
2
0
2008-09-08T19:23:00.573000
2008-09-08T19:28:02.357000
50,488
50,512
WebDev.WebServer.EXE Crashes After VS 2008 SP1 Install
Since, for various reasons, I can't use IIS for an ASP.NET website I'm developing, I run Cassini from the command line to test the site. However, after installing Visual Studio 2008 SP1, I get a System.Net.Sockets.SocketException when I try to start up the web server. Is anyone else having this problem, and if so, how did you fix it?
Is there anything in the Application section of the event log? Have you tried using a different port? Per this thread, try: Unbind from Visual Source safe, delete the web project from the solution, rename the folder where the website is stored and then re add to the solution as an existing web site and then bind to source safe again. There may be some incorrect info in your.suo or.sln file. You can safely rename the former, as it is user-specific ( s olution u ser o ptions); the latter (the s o l utio n itself) would be a bit more of a hassle to recreate.
WebDev.WebServer.EXE Crashes After VS 2008 SP1 Install Since, for various reasons, I can't use IIS for an ASP.NET website I'm developing, I run Cassini from the command line to test the site. However, after installing Visual Studio 2008 SP1, I get a System.Net.Sockets.SocketException when I try to start up the web server. Is anyone else having this problem, and if so, how did you fix it?
TITLE: WebDev.WebServer.EXE Crashes After VS 2008 SP1 Install QUESTION: Since, for various reasons, I can't use IIS for an ASP.NET website I'm developing, I run Cassini from the command line to test the site. However, after installing Visual Studio 2008 SP1, I get a System.Net.Sockets.SocketException when I try to start up the web server. Is anyone else having this problem, and if so, how did you fix it? ANSWER: Is there anything in the Application section of the event log? Have you tried using a different port? Per this thread, try: Unbind from Visual Source safe, delete the web project from the solution, rename the folder where the website is stored and then re add to the solution as an existing web site and then bind to source safe again. There may be some incorrect info in your.suo or.sln file. You can safely rename the former, as it is user-specific ( s olution u ser o ptions); the latter (the s o l utio n itself) would be a bit more of a hassle to recreate.
[ "asp.net", "webserver" ]
6
5
2,334
1
0
2008-09-08T19:32:22.063000
2008-09-08T19:48:29.187000
50,499
50,905
How do I get the path and name of the python file that is currently executing?
I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process. For example, let's say I have three files. Using execfile: script_1.py calls script_2.py. In turn, script_2.py calls script_3.py. How can I get the file name and path of script_3.py, from code within script_3.py, without having to pass that information as arguments from script_2.py? (Executing os.getcwd() returns the original starting script's filepath not the current file's.)
p1.py: execfile("p2.py") p2.py: import inspect, os print (inspect.getfile(inspect.currentframe())) # script filename (usually with path) print (os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))) # script directory
How do I get the path and name of the python file that is currently executing? I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process. For example, let's say I have three files. Using execfile: script_1.py calls script_2.py. In turn, script_2.py calls script_3.py. How can I get the file name and path of script_3.py, from code within script_3.py, without having to pass that information as arguments from script_2.py? (Executing os.getcwd() returns the original starting script's filepath not the current file's.)
TITLE: How do I get the path and name of the python file that is currently executing? QUESTION: I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process. For example, let's say I have three files. Using execfile: script_1.py calls script_2.py. In turn, script_2.py calls script_3.py. How can I get the file name and path of script_3.py, from code within script_3.py, without having to pass that information as arguments from script_2.py? (Executing os.getcwd() returns the original starting script's filepath not the current file's.) ANSWER: p1.py: execfile("p2.py") p2.py: import inspect, os print (inspect.getfile(inspect.currentframe())) # script filename (usually with path) print (os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))) # script directory
[ "python", "file", "reflection", "scripting", "filesystems" ]
575
286
618,163
26
0
2008-09-08T19:41:10.497000
2008-09-08T23:02:42.043000
50,524
50,567
What is a regex "independent non-capturing group"?
From the Java 6 Pattern documentation: Special constructs (non-capturing) (?: X ) X, as a non-capturing group … (?> X ) X, as an independent, non-capturing group Between (?:X) and (?>X) what is the difference? What does the independent mean in this context?
It means that the grouping is atomic, and it throws away backtracking information for a matched group. So, this expression is possessive; it won't back off even if doing so is the only way for the regex as a whole to succeed. It's "independent" in the sense that it doesn't cooperate, via backtracking, with other elements of the regex to ensure a match.
What is a regex "independent non-capturing group"? From the Java 6 Pattern documentation: Special constructs (non-capturing) (?: X ) X, as a non-capturing group … (?> X ) X, as an independent, non-capturing group Between (?:X) and (?>X) what is the difference? What does the independent mean in this context?
TITLE: What is a regex "independent non-capturing group"? QUESTION: From the Java 6 Pattern documentation: Special constructs (non-capturing) (?: X ) X, as a non-capturing group … (?> X ) X, as an independent, non-capturing group Between (?:X) and (?>X) what is the difference? What does the independent mean in this context? ANSWER: It means that the grouping is atomic, and it throws away backtracking information for a matched group. So, this expression is possessive; it won't back off even if doing so is the only way for the regex as a whole to succeed. It's "independent" in the sense that it doesn't cooperate, via backtracking, with other elements of the regex to ensure a match.
[ "java", "regex" ]
73
53
8,003
4
0
2008-09-08T19:57:03.767000
2008-09-08T20:16:09.667000
50,525
50,530
C: Implicit casting and integer overflowing in the evaluation of expressions
Let's take the code int a, b, c;... if ((a + b) > C) If we add the values of a and b and the sum exceeds the maximum value of an int, will the integrity of the comparison be compromised? I was thinking that there might be an implicit up cast or overflow bit check and that will be factored into the evaluation of this expression.
C will do no such thing. It will silently overflow and lead to a possibly incorrect comparison. You can up-cast yourself, but it will not be done automatically.
C: Implicit casting and integer overflowing in the evaluation of expressions Let's take the code int a, b, c;... if ((a + b) > C) If we add the values of a and b and the sum exceeds the maximum value of an int, will the integrity of the comparison be compromised? I was thinking that there might be an implicit up cast or overflow bit check and that will be factored into the evaluation of this expression.
TITLE: C: Implicit casting and integer overflowing in the evaluation of expressions QUESTION: Let's take the code int a, b, c;... if ((a + b) > C) If we add the values of a and b and the sum exceeds the maximum value of an int, will the integrity of the comparison be compromised? I was thinking that there might be an implicit up cast or overflow bit check and that will be factored into the evaluation of this expression. ANSWER: C will do no such thing. It will silently overflow and lead to a possibly incorrect comparison. You can up-cast yourself, but it will not be done automatically.
[ "c" ]
2
7
1,701
5
0
2008-09-08T19:57:12.613000
2008-09-08T19:58:23.063000
50,528
50,729
Font-size independent UI: everything broke when I switched to 120 DPI?
So I was reading those Windows Vista UI guidelines someone linked to in another question, and they mentioned that you should be able to survive a switch to 120 DPI. Well, I fire up my handy VM with my app installed, and what do we get... AAAAGH!!! MASSIVE UI FAIL! Everything's all jumbled: some containers aren't big enough for their text; some controls that were positioned "next to each other" are now all squished together/spread apart; some buttons aren't tall enough; my ListView columns aren't wide enough... eeek. It sounds like a completely different approach is in order. My previous one was basically using the VS2008 Windows Forms designer to create, I guess, a pixel-based layout. I can see that if I were to stick with Windows Forms, FlowLayoutPanel s would be helpful, although I've found them rather inflexible in the past. They also don't solve the problem where the containers (e.g. the form itself) aren't big enough; presumably there's a way to do that? Maybe that AutoSize property? This might also be a sign that it's time to jump ship to WPF; I'm under the impression that it's specifically designed for this kind of thing. The basic issue seems to come down to these: If I were to stick with Windows Forms, what are all the tricks to achieving a font-size-independent layout that can survive the user setting his fonts large, or setting the display to 120 DPI? Does WPF have significant advantages here, and if so, can you try to convince me that it's worth the switch? Are there any general "best-practices" for font-size-independent layouts, either in the.NET stack or in general?
Learn how the Anchor and Dock properties work on your controls, leave anything that can AutoSize itself alone, and use a TableLayoutPanel when you can. If you do these three things, you'll get a lot of the WPF design experience in Windows Forms. A well-designed TableLayoutPanel will do its best to size the controls so that they fit the form properly. Combined with AutoSize controls, docking, and the AutoScaleMode mentioned by Soeren Kuklau you should be able to make something that scales well. If not, your form might just have too many controls on it; consider splitting it into tab pages, floating toolboxes, or some other space. In WPF it's a lot easier because the concept of auto-sizing controls is built-in; in most cases if you are placing a WPF element by using a coordinate pair you are doing it wrong. Still, you can't change the fact that at lower resolutions it doesn't take much 120 dpi text to fill up the screen. Sometimes the problem is not your layout, but an attempt to put too much into a small space.
Font-size independent UI: everything broke when I switched to 120 DPI? So I was reading those Windows Vista UI guidelines someone linked to in another question, and they mentioned that you should be able to survive a switch to 120 DPI. Well, I fire up my handy VM with my app installed, and what do we get... AAAAGH!!! MASSIVE UI FAIL! Everything's all jumbled: some containers aren't big enough for their text; some controls that were positioned "next to each other" are now all squished together/spread apart; some buttons aren't tall enough; my ListView columns aren't wide enough... eeek. It sounds like a completely different approach is in order. My previous one was basically using the VS2008 Windows Forms designer to create, I guess, a pixel-based layout. I can see that if I were to stick with Windows Forms, FlowLayoutPanel s would be helpful, although I've found them rather inflexible in the past. They also don't solve the problem where the containers (e.g. the form itself) aren't big enough; presumably there's a way to do that? Maybe that AutoSize property? This might also be a sign that it's time to jump ship to WPF; I'm under the impression that it's specifically designed for this kind of thing. The basic issue seems to come down to these: If I were to stick with Windows Forms, what are all the tricks to achieving a font-size-independent layout that can survive the user setting his fonts large, or setting the display to 120 DPI? Does WPF have significant advantages here, and if so, can you try to convince me that it's worth the switch? Are there any general "best-practices" for font-size-independent layouts, either in the.NET stack or in general?
TITLE: Font-size independent UI: everything broke when I switched to 120 DPI? QUESTION: So I was reading those Windows Vista UI guidelines someone linked to in another question, and they mentioned that you should be able to survive a switch to 120 DPI. Well, I fire up my handy VM with my app installed, and what do we get... AAAAGH!!! MASSIVE UI FAIL! Everything's all jumbled: some containers aren't big enough for their text; some controls that were positioned "next to each other" are now all squished together/spread apart; some buttons aren't tall enough; my ListView columns aren't wide enough... eeek. It sounds like a completely different approach is in order. My previous one was basically using the VS2008 Windows Forms designer to create, I guess, a pixel-based layout. I can see that if I were to stick with Windows Forms, FlowLayoutPanel s would be helpful, although I've found them rather inflexible in the past. They also don't solve the problem where the containers (e.g. the form itself) aren't big enough; presumably there's a way to do that? Maybe that AutoSize property? This might also be a sign that it's time to jump ship to WPF; I'm under the impression that it's specifically designed for this kind of thing. The basic issue seems to come down to these: If I were to stick with Windows Forms, what are all the tricks to achieving a font-size-independent layout that can survive the user setting his fonts large, or setting the display to 120 DPI? Does WPF have significant advantages here, and if so, can you try to convince me that it's worth the switch? Are there any general "best-practices" for font-size-independent layouts, either in the.NET stack or in general? ANSWER: Learn how the Anchor and Dock properties work on your controls, leave anything that can AutoSize itself alone, and use a TableLayoutPanel when you can. If you do these three things, you'll get a lot of the WPF design experience in Windows Forms. A well-designed TableLayoutPanel will do its best to size the controls so that they fit the form properly. Combined with AutoSize controls, docking, and the AutoScaleMode mentioned by Soeren Kuklau you should be able to make something that scales well. If not, your form might just have too many controls on it; consider splitting it into tab pages, floating toolboxes, or some other space. In WPF it's a lot easier because the concept of auto-sizing controls is built-in; in most cases if you are placing a WPF element by using a coordinate pair you are doing it wrong. Still, you can't change the fact that at lower resolutions it doesn't take much 120 dpi text to fill up the screen. Sometimes the problem is not your layout, but an attempt to put too much into a small space.
[ ".net", "wpf", "winforms", "user-interface", "fonts" ]
11
11
4,782
3
0
2008-09-08T19:58:22.533000
2008-09-08T21:25:57.610000
50,532
50,543
How do I format a number in Java?
How do I format a number in Java? What are the "Best Practices"? Will I need to round a number before I format it? 32.302342342342343 => 32.30.7323 => 0.73 etc.
From this thread, there are different ways to do this: double r = 5.1234; System.out.println(r); // r is 5.1234 int decimalPlaces = 2; BigDecimal bd = new BigDecimal(r); // setScale is immutable bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP); r = bd.doubleValue(); System.out.println(r); // r is 5.12 f = (float) (Math.round(n*100.0f)/100.0f); DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" ); double dd = 100.2397; double dd2dec = new Double(df2.format(dd)).doubleValue(); // The value of dd2dec will be 100.24 The DecimalFormat() seems to be the most dynamic way to do it, and it is also very easy to understand when reading others code.
How do I format a number in Java? How do I format a number in Java? What are the "Best Practices"? Will I need to round a number before I format it? 32.302342342342343 => 32.30.7323 => 0.73 etc.
TITLE: How do I format a number in Java? QUESTION: How do I format a number in Java? What are the "Best Practices"? Will I need to round a number before I format it? 32.302342342342343 => 32.30.7323 => 0.73 etc. ANSWER: From this thread, there are different ways to do this: double r = 5.1234; System.out.println(r); // r is 5.1234 int decimalPlaces = 2; BigDecimal bd = new BigDecimal(r); // setScale is immutable bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP); r = bd.doubleValue(); System.out.println(r); // r is 5.12 f = (float) (Math.round(n*100.0f)/100.0f); DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" ); double dd = 100.2397; double dd2dec = new Double(df2.format(dd)).doubleValue(); // The value of dd2dec will be 100.24 The DecimalFormat() seems to be the most dynamic way to do it, and it is also very easy to understand when reading others code.
[ "java", "number-formatting" ]
121
127
324,365
9
0
2008-09-08T19:59:45.180000
2008-09-08T20:04:03.673000
50,539
51,249
Multiline ddl Custom Control
One of the guys I work with needs a custom control that would work like a multiline ddl since such a thing does not exist as far as we have been able to discover does anyone have any ideas or have created such a thing before we have a couple ideas but they involve to much database usage We prefer that it be FREE!!!
We use a custom modified version of suckerfish at work. DB performance isn't an issue for us because we cache the control. The control renders out nested UL / LI s either for all nodes in the web.sitemap or for a certain set of pages pulled from the DB. We then use jQuery to do all the cool javascript stuff. Because it uses such basic HTML, it's pretty easy to have multi-line or wrapped long items once you style it with CSS.
Multiline ddl Custom Control One of the guys I work with needs a custom control that would work like a multiline ddl since such a thing does not exist as far as we have been able to discover does anyone have any ideas or have created such a thing before we have a couple ideas but they involve to much database usage We prefer that it be FREE!!!
TITLE: Multiline ddl Custom Control QUESTION: One of the guys I work with needs a custom control that would work like a multiline ddl since such a thing does not exist as far as we have been able to discover does anyone have any ideas or have created such a thing before we have a couple ideas but they involve to much database usage We prefer that it be FREE!!! ANSWER: We use a custom modified version of suckerfish at work. DB performance isn't an issue for us because we cache the control. The control renders out nested UL / LI s either for all nodes in the web.sitemap or for a certain set of pages pulled from the DB. We then use jQuery to do all the cool javascript stuff. Because it uses such basic HTML, it's pretty easy to have multi-line or wrapped long items once you style it with CSS.
[ "c#", "asp.net", "custom-controls" ]
0
0
570
3
0
2008-09-08T20:02:26.093000
2008-09-09T05:15:08.933000
50,558
50,581
How do you initialize a 2 dimensional array when you do not know the size
I have a two dimensional array that I need to load data into. I know the width of the data (22 values) but I do not know the height (estimated around 4000 records, but variable). I have it declared as follows: float[,] _calibrationSet;.... int calibrationRow = 0; While (recordsToRead) { for (int i = 0; i < SensorCount; i++) { _calibrationSet[calibrationRow, i] = calibrationArrayView.ReadFloat(); } calibrationRow++; } This causes a NullReferenceException, so when I try to initialize it like this: _calibrationSet = new float[,]; I get an "Array creation must have array size or array initializer." Thank you, Keith
You can't use an array. Or rather, you would need to pick a size, and if you ended up needing more then you would have to allocate a new, larger, array, copy the data from the old one into the new one, and continue on as before (until you exceed the size of the new one...) Generally, you would go with one of the collection classes - ArrayList, List<>, LinkedList<>, etc. - which one depends a lot on what you're looking for; List will give you the closest thing to what i described initially, while LinkedList<> will avoid the problem of frequent re-allocations (at the cost of slower access and greater memory usage). Example: List _calibrationSet = new List (); //... while (recordsToRead) { float[] record = new float[SensorCount]; for (int i = 0; i < SensorCount; i++) { record[i] = calibrationArrayView.ReadFloat(); } _calibrationSet.Add(record); } // access later: _calibrationSet[record][sensor] Oh, and it's worth noting (as Grauenwolf did), that what i'm doing here doesn't give you the same memory structure as a single, multi-dimensional array would - under the hood, it's an array of references to other arrays that actually hold the data. This speeds up building the array a good deal by making reallocation cheaper, but can have an impact on access speed (and, of course, memory usage). Whether this is an issue for you depends a lot on what you'll be doing with the data after it's loaded... and whether there are two hundred records or two million records.
How do you initialize a 2 dimensional array when you do not know the size I have a two dimensional array that I need to load data into. I know the width of the data (22 values) but I do not know the height (estimated around 4000 records, but variable). I have it declared as follows: float[,] _calibrationSet;.... int calibrationRow = 0; While (recordsToRead) { for (int i = 0; i < SensorCount; i++) { _calibrationSet[calibrationRow, i] = calibrationArrayView.ReadFloat(); } calibrationRow++; } This causes a NullReferenceException, so when I try to initialize it like this: _calibrationSet = new float[,]; I get an "Array creation must have array size or array initializer." Thank you, Keith
TITLE: How do you initialize a 2 dimensional array when you do not know the size QUESTION: I have a two dimensional array that I need to load data into. I know the width of the data (22 values) but I do not know the height (estimated around 4000 records, but variable). I have it declared as follows: float[,] _calibrationSet;.... int calibrationRow = 0; While (recordsToRead) { for (int i = 0; i < SensorCount; i++) { _calibrationSet[calibrationRow, i] = calibrationArrayView.ReadFloat(); } calibrationRow++; } This causes a NullReferenceException, so when I try to initialize it like this: _calibrationSet = new float[,]; I get an "Array creation must have array size or array initializer." Thank you, Keith ANSWER: You can't use an array. Or rather, you would need to pick a size, and if you ended up needing more then you would have to allocate a new, larger, array, copy the data from the old one into the new one, and continue on as before (until you exceed the size of the new one...) Generally, you would go with one of the collection classes - ArrayList, List<>, LinkedList<>, etc. - which one depends a lot on what you're looking for; List will give you the closest thing to what i described initially, while LinkedList<> will avoid the problem of frequent re-allocations (at the cost of slower access and greater memory usage). Example: List _calibrationSet = new List (); //... while (recordsToRead) { float[] record = new float[SensorCount]; for (int i = 0; i < SensorCount; i++) { record[i] = calibrationArrayView.ReadFloat(); } _calibrationSet.Add(record); } // access later: _calibrationSet[record][sensor] Oh, and it's worth noting (as Grauenwolf did), that what i'm doing here doesn't give you the same memory structure as a single, multi-dimensional array would - under the hood, it's an array of references to other arrays that actually hold the data. This speeds up building the array a good deal by making reallocation cheaper, but can have an impact on access speed (and, of course, memory usage). Whether this is an issue for you depends a lot on what you'll be doing with the data after it's loaded... and whether there are two hundred records or two million records.
[ "c#", "array-initialize" ]
8
8
15,955
6
0
2008-09-08T20:09:45.623000
2008-09-08T20:23:58.133000
50,561
50,573
Programmatically determine which Java thread holds a lock
Is it possible at runtime to programmatically check the name of the Thread that is holding the lock of a given object?
You can only tell whether the current thread holds a normal lock ( Thread.holdsLock(Object) ). You can't get a reference to the thread that has the lock without native code. However, if you're doing anything complicated with threading, you probably want to familiarize yourself with the java.util.concurrent packages. The ReentrantLock does allow you to get its owner (but its a protected method, so you'd have to extend this). Depending on your application, it may well be that by using the concurrency packages, you'll find that you don't need to get the lock's owner after all. There are non-programmatic methods to find the lock owners, such as signaling the JVM to issue a thread dump to stderr, that are useful to determine the cause of deadlocks.
Programmatically determine which Java thread holds a lock Is it possible at runtime to programmatically check the name of the Thread that is holding the lock of a given object?
TITLE: Programmatically determine which Java thread holds a lock QUESTION: Is it possible at runtime to programmatically check the name of the Thread that is holding the lock of a given object? ANSWER: You can only tell whether the current thread holds a normal lock ( Thread.holdsLock(Object) ). You can't get a reference to the thread that has the lock without native code. However, if you're doing anything complicated with threading, you probably want to familiarize yourself with the java.util.concurrent packages. The ReentrantLock does allow you to get its owner (but its a protected method, so you'd have to extend this). Depending on your application, it may well be that by using the concurrency packages, you'll find that you don't need to get the lock's owner after all. There are non-programmatic methods to find the lock owners, such as signaling the JVM to issue a thread dump to stderr, that are useful to determine the cause of deadlocks.
[ "java", "multithreading", "concurrency" ]
46
31
27,166
9
0
2008-09-08T20:10:55.670000
2008-09-08T20:21:07.780000
50,565
50,590
Context Menu Resets ComboBox's SelectedIndex
I have a ContextMenu that is displayed after a user right clicks on a ComboBox. When the user selects an item in the context menu, a form is brought up using the ShowDialog() method. If frmOptions.ShowDialog() = Windows.Forms.DialogResult.Cancel Then LoadComboBoxes() End If When that form is closed, I refresh all the data in the ComboBoxes on the parent form. However, when this happens the ComboBox that opened the ContextMenu is reset to have a selected index of -1 but the other selected indexes of the other ComboBoxes remain the same. How do I prevent the ComboBox that opened the context menu from being reset?
One way to handle this would be to use the context menu's Popup event to grab the selected index of the combobox launching the menu. When the dialog form closes reset the selected index.
Context Menu Resets ComboBox's SelectedIndex I have a ContextMenu that is displayed after a user right clicks on a ComboBox. When the user selects an item in the context menu, a form is brought up using the ShowDialog() method. If frmOptions.ShowDialog() = Windows.Forms.DialogResult.Cancel Then LoadComboBoxes() End If When that form is closed, I refresh all the data in the ComboBoxes on the parent form. However, when this happens the ComboBox that opened the ContextMenu is reset to have a selected index of -1 but the other selected indexes of the other ComboBoxes remain the same. How do I prevent the ComboBox that opened the context menu from being reset?
TITLE: Context Menu Resets ComboBox's SelectedIndex QUESTION: I have a ContextMenu that is displayed after a user right clicks on a ComboBox. When the user selects an item in the context menu, a form is brought up using the ShowDialog() method. If frmOptions.ShowDialog() = Windows.Forms.DialogResult.Cancel Then LoadComboBoxes() End If When that form is closed, I refresh all the data in the ComboBoxes on the parent form. However, when this happens the ComboBox that opened the ContextMenu is reset to have a selected index of -1 but the other selected indexes of the other ComboBoxes remain the same. How do I prevent the ComboBox that opened the context menu from being reset? ANSWER: One way to handle this would be to use the context menu's Popup event to grab the selected index of the combobox launching the menu. When the dialog form closes reset the selected index.
[ ".net", "winforms", "combobox", "contextmenu", "selectedindex" ]
1
1
1,218
2
0
2008-09-08T20:15:09.840000
2008-09-08T20:27:30.137000