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
41,449
41,451
I get a "An attempt was made to load a program with an incorrect format" error on a SQL Server replication project
The exact error is as follows Could not load file or assembly 'Microsoft.SqlServer.Replication, Version=9.0.242.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. An attempt was made to load a program with an incorrect format. I've recently started working on this project again after a two month move to another project. It worked perfectly before, and I've double checked all the references.
I've found the solution. I've recently upgraded my machine to Windows 2008 Server 64-bit. The SqlServer.Replication namespace was written for 32-bit platforms. All I needed to do to get it running again was to set the Target Platform in the Project Build Properties to X86.
I get a "An attempt was made to load a program with an incorrect format" error on a SQL Server replication project The exact error is as follows Could not load file or assembly 'Microsoft.SqlServer.Replication, Version=9.0.242.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. An attempt was made to load a program with an incorrect format. I've recently started working on this project again after a two month move to another project. It worked perfectly before, and I've double checked all the references.
TITLE: I get a "An attempt was made to load a program with an incorrect format" error on a SQL Server replication project QUESTION: The exact error is as follows Could not load file or assembly 'Microsoft.SqlServer.Replication, Version=9.0.242.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. An attempt was made to load a program with an incorrect format. I've recently started working on this project again after a two month move to another project. It worked perfectly before, and I've double checked all the references. ANSWER: I've found the solution. I've recently upgraded my machine to Windows 2008 Server 64-bit. The SqlServer.Replication namespace was written for 32-bit platforms. All I needed to do to get it running again was to set the Target Platform in the Project Build Properties to X86.
[ "c#", "sql-server", "replication" ]
324
120
277,406
12
0
2008-09-03T10:55:53.113000
2008-09-03T10:57:53.560000
41,460
44,701
What are the differences between GPL v2 and GPL v3 licenses?
In simple terms, what are the reasons for, and what are the differences between the GPL v2 and GPL v3 open source licenses? Explanations and references to legal terms and further descriptions would be appreciated.
The page linked to in another answer is a good source, but a lot to read. Here is a short list of some the major differences: internationalization: they used new terminology, rather than using language tied to US legal concepts patents: they specifically address patents (including the Microsoft/Novell issue noted in another answer) “Tivo-ization”: they address the restrictions (like Tivo’s) in consumer products that take away, though hardware, the ability to modify the software DRM: they address digital rights management (which they call digital restrictions management) compatibility: they addressed compatibility with some other open source licenses termination: they addressed specifically what happens if the license is violated and the cure of violations I agree with the comment about consulting a lawyer (one who knows about software license issues, though). In doing these things (and more), they more than doubled the length of the GPL. GPL 3 is many things, and one of them is that it is a very complex, technical legal document.
What are the differences between GPL v2 and GPL v3 licenses? In simple terms, what are the reasons for, and what are the differences between the GPL v2 and GPL v3 open source licenses? Explanations and references to legal terms and further descriptions would be appreciated.
TITLE: What are the differences between GPL v2 and GPL v3 licenses? QUESTION: In simple terms, what are the reasons for, and what are the differences between the GPL v2 and GPL v3 open source licenses? Explanations and references to legal terms and further descriptions would be appreciated. ANSWER: The page linked to in another answer is a good source, but a lot to read. Here is a short list of some the major differences: internationalization: they used new terminology, rather than using language tied to US legal concepts patents: they specifically address patents (including the Microsoft/Novell issue noted in another answer) “Tivo-ization”: they address the restrictions (like Tivo’s) in consumer products that take away, though hardware, the ability to modify the software DRM: they address digital rights management (which they call digital restrictions management) compatibility: they addressed compatibility with some other open source licenses termination: they addressed specifically what happens if the license is violated and the cure of violations I agree with the comment about consulting a lawyer (one who knows about software license issues, though). In doing these things (and more), they more than doubled the length of the GPL. GPL 3 is many things, and one of them is that it is a very complex, technical legal document.
[ "licensing" ]
221
127
95,634
3
0
2008-09-03T11:05:11.203000
2008-09-04T20:27:35.820000
41,469
151,593
How to fetch a Book Title from an ISBN number?
I am planning on creating a small website for my personal book collection. To automate the process a little bit, I would like to create the following functionality: The website will ask me for the ISBN number of the book and will then automatically fetch the title and add it to my database. Although I am mainly interested in doing this in php, I also have some Java implementation ideas for this. I believe it could also help if the answer was as much language-agnostic as possible.
This is the LibraryThing founder. We have nothing to offer here, so I hope my comments will not seem self-serving. First, the comment about Amazon, ASINs and ISBN numbers is wrong in a number of ways. In almost every circumstance where a book has an ISBN, the ASIN and the ISBN are the same. ISBNs are not now 13 digits. Rather, ISBNs can be either 10 or 13. Ten-digit ISBNs can be expressed as 13-digit ones starting with 978, which means every ISBN currently in existence has both a 10- and a 13-digit form. There are all sorts of libraries available for converting between ISBN10 and ISBN13. Basically, you add 978 to the front and recalculate the checksum digit at the end. ISBN13 was invented because publishers were running out of ISBNs. In the near future, when 979-based ISBN13s start being used, they will not have an ISBN10 equivalent. To my knowledge, there are no published books with 979-based ISBNs, but they are coming soon. Anyway, the long and short of it is that Amazon uses the ISBN10 form for all 978 ISBN10s. In any case, whether or not Amazon uses ten or thirteen-digit ASINs, you can search Amazon by either just fine. Personally, I wouldn't put ISBN DB at the top of your list. ISBN DB mines from a number of sources, but it's not as comprehensive as Amazon or Google. Rather, I'd look into Amazon—including the various international Amazons—and then the new Google Book Data API and, after that, the OpenLibrary API. For non-English books, there are other options, like Ozone for Russian books. If you care about the highest-quality data, or if you have any books published before about 1970, you will want to look into data from libraries, available by Z39.50 protocol and usually in MARC format, or, with a few libraries in Dublin Core, using the SRU/SRW protocol. MARC format is, to a modern programmer, pretty strange stuff. But, once you get it, it's also better data and includes useful fields like the LCCN, DDC, LCC, and LCSH. LibraryThing runs off a homemade Python library that queries some 680 libraries and converts the many flavors of MARC into Amazon-compatible XML, with extras. We are currently reluctant to release the code, but maybe releasing a service soon.
How to fetch a Book Title from an ISBN number? I am planning on creating a small website for my personal book collection. To automate the process a little bit, I would like to create the following functionality: The website will ask me for the ISBN number of the book and will then automatically fetch the title and add it to my database. Although I am mainly interested in doing this in php, I also have some Java implementation ideas for this. I believe it could also help if the answer was as much language-agnostic as possible.
TITLE: How to fetch a Book Title from an ISBN number? QUESTION: I am planning on creating a small website for my personal book collection. To automate the process a little bit, I would like to create the following functionality: The website will ask me for the ISBN number of the book and will then automatically fetch the title and add it to my database. Although I am mainly interested in doing this in php, I also have some Java implementation ideas for this. I believe it could also help if the answer was as much language-agnostic as possible. ANSWER: This is the LibraryThing founder. We have nothing to offer here, so I hope my comments will not seem self-serving. First, the comment about Amazon, ASINs and ISBN numbers is wrong in a number of ways. In almost every circumstance where a book has an ISBN, the ASIN and the ISBN are the same. ISBNs are not now 13 digits. Rather, ISBNs can be either 10 or 13. Ten-digit ISBNs can be expressed as 13-digit ones starting with 978, which means every ISBN currently in existence has both a 10- and a 13-digit form. There are all sorts of libraries available for converting between ISBN10 and ISBN13. Basically, you add 978 to the front and recalculate the checksum digit at the end. ISBN13 was invented because publishers were running out of ISBNs. In the near future, when 979-based ISBN13s start being used, they will not have an ISBN10 equivalent. To my knowledge, there are no published books with 979-based ISBNs, but they are coming soon. Anyway, the long and short of it is that Amazon uses the ISBN10 form for all 978 ISBN10s. In any case, whether or not Amazon uses ten or thirteen-digit ASINs, you can search Amazon by either just fine. Personally, I wouldn't put ISBN DB at the top of your list. ISBN DB mines from a number of sources, but it's not as comprehensive as Amazon or Google. Rather, I'd look into Amazon—including the various international Amazons—and then the new Google Book Data API and, after that, the OpenLibrary API. For non-English books, there are other options, like Ozone for Russian books. If you care about the highest-quality data, or if you have any books published before about 1970, you will want to look into data from libraries, available by Z39.50 protocol and usually in MARC format, or, with a few libraries in Dublin Core, using the SRU/SRW protocol. MARC format is, to a modern programmer, pretty strange stuff. But, once you get it, it's also better data and includes useful fields like the LCCN, DDC, LCC, and LCSH. LibraryThing runs off a homemade Python library that queries some 680 libraries and converts the many flavors of MARC into Amazon-compatible XML, with extras. We are currently reluctant to release the code, but maybe releasing a service soon.
[ "php", "language-agnostic" ]
35
44
48,734
10
0
2008-09-03T11:20:26.813000
2008-09-30T03:00:03.087000
41,479
41,505
Use of var keyword in C#
After discussion with colleagues regarding the use of the 'var' keyword in C# 3 I wondered what people's opinions were on the appropriate uses of type inference via var? For example I rather lazily used var in questionable circumstances, e.g.:- foreach(var item in someList) { //... } // Type of 'item' not clear. var something = someObject.SomeProperty; // Type of 'something' not clear. var something = someMethod(); // Type of 'something' not clear. More legitimate uses of var are as follows:- var l = new List (); // Obvious what l will be. var s = new SomeClass(); // Obvious what s will be. Interestingly LINQ seems to be a bit of a grey area, e.g.:- var results = from r in dataContext.SomeTable select r; // Not *entirely clear* what results will be here. It's clear what results will be in that it will be a type which implements IEnumerable, however it isn't entirely obvious in the same way a var declaring a new object is. It's even worse when it comes to LINQ to objects, e.g.:- var results = from item in someList where item!= 3 select item; This is no better than the equivilent foreach(var item in someList) { //... } equivilent. There is a real concern about type safety here - for example if we were to place the results of that query into an overloaded method that accepted IEnumerable and IEnumerable the caller might inadvertently pass in the wrong type. var does maintain strong typing but the question is really whether it's dangerous for the type to not be immediately apparent on definition, something which is magnified when overloads mean compiler errors might not be issued when you unintentionally pass the wrong type to a method.
I still think var can make code more readable in some cases. If I have a Customer class with an Orders property, and I want to assign that to a variable, I will just do this: var orders = cust.Orders; I don't care if Customer.Orders is IEnumerable, ObservableCollection or BindingList - all I want is to keep that list in memory to iterate over it or get its count or something later on. Contrast the above declaration with: ObservableCollection orders = cust.Orders; To me, the type name is just noise. And if I go back and decide to change the type of the Customer.Orders down the track (say from ObservableCollection to IList ) then I need to change that declaration too - something I wouldn't have to do if I'd used var in the first place.
Use of var keyword in C# After discussion with colleagues regarding the use of the 'var' keyword in C# 3 I wondered what people's opinions were on the appropriate uses of type inference via var? For example I rather lazily used var in questionable circumstances, e.g.:- foreach(var item in someList) { //... } // Type of 'item' not clear. var something = someObject.SomeProperty; // Type of 'something' not clear. var something = someMethod(); // Type of 'something' not clear. More legitimate uses of var are as follows:- var l = new List (); // Obvious what l will be. var s = new SomeClass(); // Obvious what s will be. Interestingly LINQ seems to be a bit of a grey area, e.g.:- var results = from r in dataContext.SomeTable select r; // Not *entirely clear* what results will be here. It's clear what results will be in that it will be a type which implements IEnumerable, however it isn't entirely obvious in the same way a var declaring a new object is. It's even worse when it comes to LINQ to objects, e.g.:- var results = from item in someList where item!= 3 select item; This is no better than the equivilent foreach(var item in someList) { //... } equivilent. There is a real concern about type safety here - for example if we were to place the results of that query into an overloaded method that accepted IEnumerable and IEnumerable the caller might inadvertently pass in the wrong type. var does maintain strong typing but the question is really whether it's dangerous for the type to not be immediately apparent on definition, something which is magnified when overloads mean compiler errors might not be issued when you unintentionally pass the wrong type to a method.
TITLE: Use of var keyword in C# QUESTION: After discussion with colleagues regarding the use of the 'var' keyword in C# 3 I wondered what people's opinions were on the appropriate uses of type inference via var? For example I rather lazily used var in questionable circumstances, e.g.:- foreach(var item in someList) { //... } // Type of 'item' not clear. var something = someObject.SomeProperty; // Type of 'something' not clear. var something = someMethod(); // Type of 'something' not clear. More legitimate uses of var are as follows:- var l = new List (); // Obvious what l will be. var s = new SomeClass(); // Obvious what s will be. Interestingly LINQ seems to be a bit of a grey area, e.g.:- var results = from r in dataContext.SomeTable select r; // Not *entirely clear* what results will be here. It's clear what results will be in that it will be a type which implements IEnumerable, however it isn't entirely obvious in the same way a var declaring a new object is. It's even worse when it comes to LINQ to objects, e.g.:- var results = from item in someList where item!= 3 select item; This is no better than the equivilent foreach(var item in someList) { //... } equivilent. There is a real concern about type safety here - for example if we were to place the results of that query into an overloaded method that accepted IEnumerable and IEnumerable the caller might inadvertently pass in the wrong type. var does maintain strong typing but the question is really whether it's dangerous for the type to not be immediately apparent on definition, something which is magnified when overloads mean compiler errors might not be issued when you unintentionally pass the wrong type to a method. ANSWER: I still think var can make code more readable in some cases. If I have a Customer class with an Orders property, and I want to assign that to a variable, I will just do this: var orders = cust.Orders; I don't care if Customer.Orders is IEnumerable, ObservableCollection or BindingList - all I want is to keep that list in memory to iterate over it or get its count or something later on. Contrast the above declaration with: ObservableCollection orders = cust.Orders; To me, the type name is just noise. And if I go back and decide to change the type of the Customer.Orders down the track (say from ObservableCollection to IList ) then I need to change that declaration too - something I wouldn't have to do if I'd used var in the first place.
[ "c#", "type-inference", "var" ]
405
292
148,799
86
0
2008-09-03T11:29:57.650000
2008-09-03T11:53:07.377000
41,492
2,478,693
ActiveX control default property discovery
Is it possible to determine which property of an ActiveX control is the default property? For example, what is the default property of the VB6 control CommandButton and how would I found out any other controls default! /EDIT: Without having source to the object itself
Use OLE/Com Object Viewer, which is distributed with Microsoft Visual Studio. Go to type libraries and find the library the control is housed in, for example CommandButton is stored in Microsoft Forms 2.0 Object Library. Right click the library and select view. Find the coclass representing the control and select it: As can be seen, the default interface for CommandButton is ICommandButton, when you inspect ICommandButton look for a property that has a dispid of 0. The IDL for the dispid 0 property of CommandButton is: [id(00000000), propput, bindable, displaybind, hidden, helpcontext(0x001e8d04)] void Value([in] VARIANT_BOOL rhs); [id(00000000), propget, bindable, displaybind, hidden, helpcontext(0x001e8d04)] VARIANT_BOOL Value(); Showing you the default property.
ActiveX control default property discovery Is it possible to determine which property of an ActiveX control is the default property? For example, what is the default property of the VB6 control CommandButton and how would I found out any other controls default! /EDIT: Without having source to the object itself
TITLE: ActiveX control default property discovery QUESTION: Is it possible to determine which property of an ActiveX control is the default property? For example, what is the default property of the VB6 control CommandButton and how would I found out any other controls default! /EDIT: Without having source to the object itself ANSWER: Use OLE/Com Object Viewer, which is distributed with Microsoft Visual Studio. Go to type libraries and find the library the control is housed in, for example CommandButton is stored in Microsoft Forms 2.0 Object Library. Right click the library and select view. Find the coclass representing the control and select it: As can be seen, the default interface for CommandButton is ICommandButton, when you inspect ICommandButton look for a property that has a dispid of 0. The IDL for the dispid 0 property of CommandButton is: [id(00000000), propput, bindable, displaybind, hidden, helpcontext(0x001e8d04)] void Value([in] VARIANT_BOOL rhs); [id(00000000), propget, bindable, displaybind, hidden, helpcontext(0x001e8d04)] VARIANT_BOOL Value(); Showing you the default property.
[ "vb6", "activex" ]
1
1
861
4
0
2008-09-03T11:40:15.660000
2010-03-19T15:55:49.423000
41,499
42,674
Java serialization with static initialization
In Java, static and transient fields are not serialized. However, I found out that initialization of static fields causes the generated serialVersionUID to be changed. For example, static int MYINT = 3; causes the serialVersionUID to change. In this example, it makes sense because different versions of the class would get different initial values. Why does any initialization change the serialVersionUID? For example, static String MYSTRING = System.getProperty("foo"); also causes the serialVersionUID to change. To be specific, my question is why does initialization with a method cause the serialVersionUID to change. The problem I hit is that I added a new static field that was initialized with a system property value (getProperty). That change caused a serialization exception on a remote call.
You can find some information about that in the bug 4365406 and in the algorithm for computing serialVersionUID. Basically, when changing the initialization of your static member with System.getProperty(), the compiler introduces a new static property in your class referencing the System class (I assume that the System class was previously unreferenced in your class), and since this property introduced by the compiler is not private, it takes part in the serialVersionUID computation. Morality: always use explicit serialVersionUID, you'll save some CPU cycles and some headaches:)
Java serialization with static initialization In Java, static and transient fields are not serialized. However, I found out that initialization of static fields causes the generated serialVersionUID to be changed. For example, static int MYINT = 3; causes the serialVersionUID to change. In this example, it makes sense because different versions of the class would get different initial values. Why does any initialization change the serialVersionUID? For example, static String MYSTRING = System.getProperty("foo"); also causes the serialVersionUID to change. To be specific, my question is why does initialization with a method cause the serialVersionUID to change. The problem I hit is that I added a new static field that was initialized with a system property value (getProperty). That change caused a serialization exception on a remote call.
TITLE: Java serialization with static initialization QUESTION: In Java, static and transient fields are not serialized. However, I found out that initialization of static fields causes the generated serialVersionUID to be changed. For example, static int MYINT = 3; causes the serialVersionUID to change. In this example, it makes sense because different versions of the class would get different initial values. Why does any initialization change the serialVersionUID? For example, static String MYSTRING = System.getProperty("foo"); also causes the serialVersionUID to change. To be specific, my question is why does initialization with a method cause the serialVersionUID to change. The problem I hit is that I added a new static field that was initialized with a system property value (getProperty). That change caused a serialization exception on a remote call. ANSWER: You can find some information about that in the bug 4365406 and in the algorithm for computing serialVersionUID. Basically, when changing the initialization of your static member with System.getProperty(), the compiler introduces a new static property in your class referencing the System class (I assume that the System class was previously unreferenced in your class), and since this property introduced by the compiler is not private, it takes part in the serialVersionUID computation. Morality: always use explicit serialVersionUID, you'll save some CPU cycles and some headaches:)
[ "java", "serialization" ]
8
6
3,844
4
0
2008-09-03T11:46:34.630000
2008-09-03T21:46:04.563000
41,504
5,519,523
Timezone lookup from latitude longitude
Is there any library (or even better, web service) available which can convert from a latitude/longitude into a time zone?
I looked fairly deeply into this question for a project I am working on. GeoNames.org and EarthTools.com are both good options for many situations but with the following serious flaws: GeoNames.org finds the time zone by searching for the nearest point in their database that contains a time zone field. This often leads to the wrong result near borders. It is also painfully slow, leading to query times on the order of a couple seconds per request. It also doesn't return a valid time zone if there is no item in their database near the query point. GeoNames also restricts the number of queries that can be made per day, making bulk operations difficult. EarthTools.org uses a map and is able to return queries quickly, but it doesn't take into account daylight savings time for most locations, and it returns a raw offset rather than a time zone ID (i.e., they return "GMT-7" instead of "America/Chicago"). Also, I just looked at their page while preparing this post and Google Chrome warned about malware on their site. That is new to me and it may change, but is obviously a cause for concern. These flaws meant that these existing tools were not suitable for my needs so I rolled my own solution and have published it for general use. You can find it here: http://www.askgeo.com/ AskGeo is based on a time zone map of the world, so it returns a valid time zone for every valid latitude and longitude. It returns the standard time zone ID (e.g., "America/Los_Angeles") used on Linux and most other operating systems and programming frameworks. It also returns the current offset, taking full account of daylight savings time. It is extremely easy to use and usage is documented on the main page of the site. The API supports batch queries, so if you need to do a lot of look-ups, please use the batch interface rather than bog down our servers with serial requests. The bulk queries are also much faster, so everybody wins. When we first launched this, we built it on Google App Engine (GAE) and made it free to all users. This was possible because GAE's prices were so low at that time. Since then, our server load has increased substantially and GAE's prices went way up. Both factors combined led us to switch to Amazon Web Services for hosting and to start charging for commercial use, while keeping the service free for non-profit, non-commercial open source projects, and researchers. For commercial users, we provide 1000 free queries to let potential customers evaluate the API to make sure it meets their needs. See the web site for pricing and terms. The underlying library was written in Java and due to popular demand, we also released the library under a commercial license. Full documentation of the library and pricing details are on the web site. I hope this is useful. It certainly was useful for the project I was working on.
Timezone lookup from latitude longitude Is there any library (or even better, web service) available which can convert from a latitude/longitude into a time zone?
TITLE: Timezone lookup from latitude longitude QUESTION: Is there any library (or even better, web service) available which can convert from a latitude/longitude into a time zone? ANSWER: I looked fairly deeply into this question for a project I am working on. GeoNames.org and EarthTools.com are both good options for many situations but with the following serious flaws: GeoNames.org finds the time zone by searching for the nearest point in their database that contains a time zone field. This often leads to the wrong result near borders. It is also painfully slow, leading to query times on the order of a couple seconds per request. It also doesn't return a valid time zone if there is no item in their database near the query point. GeoNames also restricts the number of queries that can be made per day, making bulk operations difficult. EarthTools.org uses a map and is able to return queries quickly, but it doesn't take into account daylight savings time for most locations, and it returns a raw offset rather than a time zone ID (i.e., they return "GMT-7" instead of "America/Chicago"). Also, I just looked at their page while preparing this post and Google Chrome warned about malware on their site. That is new to me and it may change, but is obviously a cause for concern. These flaws meant that these existing tools were not suitable for my needs so I rolled my own solution and have published it for general use. You can find it here: http://www.askgeo.com/ AskGeo is based on a time zone map of the world, so it returns a valid time zone for every valid latitude and longitude. It returns the standard time zone ID (e.g., "America/Los_Angeles") used on Linux and most other operating systems and programming frameworks. It also returns the current offset, taking full account of daylight savings time. It is extremely easy to use and usage is documented on the main page of the site. The API supports batch queries, so if you need to do a lot of look-ups, please use the batch interface rather than bog down our servers with serial requests. The bulk queries are also much faster, so everybody wins. When we first launched this, we built it on Google App Engine (GAE) and made it free to all users. This was possible because GAE's prices were so low at that time. Since then, our server load has increased substantially and GAE's prices went way up. Both factors combined led us to switch to Amazon Web Services for hosting and to start charging for commercial use, while keeping the service free for non-profit, non-commercial open source projects, and researchers. For commercial users, we provide 1000 free queries to let potential customers evaluate the API to make sure it meets their needs. See the web site for pricing and terms. The underlying library was written in Java and due to popular demand, we also released the library under a commercial license. Full documentation of the library and pricing details are on the web site. I hope this is useful. It certainly was useful for the project I was working on.
[ "web-services", "api", "timezone", "geocoding" ]
83
65
98,636
8
0
2008-09-03T11:52:41.807000
2011-04-01T22:26:59.150000
41,525
41,549
Do the vi and emacs implementations for Windows behave like their Unix counterparts?
If not, what are the significant differences? Edit: Daren Thomas asks: which ones? I use gvim on Windows and MacVim on the mac. Seem similar enough to be the same to me... By which ones, I'm guessing that you mean a specific implementation of vi and emacs for Windows. I'm not sure as I thought there were only one or two. I'm looking for the ones that are closest to the Unix counterparts.
I use GNU emacs built for Windows, and have found very few, if any, differences. There's the option to load your.emacs file from _emacs or.emacs (although.emacs works fine on XP and above). You can configure it to use Windows-style or Unix-style line endings by default (which I suppose you could do on a Unix system too...). You may want to tweak such settings as Emacs's startup directory and home directory. To do the former, modify the shortcut that starts emacs. To do the latter, add a HOME environment variable - this will control where your.emacs is loaded from. For more information, check the always-excellent EmacsWiki's MsWindowsInstallation page.
Do the vi and emacs implementations for Windows behave like their Unix counterparts? If not, what are the significant differences? Edit: Daren Thomas asks: which ones? I use gvim on Windows and MacVim on the mac. Seem similar enough to be the same to me... By which ones, I'm guessing that you mean a specific implementation of vi and emacs for Windows. I'm not sure as I thought there were only one or two. I'm looking for the ones that are closest to the Unix counterparts.
TITLE: Do the vi and emacs implementations for Windows behave like their Unix counterparts? QUESTION: If not, what are the significant differences? Edit: Daren Thomas asks: which ones? I use gvim on Windows and MacVim on the mac. Seem similar enough to be the same to me... By which ones, I'm guessing that you mean a specific implementation of vi and emacs for Windows. I'm not sure as I thought there were only one or two. I'm looking for the ones that are closest to the Unix counterparts. ANSWER: I use GNU emacs built for Windows, and have found very few, if any, differences. There's the option to load your.emacs file from _emacs or.emacs (although.emacs works fine on XP and above). You can configure it to use Windows-style or Unix-style line endings by default (which I suppose you could do on a Unix system too...). You may want to tweak such settings as Emacs's startup directory and home directory. To do the former, modify the shortcut that starts emacs. To do the latter, add a HOME environment variable - this will control where your.emacs is loaded from. For more information, check the always-excellent EmacsWiki's MsWindowsInstallation page.
[ "windows", "emacs", "vi" ]
1
2
606
5
0
2008-09-03T12:11:37.503000
2008-09-03T12:24:40.793000
41,547
41,558
Always including the user in the django template context
I am working on a small intranet site for a small company, where user should be able to post. I have imagined a very simple authentication mechanism where people just enter their email address, and gets sent a unique login url, that sets a cookie that will always identify them for future requests. In my template setup, I have base.html, and the other pages extend this. I want to show logged in or register button in the base.html, but how can I ensure that the necessary variables are always a part of the context? It seems that each view just sets up the context as they like, and there is no global context population. Is there a way of doing this without including the user in each context creation? Or will I have to make my own custom shortcuts to setup the context properly?
In a more general sense of not having to explicitly set variables in each view, it sounds like you want to look at writing your own context processor. From the docs: A context processor has a very simple interface: It's just a Python function that takes one argument, an HttpRequest object, and returns a dictionary that gets added to the template context. Each context processor must return a dictionary.
Always including the user in the django template context I am working on a small intranet site for a small company, where user should be able to post. I have imagined a very simple authentication mechanism where people just enter their email address, and gets sent a unique login url, that sets a cookie that will always identify them for future requests. In my template setup, I have base.html, and the other pages extend this. I want to show logged in or register button in the base.html, but how can I ensure that the necessary variables are always a part of the context? It seems that each view just sets up the context as they like, and there is no global context population. Is there a way of doing this without including the user in each context creation? Or will I have to make my own custom shortcuts to setup the context properly?
TITLE: Always including the user in the django template context QUESTION: I am working on a small intranet site for a small company, where user should be able to post. I have imagined a very simple authentication mechanism where people just enter their email address, and gets sent a unique login url, that sets a cookie that will always identify them for future requests. In my template setup, I have base.html, and the other pages extend this. I want to show logged in or register button in the base.html, but how can I ensure that the necessary variables are always a part of the context? It seems that each view just sets up the context as they like, and there is no global context population. Is there a way of doing this without including the user in each context creation? Or will I have to make my own custom shortcuts to setup the context properly? ANSWER: In a more general sense of not having to explicitly set variables in each view, it sounds like you want to look at writing your own context processor. From the docs: A context processor has a very simple interface: It's just a Python function that takes one argument, an HttpRequest object, and returns a dictionary that gets added to the template context. Each context processor must return a dictionary.
[ "python", "django", "authentication", "session", "cookies" ]
36
20
32,077
8
0
2008-09-03T12:22:44.043000
2008-09-03T12:31:58.703000
41,562
41,574
How do I do monkeypatching in python?
I've had to do some introspection in python and it wasn't pretty: name = sys._getframe(1).f_code name = "%s:%d %s()" %(os.path.split(name.co_filename)[1],name.co_firstlineno,name.co_name) To get something like foo.py:22 bar() blah blah In our debugging output. I'd ideally like to prepend anything to stderr with this sort of information -- Is it possible to change the behaviour of print globally within python?
A print statement does its IO through "sys.stdout.write" so you can override sys.stdout if you want to manipulate the print stream.
How do I do monkeypatching in python? I've had to do some introspection in python and it wasn't pretty: name = sys._getframe(1).f_code name = "%s:%d %s()" %(os.path.split(name.co_filename)[1],name.co_firstlineno,name.co_name) To get something like foo.py:22 bar() blah blah In our debugging output. I'd ideally like to prepend anything to stderr with this sort of information -- Is it possible to change the behaviour of print globally within python?
TITLE: How do I do monkeypatching in python? QUESTION: I've had to do some introspection in python and it wasn't pretty: name = sys._getframe(1).f_code name = "%s:%d %s()" %(os.path.split(name.co_filename)[1],name.co_firstlineno,name.co_name) To get something like foo.py:22 bar() blah blah In our debugging output. I'd ideally like to prepend anything to stderr with this sort of information -- Is it possible to change the behaviour of print globally within python? ANSWER: A print statement does its IO through "sys.stdout.write" so you can override sys.stdout if you want to manipulate the print stream.
[ "python", "monkeypatching" ]
9
3
568
2
0
2008-09-03T12:35:45.683000
2008-09-03T12:42:43.950000
41,568
41,589
Whats the best way to unit test from multiple threads?
this kind of follows on from another question of mine. Basically, once I have the code to access the file (will review the answers there in a minute) what would be the best way to test it? I am thinking of creating a method which just spawns lots of BackgroundWorker 's or something and tells them all load/save the file, and test with varying file/object sizes. Then, get a response back from the threads to see if it failed/succeeded/made the world implode etc. Can you guys offer any suggestions on the best way to approach this? As I said before, this is all kinda new to me:) Edit Following ajmastrean's post: I am using a console app to test with Debug.Asserts:) Update I originally rolled with using BackgroundWorker to deal with the threading (since I am used to that from Windows dev) I soon realised that when I was performing tests where multiple ops (threads) needed to complete before continuing, I realised it was going to be a bit of a hack to get it to do this. I then followed up on ajmastrean 's post and realised I should really be using the Thread class for working with concurrent operations. I will now refactor using this method (albeit a different approach).
In.NET, ThreadPool threads won't return without setting up ManualResetEvent s or AutoResetEvent s. I find these overkill for a quick test method (not to mention kind of complicated to create, set, and manage). Background worker is a also a bit complex with the callbacks and such. Something I have found that works is Create an array of threads. Setup the ThreadStart method of each thread. Start each thread. Join on all threads (blocks the current thread until all other threads complete or abort) public static void MultiThreadedTest() { Thread[] threads = new Thread[count]; for (int i = 0; i < threads.Length; i++) { threads[i] = new Thread(DoSomeWork()); } foreach(Thread thread in threads) { thread.Start(); } foreach(Thread thread in threads) { thread.Join(); } }
Whats the best way to unit test from multiple threads? this kind of follows on from another question of mine. Basically, once I have the code to access the file (will review the answers there in a minute) what would be the best way to test it? I am thinking of creating a method which just spawns lots of BackgroundWorker 's or something and tells them all load/save the file, and test with varying file/object sizes. Then, get a response back from the threads to see if it failed/succeeded/made the world implode etc. Can you guys offer any suggestions on the best way to approach this? As I said before, this is all kinda new to me:) Edit Following ajmastrean's post: I am using a console app to test with Debug.Asserts:) Update I originally rolled with using BackgroundWorker to deal with the threading (since I am used to that from Windows dev) I soon realised that when I was performing tests where multiple ops (threads) needed to complete before continuing, I realised it was going to be a bit of a hack to get it to do this. I then followed up on ajmastrean 's post and realised I should really be using the Thread class for working with concurrent operations. I will now refactor using this method (albeit a different approach).
TITLE: Whats the best way to unit test from multiple threads? QUESTION: this kind of follows on from another question of mine. Basically, once I have the code to access the file (will review the answers there in a minute) what would be the best way to test it? I am thinking of creating a method which just spawns lots of BackgroundWorker 's or something and tells them all load/save the file, and test with varying file/object sizes. Then, get a response back from the threads to see if it failed/succeeded/made the world implode etc. Can you guys offer any suggestions on the best way to approach this? As I said before, this is all kinda new to me:) Edit Following ajmastrean's post: I am using a console app to test with Debug.Asserts:) Update I originally rolled with using BackgroundWorker to deal with the threading (since I am used to that from Windows dev) I soon realised that when I was performing tests where multiple ops (threads) needed to complete before continuing, I realised it was going to be a bit of a hack to get it to do this. I then followed up on ajmastrean 's post and realised I should really be using the Thread class for working with concurrent operations. I will now refactor using this method (albeit a different approach). ANSWER: In.NET, ThreadPool threads won't return without setting up ManualResetEvent s or AutoResetEvent s. I find these overkill for a quick test method (not to mention kind of complicated to create, set, and manage). Background worker is a also a bit complex with the callbacks and such. Something I have found that works is Create an array of threads. Setup the ThreadStart method of each thread. Start each thread. Join on all threads (blocks the current thread until all other threads complete or abort) public static void MultiThreadedTest() { Thread[] threads = new Thread[count]; for (int i = 0; i < threads.Length; i++) { threads[i] = new Thread(DoSomeWork()); } foreach(Thread thread in threads) { thread.Start(); } foreach(Thread thread in threads) { thread.Join(); } }
[ "c#", "multithreading", "unit-testing", "testing" ]
25
22
30,585
4
0
2008-09-03T12:39:52.630000
2008-09-03T12:52:52.613000
41,576
43,255
Conditional Display in ASPX Pages on Sharepoint
I wonder what the best practice for this scenario is: I have a Sharepoint Site (MOSS2007) with an ASPX Page on it. However, I cannot use any inline source and stuff like Event handlers do not work, because Sharepoint does not allow Server Side Script on ASPX Pages per default. Two solutions: Change the PageParserPath in web.config as per this site Create all the controls and Wire them up to Events in the.CS File, thus completely eliminating some of the benefits of ASP.net I wonder, what the best practice would be? Number one looks like it's the correct choice, but changing the web.config is something I want to use sparingly whenever possible.
So in that case I would wrap it up in a feature and deploy it via a solution. This way I think you will avoid the issue you are seeing. This is especially useful if you plan to use this functionality within other sites too. You can also embed web parts directly in the page, much like you do a WebControl, thereby avoiding any gallery clutter.
Conditional Display in ASPX Pages on Sharepoint I wonder what the best practice for this scenario is: I have a Sharepoint Site (MOSS2007) with an ASPX Page on it. However, I cannot use any inline source and stuff like Event handlers do not work, because Sharepoint does not allow Server Side Script on ASPX Pages per default. Two solutions: Change the PageParserPath in web.config as per this site Create all the controls and Wire them up to Events in the.CS File, thus completely eliminating some of the benefits of ASP.net I wonder, what the best practice would be? Number one looks like it's the correct choice, but changing the web.config is something I want to use sparingly whenever possible.
TITLE: Conditional Display in ASPX Pages on Sharepoint QUESTION: I wonder what the best practice for this scenario is: I have a Sharepoint Site (MOSS2007) with an ASPX Page on it. However, I cannot use any inline source and stuff like Event handlers do not work, because Sharepoint does not allow Server Side Script on ASPX Pages per default. Two solutions: Change the PageParserPath in web.config as per this site Create all the controls and Wire them up to Events in the.CS File, thus completely eliminating some of the benefits of ASP.net I wonder, what the best practice would be? Number one looks like it's the correct choice, but changing the web.config is something I want to use sparingly whenever possible. ANSWER: So in that case I would wrap it up in a feature and deploy it via a solution. This way I think you will avoid the issue you are seeing. This is especially useful if you plan to use this functionality within other sites too. You can also embed web parts directly in the page, much like you do a WebControl, thereby avoiding any gallery clutter.
[ "asp.net", "sharepoint" ]
0
1
1,689
4
0
2008-09-03T12:43:50.920000
2008-09-04T06:50:25.147000
41,583
41,591
How to do a sample rate conversion in Windows (and OSX)
I am about to write an audio file converter for my side job at the university. As part of this I would need sample rate conversion. However, my professor said that it would be pretty hard to write a sample rate converter that was both of good quality and fast. On my research on the subject, I found some functions in the OSX CoreAudio-framework, that could do a sample rate conversion (AudioConverter.h). After all, an OS has to have some facilities to do that for its own audio stack. Do you know a similar method for C/C++ and Windows, that are either part of the OS or open source? I am pretty sure that this function exists within DirectX Audio (XAudio2?), but I seem to be unable to find a reference to it in the MSDN library.
Try Secret Rabbit Code (= SRC = Sample Rate Conversion ) It's GPL, it's fast and it's high quality. http://www.mega-nerd.com/SRC/license.html
How to do a sample rate conversion in Windows (and OSX) I am about to write an audio file converter for my side job at the university. As part of this I would need sample rate conversion. However, my professor said that it would be pretty hard to write a sample rate converter that was both of good quality and fast. On my research on the subject, I found some functions in the OSX CoreAudio-framework, that could do a sample rate conversion (AudioConverter.h). After all, an OS has to have some facilities to do that for its own audio stack. Do you know a similar method for C/C++ and Windows, that are either part of the OS or open source? I am pretty sure that this function exists within DirectX Audio (XAudio2?), but I seem to be unable to find a reference to it in the MSDN library.
TITLE: How to do a sample rate conversion in Windows (and OSX) QUESTION: I am about to write an audio file converter for my side job at the university. As part of this I would need sample rate conversion. However, my professor said that it would be pretty hard to write a sample rate converter that was both of good quality and fast. On my research on the subject, I found some functions in the OSX CoreAudio-framework, that could do a sample rate conversion (AudioConverter.h). After all, an OS has to have some facilities to do that for its own audio stack. Do you know a similar method for C/C++ and Windows, that are either part of the OS or open source? I am pretty sure that this function exists within DirectX Audio (XAudio2?), but I seem to be unable to find a reference to it in the MSDN library. ANSWER: Try Secret Rabbit Code (= SRC = Sample Rate Conversion ) It's GPL, it's fast and it's high quality. http://www.mega-nerd.com/SRC/license.html
[ "c++", "windows", "macos", "audio" ]
4
5
3,669
2
0
2008-09-03T12:48:42.203000
2008-09-03T12:54:16.417000
41,590
41,598
How do you properly use namespaces in C++?
I come from a Java background, where packages are used, not namespaces. I'm used to putting classes that work together to form a complete object into packages, and then reusing them later from that package. But now I'm working in C++. How do you use namespaces in C++? Do you create a single namespace for the entire application, or do you create namespaces for the major components? If so, how do you create objects from classes in other namespaces?
Namespaces are packages essentially. They can be used like this: namespace MyNamespace { class MyClass { }; } Then in code: MyNamespace::MyClass* pClass = new MyNamespace::MyClass(); Or, if you want to always use a specific namespace, you can do this: using namespace MyNamespace; MyClass* pClass = new MyClass(); Edit: Following what bernhardrusch has said, I tend not to use the "using namespace x" syntax at all, I usually explicitly specify the namespace when instantiating my objects (i.e. the first example I showed). And as you asked below, you can use as many namespaces as you like.
How do you properly use namespaces in C++? I come from a Java background, where packages are used, not namespaces. I'm used to putting classes that work together to form a complete object into packages, and then reusing them later from that package. But now I'm working in C++. How do you use namespaces in C++? Do you create a single namespace for the entire application, or do you create namespaces for the major components? If so, how do you create objects from classes in other namespaces?
TITLE: How do you properly use namespaces in C++? QUESTION: I come from a Java background, where packages are used, not namespaces. I'm used to putting classes that work together to form a complete object into packages, and then reusing them later from that package. But now I'm working in C++. How do you use namespaces in C++? Do you create a single namespace for the entire application, or do you create namespaces for the major components? If so, how do you create objects from classes in other namespaces? ANSWER: Namespaces are packages essentially. They can be used like this: namespace MyNamespace { class MyClass { }; } Then in code: MyNamespace::MyClass* pClass = new MyNamespace::MyClass(); Or, if you want to always use a specific namespace, you can do this: using namespace MyNamespace; MyClass* pClass = new MyClass(); Edit: Following what bernhardrusch has said, I tend not to use the "using namespace x" syntax at all, I usually explicitly specify the namespace when instantiating my objects (i.e. the first example I showed). And as you asked below, you can use as many namespaces as you like.
[ "c++", "namespaces" ]
248
179
213,690
16
0
2008-09-03T12:54:06.637000
2008-09-03T12:57:13.900000
41,594
41,985
Import OLE Object from Access to MySQL
I have a table in an access table which contains Product entries, one of the columns has a jpg image stored as an OLE Object. I am trying to import this table to MySQL but nothing seems to work. I have tried the MySQL migration tool but that has a known issue with Access and OLE Objects. (The issue being it doesnt work and leaves the fields blank) I also tried the suggestion on this site and while the data is imported it seems as though the image is getting corrupted in the transfer. When i try to preview the image i just get a binary view, if i save it on disk as a jpg image and try to open it i get an error stating the image is corrupt. The images in Access are fine and can be previewed. Access is storing the data as an OLE Object and when i import it to MySql it is saved in a MediumBlob field. Has anyone had this issue before and how did they resolve it?
Ok so in the interests of airing my dirty code in public here what i came up with. Note: this is a hack designed to be used once and then thrown away. This Method takes in a datarowview containing 1 row of data from the access table. The Images are wrapped in OLE serialization, im not entirely familiar with how this works but its how Microsoft apps allow any object to be embedded into something else. (eg images into Excel Cells). I needed to remove the serialization junk around the image so i loaded the entire field as a Byte array and searched through it for 3 concurrent entries (FF D8 FF) which represent the beginning of the image data within the field. Private Function GetImageFromRow(ByRef row As DataRowView, ByVal columnName As String) As Bitmap Dim oImage As Bitmap = New Bitmap("c:\default.jpg") Try If Not IsDBNull(row(columnName)) Then If row(columnName) IsNot Nothing Then Dim mStream As New System.IO.MemoryStream(CType(row(columnName), Byte())) If mStream.Length > 0 Then Dim b(Convert.ToInt32(mStream.Length - 1)) As Byte mStream.Read(b, 0, Convert.ToInt32(mStream.Length - 1)) Dim position As Integer = 0 For index As Integer = 0 To b.Length - 3 If b(index) = &HFF And b(index + 1) = &HD8 And b(index + 2) = &HFF Then position = index Exit For End If Next If position > 0 Then Dim jpgStream As New System.IO.MemoryStream(b, position, b.Length - position) oImage = New Bitmap(jpgStream) End If End If End If End If Catch ex As Exception Throw New ApplicationException(ex.Message, ex) End Try Return oImage End Function Then its a matter of pulling out this data into a bitmap. So for each row in the access table i extract the bitmap and then update the corresponding MySQL entry. It worked fine but im guessing i could have removed the serialisation stuff in a better way, perhaps theres an API to do it.
Import OLE Object from Access to MySQL I have a table in an access table which contains Product entries, one of the columns has a jpg image stored as an OLE Object. I am trying to import this table to MySQL but nothing seems to work. I have tried the MySQL migration tool but that has a known issue with Access and OLE Objects. (The issue being it doesnt work and leaves the fields blank) I also tried the suggestion on this site and while the data is imported it seems as though the image is getting corrupted in the transfer. When i try to preview the image i just get a binary view, if i save it on disk as a jpg image and try to open it i get an error stating the image is corrupt. The images in Access are fine and can be previewed. Access is storing the data as an OLE Object and when i import it to MySql it is saved in a MediumBlob field. Has anyone had this issue before and how did they resolve it?
TITLE: Import OLE Object from Access to MySQL QUESTION: I have a table in an access table which contains Product entries, one of the columns has a jpg image stored as an OLE Object. I am trying to import this table to MySQL but nothing seems to work. I have tried the MySQL migration tool but that has a known issue with Access and OLE Objects. (The issue being it doesnt work and leaves the fields blank) I also tried the suggestion on this site and while the data is imported it seems as though the image is getting corrupted in the transfer. When i try to preview the image i just get a binary view, if i save it on disk as a jpg image and try to open it i get an error stating the image is corrupt. The images in Access are fine and can be previewed. Access is storing the data as an OLE Object and when i import it to MySql it is saved in a MediumBlob field. Has anyone had this issue before and how did they resolve it? ANSWER: Ok so in the interests of airing my dirty code in public here what i came up with. Note: this is a hack designed to be used once and then thrown away. This Method takes in a datarowview containing 1 row of data from the access table. The Images are wrapped in OLE serialization, im not entirely familiar with how this works but its how Microsoft apps allow any object to be embedded into something else. (eg images into Excel Cells). I needed to remove the serialization junk around the image so i loaded the entire field as a Byte array and searched through it for 3 concurrent entries (FF D8 FF) which represent the beginning of the image data within the field. Private Function GetImageFromRow(ByRef row As DataRowView, ByVal columnName As String) As Bitmap Dim oImage As Bitmap = New Bitmap("c:\default.jpg") Try If Not IsDBNull(row(columnName)) Then If row(columnName) IsNot Nothing Then Dim mStream As New System.IO.MemoryStream(CType(row(columnName), Byte())) If mStream.Length > 0 Then Dim b(Convert.ToInt32(mStream.Length - 1)) As Byte mStream.Read(b, 0, Convert.ToInt32(mStream.Length - 1)) Dim position As Integer = 0 For index As Integer = 0 To b.Length - 3 If b(index) = &HFF And b(index + 1) = &HD8 And b(index + 2) = &HFF Then position = index Exit For End If Next If position > 0 Then Dim jpgStream As New System.IO.MemoryStream(b, position, b.Length - position) oImage = New Bitmap(jpgStream) End If End If End If End If Catch ex As Exception Throw New ApplicationException(ex.Message, ex) End Try Return oImage End Function Then its a matter of pulling out this data into a bitmap. So for each row in the access table i extract the bitmap and then update the corresponding MySQL entry. It worked fine but im guessing i could have removed the serialisation stuff in a better way, perhaps theres an API to do it.
[ "mysql", "ms-access", "import", "data-transfer" ]
2
2
4,243
3
0
2008-09-03T12:55:25.743000
2008-09-03T15:56:58.053000
41,601
41,607
User Interface Testing
We are working on a large project with a measure of new/modified GUI functionality. We've found in the past that we often introduced new problems in related code when adding new functionality. We have non-technical users perform testing, but they often miss parts and allow bugs to slip through. Are there any best practices for organizing the UI testing of a WinForms project? Is there any way to automate it?
There are GUI testing tools that will click buttons and stuff for you but they're pretty fragile in my experience. The best thing to do is to keep your UI layer as thin as possible. Your event handler classes should optimally be only one or two lines that call out to other more testable classes. That way you can test your business logic in unit tests without having to actually do a button click.
User Interface Testing We are working on a large project with a measure of new/modified GUI functionality. We've found in the past that we often introduced new problems in related code when adding new functionality. We have non-technical users perform testing, but they often miss parts and allow bugs to slip through. Are there any best practices for organizing the UI testing of a WinForms project? Is there any way to automate it?
TITLE: User Interface Testing QUESTION: We are working on a large project with a measure of new/modified GUI functionality. We've found in the past that we often introduced new problems in related code when adding new functionality. We have non-technical users perform testing, but they often miss parts and allow bugs to slip through. Are there any best practices for organizing the UI testing of a WinForms project? Is there any way to automate it? ANSWER: There are GUI testing tools that will click buttons and stuff for you but they're pretty fragile in my experience. The best thing to do is to keep your UI layer as thin as possible. Your event handler classes should optimally be only one or two lines that call out to other more testable classes. That way you can test your business logic in unit tests without having to actually do a button click.
[ "user-interface", "testing", "integration-testing" ]
16
19
8,403
11
0
2008-09-03T12:57:25.443000
2008-09-03T13:02:12.793000
41,630
41,635
is it possible to concat arguments to a command line using backquotes ?
I would like to execute an OS command from my ruby script but I want to add an argument from a ruby variable. I know that's possible by using keyword system like that: #!/usr/bin/env ruby directory = '/home/paulgreg/' system 'ls ' + directory but is that possible by using the "backquotes or backticks syntax"? (I mean by using that syntax: ls )
No, that will just concatenate the output from ls and the contents of directory. But you can do this: #!/usr/bin/env ruby directory = '/home/paulgreg/' `ls #{directory}`
is it possible to concat arguments to a command line using backquotes ? I would like to execute an OS command from my ruby script but I want to add an argument from a ruby variable. I know that's possible by using keyword system like that: #!/usr/bin/env ruby directory = '/home/paulgreg/' system 'ls ' + directory but is that possible by using the "backquotes or backticks syntax"? (I mean by using that syntax: ls )
TITLE: is it possible to concat arguments to a command line using backquotes ? QUESTION: I would like to execute an OS command from my ruby script but I want to add an argument from a ruby variable. I know that's possible by using keyword system like that: #!/usr/bin/env ruby directory = '/home/paulgreg/' system 'ls ' + directory but is that possible by using the "backquotes or backticks syntax"? (I mean by using that syntax: ls ) ANSWER: No, that will just concatenate the output from ls and the contents of directory. But you can do this: #!/usr/bin/env ruby directory = '/home/paulgreg/' `ls #{directory}`
[ "ruby", "command-line", "command-line-interface" ]
2
6
2,744
3
0
2008-09-03T13:13:06.980000
2008-09-03T13:16:29.330000
41,643
41,661
Store more than 3GB of video-frames in memory, on 32-bit OS
At work we have an application to play 2K (2048*1556px) OpenEXR film sequences. It works well.. apart from when sequences that are over 3GB (quite common), then it has to unload old frames from memory, despite the fact all machines have 8-16GB of memory (which is addressable via the linux BIGMEM stuff). The frames have to he cached into memory to play back in realtime. The OS is a several-year old 32-bit Fedora Distro (not possible to upgradable to 64bit, for the foreseeable future). The per-process limitation is 3GB per process. Basically, is it possible to cache more than 3GB of data in memory, somehow? My initial idea was to spread the data between multiple processes, but I've no idea if this is possible..
How about creating a RAM drive and loading the file into that... assuming the RAM drive supports the BIGMEM stuff for you. You could use multiple processes: each process loads a view of the file as a shared memory segment, and the player process then maps the segments in turn as needed.
Store more than 3GB of video-frames in memory, on 32-bit OS At work we have an application to play 2K (2048*1556px) OpenEXR film sequences. It works well.. apart from when sequences that are over 3GB (quite common), then it has to unload old frames from memory, despite the fact all machines have 8-16GB of memory (which is addressable via the linux BIGMEM stuff). The frames have to he cached into memory to play back in realtime. The OS is a several-year old 32-bit Fedora Distro (not possible to upgradable to 64bit, for the foreseeable future). The per-process limitation is 3GB per process. Basically, is it possible to cache more than 3GB of data in memory, somehow? My initial idea was to spread the data between multiple processes, but I've no idea if this is possible..
TITLE: Store more than 3GB of video-frames in memory, on 32-bit OS QUESTION: At work we have an application to play 2K (2048*1556px) OpenEXR film sequences. It works well.. apart from when sequences that are over 3GB (quite common), then it has to unload old frames from memory, despite the fact all machines have 8-16GB of memory (which is addressable via the linux BIGMEM stuff). The frames have to he cached into memory to play back in realtime. The OS is a several-year old 32-bit Fedora Distro (not possible to upgradable to 64bit, for the foreseeable future). The per-process limitation is 3GB per process. Basically, is it possible to cache more than 3GB of data in memory, somehow? My initial idea was to spread the data between multiple processes, but I've no idea if this is possible.. ANSWER: How about creating a RAM drive and loading the file into that... assuming the RAM drive supports the BIGMEM stuff for you. You could use multiple processes: each process loads a view of the file as a shared memory segment, and the player process then maps the segments in turn as needed.
[ "linux", "memory", "32-bit" ]
4
2
610
5
0
2008-09-03T13:19:39.117000
2008-09-03T13:27:57.913000
41,647
41,691
PHP Include function outputting unknown char
When using the php include function the include is succesfully executed, but it is also outputting a char before the output of the include is outputted, the char is of hex value 3F and I have no idea where it is coming from, although it seems to happen with every include. At first I thbought it was file encoding, but this doesn't seem to be a problem. I have created a test case to demonstrate it: ( link no longer working ) http://driveefficiently.com/testinclude.php this file consists of only: and include.inc consists of only: and yet, the output is: "?hello, world" where the? is a char with a random value. It is this value that I do not know the origins of and it is sometimes screwing up my sites a bit. Any ideas of where this could be coming from? At first I thought it might be something to do with file encoding, but I don't think its a problem.
What you are seeing is a UTF-8 Byte Order Mark: The UTF-8 representation of the BOM is the byte sequence EF BB BF, which appears as the ISO-8859-1 characters  in most text editors and web browsers not prepared to handle UTF-8. Byte Order Mark on Wikipedia PHP does not understand that these characters should be "hidden" and sends these to the browser as if they were normal characters. To get rid of them you will need to open the file using a "proper" text editor that will allow you to save the file as UTF-8 without the leading BOM. You can read more about this problem here
PHP Include function outputting unknown char When using the php include function the include is succesfully executed, but it is also outputting a char before the output of the include is outputted, the char is of hex value 3F and I have no idea where it is coming from, although it seems to happen with every include. At first I thbought it was file encoding, but this doesn't seem to be a problem. I have created a test case to demonstrate it: ( link no longer working ) http://driveefficiently.com/testinclude.php this file consists of only: and include.inc consists of only: and yet, the output is: "?hello, world" where the? is a char with a random value. It is this value that I do not know the origins of and it is sometimes screwing up my sites a bit. Any ideas of where this could be coming from? At first I thought it might be something to do with file encoding, but I don't think its a problem.
TITLE: PHP Include function outputting unknown char QUESTION: When using the php include function the include is succesfully executed, but it is also outputting a char before the output of the include is outputted, the char is of hex value 3F and I have no idea where it is coming from, although it seems to happen with every include. At first I thbought it was file encoding, but this doesn't seem to be a problem. I have created a test case to demonstrate it: ( link no longer working ) http://driveefficiently.com/testinclude.php this file consists of only: and include.inc consists of only: and yet, the output is: "?hello, world" where the? is a char with a random value. It is this value that I do not know the origins of and it is sometimes screwing up my sites a bit. Any ideas of where this could be coming from? At first I thought it might be something to do with file encoding, but I don't think its a problem. ANSWER: What you are seeing is a UTF-8 Byte Order Mark: The UTF-8 representation of the BOM is the byte sequence EF BB BF, which appears as the ISO-8859-1 characters  in most text editors and web browsers not prepared to handle UTF-8. Byte Order Mark on Wikipedia PHP does not understand that these characters should be "hidden" and sends these to the browser as if they were normal characters. To get rid of them you will need to open the file using a "proper" text editor that will allow you to save the file as UTF-8 without the leading BOM. You can read more about this problem here
[ "php", "encoding", "byte-order-mark" ]
5
11
2,998
6
0
2008-09-03T13:23:43.320000
2008-09-03T13:44:59.447000
41,652
41,664
Using Custom MembershipProvider without a Login control in ASP.NET
We have got a custom MembershipProvider in ASP.NET. Now there are 2 possible scenario the user can be validated: User login via login.aspx page by entering his username/password. I have used Login control and linked it with the MyMembershipProvider. This is working perfectly fine. An authentication token is passed via some URL in query string form a different web sites. For this I have one overload in MembershipProvider.Validate(string authenticationToken), which is actually validating the user. In this case we cannot use the Login control. Now how can I use the same MembershipProvider to validate the user without actually using the Login control? I tried to call Validate manually, but this is not signing the user in. Here is the code snippet I am using if (!string.IsNullOrEmpty(Request.QueryString["authenticationToken"])) { string ticket = Request.QueryString["authenticationToken"]; MyMembershipProvider provider = Membership.Provider as MyMembershipProvider; if (provider!= null) { if (provider.ValidateUser(ticket)) // Login Success else // Login Fail } }
After validation is successful, you need to sign in the user, by calling FormsAuthentication.Authenticate: http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.authenticate.aspx EDIT: It is FormsAuthentication.SetAuthCookie: http://msdn.microsoft.com/en-us/library/twk5762b.aspx Also, to redirect the user back where he wanted to go, call: FormsAuthentication.RedirectFromLoginPage: http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.redirectfromloginpage.aspx link text
Using Custom MembershipProvider without a Login control in ASP.NET We have got a custom MembershipProvider in ASP.NET. Now there are 2 possible scenario the user can be validated: User login via login.aspx page by entering his username/password. I have used Login control and linked it with the MyMembershipProvider. This is working perfectly fine. An authentication token is passed via some URL in query string form a different web sites. For this I have one overload in MembershipProvider.Validate(string authenticationToken), which is actually validating the user. In this case we cannot use the Login control. Now how can I use the same MembershipProvider to validate the user without actually using the Login control? I tried to call Validate manually, but this is not signing the user in. Here is the code snippet I am using if (!string.IsNullOrEmpty(Request.QueryString["authenticationToken"])) { string ticket = Request.QueryString["authenticationToken"]; MyMembershipProvider provider = Membership.Provider as MyMembershipProvider; if (provider!= null) { if (provider.ValidateUser(ticket)) // Login Success else // Login Fail } }
TITLE: Using Custom MembershipProvider without a Login control in ASP.NET QUESTION: We have got a custom MembershipProvider in ASP.NET. Now there are 2 possible scenario the user can be validated: User login via login.aspx page by entering his username/password. I have used Login control and linked it with the MyMembershipProvider. This is working perfectly fine. An authentication token is passed via some URL in query string form a different web sites. For this I have one overload in MembershipProvider.Validate(string authenticationToken), which is actually validating the user. In this case we cannot use the Login control. Now how can I use the same MembershipProvider to validate the user without actually using the Login control? I tried to call Validate manually, but this is not signing the user in. Here is the code snippet I am using if (!string.IsNullOrEmpty(Request.QueryString["authenticationToken"])) { string ticket = Request.QueryString["authenticationToken"]; MyMembershipProvider provider = Membership.Provider as MyMembershipProvider; if (provider!= null) { if (provider.ValidateUser(ticket)) // Login Success else // Login Fail } } ANSWER: After validation is successful, you need to sign in the user, by calling FormsAuthentication.Authenticate: http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.authenticate.aspx EDIT: It is FormsAuthentication.SetAuthCookie: http://msdn.microsoft.com/en-us/library/twk5762b.aspx Also, to redirect the user back where he wanted to go, call: FormsAuthentication.RedirectFromLoginPage: http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.redirectfromloginpage.aspx link text
[ "asp.net", "authentication" ]
8
13
13,262
3
0
2008-09-03T13:24:56.187000
2008-09-03T13:29:53.367000
41,654
41,668
C++ libraries to manipulate images
Do you know any open source/free software C++ libraries to manipulate images in these formats:.jpg.gif.png.bmp? The more formats it supports, the better. I am implementing a free program in C++ which hides a text file into one or more images, using steganography. I am working under Unix.
ImageMagick can manipulate about anything and has interfaces for a dozen of languages, including the Magick++ API for C++.
C++ libraries to manipulate images Do you know any open source/free software C++ libraries to manipulate images in these formats:.jpg.gif.png.bmp? The more formats it supports, the better. I am implementing a free program in C++ which hides a text file into one or more images, using steganography. I am working under Unix.
TITLE: C++ libraries to manipulate images QUESTION: Do you know any open source/free software C++ libraries to manipulate images in these formats:.jpg.gif.png.bmp? The more formats it supports, the better. I am implementing a free program in C++ which hides a text file into one or more images, using steganography. I am working under Unix. ANSWER: ImageMagick can manipulate about anything and has interfaces for a dozen of languages, including the Magick++ API for C++.
[ "c++", "image", "steganography" ]
9
7
3,798
7
0
2008-09-03T13:25:01.383000
2008-09-03T13:31:00.963000
41,659
41,814
Is there a way to access web.xml properties from a Java Bean?
Is there any way in the Servlet API to access properties specified in web.xml (such as initialization parameters) from within a Bean or Factory class that is not associated at all with the web container? For example, I'm writing a Factory class, and I'd like to include some logic within the Factory to check a hierarchy of files and configuration locations to see which if any are available to determine which implementation class to instantiate - for example, a properties file in the classpath, a web.xml parameter, a system property, or some default logic if nothing else is available. I'd like to be able to do this without injecting any reference to ServletConfig or anything similiar to my Factory - the code should be able to run ok outside of a Servlet Container. This might sound a little bit uncommon, but I'd like for this component I'm working on to be able to be packaged with one of our webapps, and also be versatile enough to be packaged with some of our command-line tools without requiring a new properties file just for my component - so I was hoping to piggyback on top of other configuration files such as web.xml. If I recall correctly,.NET has something like Request.GetCurrentRequest() to get a reference to the currently executing Request - but since this is a Java app I'm looking for something simliar that could be used to gain access to ServletConfig.
One way you could do this is: public class FactoryInitialisingServletContextListener implements ServletContextListener { public void contextDestroyed(ServletContextEvent event) { } public void contextInitialized(ServletContextEvent event) { Properties properties = new Properties(); ServletContext servletContext = event.getServletContext(); Enumeration keys = servletContext.getInitParameterNames(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); String value = servletContext.getInitParameter(key); properties.setProperty(key, value); } Factory.setServletContextProperties(properties); } } public class Factory { static Properties _servletContextProperties = new Properties(); public static void setServletContextProperties(Properties servletContextProperties) { _servletContextProperties = servletContextProperties; } } And then have the following in your web.xml com.acme.FactoryInitialisingServletContextListener If your application is running in a web container, then the listener will be invoked by the container once the context has been created. In which case, the _servletContextProperties will be replaced with any context-params specified in the web.xml. If your application is running outside a web container, then _servletContextProperties will be empty.
Is there a way to access web.xml properties from a Java Bean? Is there any way in the Servlet API to access properties specified in web.xml (such as initialization parameters) from within a Bean or Factory class that is not associated at all with the web container? For example, I'm writing a Factory class, and I'd like to include some logic within the Factory to check a hierarchy of files and configuration locations to see which if any are available to determine which implementation class to instantiate - for example, a properties file in the classpath, a web.xml parameter, a system property, or some default logic if nothing else is available. I'd like to be able to do this without injecting any reference to ServletConfig or anything similiar to my Factory - the code should be able to run ok outside of a Servlet Container. This might sound a little bit uncommon, but I'd like for this component I'm working on to be able to be packaged with one of our webapps, and also be versatile enough to be packaged with some of our command-line tools without requiring a new properties file just for my component - so I was hoping to piggyback on top of other configuration files such as web.xml. If I recall correctly,.NET has something like Request.GetCurrentRequest() to get a reference to the currently executing Request - but since this is a Java app I'm looking for something simliar that could be used to gain access to ServletConfig.
TITLE: Is there a way to access web.xml properties from a Java Bean? QUESTION: Is there any way in the Servlet API to access properties specified in web.xml (such as initialization parameters) from within a Bean or Factory class that is not associated at all with the web container? For example, I'm writing a Factory class, and I'd like to include some logic within the Factory to check a hierarchy of files and configuration locations to see which if any are available to determine which implementation class to instantiate - for example, a properties file in the classpath, a web.xml parameter, a system property, or some default logic if nothing else is available. I'd like to be able to do this without injecting any reference to ServletConfig or anything similiar to my Factory - the code should be able to run ok outside of a Servlet Container. This might sound a little bit uncommon, but I'd like for this component I'm working on to be able to be packaged with one of our webapps, and also be versatile enough to be packaged with some of our command-line tools without requiring a new properties file just for my component - so I was hoping to piggyback on top of other configuration files such as web.xml. If I recall correctly,.NET has something like Request.GetCurrentRequest() to get a reference to the currently executing Request - but since this is a Java app I'm looking for something simliar that could be used to gain access to ServletConfig. ANSWER: One way you could do this is: public class FactoryInitialisingServletContextListener implements ServletContextListener { public void contextDestroyed(ServletContextEvent event) { } public void contextInitialized(ServletContextEvent event) { Properties properties = new Properties(); ServletContext servletContext = event.getServletContext(); Enumeration keys = servletContext.getInitParameterNames(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); String value = servletContext.getInitParameter(key); properties.setProperty(key, value); } Factory.setServletContextProperties(properties); } } public class Factory { static Properties _servletContextProperties = new Properties(); public static void setServletContextProperties(Properties servletContextProperties) { _servletContextProperties = servletContextProperties; } } And then have the following in your web.xml com.acme.FactoryInitialisingServletContextListener If your application is running in a web container, then the listener will be invoked by the container once the context has been created. In which case, the _servletContextProperties will be replaced with any context-params specified in the web.xml. If your application is running outside a web container, then _servletContextProperties will be empty.
[ "java", "servlets" ]
4
5
5,239
3
0
2008-09-03T13:26:55.327000
2008-09-03T14:36:25.657000
41,665
41,684
Bmp to jpg/png in C#
Is there any way to convert a bmp image to jpg/png without losing the quality in C#? Using Image class we can convert bmp to jpg but the quality of output image is very poor. Can we gain the quality level as good as an image converted to jpg using photoshop with highest quality?
var qualityEncoder = Encoder.Quality; var quality = (long); var ratio = new EncoderParameter(qualityEncoder, quality ); var codecParams = new EncoderParameters(1); codecParams.Param[0] = ratio; var jpegCodecInfo =; bmp.Save(fileName, jpegCodecInfo, codecParams); // Save to JPG
Bmp to jpg/png in C# Is there any way to convert a bmp image to jpg/png without losing the quality in C#? Using Image class we can convert bmp to jpg but the quality of output image is very poor. Can we gain the quality level as good as an image converted to jpg using photoshop with highest quality?
TITLE: Bmp to jpg/png in C# QUESTION: Is there any way to convert a bmp image to jpg/png without losing the quality in C#? Using Image class we can convert bmp to jpg but the quality of output image is very poor. Can we gain the quality level as good as an image converted to jpg using photoshop with highest quality? ANSWER: var qualityEncoder = Encoder.Quality; var quality = (long); var ratio = new EncoderParameter(qualityEncoder, quality ); var codecParams = new EncoderParameters(1); codecParams.Param[0] = ratio; var jpegCodecInfo =; bmp.Save(fileName, jpegCodecInfo, codecParams); // Save to JPG
[ "c#", "image-manipulation" ]
58
58
99,997
7
0
2008-09-03T13:29:58.250000
2008-09-03T13:39:51.830000
41,676
41,710
Is there a way of getting the process id of my C++ application?
Is there a way of getting the process id of my C++ application? I am using the Carbon framework, but not Cocoa…
can you use the getpid() function found in unistd.h? osx reference
Is there a way of getting the process id of my C++ application? Is there a way of getting the process id of my C++ application? I am using the Carbon framework, but not Cocoa…
TITLE: Is there a way of getting the process id of my C++ application? QUESTION: Is there a way of getting the process id of my C++ application? I am using the Carbon framework, but not Cocoa… ANSWER: can you use the getpid() function found in unistd.h? osx reference
[ "c++", "macos", "macos-carbon" ]
6
8
5,669
3
0
2008-09-03T13:35:30.717000
2008-09-03T13:51:56.420000
41,686
42,202
Why is my image coming out garbled?
I've got some Java code using a servlet and Apache Commons FileUpload to upload a file to a set directory. It's working fine for character data (e.g. text files) but image files are coming out garbled. I can open them but the image doesn't look like it should. Here's my code: Servlet protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String customerPath = "\\leetest\\"; // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); // Parse the request FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); if (item.isFormField()) { // Form field. Ignore for now } else { BufferedInputStream stream = new BufferedInputStream(item.openStream()); if (stream == null) { LOGGER.error("Something went wrong with fetching the stream for field " + name); } byte[] bytes = StreamUtils.getBytes(stream); FileManager.createFile(customerPath, item.getName(), bytes); stream.close(); } } } } catch (Exception e) { throw new UploadException("An error occured during upload: " + e.getMessage()); } } StreamUtils.getBytes(stream) looks like: public static byte[] getBytes(InputStream src, int buffsize) throws IOException { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); byte[] buff = new byte[buffsize]; while (true) { int nBytesRead = src.read(buff); if (nBytesRead < 0) { break; } byteStream.write(buff); } byte[] result = byteStream.toByteArray(); byteStream.close(); return result; } And finally FileManager.createFile looks like: public static void createFile(String customerPath, String filename, byte[] fileData) throws IOException { customerPath = getFullPath(customerPath + filename); File newFile = new File(customerPath); if (!newFile.getParentFile().exists()) { newFile.getParentFile().mkdirs(); } FileOutputStream outputStream = new FileOutputStream(newFile); outputStream.write(fileData); outputStream.close(); } Can anyone spot what I'm doing wrong? Cheers, Lee
One thing I don't like is here in this block from StreamUtils.getBytes(): 1 while (true) { 2 int nBytesRead = src.read(buff); 3 if (nBytesRead < 0) { 4 break; 5 } 6 byteStream.write(buff); 7 } At line 6, it writes the entire buffer, no matter how many bytes are read in. I am not convinced this will always be the case. It would be more correct like this: 1 while (true) { 2 int nBytesRead = src.read(buff); 3 if (nBytesRead < 0) { 4 break; 5 } else { 6 byteStream.write(buff, 0, nBytesRead); 7 } 8 } Note the 'else' on line 5, along with the two additional parameters (array index start position and length to copy) on line 6. I could imagine that for larger files, like images, the buffer returns before it is filled (maybe it is waiting for more). That means you'd be unintentionally writing old data that was remaining in the tail end of the buffer. This is almost certainly happening most of the time at EoF, assuming a buffer > 1 byte, but extra data at EoF is probably not the cause of your corruption...it is just not desirable.
Why is my image coming out garbled? I've got some Java code using a servlet and Apache Commons FileUpload to upload a file to a set directory. It's working fine for character data (e.g. text files) but image files are coming out garbled. I can open them but the image doesn't look like it should. Here's my code: Servlet protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String customerPath = "\\leetest\\"; // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); // Parse the request FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); if (item.isFormField()) { // Form field. Ignore for now } else { BufferedInputStream stream = new BufferedInputStream(item.openStream()); if (stream == null) { LOGGER.error("Something went wrong with fetching the stream for field " + name); } byte[] bytes = StreamUtils.getBytes(stream); FileManager.createFile(customerPath, item.getName(), bytes); stream.close(); } } } } catch (Exception e) { throw new UploadException("An error occured during upload: " + e.getMessage()); } } StreamUtils.getBytes(stream) looks like: public static byte[] getBytes(InputStream src, int buffsize) throws IOException { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); byte[] buff = new byte[buffsize]; while (true) { int nBytesRead = src.read(buff); if (nBytesRead < 0) { break; } byteStream.write(buff); } byte[] result = byteStream.toByteArray(); byteStream.close(); return result; } And finally FileManager.createFile looks like: public static void createFile(String customerPath, String filename, byte[] fileData) throws IOException { customerPath = getFullPath(customerPath + filename); File newFile = new File(customerPath); if (!newFile.getParentFile().exists()) { newFile.getParentFile().mkdirs(); } FileOutputStream outputStream = new FileOutputStream(newFile); outputStream.write(fileData); outputStream.close(); } Can anyone spot what I'm doing wrong? Cheers, Lee
TITLE: Why is my image coming out garbled? QUESTION: I've got some Java code using a servlet and Apache Commons FileUpload to upload a file to a set directory. It's working fine for character data (e.g. text files) but image files are coming out garbled. I can open them but the image doesn't look like it should. Here's my code: Servlet protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String customerPath = "\\leetest\\"; // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); // Parse the request FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); if (item.isFormField()) { // Form field. Ignore for now } else { BufferedInputStream stream = new BufferedInputStream(item.openStream()); if (stream == null) { LOGGER.error("Something went wrong with fetching the stream for field " + name); } byte[] bytes = StreamUtils.getBytes(stream); FileManager.createFile(customerPath, item.getName(), bytes); stream.close(); } } } } catch (Exception e) { throw new UploadException("An error occured during upload: " + e.getMessage()); } } StreamUtils.getBytes(stream) looks like: public static byte[] getBytes(InputStream src, int buffsize) throws IOException { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); byte[] buff = new byte[buffsize]; while (true) { int nBytesRead = src.read(buff); if (nBytesRead < 0) { break; } byteStream.write(buff); } byte[] result = byteStream.toByteArray(); byteStream.close(); return result; } And finally FileManager.createFile looks like: public static void createFile(String customerPath, String filename, byte[] fileData) throws IOException { customerPath = getFullPath(customerPath + filename); File newFile = new File(customerPath); if (!newFile.getParentFile().exists()) { newFile.getParentFile().mkdirs(); } FileOutputStream outputStream = new FileOutputStream(newFile); outputStream.write(fileData); outputStream.close(); } Can anyone spot what I'm doing wrong? Cheers, Lee ANSWER: One thing I don't like is here in this block from StreamUtils.getBytes(): 1 while (true) { 2 int nBytesRead = src.read(buff); 3 if (nBytesRead < 0) { 4 break; 5 } 6 byteStream.write(buff); 7 } At line 6, it writes the entire buffer, no matter how many bytes are read in. I am not convinced this will always be the case. It would be more correct like this: 1 while (true) { 2 int nBytesRead = src.read(buff); 3 if (nBytesRead < 0) { 4 break; 5 } else { 6 byteStream.write(buff, 0, nBytesRead); 7 } 8 } Note the 'else' on line 5, along with the two additional parameters (array index start position and length to copy) on line 6. I could imagine that for larger files, like images, the buffer returns before it is filled (maybe it is waiting for more). That means you'd be unintentionally writing old data that was remaining in the tail end of the buffer. This is almost certainly happening most of the time at EoF, assuming a buffer > 1 byte, but extra data at EoF is probably not the cause of your corruption...it is just not desirable.
[ "java", "file-io", "apache-commons-fileupload" ]
4
4
719
5
0
2008-09-03T13:41:07.430000
2008-09-03T17:49:35.350000
41,692
41,702
jQuery tablesorter plugin column width incorrect in IE7
I am using the tablesorter plugin ( http://tablesorter.com ) and am having a problem with column widths in IE7. It looks fine in Firefox and sometimes in IE7. Here's a screenshot of the problem: IE7 View and here's how it's supposed to look: Firefox view
This is a common layout problem in IE. If you are using CSS to style the columns width, also add the column widths to the td tags. Set the first column to a percentage that will try to suck up most of the space, like 50% or something. The first column width will take everything that it can and the other columns will abide by their static width.
jQuery tablesorter plugin column width incorrect in IE7 I am using the tablesorter plugin ( http://tablesorter.com ) and am having a problem with column widths in IE7. It looks fine in Firefox and sometimes in IE7. Here's a screenshot of the problem: IE7 View and here's how it's supposed to look: Firefox view
TITLE: jQuery tablesorter plugin column width incorrect in IE7 QUESTION: I am using the tablesorter plugin ( http://tablesorter.com ) and am having a problem with column widths in IE7. It looks fine in Firefox and sometimes in IE7. Here's a screenshot of the problem: IE7 View and here's how it's supposed to look: Firefox view ANSWER: This is a common layout problem in IE. If you are using CSS to style the columns width, also add the column widths to the td tags. Set the first column to a percentage that will try to suck up most of the space, like 50% or something. The first column width will take everything that it can and the other columns will abide by their static width.
[ "javascript", "jquery", "html", "internet-explorer-7", "tablesorter" ]
8
6
1,992
1
0
2008-09-03T13:45:14.250000
2008-09-03T13:48:41.420000
41,701
41,707
Splitting tuples in Python - best practice?
I have a method in my Python code that returns a tuple - a row from a SQL query. Let's say it has three fields: (jobId, label, username) For ease of passing it around between functions, I've been passing the entire tuple as a variable called 'job'. Eventually, however, I want to get at the bits, so I've been using code like this: (jobId, label, username) = job I've realised, however, that this is a maintenance nightmare, because now I can never add new fields to the result set without breaking all of my existing code. How should I have written this? Here are my two best guesses: (jobId, label, username) = (job[0], job[1], job[2])...but that doesn't scale nicely when you have 15...20 fields or to convert the results from the SQL query to a dictionary straight away and pass that around (I don't have control over the fact that it starts life as a tuple, that's fixed for me)
I'd say that a dictionary is definitely the best way to do it. It's easily extensible, allows you to give each value a sensible name, and Python has a lot of built-in language features for using and manipulating dictionaries. If you need to add more fields later, all you need to change is the code that converts the tuple to a dictionary and the code that actually makes use of the new values. For example: job={} job['jobid'], job['label'], job['username']=
Splitting tuples in Python - best practice? I have a method in my Python code that returns a tuple - a row from a SQL query. Let's say it has three fields: (jobId, label, username) For ease of passing it around between functions, I've been passing the entire tuple as a variable called 'job'. Eventually, however, I want to get at the bits, so I've been using code like this: (jobId, label, username) = job I've realised, however, that this is a maintenance nightmare, because now I can never add new fields to the result set without breaking all of my existing code. How should I have written this? Here are my two best guesses: (jobId, label, username) = (job[0], job[1], job[2])...but that doesn't scale nicely when you have 15...20 fields or to convert the results from the SQL query to a dictionary straight away and pass that around (I don't have control over the fact that it starts life as a tuple, that's fixed for me)
TITLE: Splitting tuples in Python - best practice? QUESTION: I have a method in my Python code that returns a tuple - a row from a SQL query. Let's say it has three fields: (jobId, label, username) For ease of passing it around between functions, I've been passing the entire tuple as a variable called 'job'. Eventually, however, I want to get at the bits, so I've been using code like this: (jobId, label, username) = job I've realised, however, that this is a maintenance nightmare, because now I can never add new fields to the result set without breaking all of my existing code. How should I have written this? Here are my two best guesses: (jobId, label, username) = (job[0], job[1], job[2])...but that doesn't scale nicely when you have 15...20 fields or to convert the results from the SQL query to a dictionary straight away and pass that around (I don't have control over the fact that it starts life as a tuple, that's fixed for me) ANSWER: I'd say that a dictionary is definitely the best way to do it. It's easily extensible, allows you to give each value a sensible name, and Python has a lot of built-in language features for using and manipulating dictionaries. If you need to add more fields later, all you need to change is the code that converts the tuple to a dictionary and the code that actually makes use of the new values. For example: job={} job['jobid'], job['label'], job['username']=
[ "python", "tuples" ]
13
13
9,874
9
0
2008-09-03T13:48:30.657000
2008-09-03T13:50:24.927000
41,712
41,720
Traditional ASP .NET Web Forms vs MVC
As someone with some winforms and client applications experience - is it worth going back and learning the way traditional ASP.NET pages work, or is it okay with moving straight into ASP.NET MVC? I'm kind of looking for pitfalls or traps in my knowledge of general C#, that I won't know from the screencast series and things on the ASP.NET site.
Here is the great thing about MVC. It works closer to the base of the framework than normal ASP.NET Web Forms. So by using MVC and understanding it, you will have a better understanding of how WebForms work. The problem with WebForms is there is a lot of magic and about 6 years of trying to make the Web work like Windows Forms, so you have the control tree hierarchy and everything translated to the Web. With MVC you get the core with out the WinForm influence. So start with MVC, and you will easily be able to move in to WebForms if needed.
Traditional ASP .NET Web Forms vs MVC As someone with some winforms and client applications experience - is it worth going back and learning the way traditional ASP.NET pages work, or is it okay with moving straight into ASP.NET MVC? I'm kind of looking for pitfalls or traps in my knowledge of general C#, that I won't know from the screencast series and things on the ASP.NET site.
TITLE: Traditional ASP .NET Web Forms vs MVC QUESTION: As someone with some winforms and client applications experience - is it worth going back and learning the way traditional ASP.NET pages work, or is it okay with moving straight into ASP.NET MVC? I'm kind of looking for pitfalls or traps in my knowledge of general C#, that I won't know from the screencast series and things on the ASP.NET site. ANSWER: Here is the great thing about MVC. It works closer to the base of the framework than normal ASP.NET Web Forms. So by using MVC and understanding it, you will have a better understanding of how WebForms work. The problem with WebForms is there is a lot of magic and about 6 years of trying to make the Web work like Windows Forms, so you have the control tree hierarchy and everything translated to the Web. With MVC you get the core with out the WinForm influence. So start with MVC, and you will easily be able to move in to WebForms if needed.
[ "asp.net-mvc", "webforms" ]
23
41
11,718
8
0
2008-09-03T13:54:22.857000
2008-09-03T13:57:05.753000
41,715
190,743
Excluding a folder from source control in an ASP.NET website?
Right now I'm working with an ASP.NET website that automatically generates images and stores them in a temporary folder. When working on my local system these go going into a temporary folder that gets picked up by Visual Source Safe which then wants to check them in. As such, I am wondering if there is a way to just exclude that particular folder from source control? I've done a bit of reading and found that there are ways to do this for individual files, but I haven't found anything yet about an entire folder.
I think you've found one of the main reasons MS went back to projects in VS2008 and in MVC. It's been a long time since I've used VSS (mainly because it's really out of date now), but most source providers let you exclude files and folders as a setting of the provider, rather than the project under control. If you can switch to a Web Project rather than a WebSite then do so, otherwise I'd look at updating your source control provider, as this sort of exclusion is easy with Vault, CSV, SVN, Git, VSTS and so on (to name but a few).
Excluding a folder from source control in an ASP.NET website? Right now I'm working with an ASP.NET website that automatically generates images and stores them in a temporary folder. When working on my local system these go going into a temporary folder that gets picked up by Visual Source Safe which then wants to check them in. As such, I am wondering if there is a way to just exclude that particular folder from source control? I've done a bit of reading and found that there are ways to do this for individual files, but I haven't found anything yet about an entire folder.
TITLE: Excluding a folder from source control in an ASP.NET website? QUESTION: Right now I'm working with an ASP.NET website that automatically generates images and stores them in a temporary folder. When working on my local system these go going into a temporary folder that gets picked up by Visual Source Safe which then wants to check them in. As such, I am wondering if there is a way to just exclude that particular folder from source control? I've done a bit of reading and found that there are ways to do this for individual files, but I haven't found anything yet about an entire folder. ANSWER: I think you've found one of the main reasons MS went back to projects in VS2008 and in MVC. It's been a long time since I've used VSS (mainly because it's really out of date now), but most source providers let you exclude files and folders as a setting of the provider, rather than the project under control. If you can switch to a Web Project rather than a WebSite then do so, otherwise I'd look at updating your source control provider, as this sort of exclusion is easy with Vault, CSV, SVN, Git, VSTS and so on (to name but a few).
[ "asp.net", "visual-sourcesafe" ]
1
3
3,416
6
0
2008-09-03T13:54:39.643000
2008-10-10T10:30:50.920000
41,717
41,722
What's the best way to implement user controls in ASP.NET MVC?
Like many others on this site I am considering a move to ASP.NET MVC for future projects. Currently my sites are running the traditional ASP.NET 2.0 Web Forms, and it works OK for us, so my other option is just to stick with what I know and make the move to ASP.NET 3.5 with the integrated AJAX stuff. I'm wondering about how user controls work in ASP.NET MVC. We have tons of.ASCX controls, and a few composite controls. When I work with web designers it is very easy to get them to use ASCX controls effectively, even without any programming knowledge, so that's a definite plus. But then of course the downsides are the page life cycle, which can be maddening, and the fact that ASCX controls are hard to share between different projects. Composite controls are share-able, but basically a black box to a designer. What's the model in ASP.NET MVC? Is there a way to create controls that solves the problems we've dealt with using ASCX and composite controls? Allowing easy access for web designers without having to worry about code being broken is an important consideration.
To implement a user control you do the following call: <% Html.RenderPartial("~/Views/Shared/MyControl.ascx", {data model object}) %> You may also see the older syntax which as of PR5 is not valid anymore <%= Html.RenderUserControl("~/Views/Shared/MyControl.ascx", {data model object}) %> You will always have to worry about code breaking when moving from Web Forms to MVC, however the ASP.NET MVC team has done a great job to minimize the problems.
What's the best way to implement user controls in ASP.NET MVC? Like many others on this site I am considering a move to ASP.NET MVC for future projects. Currently my sites are running the traditional ASP.NET 2.0 Web Forms, and it works OK for us, so my other option is just to stick with what I know and make the move to ASP.NET 3.5 with the integrated AJAX stuff. I'm wondering about how user controls work in ASP.NET MVC. We have tons of.ASCX controls, and a few composite controls. When I work with web designers it is very easy to get them to use ASCX controls effectively, even without any programming knowledge, so that's a definite plus. But then of course the downsides are the page life cycle, which can be maddening, and the fact that ASCX controls are hard to share between different projects. Composite controls are share-able, but basically a black box to a designer. What's the model in ASP.NET MVC? Is there a way to create controls that solves the problems we've dealt with using ASCX and composite controls? Allowing easy access for web designers without having to worry about code being broken is an important consideration.
TITLE: What's the best way to implement user controls in ASP.NET MVC? QUESTION: Like many others on this site I am considering a move to ASP.NET MVC for future projects. Currently my sites are running the traditional ASP.NET 2.0 Web Forms, and it works OK for us, so my other option is just to stick with what I know and make the move to ASP.NET 3.5 with the integrated AJAX stuff. I'm wondering about how user controls work in ASP.NET MVC. We have tons of.ASCX controls, and a few composite controls. When I work with web designers it is very easy to get them to use ASCX controls effectively, even without any programming knowledge, so that's a definite plus. But then of course the downsides are the page life cycle, which can be maddening, and the fact that ASCX controls are hard to share between different projects. Composite controls are share-able, but basically a black box to a designer. What's the model in ASP.NET MVC? Is there a way to create controls that solves the problems we've dealt with using ASCX and composite controls? Allowing easy access for web designers without having to worry about code being broken is an important consideration. ANSWER: To implement a user control you do the following call: <% Html.RenderPartial("~/Views/Shared/MyControl.ascx", {data model object}) %> You may also see the older syntax which as of PR5 is not valid anymore <%= Html.RenderUserControl("~/Views/Shared/MyControl.ascx", {data model object}) %> You will always have to worry about code breaking when moving from Web Forms to MVC, however the ASP.NET MVC team has done a great job to minimize the problems.
[ "asp.net-mvc", "user-controls" ]
11
8
4,790
4
0
2008-09-03T13:55:15.257000
2008-09-03T13:58:44.093000
41,724
41,743
What is a DSL and where should I use it?
I'm hearing more and more about domain specific languages being thrown about and how they change the way you treat business logic, and I've seen Ayende's blog posts and things, but I've never really gotten exactly why I would take my business logic away from the methods and situations I'm using in my provider. If you've got some background using these things, any chance you could put it in real laymans terms: What exactly building DSLs means? What languages are you using? Where using a DSL makes sense? What is the benefit of using DSLs?
DSL's are good in situations where you need to give some aspect of the system's control over to someone else. I've used them in Rules Engines, where you create a simple language that is easier for less-technical folks to use to express themselves- particularly in workflows. In other words, instead of making them learn java: DocumentDAO myDocumentDAO = ServiceLocator.getDocumentDAO(); for (int id: documentIDS) { Document myDoc = MyDocumentDAO.loadDoc(id); if (myDoc.getDocumentStatus().equals(DocumentStatus.UNREAD)) { ReminderService.sendUnreadReminder(myDoc) } I can write a DSL that lets me say: for (document: documents) { if (document is unread) { document.sendReminder } There are other situations, but basically, anywhere you might want to use a macro language, script a workflow, or allow after-market customization- these are all candidates for DSL's.
What is a DSL and where should I use it? I'm hearing more and more about domain specific languages being thrown about and how they change the way you treat business logic, and I've seen Ayende's blog posts and things, but I've never really gotten exactly why I would take my business logic away from the methods and situations I'm using in my provider. If you've got some background using these things, any chance you could put it in real laymans terms: What exactly building DSLs means? What languages are you using? Where using a DSL makes sense? What is the benefit of using DSLs?
TITLE: What is a DSL and where should I use it? QUESTION: I'm hearing more and more about domain specific languages being thrown about and how they change the way you treat business logic, and I've seen Ayende's blog posts and things, but I've never really gotten exactly why I would take my business logic away from the methods and situations I'm using in my provider. If you've got some background using these things, any chance you could put it in real laymans terms: What exactly building DSLs means? What languages are you using? Where using a DSL makes sense? What is the benefit of using DSLs? ANSWER: DSL's are good in situations where you need to give some aspect of the system's control over to someone else. I've used them in Rules Engines, where you create a simple language that is easier for less-technical folks to use to express themselves- particularly in workflows. In other words, instead of making them learn java: DocumentDAO myDocumentDAO = ServiceLocator.getDocumentDAO(); for (int id: documentIDS) { Document myDoc = MyDocumentDAO.loadDoc(id); if (myDoc.getDocumentStatus().equals(DocumentStatus.UNREAD)) { ReminderService.sendUnreadReminder(myDoc) } I can write a DSL that lets me say: for (document: documents) { if (document is unread) { document.sendReminder } There are other situations, but basically, anywhere you might want to use a macro language, script a workflow, or allow after-market customization- these are all candidates for DSL's.
[ "theory", "dsl" ]
26
22
6,589
7
0
2008-09-03T14:00:51.623000
2008-09-03T14:09:36.113000
41,733
41,951
Best way to sort an array
Say I have an array of records which I want to sort based on one of the fields in the record. What's the best way to achieve this? TExample = record SortOrder: integer; SomethingElse: string; end; var SomeVar: array of TExample;
You can add pointers to the elements of the array to a TList, then call TList.Sort with a comparison function, and finally create a new array and copy the values out of the TList in the desired order. However, if you're using the next version, D2009, there is a new collections library which can sort arrays. It takes an optional IComparer implementation for custom sorting orders. Here it is in action for your specific case: TArray.Sort (SomeVar, TDelegatedComparer.Construct( function(const Left, Right: TExample): Integer begin Result:= TComparer.Default.Compare(Left.SortOrder, Right.SortOrder); end));
Best way to sort an array Say I have an array of records which I want to sort based on one of the fields in the record. What's the best way to achieve this? TExample = record SortOrder: integer; SomethingElse: string; end; var SomeVar: array of TExample;
TITLE: Best way to sort an array QUESTION: Say I have an array of records which I want to sort based on one of the fields in the record. What's the best way to achieve this? TExample = record SortOrder: integer; SomethingElse: string; end; var SomeVar: array of TExample; ANSWER: You can add pointers to the elements of the array to a TList, then call TList.Sort with a comparison function, and finally create a new array and copy the values out of the TList in the desired order. However, if you're using the next version, D2009, there is a new collections library which can sort arrays. It takes an optional IComparer implementation for custom sorting orders. Here it is in action for your specific case: TArray.Sort (SomeVar, TDelegatedComparer.Construct( function(const Left, Right: TExample): Integer begin Result:= TComparer.Default.Compare(Left.SortOrder, Right.SortOrder); end));
[ "delphi", "arrays", "sorting" ]
33
40
53,101
10
0
2008-09-03T14:04:08.980000
2008-09-03T15:36:17.073000
41,766
41,776
How do I download code using SVN/Tortoise from Google Code?
I just saw a really cool WPF twitter client that I think is developed by the Herding Code podcast guys HerdingCode called Witty. (or at least, I see a lot of those guys using this client). This project is currently posted up on Google Code. Many of the projects on Google Code use Subversion as the version control system (including Witty). Having never used Subversion, I'm not sure what to do to download the code. On the source page for this project ( google code witty source ) it gives the following instruction: Non-members may check out a read-only working copy anonymously over HTTP. svn checkout http://wittytwitter.googlecode.com/svn/trunk/ wittytwitter-read-only I'm confused as to where I am supposed to enter the above command so that I can download the code. I have installed SVN and Tortoise (which I know almost nothing about). Thanks for any help or simply pointing me in the right direction....Ed (@emcpadden)
After you install Tortoise (separate SVN client not required), create a new empty folder for the project somewhere and right click it in Windows. There should be an option for SVN Checkout. Choosing that option will open a dialog box. Paste the URL you posted above in the first textbox of that dialog box and click "OK".
How do I download code using SVN/Tortoise from Google Code? I just saw a really cool WPF twitter client that I think is developed by the Herding Code podcast guys HerdingCode called Witty. (or at least, I see a lot of those guys using this client). This project is currently posted up on Google Code. Many of the projects on Google Code use Subversion as the version control system (including Witty). Having never used Subversion, I'm not sure what to do to download the code. On the source page for this project ( google code witty source ) it gives the following instruction: Non-members may check out a read-only working copy anonymously over HTTP. svn checkout http://wittytwitter.googlecode.com/svn/trunk/ wittytwitter-read-only I'm confused as to where I am supposed to enter the above command so that I can download the code. I have installed SVN and Tortoise (which I know almost nothing about). Thanks for any help or simply pointing me in the right direction....Ed (@emcpadden)
TITLE: How do I download code using SVN/Tortoise from Google Code? QUESTION: I just saw a really cool WPF twitter client that I think is developed by the Herding Code podcast guys HerdingCode called Witty. (or at least, I see a lot of those guys using this client). This project is currently posted up on Google Code. Many of the projects on Google Code use Subversion as the version control system (including Witty). Having never used Subversion, I'm not sure what to do to download the code. On the source page for this project ( google code witty source ) it gives the following instruction: Non-members may check out a read-only working copy anonymously over HTTP. svn checkout http://wittytwitter.googlecode.com/svn/trunk/ wittytwitter-read-only I'm confused as to where I am supposed to enter the above command so that I can download the code. I have installed SVN and Tortoise (which I know almost nothing about). Thanks for any help or simply pointing me in the right direction....Ed (@emcpadden) ANSWER: After you install Tortoise (separate SVN client not required), create a new empty folder for the project somewhere and right click it in Windows. There should be an option for SVN Checkout. Choosing that option will open a dialog box. Paste the URL you posted above in the first textbox of that dialog box and click "OK".
[ "svn", "tortoisesvn", "google-code" ]
88
100
163,451
9
0
2008-09-03T14:19:55.433000
2008-09-03T14:23:27.920000
41,792
41,820
Instance constructor sets a static member, is it thread safe?
I am re-factoring some code and am wondering about the use of a lock in the instance constructor. public class MyClass { private static Int32 counter = 0; private Int32 myCount; public MyClass() { lock(this) { counter++; myCount = counter; } } } Please confirm Instance constructors are thread-safe. The lock statement prevents access to that code block, not to the static 'counter' member. If the intent of the original programmer were to have each instance know its 'count', how would I synchronize access to the 'counter' member to ensure that another thread isn't new'ing a MyClass and changing the count before this one sets its count? FYI - This class is not a singleton. Instances must simply be aware of their number.
@ajmastrean I am not saying you should use the singleton pattern itself, but adopt its method of encapsulating the instantiation process. i.e. Make the constructor private. Create a static instance method that returns the type. In the static instance method, use the lock keyword before instantiating. Instantiate a new instance of the type. Increment the count. Unlock and return the new instance. EDIT One problem that has occurred to me, if how would you know when the count has gone down?;) EDIT AGAIN Thinking about it, you could add code to the destructor that calls another static method to decrement the counter:D
Instance constructor sets a static member, is it thread safe? I am re-factoring some code and am wondering about the use of a lock in the instance constructor. public class MyClass { private static Int32 counter = 0; private Int32 myCount; public MyClass() { lock(this) { counter++; myCount = counter; } } } Please confirm Instance constructors are thread-safe. The lock statement prevents access to that code block, not to the static 'counter' member. If the intent of the original programmer were to have each instance know its 'count', how would I synchronize access to the 'counter' member to ensure that another thread isn't new'ing a MyClass and changing the count before this one sets its count? FYI - This class is not a singleton. Instances must simply be aware of their number.
TITLE: Instance constructor sets a static member, is it thread safe? QUESTION: I am re-factoring some code and am wondering about the use of a lock in the instance constructor. public class MyClass { private static Int32 counter = 0; private Int32 myCount; public MyClass() { lock(this) { counter++; myCount = counter; } } } Please confirm Instance constructors are thread-safe. The lock statement prevents access to that code block, not to the static 'counter' member. If the intent of the original programmer were to have each instance know its 'count', how would I synchronize access to the 'counter' member to ensure that another thread isn't new'ing a MyClass and changing the count before this one sets its count? FYI - This class is not a singleton. Instances must simply be aware of their number. ANSWER: @ajmastrean I am not saying you should use the singleton pattern itself, but adopt its method of encapsulating the instantiation process. i.e. Make the constructor private. Create a static instance method that returns the type. In the static instance method, use the lock keyword before instantiating. Instantiate a new instance of the type. Increment the count. Unlock and return the new instance. EDIT One problem that has occurred to me, if how would you know when the count has gone down?;) EDIT AGAIN Thinking about it, you could add code to the destructor that calls another static method to decrement the counter:D
[ "c#", ".net", "multithreading", "thread-safety" ]
6
3
4,066
7
0
2008-09-03T14:28:57.423000
2008-09-03T14:41:55.380000
41,832
41,859
Maintain the correct version for a COM dll referenced in a .NET project
I want to reference a COM DLL in a.NET project, but I also want to make sure that the interop DLL created will have the correct version (so that patches will know when the DLL must be changed). If I use TlbImp I can specify the required version with the /asmversion flag but when I add it directly from Visual Studio it gets a version that has nothing to do with the original COM DLL's version. I tried changing the version in the.vcproj file {459F8813-D74D-DEAD-BEEF-00CAFEBABEA5} 1 0 0 tlbimp False But then the project failed to build with the following error: error CS0246: The type or namespace name 'MYDLLLib' could not be found (are you missing a using directive or an assembly reference?) Is there any way to get this done without creating all my COM references with TlbImp in advance? If the answer is yes is there a way to specify a build number in addition to the major and minor versions? (e.g 1.2. 42.0)
The Guid refers to the Guid for the TypeLib not the DLL directly. The version numbers refer to the TypeLib's version not the DLLs. The version number will come from your idl file, and I believe it only supports a major and minor version and not a build version. Is this version changing when you modify the typelib? The version numbers will appear in the registry under: HKEY_CLASSES_ROOT\Typelib\{typelib uuid}\Major.Minor If the minor version is set to 0 then I believe it will import the 'latest' version that matches the major version, but the major version must be set to something.
Maintain the correct version for a COM dll referenced in a .NET project I want to reference a COM DLL in a.NET project, but I also want to make sure that the interop DLL created will have the correct version (so that patches will know when the DLL must be changed). If I use TlbImp I can specify the required version with the /asmversion flag but when I add it directly from Visual Studio it gets a version that has nothing to do with the original COM DLL's version. I tried changing the version in the.vcproj file {459F8813-D74D-DEAD-BEEF-00CAFEBABEA5} 1 0 0 tlbimp False But then the project failed to build with the following error: error CS0246: The type or namespace name 'MYDLLLib' could not be found (are you missing a using directive or an assembly reference?) Is there any way to get this done without creating all my COM references with TlbImp in advance? If the answer is yes is there a way to specify a build number in addition to the major and minor versions? (e.g 1.2. 42.0)
TITLE: Maintain the correct version for a COM dll referenced in a .NET project QUESTION: I want to reference a COM DLL in a.NET project, but I also want to make sure that the interop DLL created will have the correct version (so that patches will know when the DLL must be changed). If I use TlbImp I can specify the required version with the /asmversion flag but when I add it directly from Visual Studio it gets a version that has nothing to do with the original COM DLL's version. I tried changing the version in the.vcproj file {459F8813-D74D-DEAD-BEEF-00CAFEBABEA5} 1 0 0 tlbimp False But then the project failed to build with the following error: error CS0246: The type or namespace name 'MYDLLLib' could not be found (are you missing a using directive or an assembly reference?) Is there any way to get this done without creating all my COM references with TlbImp in advance? If the answer is yes is there a way to specify a build number in addition to the major and minor versions? (e.g 1.2. 42.0) ANSWER: The Guid refers to the Guid for the TypeLib not the DLL directly. The version numbers refer to the TypeLib's version not the DLLs. The version number will come from your idl file, and I believe it only supports a major and minor version and not a build version. Is this version changing when you modify the typelib? The version numbers will appear in the registry under: HKEY_CLASSES_ROOT\Typelib\{typelib uuid}\Major.Minor If the minor version is set to 0 then I believe it will import the 'latest' version that matches the major version, but the major version must be set to something.
[ ".net", "c++", "com" ]
2
2
1,076
1
0
2008-09-03T14:45:16.697000
2008-09-03T14:56:05.470000
41,836
2,227,991
Setting include path in PHP intermittently fails
I have tried both of: ini_set('include_path', '.:/usr/share/php5:/usr/share/php5/PEAR:lib:app/classes'); and also: php_value include_path ".:/usr/share/php5:/usr/share/php5/PEAR:lib:app/classes" in the.htaccess file. Both methods actually do work but only intermittently. That is, they will work fine for about 37 pages requests and then fail about 42 pages requests resulting in an require() call to cause a fatal error effectively crashing the site. I'm not even sure where to begin trying to find out what is going on! @ cnote Looks like you duplicated the current directory in your include path. Try removing one of the '.:' from your string. The in script version was originally ini_set('include_path', ini_get('include_path'). PATH_SEPARATOR. 'lib'. PATH_SEPARATOR. 'app'. DIRECTORY_SEPARATOR. 'classes'); and thus the.:.: was coming from the existing path: ini_get('include_path') I tried removing it anyway and the problem persists.
It turned out the issue was related to a PHP bug in 5.2.5 Setting an "admin_flag" for include_path caused the include path to be empty in some requests, and Plesk sets an admin_flag in the default config for something or other. An update of PHP solved the issue. http://bugs.php.net/bug.php?id=43677
Setting include path in PHP intermittently fails I have tried both of: ini_set('include_path', '.:/usr/share/php5:/usr/share/php5/PEAR:lib:app/classes'); and also: php_value include_path ".:/usr/share/php5:/usr/share/php5/PEAR:lib:app/classes" in the.htaccess file. Both methods actually do work but only intermittently. That is, they will work fine for about 37 pages requests and then fail about 42 pages requests resulting in an require() call to cause a fatal error effectively crashing the site. I'm not even sure where to begin trying to find out what is going on! @ cnote Looks like you duplicated the current directory in your include path. Try removing one of the '.:' from your string. The in script version was originally ini_set('include_path', ini_get('include_path'). PATH_SEPARATOR. 'lib'. PATH_SEPARATOR. 'app'. DIRECTORY_SEPARATOR. 'classes'); and thus the.:.: was coming from the existing path: ini_get('include_path') I tried removing it anyway and the problem persists.
TITLE: Setting include path in PHP intermittently fails QUESTION: I have tried both of: ini_set('include_path', '.:/usr/share/php5:/usr/share/php5/PEAR:lib:app/classes'); and also: php_value include_path ".:/usr/share/php5:/usr/share/php5/PEAR:lib:app/classes" in the.htaccess file. Both methods actually do work but only intermittently. That is, they will work fine for about 37 pages requests and then fail about 42 pages requests resulting in an require() call to cause a fatal error effectively crashing the site. I'm not even sure where to begin trying to find out what is going on! @ cnote Looks like you duplicated the current directory in your include path. Try removing one of the '.:' from your string. The in script version was originally ini_set('include_path', ini_get('include_path'). PATH_SEPARATOR. 'lib'. PATH_SEPARATOR. 'app'. DIRECTORY_SEPARATOR. 'classes'); and thus the.:.: was coming from the existing path: ini_get('include_path') I tried removing it anyway and the problem persists. ANSWER: It turned out the issue was related to a PHP bug in 5.2.5 Setting an "admin_flag" for include_path caused the include path to be empty in some requests, and Plesk sets an admin_flag in the default config for something or other. An update of PHP solved the issue. http://bugs.php.net/bug.php?id=43677
[ "php", "include-path" ]
2
3
953
3
0
2008-09-03T14:47:35.147000
2010-02-09T09:32:29.833000
41,837
41,899
Cost of Inserts vs Update in SQL Server
I have a table with more than a millon rows. This table is used to index tiff images. Each image has fields like date, number, etc. I have users that index these images in batches of 500. I need to know if it is better to first insert 500 rows and then perform 500 updates or, when the user finishes indexing, to do the 500 inserts with all the data. A very important thing is that if I do the 500 inserts at first, this time is free for me because I can do it the night before. So the question is: is it better to do inserts or inserts and updates, and why? I have defined a id value for each image, and I also have other indices on the fields.
Updates in Sql server result in ghosted rows - i.e. Sql crosses one row out and puts a new one in. The crossed out row is deleted later. Both inserts and updates can cause page-splits in this way, they both effectively 'add' data, it's just that updates flag the old stuff out first. On top of this updates need to look up the row first, which for lots of data can take longer than the update. Inserts will just about always be quicker, especially if they are either in order or if the underlying table doesn't have a clustered index. When inserting larger amounts of data into a table look at the current indexes - they can take a while to change and build. Adding values in the middle of an index is always slower. You can think of it like appending to an address book: Mr Z can just be added to the last page, while you'll have to find space in the middle for Mr M.
Cost of Inserts vs Update in SQL Server I have a table with more than a millon rows. This table is used to index tiff images. Each image has fields like date, number, etc. I have users that index these images in batches of 500. I need to know if it is better to first insert 500 rows and then perform 500 updates or, when the user finishes indexing, to do the 500 inserts with all the data. A very important thing is that if I do the 500 inserts at first, this time is free for me because I can do it the night before. So the question is: is it better to do inserts or inserts and updates, and why? I have defined a id value for each image, and I also have other indices on the fields.
TITLE: Cost of Inserts vs Update in SQL Server QUESTION: I have a table with more than a millon rows. This table is used to index tiff images. Each image has fields like date, number, etc. I have users that index these images in batches of 500. I need to know if it is better to first insert 500 rows and then perform 500 updates or, when the user finishes indexing, to do the 500 inserts with all the data. A very important thing is that if I do the 500 inserts at first, this time is free for me because I can do it the night before. So the question is: is it better to do inserts or inserts and updates, and why? I have defined a id value for each image, and I also have other indices on the fields. ANSWER: Updates in Sql server result in ghosted rows - i.e. Sql crosses one row out and puts a new one in. The crossed out row is deleted later. Both inserts and updates can cause page-splits in this way, they both effectively 'add' data, it's just that updates flag the old stuff out first. On top of this updates need to look up the row first, which for lots of data can take longer than the update. Inserts will just about always be quicker, especially if they are either in order or if the underlying table doesn't have a clustered index. When inserting larger amounts of data into a table look at the current indexes - they can take a while to change and build. Adding values in the middle of an index is always slower. You can think of it like appending to an address book: Mr Z can just be added to the last page, while you'll have to find space in the middle for Mr M.
[ "sql-server", "performance" ]
26
40
45,449
6
0
2008-09-03T14:47:52.400000
2008-09-03T15:13:04.523000
41,838
93,581
Black Box testing software
We are about to get a canned package in that has been modified to our needs. I'm part of the team setup to prepare tests for it. It has an Oracle back end and I believe it's written in C++.NET. My question is what free or open source testing tools would you recommend. Thanks Ken
For regression testing of our applications I use a free tool called AutoHotKey http://www.autohotkey.com/. It is simple, batch configurable, and can work for virtually any application you have. Not exactly designed for black box testing, but a good free tool to add to your toolbox. While there are a few good commercial applications for black box testing of applications (HoloDeck http://www.sisecure.com/holodeck/index.shtml, Cenzic Hailstorm http://www.cenzic.com/ ), the only open source applications that I know about only test network security (Spike http://www.immunitysec.com/resources-freesoftware.shtml, OWASP WebScarab http://www.owasp.org/index.php/Category:OWASP_WebScarab_Project, and Nikto http://www.cirt.net/nikto2 )
Black Box testing software We are about to get a canned package in that has been modified to our needs. I'm part of the team setup to prepare tests for it. It has an Oracle back end and I believe it's written in C++.NET. My question is what free or open source testing tools would you recommend. Thanks Ken
TITLE: Black Box testing software QUESTION: We are about to get a canned package in that has been modified to our needs. I'm part of the team setup to prepare tests for it. It has an Oracle back end and I believe it's written in C++.NET. My question is what free or open source testing tools would you recommend. Thanks Ken ANSWER: For regression testing of our applications I use a free tool called AutoHotKey http://www.autohotkey.com/. It is simple, batch configurable, and can work for virtually any application you have. Not exactly designed for black box testing, but a good free tool to add to your toolbox. While there are a few good commercial applications for black box testing of applications (HoloDeck http://www.sisecure.com/holodeck/index.shtml, Cenzic Hailstorm http://www.cenzic.com/ ), the only open source applications that I know about only test network security (Spike http://www.immunitysec.com/resources-freesoftware.shtml, OWASP WebScarab http://www.owasp.org/index.php/Category:OWASP_WebScarab_Project, and Nikto http://www.cirt.net/nikto2 )
[ "oracle", "testing", "black-box" ]
2
2
1,219
6
0
2008-09-03T14:48:16.660000
2008-09-18T15:28:12.223000
41,839
41,947
What is a good markup language to use for tests?
I'm writing a tool to run a series of integration tests on my product. It will install it and then run a bunch of commands against it to make sure its doing what it is supposed to. I'm exploring different options for how to markup the commands for each test case and wondering if folks had insight to share on this. I'm thinking of using YAML and doing something like this (kinda adapted from rails fixtures): case: name: caseN description: this tests foo to make sure bar happens expected_results: bar should happen commands: | command to run next command to run verification: command to see if it worked Does anyone have another, or better idea? Or is there a domain specific language I'm unaware of?
Go and have a look at the XUnit suite of test tools. This framework was originally designed for Smalltalk by Kent Beck and, I think, Erich Gamma, and it has now been ported to a whole stack of other languages, e.g. CUnit
What is a good markup language to use for tests? I'm writing a tool to run a series of integration tests on my product. It will install it and then run a bunch of commands against it to make sure its doing what it is supposed to. I'm exploring different options for how to markup the commands for each test case and wondering if folks had insight to share on this. I'm thinking of using YAML and doing something like this (kinda adapted from rails fixtures): case: name: caseN description: this tests foo to make sure bar happens expected_results: bar should happen commands: | command to run next command to run verification: command to see if it worked Does anyone have another, or better idea? Or is there a domain specific language I'm unaware of?
TITLE: What is a good markup language to use for tests? QUESTION: I'm writing a tool to run a series of integration tests on my product. It will install it and then run a bunch of commands against it to make sure its doing what it is supposed to. I'm exploring different options for how to markup the commands for each test case and wondering if folks had insight to share on this. I'm thinking of using YAML and doing something like this (kinda adapted from rails fixtures): case: name: caseN description: this tests foo to make sure bar happens expected_results: bar should happen commands: | command to run next command to run verification: command to see if it worked Does anyone have another, or better idea? Or is there a domain specific language I'm unaware of? ANSWER: Go and have a look at the XUnit suite of test tools. This framework was originally designed for Smalltalk by Kent Beck and, I think, Erich Gamma, and it has now been ported to a whole stack of other languages, e.g. CUnit
[ "testing", "integration-testing" ]
1
2
281
3
0
2008-09-03T14:48:48.187000
2008-09-03T15:32:49.423000
41,842
41,871
PDB files for production app and the "Optimize code" flag
When should I include PDB files for a production release? Should I use the Optimize code flag and how would that affect the information I get from an exception? If there is a noticeable performance benefit I would want to use the optimizations but if not I'd rather have accurate debugging info. What is typically done for a production app?
When you want to see source filenames and line numbers in your stacktraces, generate PDBs using the pdb-only option. Optimization is separate from PDB generation, i.e. you can optimize and generate PDBs without a performance hit. From the C# Language Reference If you use /debug:full, be aware that there is some impact on the speed and size of JIT optimized code and a small impact on code quality with /debug:full. We recommend /debug:pdbonly or no PDB for generating release code.
PDB files for production app and the "Optimize code" flag When should I include PDB files for a production release? Should I use the Optimize code flag and how would that affect the information I get from an exception? If there is a noticeable performance benefit I would want to use the optimizations but if not I'd rather have accurate debugging info. What is typically done for a production app?
TITLE: PDB files for production app and the "Optimize code" flag QUESTION: When should I include PDB files for a production release? Should I use the Optimize code flag and how would that affect the information I get from an exception? If there is a noticeable performance benefit I would want to use the optimizations but if not I'd rather have accurate debugging info. What is typically done for a production app? ANSWER: When you want to see source filenames and line numbers in your stacktraces, generate PDBs using the pdb-only option. Optimization is separate from PDB generation, i.e. you can optimize and generate PDBs without a performance hit. From the C# Language Reference If you use /debug:full, be aware that there is some impact on the speed and size of JIT optimized code and a small impact on code quality with /debug:full. We recommend /debug:pdbonly or no PDB for generating release code.
[ "c#", "visual-studio", "build-process" ]
17
19
6,327
3
0
2008-09-03T14:50:03.223000
2008-09-03T15:03:14.220000
41,857
41,875
Recommendations for Web application performance benchmarks
I'm about to start testing an intranet web application. Specifically, I've to determine the application's performance. Please could someone suggest formal/informal standards for how I can judge the application's performance.
Use some tool for stress and load testing. If you're using Java take a look at JMeter. It provides different methods to test you application performance. You should focus on: Response time: How fast your application is running for normal requests. Test some read/write use case Load test: How your application behaves in high traffic times. The tool will submit several requests (you can configure that properly) during a period of time. Stress test: Do your application can operate during a long period of time? This test will push your application to the limits Start with this, if you're interested, there are other kinds of tests.
Recommendations for Web application performance benchmarks I'm about to start testing an intranet web application. Specifically, I've to determine the application's performance. Please could someone suggest formal/informal standards for how I can judge the application's performance.
TITLE: Recommendations for Web application performance benchmarks QUESTION: I'm about to start testing an intranet web application. Specifically, I've to determine the application's performance. Please could someone suggest formal/informal standards for how I can judge the application's performance. ANSWER: Use some tool for stress and load testing. If you're using Java take a look at JMeter. It provides different methods to test you application performance. You should focus on: Response time: How fast your application is running for normal requests. Test some read/write use case Load test: How your application behaves in high traffic times. The tool will submit several requests (you can configure that properly) during a period of time. Stress test: Do your application can operate during a long period of time? This test will push your application to the limits Start with this, if you're interested, there are other kinds of tests.
[ "performance", "testing", "web-applications", "benchmarking" ]
7
8
11,694
4
0
2008-09-03T14:55:40.027000
2008-09-03T15:04:41.517000
41,869
152,695
Is SQL Server Bulk Insert Transactional?
If I run the following query in SQL Server 2000 Query Analyzer: BULK INSERT OurTable FROM 'c:\OurTable.txt' WITH (CODEPAGE = 'RAW', DATAFILETYPE = 'char', FIELDTERMINATOR = '\t', ROWS_PER_BATCH = 10000, TABLOCK) On a text file that conforms to OurTable's schema for 40 lines, but then changes format for the last 20 lines (lets say the last 20 lines have fewer fields), I receive an error. However, the first 40 lines are committed to the table. Is there something about the way I'm calling Bulk Insert that makes it not be transactional, or do I need to do something explicit to force it to rollback on failure?
BULK INSERT acts as a series of individual INSERT statements and thus, if the job fails, it doesn't roll back all of the committed inserts. It can, however, be placed within a transaction so you could do something like this: BEGIN TRANSACTION BEGIN TRY BULK INSERT OurTable FROM 'c:\OurTable.txt' WITH (CODEPAGE = 'RAW', DATAFILETYPE = 'char', FIELDTERMINATOR = '\t', ROWS_PER_BATCH = 10000, TABLOCK) COMMIT TRANSACTION END TRY BEGIN CATCH ROLLBACK TRANSACTION END CATCH
Is SQL Server Bulk Insert Transactional? If I run the following query in SQL Server 2000 Query Analyzer: BULK INSERT OurTable FROM 'c:\OurTable.txt' WITH (CODEPAGE = 'RAW', DATAFILETYPE = 'char', FIELDTERMINATOR = '\t', ROWS_PER_BATCH = 10000, TABLOCK) On a text file that conforms to OurTable's schema for 40 lines, but then changes format for the last 20 lines (lets say the last 20 lines have fewer fields), I receive an error. However, the first 40 lines are committed to the table. Is there something about the way I'm calling Bulk Insert that makes it not be transactional, or do I need to do something explicit to force it to rollback on failure?
TITLE: Is SQL Server Bulk Insert Transactional? QUESTION: If I run the following query in SQL Server 2000 Query Analyzer: BULK INSERT OurTable FROM 'c:\OurTable.txt' WITH (CODEPAGE = 'RAW', DATAFILETYPE = 'char', FIELDTERMINATOR = '\t', ROWS_PER_BATCH = 10000, TABLOCK) On a text file that conforms to OurTable's schema for 40 lines, but then changes format for the last 20 lines (lets say the last 20 lines have fewer fields), I receive an error. However, the first 40 lines are committed to the table. Is there something about the way I'm calling Bulk Insert that makes it not be transactional, or do I need to do something explicit to force it to rollback on failure? ANSWER: BULK INSERT acts as a series of individual INSERT statements and thus, if the job fails, it doesn't roll back all of the committed inserts. It can, however, be placed within a transaction so you could do something like this: BEGIN TRANSACTION BEGIN TRY BULK INSERT OurTable FROM 'c:\OurTable.txt' WITH (CODEPAGE = 'RAW', DATAFILETYPE = 'char', FIELDTERMINATOR = '\t', ROWS_PER_BATCH = 10000, TABLOCK) COMMIT TRANSACTION END TRY BEGIN CATCH ROLLBACK TRANSACTION END CATCH
[ "sql-server", "transactions", "bulkinsert" ]
19
26
27,552
4
0
2008-09-03T15:01:53.863000
2008-09-30T11:50:58.193000
41,894
41,904
$0 (Program Name) in Java? Discover main class?
Is there a way to find the name of the program that is running in Java? The class of the main method would be good enough.
Try this: StackTraceElement[] stack = Thread.currentThread ().getStackTrace (); StackTraceElement main = stack[stack.length - 1]; String mainClass = main.getClassName (); Of course, this only works if you're running from the main thread. Unfortunately I don't think there's a system property you can query to find this out. Edit: Pulling in @John Meagher's comment, which is a great idea: To expand on @jodonnell you can also get all stack traces in the system using Thread.getAllStackTraces(). From this you can search all the stack traces for the "main" Thread to determine what the main class is. This will work even if your class is not running in the main thread.
$0 (Program Name) in Java? Discover main class? Is there a way to find the name of the program that is running in Java? The class of the main method would be good enough.
TITLE: $0 (Program Name) in Java? Discover main class? QUESTION: Is there a way to find the name of the program that is running in Java? The class of the main method would be good enough. ANSWER: Try this: StackTraceElement[] stack = Thread.currentThread ().getStackTrace (); StackTraceElement main = stack[stack.length - 1]; String mainClass = main.getClassName (); Of course, this only works if you're running from the main thread. Unfortunately I don't think there's a system property you can query to find this out. Edit: Pulling in @John Meagher's comment, which is a great idea: To expand on @jodonnell you can also get all stack traces in the system using Thread.getAllStackTraces(). From this you can search all the stack traces for the "main" Thread to determine what the main class is. This will work even if your class is not running in the main thread.
[ "java" ]
54
45
28,851
8
0
2008-09-03T15:11:01.813000
2008-09-03T15:13:51.370000
41,898
41,913
How do you choose an open-source license?
I'm a software engineer, not a lawyer, and my university doesn't offer any courses geared toward licensing software. In fact, their law-related courses are lacking (but slowly growing in number). Where can I go to learn about open-source licenses and how to choose them?
There are lots described here: http://www.gnu.org/licenses/license-list.html#SoftwareLicenses The decision of which one to use can be political, but should ultimately be determined by your plans/desires for the software. If you want to ensure it is always free then choose GPL or another "Copyleft" license. If you don't mind some commercial use, choose another one that's compatible with that.
How do you choose an open-source license? I'm a software engineer, not a lawyer, and my university doesn't offer any courses geared toward licensing software. In fact, their law-related courses are lacking (but slowly growing in number). Where can I go to learn about open-source licenses and how to choose them?
TITLE: How do you choose an open-source license? QUESTION: I'm a software engineer, not a lawyer, and my university doesn't offer any courses geared toward licensing software. In fact, their law-related courses are lacking (but slowly growing in number). Where can I go to learn about open-source licenses and how to choose them? ANSWER: There are lots described here: http://www.gnu.org/licenses/license-list.html#SoftwareLicenses The decision of which one to use can be political, but should ultimately be determined by your plans/desires for the software. If you want to ensure it is always free then choose GPL or another "Copyleft" license. If you don't mind some commercial use, choose another one that's compatible with that.
[ "open-source", "licensing" ]
26
17
3,942
10
0
2008-09-03T15:12:38.567000
2008-09-03T15:16:32.940000
41,908
42,145
Customizing Visual Studio
I have been working with Visual Studio (WinForm and ASP.NET applications using mostly C#) for several months now. For the most part my IDE is set up fairly standard but I have been wondering what are some suggestions in terms of plugins/settings that you find to be the most useful? Update: Thanks for all the great suggestions. It looks like a general consensus that I should look into 'Resharper' along with some eye-candy with themes and custom fonts. Themes Consolas Font Pack for Visual Studio 2005/2008 Scott Hanselman's Visual Studio Themes Gallery Visual Studio Theme Generator Free Tools PowerCommands for Visual Studio 2008 GhostDoc HyperAddin RockScroll CodeRush XPress.NET Reflector - (Not a plugin but still useful) Paid Tools Resharper - Free (Open Source), $49 (Academic), $199 (Personal), $349 (Commercial) CodeRush with Refactor!™ Pro - $249
Resharper is definitely a great tool. It has a moderate learning curve but is easy to pick up for some simple things and add mastery later. It is a good price for students and kinda expensive for the rest of us. Resharper is similar to CodeRush, but seems to have a larger following. PowerCommands is a great set of add-ons that comes free from Microsoft. Things like "Open in Windows Explorer", "Command Prompt Here", and Copy/Paste references. A discussion regarding add-ins is floating around here somewhere. For straight-up customization, changing colors is fun, easy, and gives you a big bang for your buck. I prefer a slightly personalized version of Rob Conery's TextMate theme for Visual Studio. Once you get colors you like, you can just export the settings and carry them with you wherever you go. Related to colors and themes, the Consolas font pack is pretty nifty and easy on the eye. And like John recommends, a mastery of keyboard shortcuts will pay big dividends.
Customizing Visual Studio I have been working with Visual Studio (WinForm and ASP.NET applications using mostly C#) for several months now. For the most part my IDE is set up fairly standard but I have been wondering what are some suggestions in terms of plugins/settings that you find to be the most useful? Update: Thanks for all the great suggestions. It looks like a general consensus that I should look into 'Resharper' along with some eye-candy with themes and custom fonts. Themes Consolas Font Pack for Visual Studio 2005/2008 Scott Hanselman's Visual Studio Themes Gallery Visual Studio Theme Generator Free Tools PowerCommands for Visual Studio 2008 GhostDoc HyperAddin RockScroll CodeRush XPress.NET Reflector - (Not a plugin but still useful) Paid Tools Resharper - Free (Open Source), $49 (Academic), $199 (Personal), $349 (Commercial) CodeRush with Refactor!™ Pro - $249
TITLE: Customizing Visual Studio QUESTION: I have been working with Visual Studio (WinForm and ASP.NET applications using mostly C#) for several months now. For the most part my IDE is set up fairly standard but I have been wondering what are some suggestions in terms of plugins/settings that you find to be the most useful? Update: Thanks for all the great suggestions. It looks like a general consensus that I should look into 'Resharper' along with some eye-candy with themes and custom fonts. Themes Consolas Font Pack for Visual Studio 2005/2008 Scott Hanselman's Visual Studio Themes Gallery Visual Studio Theme Generator Free Tools PowerCommands for Visual Studio 2008 GhostDoc HyperAddin RockScroll CodeRush XPress.NET Reflector - (Not a plugin but still useful) Paid Tools Resharper - Free (Open Source), $49 (Academic), $199 (Personal), $349 (Commercial) CodeRush with Refactor!™ Pro - $249 ANSWER: Resharper is definitely a great tool. It has a moderate learning curve but is easy to pick up for some simple things and add mastery later. It is a good price for students and kinda expensive for the rest of us. Resharper is similar to CodeRush, but seems to have a larger following. PowerCommands is a great set of add-ons that comes free from Microsoft. Things like "Open in Windows Explorer", "Command Prompt Here", and Copy/Paste references. A discussion regarding add-ins is floating around here somewhere. For straight-up customization, changing colors is fun, easy, and gives you a big bang for your buck. I prefer a slightly personalized version of Rob Conery's TextMate theme for Visual Studio. Once you get colors you like, you can just export the settings and carry them with you wherever you go. Related to colors and themes, the Consolas font pack is pretty nifty and easy on the eye. And like John recommends, a mastery of keyboard shortcuts will pay big dividends.
[ "c#", "asp.net", "winforms", "visual-studio" ]
16
10
3,547
12
0
2008-09-03T15:15:24.753000
2008-09-03T17:24:46.907000
41,925
41,982
Is there a standard for storing normalized phone numbers in a database?
What is a good data structure for storing phone numbers in database fields? I'm looking for something that is flexible enough to handle international numbers, and also something that allows the various parts of the number to be queried efficiently. Edit: Just to clarify the use case here: I currently store numbers in a single varchar field, and I leave them just as the customer entered them. Then, when the number is needed by code, I normalize it. The problem is that if I want to query a few million rows to find matching phone numbers, it involves a function, like where dbo.f_normalizenum(num1) = dbo.f_normalizenum(num2) which is terribly inefficient. Also queries that are looking for things like the area code become extremely tricky when it's just a single varchar field. [Edit] People have made lots of good suggestions here, thanks! As an update, here is what I'm doing now: I still store numbers exactly as they were entered, in a varchar field, but instead of normalizing things at query time, I have a trigger that does all that work as records are inserted or updated. So I have ints or bigints for any parts that I need to query, and those fields are indexed to make queries run faster.
First, beyond the country code, there is no real standard. About the best you can do is recognize, by the country code, which nation a particular phone number belongs to and deal with the rest of the number according to that nation's format. Generally, however, phone equipment and such is standardized so you can almost always break a given phone number into the following components C Country code 1-10 digits (right now 4 or less, but that may change) A Area code (Province/state/region) code 0-10 digits (may actually want a region field and an area field separately, rather than one area code) E Exchange (prefix, or switch) code 0-10 digits L Line number 1-10 digits With this method you can potentially separate numbers such that you can find, for instance, people that might be close to each other because they have the same country, area, and exchange codes. With cell phones that is no longer something you can count on though. Further, inside each country there are differing standards. You can always depend on a (AAA) EEE-LLLL in the US, but in another country you may have exchanges in the cities (AAA) EE-LLL, and simply line numbers in the rural areas (AAA) LLLL. You will have to start at the top in a tree of some form, and format them as you have information. For example, country code 0 has a known format for the rest of the number, but for country code 5432 you might need to examine the area code before you understand the rest of the number. You may also want to handle vanity numbers such as (800) Lucky-Guy, which requires recognizing that, if it's a US number, there's one too many digits (and you may need to full representation for advertising or other purposes) and that in the US the letters map to the numbers differently than in Germany. You may also want to store the entire number separately as a text field (with internationalization) so you can go back later and re-parse numbers as things change, or as a backup in case someone submits a bad method to parse a particular country's format and loses information.
Is there a standard for storing normalized phone numbers in a database? What is a good data structure for storing phone numbers in database fields? I'm looking for something that is flexible enough to handle international numbers, and also something that allows the various parts of the number to be queried efficiently. Edit: Just to clarify the use case here: I currently store numbers in a single varchar field, and I leave them just as the customer entered them. Then, when the number is needed by code, I normalize it. The problem is that if I want to query a few million rows to find matching phone numbers, it involves a function, like where dbo.f_normalizenum(num1) = dbo.f_normalizenum(num2) which is terribly inefficient. Also queries that are looking for things like the area code become extremely tricky when it's just a single varchar field. [Edit] People have made lots of good suggestions here, thanks! As an update, here is what I'm doing now: I still store numbers exactly as they were entered, in a varchar field, but instead of normalizing things at query time, I have a trigger that does all that work as records are inserted or updated. So I have ints or bigints for any parts that I need to query, and those fields are indexed to make queries run faster.
TITLE: Is there a standard for storing normalized phone numbers in a database? QUESTION: What is a good data structure for storing phone numbers in database fields? I'm looking for something that is flexible enough to handle international numbers, and also something that allows the various parts of the number to be queried efficiently. Edit: Just to clarify the use case here: I currently store numbers in a single varchar field, and I leave them just as the customer entered them. Then, when the number is needed by code, I normalize it. The problem is that if I want to query a few million rows to find matching phone numbers, it involves a function, like where dbo.f_normalizenum(num1) = dbo.f_normalizenum(num2) which is terribly inefficient. Also queries that are looking for things like the area code become extremely tricky when it's just a single varchar field. [Edit] People have made lots of good suggestions here, thanks! As an update, here is what I'm doing now: I still store numbers exactly as they were entered, in a varchar field, but instead of normalizing things at query time, I have a trigger that does all that work as records are inserted or updated. So I have ints or bigints for any parts that I need to query, and those fields are indexed to make queries run faster. ANSWER: First, beyond the country code, there is no real standard. About the best you can do is recognize, by the country code, which nation a particular phone number belongs to and deal with the rest of the number according to that nation's format. Generally, however, phone equipment and such is standardized so you can almost always break a given phone number into the following components C Country code 1-10 digits (right now 4 or less, but that may change) A Area code (Province/state/region) code 0-10 digits (may actually want a region field and an area field separately, rather than one area code) E Exchange (prefix, or switch) code 0-10 digits L Line number 1-10 digits With this method you can potentially separate numbers such that you can find, for instance, people that might be close to each other because they have the same country, area, and exchange codes. With cell phones that is no longer something you can count on though. Further, inside each country there are differing standards. You can always depend on a (AAA) EEE-LLLL in the US, but in another country you may have exchanges in the cities (AAA) EE-LLL, and simply line numbers in the rural areas (AAA) LLLL. You will have to start at the top in a tree of some form, and format them as you have information. For example, country code 0 has a known format for the rest of the number, but for country code 5432 you might need to examine the area code before you understand the rest of the number. You may also want to handle vanity numbers such as (800) Lucky-Guy, which requires recognizing that, if it's a US number, there's one too many digits (and you may need to full representation for advertising or other purposes) and that in the US the letters map to the numbers differently than in Germany. You may also want to store the entire number separately as a text field (with internationalization) so you can go back later and re-parse numbers as things change, or as a backup in case someone submits a bad method to parse a particular country's format and loses information.
[ "database" ]
103
84
65,055
18
0
2008-09-03T15:22:33.863000
2008-09-03T15:54:43.737000
41,928
627,554
LightWindow & IE7, "Line 444 - object does not support this property or method"
I have just received and bypassed a problem with LightWindow and IE7 where, on page load, it throws a JavaScript error on line 444 of lightwindow.js, claiming that the object does not support this property or method. Despite finding various postings on various forums, no Google result I could find had a solution, so I am posting this here in the hopes that it will help someone / myself later. Many suggested a specific order of the script files but I was already using this order (prototype, scriptaculous, lightwindow). These are the steps I took that seemed to finally work, I write them here only as a record as I do not know nor have time to test which ones specifically "fixed" the issue: Moved the call to lightwindow.js to the bottom of the page. Changed line 444 to: if (this._getGalleryInfo(link.rel)) { Changed line 1157 to: if (this._getGalleryInfo(this.element.rel)) { Finally, I enclosed (and this is dirty, my apologies) lines 1417 to 1474 with a try/catch block, swallowing the exception. EDIT: I realised that this broke Firefox. Adding the following as line 445 now makes it work - try { gallery = this._getGalleryInfo(link.rel); } catch (e) { } It's not a very nice fix, but my page (which contains a lightwindow link with no "rel" tag, several lightwindow links which do have "rel" tags, and one "inline" link) works just fine in IE7 now. Please comment if you have anything to add about this issue or problems with / improvements to my given solution.
I fixed this by changing line 444 to: var gallery = this._getGalleryInfo(link.rel) Then changing the subsequent comparison statement to: if(gallery.length > 0) { // Rest of code here......which seems to have sorted it in IE6+ and kept it working in Firefox etc. I didn't change line 1157 at all, but I haven't read the code to see what I actually does so I can't comment on its relevance? I suspect the? used in the example rel attribute (Evoution?[man]) may be causing the problem with IE but without spending some time testing a few things, I can't be sure? HTH.
LightWindow & IE7, "Line 444 - object does not support this property or method" I have just received and bypassed a problem with LightWindow and IE7 where, on page load, it throws a JavaScript error on line 444 of lightwindow.js, claiming that the object does not support this property or method. Despite finding various postings on various forums, no Google result I could find had a solution, so I am posting this here in the hopes that it will help someone / myself later. Many suggested a specific order of the script files but I was already using this order (prototype, scriptaculous, lightwindow). These are the steps I took that seemed to finally work, I write them here only as a record as I do not know nor have time to test which ones specifically "fixed" the issue: Moved the call to lightwindow.js to the bottom of the page. Changed line 444 to: if (this._getGalleryInfo(link.rel)) { Changed line 1157 to: if (this._getGalleryInfo(this.element.rel)) { Finally, I enclosed (and this is dirty, my apologies) lines 1417 to 1474 with a try/catch block, swallowing the exception. EDIT: I realised that this broke Firefox. Adding the following as line 445 now makes it work - try { gallery = this._getGalleryInfo(link.rel); } catch (e) { } It's not a very nice fix, but my page (which contains a lightwindow link with no "rel" tag, several lightwindow links which do have "rel" tags, and one "inline" link) works just fine in IE7 now. Please comment if you have anything to add about this issue or problems with / improvements to my given solution.
TITLE: LightWindow & IE7, "Line 444 - object does not support this property or method" QUESTION: I have just received and bypassed a problem with LightWindow and IE7 where, on page load, it throws a JavaScript error on line 444 of lightwindow.js, claiming that the object does not support this property or method. Despite finding various postings on various forums, no Google result I could find had a solution, so I am posting this here in the hopes that it will help someone / myself later. Many suggested a specific order of the script files but I was already using this order (prototype, scriptaculous, lightwindow). These are the steps I took that seemed to finally work, I write them here only as a record as I do not know nor have time to test which ones specifically "fixed" the issue: Moved the call to lightwindow.js to the bottom of the page. Changed line 444 to: if (this._getGalleryInfo(link.rel)) { Changed line 1157 to: if (this._getGalleryInfo(this.element.rel)) { Finally, I enclosed (and this is dirty, my apologies) lines 1417 to 1474 with a try/catch block, swallowing the exception. EDIT: I realised that this broke Firefox. Adding the following as line 445 now makes it work - try { gallery = this._getGalleryInfo(link.rel); } catch (e) { } It's not a very nice fix, but my page (which contains a lightwindow link with no "rel" tag, several lightwindow links which do have "rel" tags, and one "inline" link) works just fine in IE7 now. Please comment if you have anything to add about this issue or problems with / improvements to my given solution. ANSWER: I fixed this by changing line 444 to: var gallery = this._getGalleryInfo(link.rel) Then changing the subsequent comparison statement to: if(gallery.length > 0) { // Rest of code here......which seems to have sorted it in IE6+ and kept it working in Firefox etc. I didn't change line 1157 at all, but I haven't read the code to see what I actually does so I can't comment on its relevance? I suspect the? used in the example rel attribute (Evoution?[man]) may be causing the problem with IE but without spending some time testing a few things, I can't be sure? HTH.
[ "javascript", "debugging", "internet-explorer-7", "lightwindow" ]
0
0
2,807
3
0
2008-09-03T15:23:16.870000
2009-03-09T18:53:39.613000
41,934
3,693,293
How can I make Eclipse file search not include svn directories?
When I do a file search on eclipse it includes the.svn directories by default. I tried excluding them from the build path but they still appear on file search results.
Spaceman is right. With Helios, choose Project -> Properties -> Resource -> Resource Filters and then add an exclude filter for type "Folder" with name.svn.
How can I make Eclipse file search not include svn directories? When I do a file search on eclipse it includes the.svn directories by default. I tried excluding them from the build path but they still appear on file search results.
TITLE: How can I make Eclipse file search not include svn directories? QUESTION: When I do a file search on eclipse it includes the.svn directories by default. I tried excluding them from the build path but they still appear on file search results. ANSWER: Spaceman is right. With Helios, choose Project -> Properties -> Resource -> Resource Filters and then add an exclude filter for type "Folder" with name.svn.
[ "eclipse", "svn" ]
58
106
20,478
9
0
2008-09-03T15:27:19.670000
2010-09-12T00:48:16.483000
41,937
42,002
Converting latitude/longitude to Alberta 10 TM Projection
I need to convert latitude/longitude coordinates into Easting/Northing coordinates in the Alberta 10 TM Projection. The 10 TM projection is similar to UTM, but it is a custom projection for the province of Alberta, Canada. I think (with some effort) I could code it myself but would rather not reinvent the wheel if it's been done already.
Grab PROJ Cartographic Projections library - open source library. Suggested parameters for 10TM: +proj=tmerc +lon_0=-115 +k_0=0.9992 +x_0=500000 +datum=NAD27 According to this post you may need to: change the ellps to GRS80 if your 10TM data is referenced to the NAD83 datum (instead of NAD27/clrk66). You may also need to change the false northing (y_0) to be -5000000 if your 10TM coordinates for Alberta are less than 5,000,000 (an AltaLIS "standard"). I should mention that proj.4 is the library to get for any kind of geographic coordinate system transformation. There's pretty much no transformation it can't do. I also recommend reading Map Projections-A Working Manual (Paperback) by John Snyder if you are into these kinds of things.. it's a classic.:) (fixed the link)
Converting latitude/longitude to Alberta 10 TM Projection I need to convert latitude/longitude coordinates into Easting/Northing coordinates in the Alberta 10 TM Projection. The 10 TM projection is similar to UTM, but it is a custom projection for the province of Alberta, Canada. I think (with some effort) I could code it myself but would rather not reinvent the wheel if it's been done already.
TITLE: Converting latitude/longitude to Alberta 10 TM Projection QUESTION: I need to convert latitude/longitude coordinates into Easting/Northing coordinates in the Alberta 10 TM Projection. The 10 TM projection is similar to UTM, but it is a custom projection for the province of Alberta, Canada. I think (with some effort) I could code it myself but would rather not reinvent the wheel if it's been done already. ANSWER: Grab PROJ Cartographic Projections library - open source library. Suggested parameters for 10TM: +proj=tmerc +lon_0=-115 +k_0=0.9992 +x_0=500000 +datum=NAD27 According to this post you may need to: change the ellps to GRS80 if your 10TM data is referenced to the NAD83 datum (instead of NAD27/clrk66). You may also need to change the false northing (y_0) to be -5000000 if your 10TM coordinates for Alberta are less than 5,000,000 (an AltaLIS "standard"). I should mention that proj.4 is the library to get for any kind of geographic coordinate system transformation. There's pretty much no transformation it can't do. I also recommend reading Map Projections-A Working Manual (Paperback) by John Snyder if you are into these kinds of things.. it's a classic.:) (fixed the link)
[ "gis", "latitude-longitude", "proj4js", "proj" ]
6
12
12,967
7
0
2008-09-03T15:29:24.360000
2008-09-03T16:02:20.333000
41,948
41,960
How do I get the difference between two Dates in JavaScript?
I'm creating an application which lets you define events with a time frame. I want to automatically fill in the end date when the user selects or changes the start date. I can't quite figure out, however, how to get the difference between the two times, and then how to create a new end Date using that difference.
In JavaScript, dates can be transformed to the number of milliseconds since the epoc by calling the getTime() method or just using the date in a numeric expression. So to get the difference, just subtract the two dates. To create a new date based on the difference, just pass the number of milliseconds in the constructor. var oldBegin =... var oldEnd =... var newBegin =... var newEnd = new Date(newBegin + oldEnd - oldBegin); This should just work EDIT: Fixed bug pointed by @bdukes EDIT: For an explanation of the behavior, oldBegin, oldEnd, and newBegin are Date instances. Calling operators + and - will trigger Javascript auto casting and will automatically call the valueOf() prototype method of those objects. It happens that the valueOf() method is implemented in the Date object as a call to getTime(). So basically: date.getTime() === date.valueOf() === (0 + date) === (+date)
How do I get the difference between two Dates in JavaScript? I'm creating an application which lets you define events with a time frame. I want to automatically fill in the end date when the user selects or changes the start date. I can't quite figure out, however, how to get the difference between the two times, and then how to create a new end Date using that difference.
TITLE: How do I get the difference between two Dates in JavaScript? QUESTION: I'm creating an application which lets you define events with a time frame. I want to automatically fill in the end date when the user selects or changes the start date. I can't quite figure out, however, how to get the difference between the two times, and then how to create a new end Date using that difference. ANSWER: In JavaScript, dates can be transformed to the number of milliseconds since the epoc by calling the getTime() method or just using the date in a numeric expression. So to get the difference, just subtract the two dates. To create a new date based on the difference, just pass the number of milliseconds in the constructor. var oldBegin =... var oldEnd =... var newBegin =... var newEnd = new Date(newBegin + oldEnd - oldBegin); This should just work EDIT: Fixed bug pointed by @bdukes EDIT: For an explanation of the behavior, oldBegin, oldEnd, and newBegin are Date instances. Calling operators + and - will trigger Javascript auto casting and will automatically call the valueOf() prototype method of those objects. It happens that the valueOf() method is implemented in the Date object as a call to getTime(). So basically: date.getTime() === date.valueOf() === (0 + date) === (+date)
[ "javascript", "date" ]
124
81
159,049
18
0
2008-09-03T15:34:39.137000
2008-09-03T15:42:01.787000
41,963
42,032
Are there any version control systems for 3d models / 3d data?
Well the subject is the question basically. Are there any version control systems out there for 3d models. An open source approach would be preferred of course. I am looking for functionality along the lines of subversion however more basic systems would be of interest as well. Basic operations like branching / merging / commit should be available in one form or another. UPDATE: With open source approach I don't mean free but the option of heavily expanding and customizing the system when needed UPDATE2: I don't know how to describe this in the best way but the format of the 3d model is not that important. We will be using IFC models and mostly CAD programs. The approach Adam Davis describes is probably what I am looking for.
This is going to be difficult since most 3D CAD programs do not take into account the possibility of revision, so when you load something and then save it again it may completely re-order the points (there are reasons for this, usually done for performance). Further, large models represented in a text format are huge files, and will take forever to copy/merge/etc. There is no current system that will manage this, but there's a really big need in the industry for it. I would expect such a system would have a model normalizer that converts to and from the desired CAD format and the revision format. It could then handle merges and track changes more easily. It would also need to output diffs in a form that you could open a "diffed" model in a cad program and the changes are shown in a different color or otherwise highlighted. No one is going to be able to look at a text diff and understand what they're looking at. This diffing program would ultimately need to support understanding that two models are the same even though the 0,0,0 location and rotation are not the same (difficult matching problem) and give the user some interface to allow them to help it when it gets stuck. You'd probably have to deal with the parts of the model separately (bones, mesh, textures, etc) and have a third file that synchronizes them when converting them to an inclusive model file for use and modification. It's not a trivial problem... But if you started on something that just handled meshes and open sourced it, you'd probably get a lot of people interested.
Are there any version control systems for 3d models / 3d data? Well the subject is the question basically. Are there any version control systems out there for 3d models. An open source approach would be preferred of course. I am looking for functionality along the lines of subversion however more basic systems would be of interest as well. Basic operations like branching / merging / commit should be available in one form or another. UPDATE: With open source approach I don't mean free but the option of heavily expanding and customizing the system when needed UPDATE2: I don't know how to describe this in the best way but the format of the 3d model is not that important. We will be using IFC models and mostly CAD programs. The approach Adam Davis describes is probably what I am looking for.
TITLE: Are there any version control systems for 3d models / 3d data? QUESTION: Well the subject is the question basically. Are there any version control systems out there for 3d models. An open source approach would be preferred of course. I am looking for functionality along the lines of subversion however more basic systems would be of interest as well. Basic operations like branching / merging / commit should be available in one form or another. UPDATE: With open source approach I don't mean free but the option of heavily expanding and customizing the system when needed UPDATE2: I don't know how to describe this in the best way but the format of the 3d model is not that important. We will be using IFC models and mostly CAD programs. The approach Adam Davis describes is probably what I am looking for. ANSWER: This is going to be difficult since most 3D CAD programs do not take into account the possibility of revision, so when you load something and then save it again it may completely re-order the points (there are reasons for this, usually done for performance). Further, large models represented in a text format are huge files, and will take forever to copy/merge/etc. There is no current system that will manage this, but there's a really big need in the industry for it. I would expect such a system would have a model normalizer that converts to and from the desired CAD format and the revision format. It could then handle merges and track changes more easily. It would also need to output diffs in a form that you could open a "diffed" model in a cad program and the changes are shown in a different color or otherwise highlighted. No one is going to be able to look at a text diff and understand what they're looking at. This diffing program would ultimately need to support understanding that two models are the same even though the 0,0,0 location and rotation are not the same (difficult matching problem) and give the user some interface to allow them to help it when it gets stuck. You'd probably have to deal with the parts of the model separately (bones, mesh, textures, etc) and have a third file that synchronizes them when converting them to an inclusive model file for use and modification. It's not a trivial problem... But if you started on something that just handled meshes and open sourced it, you'd probably get a lot of people interested.
[ "version-control" ]
20
18
23,724
10
0
2008-09-03T15:43:42.983000
2008-09-03T16:12:24.303000
41,969
42,046
Standard way to open a folder window in linux?
I want to open a folder window, in the appropriate file manager, from within a cross-platform (windows/mac/linux) Python application. On OSX, I can open a window in the finder with os.system('open "%s"' % foldername) and on Windows with os.startfile(foldername) What about unix/linux? Is there a standard way to do this or do I have to special case gnome/kde/etc and manually run the appropriate application (nautilus/konqueror/etc)? This looks like something that could be specified by the freedesktop.org folks (a python module, similar to webbrowser, would also be nice!).
os.system('xdg-open "%s"' % foldername) xdg-open can be used for files/urls also
Standard way to open a folder window in linux? I want to open a folder window, in the appropriate file manager, from within a cross-platform (windows/mac/linux) Python application. On OSX, I can open a window in the finder with os.system('open "%s"' % foldername) and on Windows with os.startfile(foldername) What about unix/linux? Is there a standard way to do this or do I have to special case gnome/kde/etc and manually run the appropriate application (nautilus/konqueror/etc)? This looks like something that could be specified by the freedesktop.org folks (a python module, similar to webbrowser, would also be nice!).
TITLE: Standard way to open a folder window in linux? QUESTION: I want to open a folder window, in the appropriate file manager, from within a cross-platform (windows/mac/linux) Python application. On OSX, I can open a window in the finder with os.system('open "%s"' % foldername) and on Windows with os.startfile(foldername) What about unix/linux? Is there a standard way to do this or do I have to special case gnome/kde/etc and manually run the appropriate application (nautilus/konqueror/etc)? This looks like something that could be specified by the freedesktop.org folks (a python module, similar to webbrowser, would also be nice!). ANSWER: os.system('xdg-open "%s"' % foldername) xdg-open can be used for files/urls also
[ "python", "linux", "cross-platform", "desktop" ]
13
16
11,173
3
0
2008-09-03T15:47:23.677000
2008-09-03T16:18:25.303000
41,994
42,014
Parsing an XML file in C#
What is the fastest method of parsing an XML file in C#? I'm using.Net 2.0
If you're using.Net 2 then the XmlReader and XmlDocument are about it. If you can use.Net 3.5 then the new Linq to Xml methods are a big improvement.
Parsing an XML file in C# What is the fastest method of parsing an XML file in C#? I'm using.Net 2.0
TITLE: Parsing an XML file in C# QUESTION: What is the fastest method of parsing an XML file in C#? I'm using.Net 2.0 ANSWER: If you're using.Net 2 then the XmlReader and XmlDocument are about it. If you can use.Net 3.5 then the new Linq to Xml methods are a big improvement.
[ "c#", "xml" ]
9
13
3,562
3
0
2008-09-03T16:00:08.797000
2008-09-03T16:04:56.553000
41,996
42,024
How to display line breaks in SharePoint comment history field
We have a SharePoint list setup with history enabled so the Comments field keeps all the past values. When it displays, the Comments field is void of all line breaks. However, when SharePoint e-mails the change to us, the line breaks are in there. The Description field also shows the line breaks. So, something must be stripping out the line breaks in the read-only view of the Comments field. Any idea on how to customize that so it retains the formatting in the detail view of the SharePoint list item? Update: the stock pages with this behavior are /EditForm.aspx /DispForm.aspx
What are you using to view the list? A default SharePoint view (AllItems.aspx?), or a DataFormWebPart? Something else? If you can customize the page that displays this list in SharePoint Designer, make sure this field is set to display "Rich Text" and not just "Plain Text". If this is the cause of your problem, then another symptom you might see is that certain symbols are displayed as their HTML codes (e.g. "&" as " & ").
How to display line breaks in SharePoint comment history field We have a SharePoint list setup with history enabled so the Comments field keeps all the past values. When it displays, the Comments field is void of all line breaks. However, when SharePoint e-mails the change to us, the line breaks are in there. The Description field also shows the line breaks. So, something must be stripping out the line breaks in the read-only view of the Comments field. Any idea on how to customize that so it retains the formatting in the detail view of the SharePoint list item? Update: the stock pages with this behavior are /EditForm.aspx /DispForm.aspx
TITLE: How to display line breaks in SharePoint comment history field QUESTION: We have a SharePoint list setup with history enabled so the Comments field keeps all the past values. When it displays, the Comments field is void of all line breaks. However, when SharePoint e-mails the change to us, the line breaks are in there. The Description field also shows the line breaks. So, something must be stripping out the line breaks in the read-only view of the Comments field. Any idea on how to customize that so it retains the formatting in the detail view of the SharePoint list item? Update: the stock pages with this behavior are /EditForm.aspx /DispForm.aspx ANSWER: What are you using to view the list? A default SharePoint view (AllItems.aspx?), or a DataFormWebPart? Something else? If you can customize the page that displays this list in SharePoint Designer, make sure this field is set to display "Rich Text" and not just "Plain Text". If this is the cause of your problem, then another symptom you might see is that certain symbols are displayed as their HTML codes (e.g. "&" as " & ").
[ "sharepoint" ]
1
1
3,398
1
0
2008-09-03T16:01:01.727000
2008-09-03T16:07:39.947000
42,034
42,048
What is a tuple useful for?
I am learning Python for a class now, and we just covered tuples as one of the data types. I read the Wikipedia page on it, but, I could not figure out where such a data type would be useful in practice. Can I have some examples, perhaps in Python, where an immutable set of numbers would be needed? How is this different from a list?
Tuples are used whenever you want to return multiple results from a function. Since they're immutable, they can be used as keys for a dictionary (lists can't).
What is a tuple useful for? I am learning Python for a class now, and we just covered tuples as one of the data types. I read the Wikipedia page on it, but, I could not figure out where such a data type would be useful in practice. Can I have some examples, perhaps in Python, where an immutable set of numbers would be needed? How is this different from a list?
TITLE: What is a tuple useful for? QUESTION: I am learning Python for a class now, and we just covered tuples as one of the data types. I read the Wikipedia page on it, but, I could not figure out where such a data type would be useful in practice. Can I have some examples, perhaps in Python, where an immutable set of numbers would be needed? How is this different from a list? ANSWER: Tuples are used whenever you want to return multiple results from a function. Since they're immutable, they can be used as keys for a dictionary (lists can't).
[ "python", "tuples" ]
57
66
51,708
12
0
2008-09-03T16:13:06.737000
2008-09-03T16:18:53.493000
42,068
42,073
How do I handle newlines in JSON?
I've generated some JSON and I'm trying to pull it into an object in JavaScript. I keep getting errors. Here's what I have: var data = '{"count": 1, "stack": "sometext\n\n"}'; var dataObj = eval('('+data+')'); This gives me an error: unterminated string literal With JSON.parse(data), I see similar error messages: " Unexpected token ↵ " in Chrome, and " unterminated string literal " in Firefox and IE. When I take out the \n after sometext the error goes away in both cases. I can't seem to figure out why the \n makes eval and JSON.parse fail.
This is what you want: var data = '{"count": 1, "stack": "sometext\\n\\n"}'; You need to escape the \ in your string (turning it into a double- \ ), otherwise it will become a newline in the JSON source, not the JSON data.
How do I handle newlines in JSON? I've generated some JSON and I'm trying to pull it into an object in JavaScript. I keep getting errors. Here's what I have: var data = '{"count": 1, "stack": "sometext\n\n"}'; var dataObj = eval('('+data+')'); This gives me an error: unterminated string literal With JSON.parse(data), I see similar error messages: " Unexpected token ↵ " in Chrome, and " unterminated string literal " in Firefox and IE. When I take out the \n after sometext the error goes away in both cases. I can't seem to figure out why the \n makes eval and JSON.parse fail.
TITLE: How do I handle newlines in JSON? QUESTION: I've generated some JSON and I'm trying to pull it into an object in JavaScript. I keep getting errors. Here's what I have: var data = '{"count": 1, "stack": "sometext\n\n"}'; var dataObj = eval('('+data+')'); This gives me an error: unterminated string literal With JSON.parse(data), I see similar error messages: " Unexpected token ↵ " in Chrome, and " unterminated string literal " in Firefox and IE. When I take out the \n after sometext the error goes away in both cases. I can't seem to figure out why the \n makes eval and JSON.parse fail. ANSWER: This is what you want: var data = '{"count": 1, "stack": "sometext\\n\\n"}'; You need to escape the \ in your string (turning it into a double- \ ), otherwise it will become a newline in the JSON source, not the JSON data.
[ "javascript", "json", "newline" ]
429
507
892,922
10
0
2008-09-03T16:30:12.327000
2008-09-03T16:32:16.893000
42,070
42,092
Why does the Bourne shell printf iterate over a %s argument?
What's going on here? printf.sh: #! /bin/sh NAME="George W. Bush" printf "Hello, %s\n" $NAME Command line session: $./printf.sh Hello, George Hello, W. Hello, Bush UPDATE: printf "Hello, %s\n" "$NAME" works. For why I'm not using echo, consider echo.sh: #! /bin/sh FILE="C:\tmp" echo "Filename: $FILE" Command-line: $./echo.sh Filename: C: mp The POSIX spec for echo says, "New applications are encouraged to use printf instead of echo " (for this and other reasons).
Your NAME variable is being substituted like this: printf "Hello, %s\n" George W. Bush Use this: #! /bin/sh NAME="George W. Bush" printf "Hello, %s\n" "$NAME"
Why does the Bourne shell printf iterate over a %s argument? What's going on here? printf.sh: #! /bin/sh NAME="George W. Bush" printf "Hello, %s\n" $NAME Command line session: $./printf.sh Hello, George Hello, W. Hello, Bush UPDATE: printf "Hello, %s\n" "$NAME" works. For why I'm not using echo, consider echo.sh: #! /bin/sh FILE="C:\tmp" echo "Filename: $FILE" Command-line: $./echo.sh Filename: C: mp The POSIX spec for echo says, "New applications are encouraged to use printf instead of echo " (for this and other reasons).
TITLE: Why does the Bourne shell printf iterate over a %s argument? QUESTION: What's going on here? printf.sh: #! /bin/sh NAME="George W. Bush" printf "Hello, %s\n" $NAME Command line session: $./printf.sh Hello, George Hello, W. Hello, Bush UPDATE: printf "Hello, %s\n" "$NAME" works. For why I'm not using echo, consider echo.sh: #! /bin/sh FILE="C:\tmp" echo "Filename: $FILE" Command-line: $./echo.sh Filename: C: mp The POSIX spec for echo says, "New applications are encouraged to use printf instead of echo " (for this and other reasons). ANSWER: Your NAME variable is being substituted like this: printf "Hello, %s\n" George W. Bush Use this: #! /bin/sh NAME="George W. Bush" printf "Hello, %s\n" "$NAME"
[ "unix", "shell" ]
10
8
6,545
4
0
2008-09-03T16:30:50.563000
2008-09-03T16:40:09.730000
42,076
42,094
Are you human? (or How to prevent spam)
What mechanisms do you know that prevent your site from being abused by anonymous spammers. For example, let's say that I have a site where people can vote something. But I don't want someone to spam something all the way to the top. So I found (a) creating an account and only allowed to vote once and (b) CAPTCHA to decrease spam. What other methods do you know and how good do they work?
The big thing I've noticed is that whatever you do, you want your system to be unique. You want an attacker to have to tailor their automation program for your specific site, rather than just throw a pre-existing script at it that will work almost anywhere. It doesn't even have to be cryptographically secure; it just has to make your site a little different from the norm. This doesn't mean you can't or shouldn't use something like a pre-built captcha widget. Absolutely do use one of those as a staring point! It just means you have to customize it somewhere so that something extra happens that is outside the norm and will break any pre-existing script that could normally defeat it. If your site gets big enough that you have attackers targeting it specifically, then your simple little customization probably won't hold up anymore and you might have do something a little more special and think about real cryptography and all that. But that's one of those things that's a "good" problem to have.
Are you human? (or How to prevent spam) What mechanisms do you know that prevent your site from being abused by anonymous spammers. For example, let's say that I have a site where people can vote something. But I don't want someone to spam something all the way to the top. So I found (a) creating an account and only allowed to vote once and (b) CAPTCHA to decrease spam. What other methods do you know and how good do they work?
TITLE: Are you human? (or How to prevent spam) QUESTION: What mechanisms do you know that prevent your site from being abused by anonymous spammers. For example, let's say that I have a site where people can vote something. But I don't want someone to spam something all the way to the top. So I found (a) creating an account and only allowed to vote once and (b) CAPTCHA to decrease spam. What other methods do you know and how good do they work? ANSWER: The big thing I've noticed is that whatever you do, you want your system to be unique. You want an attacker to have to tailor their automation program for your specific site, rather than just throw a pre-existing script at it that will work almost anywhere. It doesn't even have to be cryptographically secure; it just has to make your site a little different from the norm. This doesn't mean you can't or shouldn't use something like a pre-built captcha widget. Absolutely do use one of those as a staring point! It just means you have to customize it somewhere so that something extra happens that is outside the norm and will break any pre-existing script that could normally defeat it. If your site gets big enough that you have attackers targeting it specifically, then your simple little customization probably won't hold up anymore and you might have do something a little more special and think about real cryptography and all that. But that's one of those things that's a "good" problem to have.
[ "captcha" ]
12
13
4,154
11
0
2008-09-03T16:34:51.350000
2008-09-03T16:41:08.697000
42,093
42,175
Pure Python library to generate Identicons?
Does anyone know of a FOSS Python lib for generating Identicons? I've looked, but so far I haven't had much luck.
I've found two implementations: http://coderepos.org/share/browser/lang/python/misc/identicon.py http://code.google.com/p/visicon/
Pure Python library to generate Identicons? Does anyone know of a FOSS Python lib for generating Identicons? I've looked, but so far I haven't had much luck.
TITLE: Pure Python library to generate Identicons? QUESTION: Does anyone know of a FOSS Python lib for generating Identicons? I've looked, but so far I haven't had much luck. ANSWER: I've found two implementations: http://coderepos.org/share/browser/lang/python/misc/identicon.py http://code.google.com/p/visicon/
[ "python", "identicon" ]
17
12
2,636
1
0
2008-09-03T16:40:20.167000
2008-09-03T17:38:53.143000
42,115
373,205
App.config connection string Protection error
I am running into an issue I had before; can't find my reference on how to solve it. Here is the issue. We encrypt the connection strings section in the app.config for our client application using code below: config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None) If config.ConnectionStrings.SectionInformation.IsProtected = False Then config.ConnectionStrings.SectionInformation.ProtectSection(Nothing) ' We must save the changes to the configuration file.' config.Save(ConfigurationSaveMode.Modified, True) End If The issue is we had a salesperson leave. The old laptop is going to a new salesperson and under the new user's login, when it tries to to do this we get an error. The error is: Unhandled Exception: System.Configuration.ConfigurationErrorsException: An error occurred executing the configuration section handler for connectionStrings. ---> System.Configuration.ConfigurationErrorsException: Failed to encrypt the section 'connectionStrings' using provider 'RsaProtectedConfigurationProvider'. Error message from the provider: Object already exists. ---> System.Security.Cryptography.CryptographicException: Object already exists
I found a more elegant solution that in my original answer to myself. I found if I just logged in as th euser who orignally installed the application and caused the config file connectionstrings to be encrypted and go to the.net framework directory in a commadn prompt and run aspnet_regiis -pa "NetFrameworkConfigurationKey" "{domain}\{user}" it gave the other user permission to access the RSA encryption key container and it then works for the other user(s). Just wanted to add it here as I thought I had blogged this issue on our dev blog but found it here, so in case I need to look it up again it will be here. Will add link to our dev blog point at this thread as well.
App.config connection string Protection error I am running into an issue I had before; can't find my reference on how to solve it. Here is the issue. We encrypt the connection strings section in the app.config for our client application using code below: config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None) If config.ConnectionStrings.SectionInformation.IsProtected = False Then config.ConnectionStrings.SectionInformation.ProtectSection(Nothing) ' We must save the changes to the configuration file.' config.Save(ConfigurationSaveMode.Modified, True) End If The issue is we had a salesperson leave. The old laptop is going to a new salesperson and under the new user's login, when it tries to to do this we get an error. The error is: Unhandled Exception: System.Configuration.ConfigurationErrorsException: An error occurred executing the configuration section handler for connectionStrings. ---> System.Configuration.ConfigurationErrorsException: Failed to encrypt the section 'connectionStrings' using provider 'RsaProtectedConfigurationProvider'. Error message from the provider: Object already exists. ---> System.Security.Cryptography.CryptographicException: Object already exists
TITLE: App.config connection string Protection error QUESTION: I am running into an issue I had before; can't find my reference on how to solve it. Here is the issue. We encrypt the connection strings section in the app.config for our client application using code below: config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None) If config.ConnectionStrings.SectionInformation.IsProtected = False Then config.ConnectionStrings.SectionInformation.ProtectSection(Nothing) ' We must save the changes to the configuration file.' config.Save(ConfigurationSaveMode.Modified, True) End If The issue is we had a salesperson leave. The old laptop is going to a new salesperson and under the new user's login, when it tries to to do this we get an error. The error is: Unhandled Exception: System.Configuration.ConfigurationErrorsException: An error occurred executing the configuration section handler for connectionStrings. ---> System.Configuration.ConfigurationErrorsException: Failed to encrypt the section 'connectionStrings' using provider 'RsaProtectedConfigurationProvider'. Error message from the provider: Object already exists. ---> System.Security.Cryptography.CryptographicException: Object already exists ANSWER: I found a more elegant solution that in my original answer to myself. I found if I just logged in as th euser who orignally installed the application and caused the config file connectionstrings to be encrypted and go to the.net framework directory in a commadn prompt and run aspnet_regiis -pa "NetFrameworkConfigurationKey" "{domain}\{user}" it gave the other user permission to access the RSA encryption key container and it then works for the other user(s). Just wanted to add it here as I thought I had blogged this issue on our dev blog but found it here, so in case I need to look it up again it will be here. Will add link to our dev blog point at this thread as well.
[ "vb.net", "cryptography", "app-config", "cryptographicexception" ]
3
1
13,140
4
0
2008-09-03T17:03:35.273000
2008-12-16T23:50:52.030000
42,122
42,170
Easy .NET XML Library
Following my question regarding a.NET YAML Library... as there doesn't seem to be great support for YAML in.NET, are there and good open source really simple.NET XML libraries. I just want something where I can pass it a section name and a key and it gives me the value as well as being able to give me a list of all the current sections and keys. Also, preferably something with a license that allows it to be used commercially.
isn't the system.xml namespace suficient? once i had to use it for the simple scenarios that you described and thought that it was a simple and efficient solutions. take a look at this examples Reading Node Trees with XmlNodeReader and the XML Document Object Model (DOM) Reference
Easy .NET XML Library Following my question regarding a.NET YAML Library... as there doesn't seem to be great support for YAML in.NET, are there and good open source really simple.NET XML libraries. I just want something where I can pass it a section name and a key and it gives me the value as well as being able to give me a list of all the current sections and keys. Also, preferably something with a license that allows it to be used commercially.
TITLE: Easy .NET XML Library QUESTION: Following my question regarding a.NET YAML Library... as there doesn't seem to be great support for YAML in.NET, are there and good open source really simple.NET XML libraries. I just want something where I can pass it a section name and a key and it gives me the value as well as being able to give me a list of all the current sections and keys. Also, preferably something with a license that allows it to be used commercially. ANSWER: isn't the system.xml namespace suficient? once i had to use it for the simple scenarios that you described and thought that it was a simple and efficient solutions. take a look at this examples Reading Node Trees with XmlNodeReader and the XML Document Object Model (DOM) Reference
[ ".net", "xml" ]
2
2
913
3
0
2008-09-03T17:06:40.180000
2008-09-03T17:37:13.023000
42,125
47,693
Warning/error "function declaration isn't a prototype"
I have a library I created, File mylib.c: #include int testlib() { printf("Hello, World!\n"); return (0); } File mylib.h: #include extern int testlib(); In my program, I've attempted to call this library function: File myprogram.c: #include int main (int argc, char *argv[]) { testlib(); return (0); } When I attempt to compile this program I get the following error: In file included from myprogram.c:1 mylib.h:2 warning: function declaration isn't a prototype I'm using: gcc (GCC) 3.4.5 20051201 (Red Hat 3.4.5-2) What is the proper way to declare a function prototype?
In C int foo() and int foo(void) are different functions. int foo() accepts an arbitrary number of arguments, while int foo(void) accepts 0 arguments. In C++ they mean the same thing. I suggest that you use void consistently when you mean no arguments. If you have a variable a, extern int a; is a way to tell the compiler that a is a symbol that might be present in a different translation unit (C compiler speak for source file), don't resolve it until link time. On the other hand, symbols which are function names are anyway resolved at link time. The meaning of a storage class specifier on a function ( extern, static ) only affects its visibility and extern is the default, so extern is actually unnecessary. I suggest removing the extern, it is extraneous and is usually omitted.
Warning/error "function declaration isn't a prototype" I have a library I created, File mylib.c: #include int testlib() { printf("Hello, World!\n"); return (0); } File mylib.h: #include extern int testlib(); In my program, I've attempted to call this library function: File myprogram.c: #include int main (int argc, char *argv[]) { testlib(); return (0); } When I attempt to compile this program I get the following error: In file included from myprogram.c:1 mylib.h:2 warning: function declaration isn't a prototype I'm using: gcc (GCC) 3.4.5 20051201 (Red Hat 3.4.5-2) What is the proper way to declare a function prototype?
TITLE: Warning/error "function declaration isn't a prototype" QUESTION: I have a library I created, File mylib.c: #include int testlib() { printf("Hello, World!\n"); return (0); } File mylib.h: #include extern int testlib(); In my program, I've attempted to call this library function: File myprogram.c: #include int main (int argc, char *argv[]) { testlib(); return (0); } When I attempt to compile this program I get the following error: In file included from myprogram.c:1 mylib.h:2 warning: function declaration isn't a prototype I'm using: gcc (GCC) 3.4.5 20051201 (Red Hat 3.4.5-2) What is the proper way to declare a function prototype? ANSWER: In C int foo() and int foo(void) are different functions. int foo() accepts an arbitrary number of arguments, while int foo(void) accepts 0 arguments. In C++ they mean the same thing. I suggest that you use void consistently when you mean no arguments. If you have a variable a, extern int a; is a way to tell the compiler that a is a symbol that might be present in a different translation unit (C compiler speak for source file), don't resolve it until link time. On the other hand, symbols which are function names are anyway resolved at link time. The meaning of a storage class specifier on a function ( extern, static ) only affects its visibility and extern is the default, so extern is actually unnecessary. I suggest removing the extern, it is extraneous and is usually omitted.
[ "c", "gcc" ]
198
410
209,659
3
0
2008-09-03T17:08:18.163000
2008-09-06T17:58:18.500000
42,126
42,327
C++ Compiler Error C2371 - Redefinition of WCHAR
I am getting C++ Compiler error C2371 when I include a header file that itself includes odbcss.h. My project is set to MBCS. C:\Program Files\Microsoft SDKs\Windows\v6.0A\include\odbcss.h(430): error C2371: 'WCHAR': redefinition; different basic types 1> C:\Program Files\Microsoft SDKs\Windows\v6.0A\include\winnt.h(289): see declaration of 'WCHAR' I don't see any defines in odbcss.h that I could set to avoid this. Has anyone else seen this?
This is a known bug - see the Microsoft Connect website: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=98699 The error doesn't occur if you compile your app as Unicode instead of MBCS.
C++ Compiler Error C2371 - Redefinition of WCHAR I am getting C++ Compiler error C2371 when I include a header file that itself includes odbcss.h. My project is set to MBCS. C:\Program Files\Microsoft SDKs\Windows\v6.0A\include\odbcss.h(430): error C2371: 'WCHAR': redefinition; different basic types 1> C:\Program Files\Microsoft SDKs\Windows\v6.0A\include\winnt.h(289): see declaration of 'WCHAR' I don't see any defines in odbcss.h that I could set to avoid this. Has anyone else seen this?
TITLE: C++ Compiler Error C2371 - Redefinition of WCHAR QUESTION: I am getting C++ Compiler error C2371 when I include a header file that itself includes odbcss.h. My project is set to MBCS. C:\Program Files\Microsoft SDKs\Windows\v6.0A\include\odbcss.h(430): error C2371: 'WCHAR': redefinition; different basic types 1> C:\Program Files\Microsoft SDKs\Windows\v6.0A\include\winnt.h(289): see declaration of 'WCHAR' I don't see any defines in odbcss.h that I could set to avoid this. Has anyone else seen this? ANSWER: This is a known bug - see the Microsoft Connect website: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=98699 The error doesn't occur if you compile your app as Unicode instead of MBCS.
[ "c++", "visual-studio" ]
1
2
7,344
4
0
2008-09-03T17:08:35.450000
2008-09-03T19:09:13.117000
42,146
42,196
What are the best ways to determine what port an application is using?
This is an adapted version of a question from someone in my office. She's trying to determine how to tell what ports MSDE is running on for an application we have in the field. Answers to that narrower question would be greatly appreciated. I'm also interested in a broader answer that could be applied to any networked applications.
I've always liked the sysinternals app TCPView, which can now be found here. Good luck.
What are the best ways to determine what port an application is using? This is an adapted version of a question from someone in my office. She's trying to determine how to tell what ports MSDE is running on for an application we have in the field. Answers to that narrower question would be greatly appreciated. I'm also interested in a broader answer that could be applied to any networked applications.
TITLE: What are the best ways to determine what port an application is using? QUESTION: This is an adapted version of a question from someone in my office. She's trying to determine how to tell what ports MSDE is running on for an application we have in the field. Answers to that narrower question would be greatly appreciated. I'm also interested in a broader answer that could be applied to any networked applications. ANSWER: I've always liked the sysinternals app TCPView, which can now be found here. Good luck.
[ "sql-server", "port", "msde" ]
14
8
12,416
4
0
2008-09-03T17:25:54.143000
2008-09-03T17:45:05.767000
42,150
42,157
How can I unit test a Windows Service?
.NET Framework: 2.0 Preferred Language: C# I am new to TDD (Test Driven Development). First of all, is it even possible to unit test Windows Service? Windows service class is derived from ServiceBase, which has overridable methods, OnStart OnStop How can I trigger those methods to be called as if unit test is an actual service that calls those methods in proper order? At this point, am I even doing a Unit testing? or an Integration test? I have looked at WCF service question but it didn't make any sense to me since I have never dealt with WCF service.
I'd probably recommend designing your app so the "OnStart" and "OnStop" overrides in the Windows Service just call methods on a class library assembly. That way you can automate unit tests against the class library methods, and the design also abstracts your business logic from the implementation of a Windows Service. In this scenario, testing the "OnStart" and "OnStop" methods themselves in a Windows Service context would then be an integration test, not something you would automate.
How can I unit test a Windows Service? .NET Framework: 2.0 Preferred Language: C# I am new to TDD (Test Driven Development). First of all, is it even possible to unit test Windows Service? Windows service class is derived from ServiceBase, which has overridable methods, OnStart OnStop How can I trigger those methods to be called as if unit test is an actual service that calls those methods in proper order? At this point, am I even doing a Unit testing? or an Integration test? I have looked at WCF service question but it didn't make any sense to me since I have never dealt with WCF service.
TITLE: How can I unit test a Windows Service? QUESTION: .NET Framework: 2.0 Preferred Language: C# I am new to TDD (Test Driven Development). First of all, is it even possible to unit test Windows Service? Windows service class is derived from ServiceBase, which has overridable methods, OnStart OnStop How can I trigger those methods to be called as if unit test is an actual service that calls those methods in proper order? At this point, am I even doing a Unit testing? or an Integration test? I have looked at WCF service question but it didn't make any sense to me since I have never dealt with WCF service. ANSWER: I'd probably recommend designing your app so the "OnStart" and "OnStop" overrides in the Windows Service just call methods on a class library assembly. That way you can automate unit tests against the class library methods, and the design also abstracts your business logic from the implementation of a Windows Service. In this scenario, testing the "OnStart" and "OnStop" methods themselves in a Windows Service context would then be an integration test, not something you would automate.
[ "c#", ".net", "unit-testing", "windows-services" ]
65
90
44,575
7
0
2008-09-03T17:28:30.173000
2008-09-03T17:33:08.027000
42,153
42,163
Java: JApplet, How do you embed it in a webpage?
I searched for this subject on Google and got some website about an experts exchange...so I figured I should just ask here instead. How do you embed a JApplet in HTML on a webpage?
Here is an example from sun's website: Your browser is completely ignoring the <APPLET> tag!
Java: JApplet, How do you embed it in a webpage? I searched for this subject on Google and got some website about an experts exchange...so I figured I should just ask here instead. How do you embed a JApplet in HTML on a webpage?
TITLE: Java: JApplet, How do you embed it in a webpage? QUESTION: I searched for this subject on Google and got some website about an experts exchange...so I figured I should just ask here instead. How do you embed a JApplet in HTML on a webpage? ANSWER: Here is an example from sun's website: Your browser is completely ignoring the <APPLET> tag!
[ "java", "html", "web-applications" ]
2
6
5,399
3
0
2008-09-03T17:30:05.850000
2008-09-03T17:34:04.747000
42,171
88,160
How to copy the contents of an FTP directory to a shared network path?
I have the need to copy the entire contents of a directory on a FTP location onto a shared networked location. FTP Task has you specify the exact file name (not a directory) and File System Task does not allow accessing a FTP location. EDIT: I ended up writing a script task.
I've had some similar issues with the FTP task before. In my case, the file names changed based on the date and some other criteria. I ended up using a Script Task to perform the FTP operation. It looks like this is what you ended up doing as well. I'd be curious if anyone else can come up with a better way to use the FTP task. It's nice to have...but VERY limited.
How to copy the contents of an FTP directory to a shared network path? I have the need to copy the entire contents of a directory on a FTP location onto a shared networked location. FTP Task has you specify the exact file name (not a directory) and File System Task does not allow accessing a FTP location. EDIT: I ended up writing a script task.
TITLE: How to copy the contents of an FTP directory to a shared network path? QUESTION: I have the need to copy the entire contents of a directory on a FTP location onto a shared networked location. FTP Task has you specify the exact file name (not a directory) and File System Task does not allow accessing a FTP location. EDIT: I ended up writing a script task. ANSWER: I've had some similar issues with the FTP task before. In my case, the file names changed based on the date and some other criteria. I ended up using a Script Task to perform the FTP operation. It looks like this is what you ended up doing as well. I'd be curious if anyone else can come up with a better way to use the FTP task. It's nice to have...but VERY limited.
[ "ssis", "ftp", "business-intelligence" ]
3
1
3,143
3
0
2008-09-03T17:37:20.153000
2008-09-17T22:01:39.243000
42,182
42,195
How to escape < and > inside <pre> tags
I'm trying to write a blog post which includes a code segment inside a tag. The code segment includes a generic type and uses <> to define that type. This is what the segment looks like: PrimeCalc calc = new PrimeCalc(); Func del = calc.GetNextPrime; The resulting HTML removes the <> and ends up like this: PrimeCalc calc = new PrimeCalc(); Func del = calc.GetNextPrime; How do I escape the <> so they show up in the HTML?
PrimeCalc calc = new PrimeCalc(); Func<int, int> del = calc.GetNextPrime;
How to escape < and > inside <pre> tags I'm trying to write a blog post which includes a code segment inside a tag. The code segment includes a generic type and uses <> to define that type. This is what the segment looks like: PrimeCalc calc = new PrimeCalc(); Func del = calc.GetNextPrime; The resulting HTML removes the <> and ends up like this: PrimeCalc calc = new PrimeCalc(); Func del = calc.GetNextPrime; How do I escape the <> so they show up in the HTML?
TITLE: How to escape < and > inside <pre> tags QUESTION: I'm trying to write a blog post which includes a code segment inside a tag. The code segment includes a generic type and uses <> to define that type. This is what the segment looks like: PrimeCalc calc = new PrimeCalc(); Func del = calc.GetNextPrime; The resulting HTML removes the <> and ends up like this: PrimeCalc calc = new PrimeCalc(); Func del = calc.GetNextPrime; How do I escape the <> so they show up in the HTML? ANSWER: PrimeCalc calc = new PrimeCalc(); Func<int, int> del = calc.GetNextPrime;
[ "html", "escaping", "blogger", "markup", "pre" ]
103
125
95,501
8
0
2008-09-03T17:41:06.430000
2008-09-03T17:44:41.523000
42,187
43,557
How are partial methods used in C# 3.0?
I have read about partial methods in the latest C# language specification, so I understand the principles, but I'm wondering how people are actually using them. Is there a particular design pattern that benefits from partial methods?
Partial methods have been introduced for similar reasons to why partial classes were in.Net 2. A partial class is one that can be split across multiple files - the compiler builds them all into one file as it runs. The advantage for this is that Visual Studio can provide a graphical designer for part of the class while coders work on the other. The most common example is the Form designer. Developers don't want to be positioning buttons, input boxes, etc by hand most of the time. In.Net 1 it was auto-generated code in a #region block In.Net 2 these became separate designer classes - the form is still one class, it's just split into one file edited by the developers and one by the form designer This makes maintaining both much easier. Merges are simpler and there's less risk of the VS form designer accidentally undoing coders' manual changes. In.Net 3.5 Linq has been introduced. Linq has a DBML designer for building your data structures, and that generates auto-code. The extra bit here is that code needed to provide methods that developers might want to fill in. As developers will extend these classes (with extra partial files) they couldn't use abstract methods here. The other issue is that most of the time these methods wont be called, and calling empty methods is a waste of time. Empty methods are not optimised out. So Linq generates empty partial methods. If you don't create your own partial to complete them the C# compiler will just optimise them out. So that it can do this partial methods always return void. If you create a new Linq DBML file it will auto-generate a partial class, something like [System.Data.Linq.Mapping.DatabaseAttribute(Name="MyDB")] public partial class MyDataContext: System.Data.Linq.DataContext {... partial void OnCreated(); partial void InsertMyTable(MyTable instance); partial void UpdateMyTable(MyTable instance); partial void DeleteMyTable(MyTable instance);... Then in your own partial file you can extend this: public partial class MyDataContext { partial void OnCreated() { //do something on data context creation } } If you don't extend these methods they get optimised right out. Partial methods can't be public - as then they'd have to be there for other classes to call. If you write your own code generators I can see them being useful, but otherwise they're only really useful for the VS designer. The example I mentioned before is one possibility: //this code will get optimised out if no body is implemented partial void DoSomethingIfCompFlag(); #if COMPILER_FLAG //this code won't exist if the flag is off partial void DoSomethingIfCompFlag() { //your code } #endif Another potential use is if you had a large and complex class spilt across multiple files you might want partial references in the calling file. However I think in that case you should consider simplifying the class first.
How are partial methods used in C# 3.0? I have read about partial methods in the latest C# language specification, so I understand the principles, but I'm wondering how people are actually using them. Is there a particular design pattern that benefits from partial methods?
TITLE: How are partial methods used in C# 3.0? QUESTION: I have read about partial methods in the latest C# language specification, so I understand the principles, but I'm wondering how people are actually using them. Is there a particular design pattern that benefits from partial methods? ANSWER: Partial methods have been introduced for similar reasons to why partial classes were in.Net 2. A partial class is one that can be split across multiple files - the compiler builds them all into one file as it runs. The advantage for this is that Visual Studio can provide a graphical designer for part of the class while coders work on the other. The most common example is the Form designer. Developers don't want to be positioning buttons, input boxes, etc by hand most of the time. In.Net 1 it was auto-generated code in a #region block In.Net 2 these became separate designer classes - the form is still one class, it's just split into one file edited by the developers and one by the form designer This makes maintaining both much easier. Merges are simpler and there's less risk of the VS form designer accidentally undoing coders' manual changes. In.Net 3.5 Linq has been introduced. Linq has a DBML designer for building your data structures, and that generates auto-code. The extra bit here is that code needed to provide methods that developers might want to fill in. As developers will extend these classes (with extra partial files) they couldn't use abstract methods here. The other issue is that most of the time these methods wont be called, and calling empty methods is a waste of time. Empty methods are not optimised out. So Linq generates empty partial methods. If you don't create your own partial to complete them the C# compiler will just optimise them out. So that it can do this partial methods always return void. If you create a new Linq DBML file it will auto-generate a partial class, something like [System.Data.Linq.Mapping.DatabaseAttribute(Name="MyDB")] public partial class MyDataContext: System.Data.Linq.DataContext {... partial void OnCreated(); partial void InsertMyTable(MyTable instance); partial void UpdateMyTable(MyTable instance); partial void DeleteMyTable(MyTable instance);... Then in your own partial file you can extend this: public partial class MyDataContext { partial void OnCreated() { //do something on data context creation } } If you don't extend these methods they get optimised right out. Partial methods can't be public - as then they'd have to be there for other classes to call. If you write your own code generators I can see them being useful, but otherwise they're only really useful for the VS designer. The example I mentioned before is one possibility: //this code will get optimised out if no body is implemented partial void DoSomethingIfCompFlag(); #if COMPILER_FLAG //this code won't exist if the flag is off partial void DoSomethingIfCompFlag() { //your code } #endif Another potential use is if you had a large and complex class spilt across multiple files you might want partial references in the calling file. However I think in that case you should consider simplifying the class first.
[ "c#", "design-patterns", ".net-3.5", "partial-methods" ]
18
23
8,187
5
0
2008-09-03T17:42:41.967000
2008-09-04T11:52:32.050000
42,197
42,285
How do I determine which process is using a serial port?
The company I work for makes hardware that communicates to the computer though a serial port. Third party companies write software that communicates with our hardware. There are times when I need to diagnose our hardware. However, a third party software app connects to the serial port when Windows starts up, blocking any other connection. I don't know the name of this application/service and it's not always the same one. Is there any way to either: Find the name/pid of the app/service that is currently using a given serial port or Steal the serial port connection from another app. vb.net preferably, but I'll take a language agnostic answer as well.
You can use the process explorer tool also from SysInternals to search for open handles. In this case you would want to search for 'Serial' since it uses device names that may not map to com port numbers. (e.g. COM1 is \Device\Serial0 on my system). If you want to take control of the serial port from another app I think you would need co-operation of the driver.
How do I determine which process is using a serial port? The company I work for makes hardware that communicates to the computer though a serial port. Third party companies write software that communicates with our hardware. There are times when I need to diagnose our hardware. However, a third party software app connects to the serial port when Windows starts up, blocking any other connection. I don't know the name of this application/service and it's not always the same one. Is there any way to either: Find the name/pid of the app/service that is currently using a given serial port or Steal the serial port connection from another app. vb.net preferably, but I'll take a language agnostic answer as well.
TITLE: How do I determine which process is using a serial port? QUESTION: The company I work for makes hardware that communicates to the computer though a serial port. Third party companies write software that communicates with our hardware. There are times when I need to diagnose our hardware. However, a third party software app connects to the serial port when Windows starts up, blocking any other connection. I don't know the name of this application/service and it's not always the same one. Is there any way to either: Find the name/pid of the app/service that is currently using a given serial port or Steal the serial port connection from another app. vb.net preferably, but I'll take a language agnostic answer as well. ANSWER: You can use the process explorer tool also from SysInternals to search for open handles. In this case you would want to search for 'Serial' since it uses device names that may not map to com port numbers. (e.g. COM1 is \Device\Serial0 on my system). If you want to take control of the serial port from another app I think you would need co-operation of the driver.
[ "vb.net", "serial-port" ]
29
22
84,105
3
0
2008-09-03T17:46:21.363000
2008-09-03T18:42:35.783000
42,204
42,241
Where did these hex named folders come from?
First off, I am using Windows XP. I have multiple hard drives and it looks like something decided to make some folders on the second one ( which is just a data drive, no os ). These folders all have names like "e69f29f1b1f166d3d30b8c9f7156ba" and "bd92c24cc278614082cd88e7a64b". They contain folders named update, whose "access is denied", so my best guess would be they are Windows updates. So I probably can't get rid of them but could someone at least explain what they are and why they are on the wrong drive?
Windows will always use the hard drive with the most space to download windows updates. This is what happened to you. http://computershopper.com/forums/showthread.php?t=265
Where did these hex named folders come from? First off, I am using Windows XP. I have multiple hard drives and it looks like something decided to make some folders on the second one ( which is just a data drive, no os ). These folders all have names like "e69f29f1b1f166d3d30b8c9f7156ba" and "bd92c24cc278614082cd88e7a64b". They contain folders named update, whose "access is denied", so my best guess would be they are Windows updates. So I probably can't get rid of them but could someone at least explain what they are and why they are on the wrong drive?
TITLE: Where did these hex named folders come from? QUESTION: First off, I am using Windows XP. I have multiple hard drives and it looks like something decided to make some folders on the second one ( which is just a data drive, no os ). These folders all have names like "e69f29f1b1f166d3d30b8c9f7156ba" and "bd92c24cc278614082cd88e7a64b". They contain folders named update, whose "access is denied", so my best guess would be they are Windows updates. So I probably can't get rid of them but could someone at least explain what they are and why they are on the wrong drive? ANSWER: Windows will always use the hard drive with the most space to download windows updates. This is what happened to you. http://computershopper.com/forums/showthread.php?t=265
[ "windows", "hex", "directory" ]
10
11
9,860
1
0
2008-09-03T17:51:00.603000
2008-09-03T18:13:09.303000
42,212
42,299
How can I use Linq with a MySql database on Mono?
There are numerous libraries providing Linq capabilities to C# code interacting with a MySql database. Which one of them is the most stable and usable on Mono? Background (mostly irrelevant): I have a simple C# (.Net 2.0) program updating values in a MySql database. It is executed nightly via a cron job and runs on a Pentium 3 450Mhz, Linux + Mono. I want to rewrite it using Linq (.Net 3.5) mostly as an exercise (I have not yet used Linq).
The only (free) linq provider for MySql is DbLinq, and I believe it is a long way from production-ready. There is also MyDirect.Net which is commercial, but I have heard mixed reviews of it's capability. I've read that MySql will be implementing the Linq to Entities API for the 5.3 version of the.net connector, but I don't know if there's even a timeline for that. In fact, MySql has been totally silent about Entity Framework support for months. Addendum: The latest release of the MySql Connector/Net 6.0 has support for the EF according to the release notes. I have no idea how stable/useful this is, so I'd love to hear from anybody who have tried it.
How can I use Linq with a MySql database on Mono? There are numerous libraries providing Linq capabilities to C# code interacting with a MySql database. Which one of them is the most stable and usable on Mono? Background (mostly irrelevant): I have a simple C# (.Net 2.0) program updating values in a MySql database. It is executed nightly via a cron job and runs on a Pentium 3 450Mhz, Linux + Mono. I want to rewrite it using Linq (.Net 3.5) mostly as an exercise (I have not yet used Linq).
TITLE: How can I use Linq with a MySql database on Mono? QUESTION: There are numerous libraries providing Linq capabilities to C# code interacting with a MySql database. Which one of them is the most stable and usable on Mono? Background (mostly irrelevant): I have a simple C# (.Net 2.0) program updating values in a MySql database. It is executed nightly via a cron job and runs on a Pentium 3 450Mhz, Linux + Mono. I want to rewrite it using Linq (.Net 3.5) mostly as an exercise (I have not yet used Linq). ANSWER: The only (free) linq provider for MySql is DbLinq, and I believe it is a long way from production-ready. There is also MyDirect.Net which is commercial, but I have heard mixed reviews of it's capability. I've read that MySql will be implementing the Linq to Entities API for the 5.3 version of the.net connector, but I don't know if there's even a timeline for that. In fact, MySql has been totally silent about Entity Framework support for months. Addendum: The latest release of the MySql Connector/Net 6.0 has support for the EF according to the release notes. I have no idea how stable/useful this is, so I'd love to hear from anybody who have tried it.
[ "c#", "mysql", "linux", "linq", "mono" ]
10
5
11,464
6
0
2008-09-03T17:54:51.313000
2008-09-03T18:53:57.317000
42,215
42,229
ASP.NET - The request was aborted: Could not create SSL/TLS secure channel
We get the following error; The request was aborted: Could not create SSL/TLS secure channel while using a WebRequest object to make an HTTPS request. The funny thing is that this only happens after a while, and is temporarily fixed when the application is restarted, which suggests that something is being filled to capacity or something. Has anyone seen this kind of thing before?
I seem to recall having this problem last year. I suspect that you aren't closing your WebRequest objects properly, which is why after a certain amount of use it won't allow you to create any new connections.
ASP.NET - The request was aborted: Could not create SSL/TLS secure channel We get the following error; The request was aborted: Could not create SSL/TLS secure channel while using a WebRequest object to make an HTTPS request. The funny thing is that this only happens after a while, and is temporarily fixed when the application is restarted, which suggests that something is being filled to capacity or something. Has anyone seen this kind of thing before?
TITLE: ASP.NET - The request was aborted: Could not create SSL/TLS secure channel QUESTION: We get the following error; The request was aborted: Could not create SSL/TLS secure channel while using a WebRequest object to make an HTTPS request. The funny thing is that this only happens after a while, and is temporarily fixed when the application is restarted, which suggests that something is being filled to capacity or something. Has anyone seen this kind of thing before? ANSWER: I seem to recall having this problem last year. I suspect that you aren't closing your WebRequest objects properly, which is why after a certain amount of use it won't allow you to create any new connections.
[ "asp.net", "web-applications", "https" ]
1
2
5,963
4
0
2008-09-03T17:57:05.020000
2008-09-03T18:04:16.377000
42,234
42,278
Simple effects in Flex
I would like to show some hidden text in a Flex application and have it fade out in a couple of seconds... I have looked into Delay and Pause effects in Flex, but have yet to see an example of how to do this realistically easy effect... anyone now how to do it or have a good resource? Thanks.
If I understand you correctly, you want to have the text automatically fade out a few seconds after it is shown? I would probably do something like this: (Haven't tested the code, so there are probably typos.) import flash.utils.*; var fadeTimer:Timer = new Timer(2000); // 2 seconds fadeTimer.addEventListener("timer", fadeTimerTickHandler); // Call this to show the hidden text. function showTheText():void{ theTextField.visible = true; fadeTimer.start(); } // This gets called every time the timer "ticks" (2 seconds) function fadeTimerTickHandler(eventArgs:TimerEvent){ fadeTimer.stop(); fadeTimer.reset(); theTextField.visible = false; } Also, you need to be sure to embed your fonts or the effect won't work on your text. See Simeon's post for more info.
Simple effects in Flex I would like to show some hidden text in a Flex application and have it fade out in a couple of seconds... I have looked into Delay and Pause effects in Flex, but have yet to see an example of how to do this realistically easy effect... anyone now how to do it or have a good resource? Thanks.
TITLE: Simple effects in Flex QUESTION: I would like to show some hidden text in a Flex application and have it fade out in a couple of seconds... I have looked into Delay and Pause effects in Flex, but have yet to see an example of how to do this realistically easy effect... anyone now how to do it or have a good resource? Thanks. ANSWER: If I understand you correctly, you want to have the text automatically fade out a few seconds after it is shown? I would probably do something like this: (Haven't tested the code, so there are probably typos.) import flash.utils.*; var fadeTimer:Timer = new Timer(2000); // 2 seconds fadeTimer.addEventListener("timer", fadeTimerTickHandler); // Call this to show the hidden text. function showTheText():void{ theTextField.visible = true; fadeTimer.start(); } // This gets called every time the timer "ticks" (2 seconds) function fadeTimerTickHandler(eventArgs:TimerEvent){ fadeTimer.stop(); fadeTimer.reset(); theTextField.visible = false; } Also, you need to be sure to embed your fonts or the effect won't work on your text. See Simeon's post for more info.
[ "actionscript-3", "apache-flex" ]
3
2
1,425
1
0
2008-09-03T18:08:37.613000
2008-09-03T18:38:01.537000
42,246
45,983
Subversion Partial Export
I have somewhat interesting development situation. The client and deployment server are inside a firewall without access to the Subversion server. But the developers are outside the firewall and are able to use the Subversion server. Right now the solution I have worked out is to update my local copy of the code and then pull out the most recently updated files using UnleashIT. The question is how to get just the updated files out of Subversion so that they can be physically transported through the firewall and put on the deployment server. I'm not worried about trying to change the firewall setup or trying to figure out an easier way to get to the Subversion server from inside the firewall. I'm just interested in a way to get a partial export from the repository of the most recently changed files. Are there any other suggestions? Answer found: In addition to the answer I marked as Answer, I've also found the following here to be able to do this from TortoiseSVN: from http://svn.haxx.se/tsvn/archive-2006-08/0051.shtml * select the two revisions * right-click, "compare revisions" * select all files in the list * right-click, choose "export to..."
I've found rsync extremely useful for synchronizing directory trees across multiple systems. If you have shell access to your server from a development workstation, you can regularly check out code locally and run rsync, which will transfer only the files that have changed to the server. (This assumes a Unix-like environment on your development workstations. Cygwin will work fine.) cd deploy svn update rsync -a. server:webdir/ Your question sounds like you don't actually have any direct network access from your development workstations to your server, and what you're really looking for is a way to get Subversion to tell you which files have changed. svn export supports an argument to let you check out only the files that changed between particular revisions. From the svn help: -r [--revision] arg: ARG (some commands also take ARG1:ARG2 range) A revision argument can be one of: NUMBER revision number '{' DATE '}' revision at start of the date 'HEAD' latest in repository 'BASE' base rev of item's working copy 'COMMITTED' last commit at or before BASE 'PREV' revision just before COMMITTED You'll need to keep track of what the latest revision you copied to the server. Assuming it's SVN revision xxxx: svn export -r xxxx:HEAD http://svn/ Then simply copy the contents of the deploy directory to your server on top of the existing files. This won't handle deleted files, which may prove problematic in some environments.
Subversion Partial Export I have somewhat interesting development situation. The client and deployment server are inside a firewall without access to the Subversion server. But the developers are outside the firewall and are able to use the Subversion server. Right now the solution I have worked out is to update my local copy of the code and then pull out the most recently updated files using UnleashIT. The question is how to get just the updated files out of Subversion so that they can be physically transported through the firewall and put on the deployment server. I'm not worried about trying to change the firewall setup or trying to figure out an easier way to get to the Subversion server from inside the firewall. I'm just interested in a way to get a partial export from the repository of the most recently changed files. Are there any other suggestions? Answer found: In addition to the answer I marked as Answer, I've also found the following here to be able to do this from TortoiseSVN: from http://svn.haxx.se/tsvn/archive-2006-08/0051.shtml * select the two revisions * right-click, "compare revisions" * select all files in the list * right-click, choose "export to..."
TITLE: Subversion Partial Export QUESTION: I have somewhat interesting development situation. The client and deployment server are inside a firewall without access to the Subversion server. But the developers are outside the firewall and are able to use the Subversion server. Right now the solution I have worked out is to update my local copy of the code and then pull out the most recently updated files using UnleashIT. The question is how to get just the updated files out of Subversion so that they can be physically transported through the firewall and put on the deployment server. I'm not worried about trying to change the firewall setup or trying to figure out an easier way to get to the Subversion server from inside the firewall. I'm just interested in a way to get a partial export from the repository of the most recently changed files. Are there any other suggestions? Answer found: In addition to the answer I marked as Answer, I've also found the following here to be able to do this from TortoiseSVN: from http://svn.haxx.se/tsvn/archive-2006-08/0051.shtml * select the two revisions * right-click, "compare revisions" * select all files in the list * right-click, choose "export to..." ANSWER: I've found rsync extremely useful for synchronizing directory trees across multiple systems. If you have shell access to your server from a development workstation, you can regularly check out code locally and run rsync, which will transfer only the files that have changed to the server. (This assumes a Unix-like environment on your development workstations. Cygwin will work fine.) cd deploy svn update rsync -a. server:webdir/ Your question sounds like you don't actually have any direct network access from your development workstations to your server, and what you're really looking for is a way to get Subversion to tell you which files have changed. svn export supports an argument to let you check out only the files that changed between particular revisions. From the svn help: -r [--revision] arg: ARG (some commands also take ARG1:ARG2 range) A revision argument can be one of: NUMBER revision number '{' DATE '}' revision at start of the date 'HEAD' latest in repository 'BASE' base rev of item's working copy 'COMMITTED' last commit at or before BASE 'PREV' revision just before COMMITTED You'll need to keep track of what the latest revision you copied to the server. Assuming it's SVN revision xxxx: svn export -r xxxx:HEAD http://svn/ Then simply copy the contents of the deploy directory to your server on top of the existing files. This won't handle deleted files, which may prove problematic in some environments.
[ "svn", "deployment" ]
4
1
5,956
8
0
2008-09-03T18:16:07.690000
2008-09-05T14:56:36.947000
42,247
42,252
Are semicolons needed after an object literal assignment in JavaScript?
The following code illustrates an object literal being assigned, but with no semicolon afterwards: var literal = { say: function(msg) { alert(msg); } } literal.say("hello world!"); This appears to be legal, and doesn't issue a warning (at least in Firefox 3). Is this completely legal, or is there a strict version of JavaScript where this is not allowed? I'm wondering in particular for future compatibility issues... I would like to be writing "correct" JavaScript, so if technically I need to use the semicolon, I would like to be using it.
Not technically, JavaScript has semicolons as optional in many situations. But, as a general rule, use them at the end of any statement. Why? Because if you ever want to compress the script, it will save you from countless hours of frustration. Automatic semicolon insertion is performed by the interpreter, so you can leave them out if you so choose. In the comments, someone claimed that Semicolons are not optional with statements like break/continue/throw but this is incorrect. They are optional; what is really happening is that line terminators affect the automatic semicolon insertion; it is a subtle difference. Here is the rest of the standard on semicolon insertion: For convenience, however, such semicolons may be omitted from the source text in certain situations. These situations are described by saying that semicolons are automatically inserted into the source code token stream in those situations.
Are semicolons needed after an object literal assignment in JavaScript? The following code illustrates an object literal being assigned, but with no semicolon afterwards: var literal = { say: function(msg) { alert(msg); } } literal.say("hello world!"); This appears to be legal, and doesn't issue a warning (at least in Firefox 3). Is this completely legal, or is there a strict version of JavaScript where this is not allowed? I'm wondering in particular for future compatibility issues... I would like to be writing "correct" JavaScript, so if technically I need to use the semicolon, I would like to be using it.
TITLE: Are semicolons needed after an object literal assignment in JavaScript? QUESTION: The following code illustrates an object literal being assigned, but with no semicolon afterwards: var literal = { say: function(msg) { alert(msg); } } literal.say("hello world!"); This appears to be legal, and doesn't issue a warning (at least in Firefox 3). Is this completely legal, or is there a strict version of JavaScript where this is not allowed? I'm wondering in particular for future compatibility issues... I would like to be writing "correct" JavaScript, so if technically I need to use the semicolon, I would like to be using it. ANSWER: Not technically, JavaScript has semicolons as optional in many situations. But, as a general rule, use them at the end of any statement. Why? Because if you ever want to compress the script, it will save you from countless hours of frustration. Automatic semicolon insertion is performed by the interpreter, so you can leave them out if you so choose. In the comments, someone claimed that Semicolons are not optional with statements like break/continue/throw but this is incorrect. They are optional; what is really happening is that line terminators affect the automatic semicolon insertion; it is a subtle difference. Here is the rest of the standard on semicolon insertion: For convenience, however, such semicolons may be omitted from the source text in certain situations. These situations are described by saying that semicolons are automatically inserted into the source code token stream in those situations.
[ "javascript" ]
36
40
14,560
7
0
2008-09-03T18:16:17.173000
2008-09-03T18:19:29.350000
42,251
98,848
Whither Managed Extensibility Framework for .NET?
Has anyone worked much with Microsoft's Managed Extensibility Framework (MEF)? Kinda sounds like it's trying to be all things to all people - It's an add-in manager! It's duck typing! I'm wondering if anyone has an experience with it, positive or negative. We're currently planning on using an generic IoC implementation ala MvcContrib for our next big project. Should we throw MEF in the mix?
We are not aiming for MEF to be an all-purpose IoC. The best way to think about the IoC aspects of MEF is an implementation detail. We use IoC as a pattern because it is a great way to address the problems we are looking to solve. MEF is focused on extensibility. When you think of MEF look at it as an investment in taking our platform forward. Our future products and the platform will leverage MEF as a standard mechanism for adding extensibility. Third-party products and frameworks will also be able to leverage this same mechanism. The average "user" of MEF will author components that MEF will consume and will not be directly consuming MEF within their applications. Imagine when you want to extend our platform in the future, you drop a dll in the bin folder and you are done. The MEF enabled app lights up with the new extension. That's the vision for MEF.
Whither Managed Extensibility Framework for .NET? Has anyone worked much with Microsoft's Managed Extensibility Framework (MEF)? Kinda sounds like it's trying to be all things to all people - It's an add-in manager! It's duck typing! I'm wondering if anyone has an experience with it, positive or negative. We're currently planning on using an generic IoC implementation ala MvcContrib for our next big project. Should we throw MEF in the mix?
TITLE: Whither Managed Extensibility Framework for .NET? QUESTION: Has anyone worked much with Microsoft's Managed Extensibility Framework (MEF)? Kinda sounds like it's trying to be all things to all people - It's an add-in manager! It's duck typing! I'm wondering if anyone has an experience with it, positive or negative. We're currently planning on using an generic IoC implementation ala MvcContrib for our next big project. Should we throw MEF in the mix? ANSWER: We are not aiming for MEF to be an all-purpose IoC. The best way to think about the IoC aspects of MEF is an implementation detail. We use IoC as a pattern because it is a great way to address the problems we are looking to solve. MEF is focused on extensibility. When you think of MEF look at it as an investment in taking our platform forward. Our future products and the platform will leverage MEF as a standard mechanism for adding extensibility. Third-party products and frameworks will also be able to leverage this same mechanism. The average "user" of MEF will author components that MEF will consume and will not be directly consuming MEF within their applications. Imagine when you want to extend our platform in the future, you drop a dll in the bin folder and you are done. The MEF enabled app lights up with the new extension. That's the vision for MEF.
[ ".net", "mef" ]
21
33
5,030
9
0
2008-09-03T18:19:10.660000
2008-09-19T02:02:31.497000
42,254
2,068,227
How do you pause before fading an element out using jQuery?
I would like to flash a success message on my page. I am using the jQuery fadeOut method to fade and then remove the element. I can increase the duration to make it last longer, however this looks strange. What I would like to happen is have the element be displayed for five seconds, then fade quickly, and finally be removed. How can you animate this using jQuery?
The new delay() function in jQuery 1.4 should do the trick. $('#foo').fadeIn(200).delay(5000).fadeOut(200).remove();
How do you pause before fading an element out using jQuery? I would like to flash a success message on my page. I am using the jQuery fadeOut method to fade and then remove the element. I can increase the duration to make it last longer, however this looks strange. What I would like to happen is have the element be displayed for five seconds, then fade quickly, and finally be removed. How can you animate this using jQuery?
TITLE: How do you pause before fading an element out using jQuery? QUESTION: I would like to flash a success message on my page. I am using the jQuery fadeOut method to fade and then remove the element. I can increase the duration to make it last longer, however this looks strange. What I would like to happen is have the element be displayed for five seconds, then fade quickly, and finally be removed. How can you animate this using jQuery? ANSWER: The new delay() function in jQuery 1.4 should do the trick. $('#foo').fadeIn(200).delay(5000).fadeOut(200).remove();
[ "javascript", "jquery", "animation" ]
28
44
25,723
8
0
2008-09-03T18:19:32.063000
2010-01-14T23:07:46.317000
42,262
43,407
Twitching Consumption of Web Services from Web Site to Web Application
I am trying to consume multiple Web Services that redefine some of the same common classes in their wsdl. I currently have them referenced in a Web Site, but I want to convert to Web Application. Since some of the same classes are redefined from multiple Web Service, the problem is that when adding them in a web Application there is no way to make the namespaces the same across multiple Web Services, like you can in a Web Site. Is there any way to do what I am looking for?
Show all files in your project, then hand-edit the autogenerated Reference.cs files to change the namespaces (and remove duplicates)? Ugly, but it ought to work. Alternatively, use wsdl.exe from the command line -- it can generate a single proxy for multiple services -- and then add the generated file to the project manually. The syntax is something like: wsdl http://svr/foo.asmx http://svr/bar.asmx /namespace:Fnord.Proxies
Twitching Consumption of Web Services from Web Site to Web Application I am trying to consume multiple Web Services that redefine some of the same common classes in their wsdl. I currently have them referenced in a Web Site, but I want to convert to Web Application. Since some of the same classes are redefined from multiple Web Service, the problem is that when adding them in a web Application there is no way to make the namespaces the same across multiple Web Services, like you can in a Web Site. Is there any way to do what I am looking for?
TITLE: Twitching Consumption of Web Services from Web Site to Web Application QUESTION: I am trying to consume multiple Web Services that redefine some of the same common classes in their wsdl. I currently have them referenced in a Web Site, but I want to convert to Web Application. Since some of the same classes are redefined from multiple Web Service, the problem is that when adding them in a web Application there is no way to make the namespaces the same across multiple Web Services, like you can in a Web Site. Is there any way to do what I am looking for? ANSWER: Show all files in your project, then hand-edit the autogenerated Reference.cs files to change the namespaces (and remove duplicates)? Ugly, but it ought to work. Alternatively, use wsdl.exe from the command line -- it can generate a single proxy for multiple services -- and then add the generated file to the project manually. The syntax is something like: wsdl http://svr/foo.asmx http://svr/bar.asmx /namespace:Fnord.Proxies
[ "web-services", "web-applications", "wsdl" ]
5
2
207
1
0
2008-09-03T18:23:03.210000
2008-09-04T09:32:05.677000
42,281
43,271
IE6 and Caching
It seems that IE6 ignores any form of cache invalidation sent via http headers, I've tried setting Pragma to No Cache and setting Cache Expiration to the current time, yet in IE6, hitting back will always pull up a cached version of a page I am working on. Is there a specific HTTP Header that IE6 does listen too?
Cache-Control: private, max-age=0 should fix it. From classic ASP this is done with Response.Expires=-1. Keep in mind when testing that just because your server is serving pages with caching turned off doesn't mean that the browser will obey that when it has an old cached page that it was told was okay to cache. Clear the cache or use F5 to force that page to be reloaded. Also, for those cases where the server is serving cached content it you can use Ctrl+F5 to signal the server not to serve it from cache.
IE6 and Caching It seems that IE6 ignores any form of cache invalidation sent via http headers, I've tried setting Pragma to No Cache and setting Cache Expiration to the current time, yet in IE6, hitting back will always pull up a cached version of a page I am working on. Is there a specific HTTP Header that IE6 does listen too?
TITLE: IE6 and Caching QUESTION: It seems that IE6 ignores any form of cache invalidation sent via http headers, I've tried setting Pragma to No Cache and setting Cache Expiration to the current time, yet in IE6, hitting back will always pull up a cached version of a page I am working on. Is there a specific HTTP Header that IE6 does listen too? ANSWER: Cache-Control: private, max-age=0 should fix it. From classic ASP this is done with Response.Expires=-1. Keep in mind when testing that just because your server is serving pages with caching turned off doesn't mean that the browser will obey that when it has an old cached page that it was told was okay to cache. Clear the cache or use F5 to force that page to be reloaded. Also, for those cases where the server is serving cached content it you can use Ctrl+F5 to signal the server not to serve it from cache.
[ "caching", "internet-explorer-6", "http-headers", "dynamic-pages" ]
3
8
3,437
6
0
2008-09-03T18:41:03.713000
2008-09-04T07:19:15.170000
42,282
42,304
Which way do you prefer to create your forms in MVC?
Which way do you prefer to create your forms in MVC? <% Html.Form() { %> <% } %> Or " method="post"> I understand that Html.Form() as of PR5 now just uses the URL provided by the request. However something about that doesn't sit well with me, especially since I will be getting all the baggage of any querystrings that are included. What is your take?
The second way, definitely. The first way is programmer-centric, which is not what the V part of MVC is about. The second way is more designer centric, only binding to the model where it is necessary, leaving the HTML as natural as possible.
Which way do you prefer to create your forms in MVC? Which way do you prefer to create your forms in MVC? <% Html.Form() { %> <% } %> Or " method="post"> I understand that Html.Form() as of PR5 now just uses the URL provided by the request. However something about that doesn't sit well with me, especially since I will be getting all the baggage of any querystrings that are included. What is your take?
TITLE: Which way do you prefer to create your forms in MVC? QUESTION: Which way do you prefer to create your forms in MVC? <% Html.Form() { %> <% } %> Or " method="post"> I understand that Html.Form() as of PR5 now just uses the URL provided by the request. However something about that doesn't sit well with me, especially since I will be getting all the baggage of any querystrings that are included. What is your take? ANSWER: The second way, definitely. The first way is programmer-centric, which is not what the V part of MVC is about. The second way is more designer centric, only binding to the model where it is necessary, leaving the HTML as natural as possible.
[ "asp.net-mvc", "forms", "model-view-controller" ]
4
7
317
6
0
2008-09-03T18:41:11.077000
2008-09-03T18:55:59.357000
42,286
42,293
What's the best way to read the contents of a text file to a string in .NET?
It seems like there should be something shorter than this: private string LoadFromFile(string path) { try { string fileContents; using(StreamReader rdr = File.OpenText(path)) { fileContents = rdr.ReadToEnd(); } return fileContents; } catch { throw; } }
First of all, the title asks for "how to write the contents of strnig to a text file" but your code example is for "how to read the contents of a text file to a string. Answer to both questions: using System.IO;... string filename = "C:/example.txt"; string content = File.ReadAllText(filename); File.WriteAllText(filename, content); See also ReadAllLines/WriteAllLines and ReadAllBytes/WriteAllBytes if instead of a string you want a string array or byte array.
What's the best way to read the contents of a text file to a string in .NET? It seems like there should be something shorter than this: private string LoadFromFile(string path) { try { string fileContents; using(StreamReader rdr = File.OpenText(path)) { fileContents = rdr.ReadToEnd(); } return fileContents; } catch { throw; } }
TITLE: What's the best way to read the contents of a text file to a string in .NET? QUESTION: It seems like there should be something shorter than this: private string LoadFromFile(string path) { try { string fileContents; using(StreamReader rdr = File.OpenText(path)) { fileContents = rdr.ReadToEnd(); } return fileContents; } catch { throw; } } ANSWER: First of all, the title asks for "how to write the contents of strnig to a text file" but your code example is for "how to read the contents of a text file to a string. Answer to both questions: using System.IO;... string filename = "C:/example.txt"; string content = File.ReadAllText(filename); File.WriteAllText(filename, content); See also ReadAllLines/WriteAllLines and ReadAllBytes/WriteAllBytes if instead of a string you want a string array or byte array.
[ ".net", "string", "text-files" ]
4
17
1,177
4
0
2008-09-03T18:45:51.970000
2008-09-03T18:51:06.730000
42,294
42,301
How do you get the footer to stay at the bottom of a Web page?
I have a simple 2-column layout with a footer that clears both the right and left div in my markup. My problem is that I can't get the footer to stay at the bottom of the page in all browsers. It works if the content pushes the footer down, but that's not always the case.
To get a sticky footer: Have a with class="wrapper" for your content. Right before the closing of the wrapper place the. Right after the closing of the wrapper place the. * { margin: 0; } html, body { height: 100%; }.wrapper { min-height: 100%; height: auto!important; height: 100%; margin: 0 auto -142px; /* the bottom margin is the negative value of the footer's height */ }.footer,.push { height: 142px; /*.push must be the same height as.footer */ } wrapper push footer
How do you get the footer to stay at the bottom of a Web page? I have a simple 2-column layout with a footer that clears both the right and left div in my markup. My problem is that I can't get the footer to stay at the bottom of the page in all browsers. It works if the content pushes the footer down, but that's not always the case.
TITLE: How do you get the footer to stay at the bottom of a Web page? QUESTION: I have a simple 2-column layout with a footer that clears both the right and left div in my markup. My problem is that I can't get the footer to stay at the bottom of the page in all browsers. It works if the content pushes the footer down, but that's not always the case. ANSWER: To get a sticky footer: Have a with class="wrapper" for your content. Right before the closing of the wrapper place the. Right after the closing of the wrapper place the. * { margin: 0; } html, body { height: 100%; }.wrapper { min-height: 100%; height: auto!important; height: 100%; margin: 0 auto -142px; /* the bottom margin is the negative value of the footer's height */ }.footer,.push { height: 142px; /*.push must be the same height as.footer */ } wrapper push footer
[ "css", "html", "footer", "sticky-footer" ]
349
212
251,548
33
0
2008-09-03T18:51:17.760000
2008-09-03T18:55:18.577000
42,308
42,513
Tool to track #include dependencies
Any good suggestions? Input will be the name of a header file and output should be a list (preferably a tree) of all files including it directly or indirectly.
If you have access to GCC/G++, then the -M option will output the dependency list. It doesn't do any of the extra stuff that the other tools do, but since it is coming from the compiler, there is no chance that it will pick up files from the "wrong" place.
Tool to track #include dependencies Any good suggestions? Input will be the name of a header file and output should be a list (preferably a tree) of all files including it directly or indirectly.
TITLE: Tool to track #include dependencies QUESTION: Any good suggestions? Input will be the name of a header file and output should be a list (preferably a tree) of all files including it directly or indirectly. ANSWER: If you have access to GCC/G++, then the -M option will output the dependency list. It doesn't do any of the extra stuff that the other tools do, but since it is coming from the compiler, there is no chance that it will pick up files from the "wrong" place.
[ "c++", "c", "header" ]
193
173
86,461
10
0
2008-09-03T18:58:35.403000
2008-09-03T20:32:23.617000
42,312
42,339
Are There Adapters for CF Type II to MicroSD?
I honestly have only started recently researching this so my knowledge is limited. I was approached about adapting some Pocket PC software to operate on the Windows 6 platform. After considering how I would go about doing that in the Compact Framework I received more details. It seems there is a desire to utilize (re-use) CF Type II devices on a mobile phone platform (using more modern miniSD or microSD slots). While there exist plenty of microSD to CF adapters, there seems to be none going the other direction (even though I realize that would be an awkward looking adapter in physical design). Is this true and what prevents this technically?
There is nothing that does this currently. Likely because you can't exactly fit a CF card in a MicroSD card....it would have to have some weird cable coming off of it, which would likely cause it to no longer fit in the slot. Also, CF is a Parallel interface while SD uses a Serial interface.
Are There Adapters for CF Type II to MicroSD? I honestly have only started recently researching this so my knowledge is limited. I was approached about adapting some Pocket PC software to operate on the Windows 6 platform. After considering how I would go about doing that in the Compact Framework I received more details. It seems there is a desire to utilize (re-use) CF Type II devices on a mobile phone platform (using more modern miniSD or microSD slots). While there exist plenty of microSD to CF adapters, there seems to be none going the other direction (even though I realize that would be an awkward looking adapter in physical design). Is this true and what prevents this technically?
TITLE: Are There Adapters for CF Type II to MicroSD? QUESTION: I honestly have only started recently researching this so my knowledge is limited. I was approached about adapting some Pocket PC software to operate on the Windows 6 platform. After considering how I would go about doing that in the Compact Framework I received more details. It seems there is a desire to utilize (re-use) CF Type II devices on a mobile phone platform (using more modern miniSD or microSD slots). While there exist plenty of microSD to CF adapters, there seems to be none going the other direction (even though I realize that would be an awkward looking adapter in physical design). Is this true and what prevents this technically? ANSWER: There is nothing that does this currently. Likely because you can't exactly fit a CF card in a MicroSD card....it would have to have some weird cable coming off of it, which would likely cause it to no longer fit in the slot. Also, CF is a Parallel interface while SD uses a Serial interface.
[ "mobile", "hardware", "pocketpc" ]
4
1
181
1
0
2008-09-03T19:00:01
2008-09-03T19:19:40.673000
42,323
42,494
Real image width with JavaScript
I have the next function: function setImagesWidth(id,width) { var images = document.getElementById(id).getElementsByTagName("img"); for(var i = 0; i < images.length;i++) { // If the real width is bigger than width parameter images[i].style.width=width; //} } } I would like to set the css width attribute of all my img tags to a particular value only when the image real width is bigger than the attribute value. If it is possible, i would like a solution which does not use any particular framework. images[i].offsetWidth returns 111 for an image of 109px width. Is this because 1px each side border?
@Sergio del Amo: Indeed, if you check out my link you'll see that you want clientWidth instead. @Sergio del Amo: You cannot, unfortunately, accept your own answer. But you do have an extraneous period in the "px" suffix, so let's go with this, including the clientWidth change: // width in pixels function setImagesWidth(id, width) { var images = document.getElementById(id).getElementsByTagName("img"); var newWidth = width + "px"; for (var i = 0; i < images.length; ++i) { if (images[i].clientWidth > width) { images[i].style.width = newWidth; } } }
Real image width with JavaScript I have the next function: function setImagesWidth(id,width) { var images = document.getElementById(id).getElementsByTagName("img"); for(var i = 0; i < images.length;i++) { // If the real width is bigger than width parameter images[i].style.width=width; //} } } I would like to set the css width attribute of all my img tags to a particular value only when the image real width is bigger than the attribute value. If it is possible, i would like a solution which does not use any particular framework. images[i].offsetWidth returns 111 for an image of 109px width. Is this because 1px each side border?
TITLE: Real image width with JavaScript QUESTION: I have the next function: function setImagesWidth(id,width) { var images = document.getElementById(id).getElementsByTagName("img"); for(var i = 0; i < images.length;i++) { // If the real width is bigger than width parameter images[i].style.width=width; //} } } I would like to set the css width attribute of all my img tags to a particular value only when the image real width is bigger than the attribute value. If it is possible, i would like a solution which does not use any particular framework. images[i].offsetWidth returns 111 for an image of 109px width. Is this because 1px each side border? ANSWER: @Sergio del Amo: Indeed, if you check out my link you'll see that you want clientWidth instead. @Sergio del Amo: You cannot, unfortunately, accept your own answer. But you do have an extraneous period in the "px" suffix, so let's go with this, including the clientWidth change: // width in pixels function setImagesWidth(id, width) { var images = document.getElementById(id).getElementsByTagName("img"); var newWidth = width + "px"; for (var i = 0; i < images.length; ++i) { if (images[i].clientWidth > width) { images[i].style.width = newWidth; } } }
[ "javascript" ]
5
1
15,181
5
0
2008-09-03T19:07:03.057000
2008-09-03T20:23:13.280000
42,333
42,684
How to display a live streaming video using VideoDisplay in Flex
I'm wondering how to use a VideoDisplay object (defined in MXML) to display video streamed from FMS via a NetStream. The Flex3 docs suggest this is possible: The Video Display... supports progressive download over HTTP, streaming from the Flash Media Server, and streaming from a Camera object. However, later in the docs all I can see is an attachCamera() method. There doesn't appear to be an attachStream() method like the old Video object has. It looks like you can play a fixed file served over HTML by using the source property, but I don't see anything about how to attach a NetStream. The old Video object still seems to exist, though it's not based on UIComponent and doesn't appear to be usable in MXML. I found this blog post that shows how to do it with a regular Video object, but I'd much prefer to use VideoDisplay (or something else that can be put directly in the MXML).
Unfortunately you can attachNetStream() only on Video object. So you are doomed to use em if you want to get data from FMS. By the way attachCamera() method publishes local camera video to the server so be careful;)
How to display a live streaming video using VideoDisplay in Flex I'm wondering how to use a VideoDisplay object (defined in MXML) to display video streamed from FMS via a NetStream. The Flex3 docs suggest this is possible: The Video Display... supports progressive download over HTTP, streaming from the Flash Media Server, and streaming from a Camera object. However, later in the docs all I can see is an attachCamera() method. There doesn't appear to be an attachStream() method like the old Video object has. It looks like you can play a fixed file served over HTML by using the source property, but I don't see anything about how to attach a NetStream. The old Video object still seems to exist, though it's not based on UIComponent and doesn't appear to be usable in MXML. I found this blog post that shows how to do it with a regular Video object, but I'd much prefer to use VideoDisplay (or something else that can be put directly in the MXML).
TITLE: How to display a live streaming video using VideoDisplay in Flex QUESTION: I'm wondering how to use a VideoDisplay object (defined in MXML) to display video streamed from FMS via a NetStream. The Flex3 docs suggest this is possible: The Video Display... supports progressive download over HTTP, streaming from the Flash Media Server, and streaming from a Camera object. However, later in the docs all I can see is an attachCamera() method. There doesn't appear to be an attachStream() method like the old Video object has. It looks like you can play a fixed file served over HTML by using the source property, but I don't see anything about how to attach a NetStream. The old Video object still seems to exist, though it's not based on UIComponent and doesn't appear to be usable in MXML. I found this blog post that shows how to do it with a regular Video object, but I'd much prefer to use VideoDisplay (or something else that can be put directly in the MXML). ANSWER: Unfortunately you can attachNetStream() only on Video object. So you are doomed to use em if you want to get data from FMS. By the way attachCamera() method publishes local camera video to the server so be careful;)
[ "apache-flex", "video", "streaming" ]
13
6
33,556
5
0
2008-09-03T19:15:55.453000
2008-09-03T21:49:59.813000
42,357
42,651
How do you check your URL for SQL Injection Attacks?
I've seen a few attempted SQL injection attacks on one of my web sites. It comes in the form of a query string that includes the "cast" keyword and a bunch of hex characters which when "decoded" are an injection of banner adverts into the DB. My solution is to scan the full URL (and params) and search for the presence of "cast(0x" and if it's there to redirect to a static page. How do you check your URL's for SQL Injection attacks?
I think it depends on what level you're looking to check/prevent SQL Injection at. At the top level, you can use URLScan or some Apache Mods/Filters (somebody help me out here) to check the incoming URLs to the web server itself and immediately drop/ignore requests that match a certain pattern. At the UI level, you can put some validators on the input fields that you give to a user and set maximum lengths for these fields. You can also white list certain values/patterns as needed. At the code level, you can use parametrized queries, as mentioned above, to make sure that string inputs go in as purely string inputs and don't attempt to execute T-SQL/PL-SQL commands. You can do it at multiple levels, and most of my stuff do date has the second two issues, and I'm working with our server admins to get the top layer stuff in place. Is that more along the lines of what you want to know?
How do you check your URL for SQL Injection Attacks? I've seen a few attempted SQL injection attacks on one of my web sites. It comes in the form of a query string that includes the "cast" keyword and a bunch of hex characters which when "decoded" are an injection of banner adverts into the DB. My solution is to scan the full URL (and params) and search for the presence of "cast(0x" and if it's there to redirect to a static page. How do you check your URL's for SQL Injection attacks?
TITLE: How do you check your URL for SQL Injection Attacks? QUESTION: I've seen a few attempted SQL injection attacks on one of my web sites. It comes in the form of a query string that includes the "cast" keyword and a bunch of hex characters which when "decoded" are an injection of banner adverts into the DB. My solution is to scan the full URL (and params) and search for the presence of "cast(0x" and if it's there to redirect to a static page. How do you check your URL's for SQL Injection attacks? ANSWER: I think it depends on what level you're looking to check/prevent SQL Injection at. At the top level, you can use URLScan or some Apache Mods/Filters (somebody help me out here) to check the incoming URLs to the web server itself and immediately drop/ignore requests that match a certain pattern. At the UI level, you can put some validators on the input fields that you give to a user and set maximum lengths for these fields. You can also white list certain values/patterns as needed. At the code level, you can use parametrized queries, as mentioned above, to make sure that string inputs go in as purely string inputs and don't attempt to execute T-SQL/PL-SQL commands. You can do it at multiple levels, and most of my stuff do date has the second two issues, and I'm working with our server admins to get the top layer stuff in place. Is that more along the lines of what you want to know?
[ "sql", "sql-server" ]
8
2
5,177
10
0
2008-09-03T19:28:30.837000
2008-09-03T21:34:27.150000
42,366
42,377
What does the EXE do in the Visual Studio setup project output
We are working on a winforms app in Visual Studio 2005 and the setup project we created output both an MSI and an EXE. We aren't sure what the EXE file is used for because we are able to install without the EXE.
It's a bootstrapper that checks to make sure that the.NET Framework is installed, before launching the MSI. It's pretty handy. I suggest using something like SFX Compiler to package the two together into one self-extracting.exe and then launch the extracted setup.exe. This way you retain the benefits of the bootstrapper, but your users only download a single thing. Edit: also see The official line: MSDN documentation Some bootstrapper customization: some guy's blog post about what he did
What does the EXE do in the Visual Studio setup project output We are working on a winforms app in Visual Studio 2005 and the setup project we created output both an MSI and an EXE. We aren't sure what the EXE file is used for because we are able to install without the EXE.
TITLE: What does the EXE do in the Visual Studio setup project output QUESTION: We are working on a winforms app in Visual Studio 2005 and the setup project we created output both an MSI and an EXE. We aren't sure what the EXE file is used for because we are able to install without the EXE. ANSWER: It's a bootstrapper that checks to make sure that the.NET Framework is installed, before launching the MSI. It's pretty handy. I suggest using something like SFX Compiler to package the two together into one self-extracting.exe and then launch the extracted setup.exe. This way you retain the benefits of the bootstrapper, but your users only download a single thing. Edit: also see The official line: MSDN documentation Some bootstrapper customization: some guy's blog post about what he did
[ "visual-studio", "installation", "windows-installer", "exe" ]
27
26
6,828
3
0
2008-09-03T19:32:00.003000
2008-09-03T19:35:15.050000
42,383
42,410
Java object allocation overhead
I am writing an immutable DOM tree in Java, to simplify access from multiple threads.* However, it does need to support inserts and updates as fast as possible. And since it is immutable, if I make a change to a node on the N'th level of the tree, I need to allocate at least N new nodes in order to return the new tree. My question is, would it be dramatically faster to pre-allocate nodes rather than create new ones every time the tree is modified? It would be fairly easy to do - keep a pool of several hundred unused nodes, and pull one out of the pool rather than create one whenever it was required for a modify operation. I can replenish the node pool when there's nothing else going on. (in case it isn't obvious, execution time is going to be much more at a premium in this application than heap space is) Is it worthwhile to do this? Any other tips on speeding it up? Alternatively, does anyone know if an immutable DOM library already? I searched, but couldn't find anything. *Note: For those of you who aren't familiar with the concept of immutability, it basically means that on any operation to an object that changes it, the method returns a copy of the object with the changes in place, rather than the changed object. Thus, if another thread is still reading the object it will continue to happily operate on the "old" version, unaware that changes have been made, rather than crashing horribly. See http://www.javapractices.com/topic/TopicAction.do?Id=29
These days, object creation is pretty dang fast, and the concept of object pooling is kind of obsolete (at least in general; connection pooling is of course still valid). Avoid premature optimization. Create your nodes when you need them when doing your copies, and then see if that becomes prohibitively slow. If so, then look into some techniques to speed it up. But unless you already know that what you've got isn't fast enough, I wouldn't go introducing all the complexity you're going to need to get pooling going.
Java object allocation overhead I am writing an immutable DOM tree in Java, to simplify access from multiple threads.* However, it does need to support inserts and updates as fast as possible. And since it is immutable, if I make a change to a node on the N'th level of the tree, I need to allocate at least N new nodes in order to return the new tree. My question is, would it be dramatically faster to pre-allocate nodes rather than create new ones every time the tree is modified? It would be fairly easy to do - keep a pool of several hundred unused nodes, and pull one out of the pool rather than create one whenever it was required for a modify operation. I can replenish the node pool when there's nothing else going on. (in case it isn't obvious, execution time is going to be much more at a premium in this application than heap space is) Is it worthwhile to do this? Any other tips on speeding it up? Alternatively, does anyone know if an immutable DOM library already? I searched, but couldn't find anything. *Note: For those of you who aren't familiar with the concept of immutability, it basically means that on any operation to an object that changes it, the method returns a copy of the object with the changes in place, rather than the changed object. Thus, if another thread is still reading the object it will continue to happily operate on the "old" version, unaware that changes have been made, rather than crashing horribly. See http://www.javapractices.com/topic/TopicAction.do?Id=29
TITLE: Java object allocation overhead QUESTION: I am writing an immutable DOM tree in Java, to simplify access from multiple threads.* However, it does need to support inserts and updates as fast as possible. And since it is immutable, if I make a change to a node on the N'th level of the tree, I need to allocate at least N new nodes in order to return the new tree. My question is, would it be dramatically faster to pre-allocate nodes rather than create new ones every time the tree is modified? It would be fairly easy to do - keep a pool of several hundred unused nodes, and pull one out of the pool rather than create one whenever it was required for a modify operation. I can replenish the node pool when there's nothing else going on. (in case it isn't obvious, execution time is going to be much more at a premium in this application than heap space is) Is it worthwhile to do this? Any other tips on speeding it up? Alternatively, does anyone know if an immutable DOM library already? I searched, but couldn't find anything. *Note: For those of you who aren't familiar with the concept of immutability, it basically means that on any operation to an object that changes it, the method returns a copy of the object with the changes in place, rather than the changed object. Thus, if another thread is still reading the object it will continue to happily operate on the "old" version, unaware that changes have been made, rather than crashing horribly. See http://www.javapractices.com/topic/TopicAction.do?Id=29 ANSWER: These days, object creation is pretty dang fast, and the concept of object pooling is kind of obsolete (at least in general; connection pooling is of course still valid). Avoid premature optimization. Create your nodes when you need them when doing your copies, and then see if that becomes prohibitively slow. If so, then look into some techniques to speed it up. But unless you already know that what you've got isn't fast enough, I wouldn't go introducing all the complexity you're going to need to get pooling going.
[ "java", "xml", "dom", "concurrency" ]
8
12
1,509
6
0
2008-09-03T19:37:58.523000
2008-09-03T19:47:53.833000
42,395
42,409
How do I write a While loop
How do you write the syntax for a While loop? C # int i = 0; while (i!= 10) { Console.WriteLine(i); i++; } VB.Net Dim i As Integer = 0 While i <> 10 Console.WriteLine(i) i += 1 End While PHP Python i = 0 while i!= 10: print i i += 1
In PHP a while loop will look like this: A real world example of this might look something like this
How do I write a While loop How do you write the syntax for a While loop? C # int i = 0; while (i!= 10) { Console.WriteLine(i); i++; } VB.Net Dim i As Integer = 0 While i <> 10 Console.WriteLine(i) i += 1 End While PHP Python i = 0 while i!= 10: print i i += 1
TITLE: How do I write a While loop QUESTION: How do you write the syntax for a While loop? C # int i = 0; while (i!= 10) { Console.WriteLine(i); i++; } VB.Net Dim i As Integer = 0 While i <> 10 Console.WriteLine(i) i += 1 End While PHP Python i = 0 while i!= 10: print i i += 1 ANSWER: In PHP a while loop will look like this: A real world example of this might look something like this
[ "language-agnostic", "conditional-statements" ]
8
5
1,294
3
0
2008-09-03T19:42:50.507000
2008-09-03T19:47:24.990000
42,396
42,412
ASP.Net: why is my button's click/command events not binding/firing in a repeater?
Here's the code from the ascx that has the repeater: A sub-header: [Some other stuff is here] And in the codebehind for the repeater's databound and events: Protected Sub ListOfEmails_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles ListOfEmails.ItemDataBound If (e.Item.ItemType = ListItemType.Item) Or (e.Item.ItemType = ListItemType.AlternatingItem) Then Dim removeEmail As Button = CType(e.Item.FindControl("removeEmail"), Button) removeEmail.CommandArgument = e.Item.ItemIndex.ToString() AddHandler removeEmail.Click, AddressOf removeEmail_Click AddHandler removeEmail.Command, AddressOf removeEmail_Command End If End Sub Sub removeEmail_Click(ByVal sender As Object, ByVal e As System.EventArgs) Response.Write(" click ") End Sub Sub removeEmail_Command(ByVal sender As Object, ByVal e As CommandEventArgs) Response.Write(" command ") End Sub Neither the click or command is getting called, what am I doing wrong?
Controls nested inside of Repeaters do not intercept events. Instead you need to bind to the Repeater.ItemCommand Event. ItemCommand contains RepeaterCommandEventArgs which has two important fields: CommandName CommandArgument So, a trivial example: void rptr_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item) { // Stuff to databind Button myButton = (Button)e.Item.FindControl("myButton"); myButton.CommandName = "Add"; myButton.CommandArgument = "Some Identifying Argument"; } } void rptr_ItemCommand(object source, RepeaterCommandEventArgs e) { if (e.CommandName == "Add") { // Do your event } }
ASP.Net: why is my button's click/command events not binding/firing in a repeater? Here's the code from the ascx that has the repeater: A sub-header: [Some other stuff is here] And in the codebehind for the repeater's databound and events: Protected Sub ListOfEmails_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles ListOfEmails.ItemDataBound If (e.Item.ItemType = ListItemType.Item) Or (e.Item.ItemType = ListItemType.AlternatingItem) Then Dim removeEmail As Button = CType(e.Item.FindControl("removeEmail"), Button) removeEmail.CommandArgument = e.Item.ItemIndex.ToString() AddHandler removeEmail.Click, AddressOf removeEmail_Click AddHandler removeEmail.Command, AddressOf removeEmail_Command End If End Sub Sub removeEmail_Click(ByVal sender As Object, ByVal e As System.EventArgs) Response.Write(" click ") End Sub Sub removeEmail_Command(ByVal sender As Object, ByVal e As CommandEventArgs) Response.Write(" command ") End Sub Neither the click or command is getting called, what am I doing wrong?
TITLE: ASP.Net: why is my button's click/command events not binding/firing in a repeater? QUESTION: Here's the code from the ascx that has the repeater: A sub-header: [Some other stuff is here] And in the codebehind for the repeater's databound and events: Protected Sub ListOfEmails_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles ListOfEmails.ItemDataBound If (e.Item.ItemType = ListItemType.Item) Or (e.Item.ItemType = ListItemType.AlternatingItem) Then Dim removeEmail As Button = CType(e.Item.FindControl("removeEmail"), Button) removeEmail.CommandArgument = e.Item.ItemIndex.ToString() AddHandler removeEmail.Click, AddressOf removeEmail_Click AddHandler removeEmail.Command, AddressOf removeEmail_Command End If End Sub Sub removeEmail_Click(ByVal sender As Object, ByVal e As System.EventArgs) Response.Write(" click ") End Sub Sub removeEmail_Command(ByVal sender As Object, ByVal e As CommandEventArgs) Response.Write(" command ") End Sub Neither the click or command is getting called, what am I doing wrong? ANSWER: Controls nested inside of Repeaters do not intercept events. Instead you need to bind to the Repeater.ItemCommand Event. ItemCommand contains RepeaterCommandEventArgs which has two important fields: CommandName CommandArgument So, a trivial example: void rptr_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item) { // Stuff to databind Button myButton = (Button)e.Item.FindControl("myButton"); myButton.CommandName = "Add"; myButton.CommandArgument = "Some Identifying Argument"; } } void rptr_ItemCommand(object source, RepeaterCommandEventArgs e) { if (e.CommandName == "Add") { // Do your event } }
[ "asp.net", "vb.net", ".net-2.0", "repeater", "button" ]
9
15
17,302
5
0
2008-09-03T19:43:22.877000
2008-09-03T19:48:16.547000
42,416
67,689
How can I install libgluezilla on Ubuntu 8.04?
I want to use the Web Browser control within an mono application, but when I do get the error "libgluezilla not found. To have webbrowser support, you need libgluezilla installed." Installing the Intrepid Deb causes any application that references the web browser control to crash on startup with: 'Thread (nil) may have been prematurely finalized'.
apt-cache search libgluezilla libmono-mozilla0.1-cil - Mono Mozilla library From the package description: Description: Mono Mozilla library Mono is a platform for running and developing applications based on the ECMA/ISO Standards. Mono is an open source effort led by Novell. Mono provides a complete CLR (Common Language Runtime) including compiler and runtime, which can produce and execute CIL (Common Intermediate Language) bytecode (aka assemblies), and a class library.. This package contains the implementation of the WebControl class based on the Mozilla engine using libgluezilla. Homepage: http://www.mono-project.com/ You'll probably need to uninstall anything that came in from intrepid without being properly backported.
How can I install libgluezilla on Ubuntu 8.04? I want to use the Web Browser control within an mono application, but when I do get the error "libgluezilla not found. To have webbrowser support, you need libgluezilla installed." Installing the Intrepid Deb causes any application that references the web browser control to crash on startup with: 'Thread (nil) may have been prematurely finalized'.
TITLE: How can I install libgluezilla on Ubuntu 8.04? QUESTION: I want to use the Web Browser control within an mono application, but when I do get the error "libgluezilla not found. To have webbrowser support, you need libgluezilla installed." Installing the Intrepid Deb causes any application that references the web browser control to crash on startup with: 'Thread (nil) may have been prematurely finalized'. ANSWER: apt-cache search libgluezilla libmono-mozilla0.1-cil - Mono Mozilla library From the package description: Description: Mono Mozilla library Mono is a platform for running and developing applications based on the ECMA/ISO Standards. Mono is an open source effort led by Novell. Mono provides a complete CLR (Common Language Runtime) including compiler and runtime, which can produce and execute CIL (Common Intermediate Language) bytecode (aka assemblies), and a class library.. This package contains the implementation of the WebControl class based on the Mozilla engine using libgluezilla. Homepage: http://www.mono-project.com/ You'll probably need to uninstall anything that came in from intrepid without being properly backported.
[ "ubuntu", "mono" ]
4
3
5,941
3
0
2008-09-03T19:50:11.363000
2008-09-15T22:41:05.220000
42,422
42,445
Is reusing a variable in VB6 a good idea?
Essentially I want to know if in VB.NET 2005 if using a sqlcommand and then reusing it by using the NEW is wrong. Will it cause a memory leak. EG: try dim mySQL as new sqlcommand(sSQL, cnInput) // do a sql execute and read the data mySQL = new sqlcommand(sSQLdifferent, cnInput) // do sql execute and read the data catch... finally if mysql isnot nothing then mysql.dispose mysql = nothing end if EDIT: put try catch in to avoid the comments about not using them
Just to extend what Longhorn213 said, here's the code for it: Using mysql as SqlCommand = new SqlCommand(sSql, cnInput) ' do stuff' End Using Using mysql as SqlCommand = new SqlCommand(otherSql, cnInput) ' do other stuff' End Using (edit) Just as an FYI, using automatically wraps the block of code around a try/finally that calls the Dispose method on the variable it is created with. Thus, it's an easy way to ensure your resource is released. http://msdn.microsoft.com/en-us/library/htd05whh(VS.80).aspx
Is reusing a variable in VB6 a good idea? Essentially I want to know if in VB.NET 2005 if using a sqlcommand and then reusing it by using the NEW is wrong. Will it cause a memory leak. EG: try dim mySQL as new sqlcommand(sSQL, cnInput) // do a sql execute and read the data mySQL = new sqlcommand(sSQLdifferent, cnInput) // do sql execute and read the data catch... finally if mysql isnot nothing then mysql.dispose mysql = nothing end if EDIT: put try catch in to avoid the comments about not using them
TITLE: Is reusing a variable in VB6 a good idea? QUESTION: Essentially I want to know if in VB.NET 2005 if using a sqlcommand and then reusing it by using the NEW is wrong. Will it cause a memory leak. EG: try dim mySQL as new sqlcommand(sSQL, cnInput) // do a sql execute and read the data mySQL = new sqlcommand(sSQLdifferent, cnInput) // do sql execute and read the data catch... finally if mysql isnot nothing then mysql.dispose mysql = nothing end if EDIT: put try catch in to avoid the comments about not using them ANSWER: Just to extend what Longhorn213 said, here's the code for it: Using mysql as SqlCommand = new SqlCommand(sSql, cnInput) ' do stuff' End Using Using mysql as SqlCommand = new SqlCommand(otherSql, cnInput) ' do other stuff' End Using (edit) Just as an FYI, using automatically wraps the block of code around a try/finally that calls the Dispose method on the variable it is created with. Thus, it's an easy way to ensure your resource is released. http://msdn.microsoft.com/en-us/library/htd05whh(VS.80).aspx
[ ".net", "vb.net", "memory-leaks", "garbage-collection" ]
1
6
802
7
0
2008-09-03T19:51:03.607000
2008-09-03T19:59:08.940000
42,428
42,498
Window managers for Windows and Macs
X Windows has special processes called Window Managers that manage the layout of windows and decorations like their title bar, control buttons etc. Such processes use an X Windows API to detect events related to windows sizes and positions. Are there any consistent ways for writing such processes for Microsoft Windows or Mac OS/X? I know that in general these systems are less flexible but I'm looking for something that will use public APIs and not undocumented hacks.
Windows and Mac OS X have built-in "window managers" that cannot be changed. There are various ways to customize the look and feel of the platform, but you can't really replace the existing window managers. Application programs use APIs to receive events and interact with the OS. You can write an application that moves other applications' windows around on screen, but you can't get the level of control you can from X.
Window managers for Windows and Macs X Windows has special processes called Window Managers that manage the layout of windows and decorations like their title bar, control buttons etc. Such processes use an X Windows API to detect events related to windows sizes and positions. Are there any consistent ways for writing such processes for Microsoft Windows or Mac OS/X? I know that in general these systems are less flexible but I'm looking for something that will use public APIs and not undocumented hacks.
TITLE: Window managers for Windows and Macs QUESTION: X Windows has special processes called Window Managers that manage the layout of windows and decorations like their title bar, control buttons etc. Such processes use an X Windows API to detect events related to windows sizes and positions. Are there any consistent ways for writing such processes for Microsoft Windows or Mac OS/X? I know that in general these systems are less flexible but I'm looking for something that will use public APIs and not undocumented hacks. ANSWER: Windows and Mac OS X have built-in "window managers" that cannot be changed. There are various ways to customize the look and feel of the platform, but you can't really replace the existing window managers. Application programs use APIs to receive events and interact with the OS. You can write an application that moves other applications' windows around on screen, but you can't get the level of control you can from X.
[ "windows", "macos", "operating-system", "x11" ]
2
3
731
2
0
2008-09-03T19:52:07.147000
2008-09-03T20:24:53.307000
42,437
42,448
Best way to handle input from a keyboard "wedge"
I'm writing a C# POS (point of sale) system that takes input from a keyboard wedge magcard reader. This means that any data it reads off of a mag stripe is entered as if it were typed on the keyboard very quickly. Currently I'm handling this by attaching to the KeyPress event and looking for a series of very fast key presses that contain the card swipe sentinel characters. Is there a better way to deal with this sort of input? Edit: The device does simply present the data as keystrokes and doesn't interface through some other driver. Also We use a wide range of these types of devices so ideally a method should work independent of the specific model of wedge being used. However if there is no other option I'll have to make do.
One thing you can do is that you should be able to configure your wedge reader so that it presents one or many escape characters before or after the string. You would use these escape characters to know that you are about to have (or just had) a magcard input. This same technique is used by barcode reader devices so you application knows to get focus or handle the data input from the device. The negative to this approach is that you have to properly configure your external devices. This can be a deployment issue. This assumes that your devices simply present the data as keystrokes and don't interface through some other driver.
Best way to handle input from a keyboard "wedge" I'm writing a C# POS (point of sale) system that takes input from a keyboard wedge magcard reader. This means that any data it reads off of a mag stripe is entered as if it were typed on the keyboard very quickly. Currently I'm handling this by attaching to the KeyPress event and looking for a series of very fast key presses that contain the card swipe sentinel characters. Is there a better way to deal with this sort of input? Edit: The device does simply present the data as keystrokes and doesn't interface through some other driver. Also We use a wide range of these types of devices so ideally a method should work independent of the specific model of wedge being used. However if there is no other option I'll have to make do.
TITLE: Best way to handle input from a keyboard "wedge" QUESTION: I'm writing a C# POS (point of sale) system that takes input from a keyboard wedge magcard reader. This means that any data it reads off of a mag stripe is entered as if it were typed on the keyboard very quickly. Currently I'm handling this by attaching to the KeyPress event and looking for a series of very fast key presses that contain the card swipe sentinel characters. Is there a better way to deal with this sort of input? Edit: The device does simply present the data as keystrokes and doesn't interface through some other driver. Also We use a wide range of these types of devices so ideally a method should work independent of the specific model of wedge being used. However if there is no other option I'll have to make do. ANSWER: One thing you can do is that you should be able to configure your wedge reader so that it presents one or many escape characters before or after the string. You would use these escape characters to know that you are about to have (or just had) a magcard input. This same technique is used by barcode reader devices so you application knows to get focus or handle the data input from the device. The negative to this approach is that you have to properly configure your external devices. This can be a deployment issue. This assumes that your devices simply present the data as keystrokes and don't interface through some other driver.
[ "c#", "point-of-sale" ]
6
10
4,785
5
0
2008-09-03T19:55:05.500000
2008-09-03T19:59:42.853000
42,446
42,968
How do I convert an IntPtr to a Stream?
class Foo { static bool Bar(Stream^ stream); }; class FooWrapper { bool Bar(LPCWSTR szUnicodeString) { return Foo::Bar(??); } }; MemoryStream will take a byte[] but I'd like to do this without copying the data if possible.
You can avoid the copy if you use an UnmanagedMemoryStream() instead (class exists in.NET FCL 2.0 and later). Like MemoryStream, it is a subclass of IO.Stream, and has all the usual stream operations. Microsoft's description of the class is: Provides access to unmanaged blocks of memory from managed code. which pretty much tells you what you need to know. Note that UnmanagedMemoryStream() is not CLS-compliant.
How do I convert an IntPtr to a Stream? class Foo { static bool Bar(Stream^ stream); }; class FooWrapper { bool Bar(LPCWSTR szUnicodeString) { return Foo::Bar(??); } }; MemoryStream will take a byte[] but I'd like to do this without copying the data if possible.
TITLE: How do I convert an IntPtr to a Stream? QUESTION: class Foo { static bool Bar(Stream^ stream); }; class FooWrapper { bool Bar(LPCWSTR szUnicodeString) { return Foo::Bar(??); } }; MemoryStream will take a byte[] but I'd like to do this without copying the data if possible. ANSWER: You can avoid the copy if you use an UnmanagedMemoryStream() instead (class exists in.NET FCL 2.0 and later). Like MemoryStream, it is a subclass of IO.Stream, and has all the usual stream operations. Microsoft's description of the class is: Provides access to unmanaged blocks of memory from managed code. which pretty much tells you what you need to know. Note that UnmanagedMemoryStream() is not CLS-compliant.
[ ".net", "c++", "interop", "managed-c++" ]
2
8
8,433
2
0
2008-09-03T19:59:11.857000
2008-09-04T01:06:58.700000
42,452
42,477
Is BCEL == monkeypatching for java?
a colleague pointed me the other day to BCEL which, as best I can tell from his explanation and a quick read, a way to modify at run time the byte code. My first thought was that it sounded dangerous, and my second thought was that it sounded cool. Then I gave it some more thought and I recalled the codinghorror post on monkey-patching and realized that this was basically the same thing. Has anyone ever used BCEL for anything practical? Am I right that this is basically run time monkey patching, or am I missing something?
It's a bit more low-level than classic monkey patching, and from what I read, the classes already loaded into the VM are not updated. It only supports saving it to class files again, not modifying run time classes.
Is BCEL == monkeypatching for java? a colleague pointed me the other day to BCEL which, as best I can tell from his explanation and a quick read, a way to modify at run time the byte code. My first thought was that it sounded dangerous, and my second thought was that it sounded cool. Then I gave it some more thought and I recalled the codinghorror post on monkey-patching and realized that this was basically the same thing. Has anyone ever used BCEL for anything practical? Am I right that this is basically run time monkey patching, or am I missing something?
TITLE: Is BCEL == monkeypatching for java? QUESTION: a colleague pointed me the other day to BCEL which, as best I can tell from his explanation and a quick read, a way to modify at run time the byte code. My first thought was that it sounded dangerous, and my second thought was that it sounded cool. Then I gave it some more thought and I recalled the codinghorror post on monkey-patching and realized that this was basically the same thing. Has anyone ever used BCEL for anything practical? Am I right that this is basically run time monkey patching, or am I missing something? ANSWER: It's a bit more low-level than classic monkey patching, and from what I read, the classes already loaded into the VM are not updated. It only supports saving it to class files again, not modifying run time classes.
[ "java", "bytecode", "monkeypatching", "bcel" ]
3
1
1,161
5
0
2008-09-03T20:00:16.160000
2008-09-03T20:15:15.780000
42,460
107,103
Custom titlebars/chrome in a WinForms app
I'm almost certain I know the answer to this question, but I'm hoping there's something I've overlooked. Certain applications seem to have the Vista Aero look and feel to their caption bars and buttons even when running on Windows XP. (Google Chrome and Windows Live Photo Gallery come to mind as examples.) I know that one way to accomplish this from WinForms would be to create a borderless form and draw the caption bar/buttons yourself, then overriding WndProc to make sure moving, resizing, and button clicks do what they're supposed to do (I'm not clear on the specifics but could probably pull it off given a day to read documentation.) I'm curious if there's a different, easier way that I'm overlooking. Perhaps some API calls or window styles I've overlooked? I believe Google has answered it for me by using the roll-your-own-window approach with Chrome. I will leave the question open for another day in case someone has new information, but I believe I have answered the question myself.
Here's an article with full code sample on how to use your own custom "chrome" for an application: http://geekswithblogs.net/kobush/articles/CustomBorderForms3.aspx This looks like some really good stuff. There are a total of 3 articles in it's series, and it runs great, and on Vista too!
Custom titlebars/chrome in a WinForms app I'm almost certain I know the answer to this question, but I'm hoping there's something I've overlooked. Certain applications seem to have the Vista Aero look and feel to their caption bars and buttons even when running on Windows XP. (Google Chrome and Windows Live Photo Gallery come to mind as examples.) I know that one way to accomplish this from WinForms would be to create a borderless form and draw the caption bar/buttons yourself, then overriding WndProc to make sure moving, resizing, and button clicks do what they're supposed to do (I'm not clear on the specifics but could probably pull it off given a day to read documentation.) I'm curious if there's a different, easier way that I'm overlooking. Perhaps some API calls or window styles I've overlooked? I believe Google has answered it for me by using the roll-your-own-window approach with Chrome. I will leave the question open for another day in case someone has new information, but I believe I have answered the question myself.
TITLE: Custom titlebars/chrome in a WinForms app QUESTION: I'm almost certain I know the answer to this question, but I'm hoping there's something I've overlooked. Certain applications seem to have the Vista Aero look and feel to their caption bars and buttons even when running on Windows XP. (Google Chrome and Windows Live Photo Gallery come to mind as examples.) I know that one way to accomplish this from WinForms would be to create a borderless form and draw the caption bar/buttons yourself, then overriding WndProc to make sure moving, resizing, and button clicks do what they're supposed to do (I'm not clear on the specifics but could probably pull it off given a day to read documentation.) I'm curious if there's a different, easier way that I'm overlooking. Perhaps some API calls or window styles I've overlooked? I believe Google has answered it for me by using the roll-your-own-window approach with Chrome. I will leave the question open for another day in case someone has new information, but I believe I have answered the question myself. ANSWER: Here's an article with full code sample on how to use your own custom "chrome" for an application: http://geekswithblogs.net/kobush/articles/CustomBorderForms3.aspx This looks like some really good stuff. There are a total of 3 articles in it's series, and it runs great, and on Vista too!
[ ".net", "winforms", "user-interface", "windows-xp" ]
12
11
31,710
6
0
2008-09-03T20:04:47.460000
2008-09-20T04:26:36.607000
42,466
42,475
MSDN subscriptions on the cheap?
As a long time Microsoft developer, I find MSDN to be an invaluable resource. However, when tinkering at home I am not able to play with the best latest technologies and the different offerings coming from Microsoft as I cannot justify paying such a hefty price for what is essentially a pastime. The Express editions are great, but fall flat when trying to use the more advanced feature I am used to from the versions I use at work. I cannot get the latest betas and play with the new offerings, not legally, anyway. Apart from getting an MVP, how would one go about getting an MSDN subscription for an acceptable price for a non-professional environment? I am aware of the Empower program, but I thought it was geared towards getting commercial software to market. If this is not the case, it appears like the way for me to go. Thanks!
There is an Empower program that Microsoft has available. It gives you several Premium subscriptions for cheap, with the catch that you have to be an ISV working towards an actual product. This (Not available anymore - broken link) gives you all the software you'll need for development, and even a few "real world" licenses for certain apps (like Office) After a couple of years, you have to pay full price though. The logic being that you should have a product on the market, and can afford it.
MSDN subscriptions on the cheap? As a long time Microsoft developer, I find MSDN to be an invaluable resource. However, when tinkering at home I am not able to play with the best latest technologies and the different offerings coming from Microsoft as I cannot justify paying such a hefty price for what is essentially a pastime. The Express editions are great, but fall flat when trying to use the more advanced feature I am used to from the versions I use at work. I cannot get the latest betas and play with the new offerings, not legally, anyway. Apart from getting an MVP, how would one go about getting an MSDN subscription for an acceptable price for a non-professional environment? I am aware of the Empower program, but I thought it was geared towards getting commercial software to market. If this is not the case, it appears like the way for me to go. Thanks!
TITLE: MSDN subscriptions on the cheap? QUESTION: As a long time Microsoft developer, I find MSDN to be an invaluable resource. However, when tinkering at home I am not able to play with the best latest technologies and the different offerings coming from Microsoft as I cannot justify paying such a hefty price for what is essentially a pastime. The Express editions are great, but fall flat when trying to use the more advanced feature I am used to from the versions I use at work. I cannot get the latest betas and play with the new offerings, not legally, anyway. Apart from getting an MVP, how would one go about getting an MSDN subscription for an acceptable price for a non-professional environment? I am aware of the Empower program, but I thought it was geared towards getting commercial software to market. If this is not the case, it appears like the way for me to go. Thanks! ANSWER: There is an Empower program that Microsoft has available. It gives you several Premium subscriptions for cheap, with the catch that you have to be an ISV working towards an actual product. This (Not available anymore - broken link) gives you all the software you'll need for development, and even a few "real world" licenses for certain apps (like Office) After a couple of years, you have to pay full price though. The logic being that you should have a product on the market, and can afford it.
[ "msdn" ]
81
21
86,273
9
0
2008-09-03T20:11:32.653000
2008-09-03T20:14:53.533000